Add nand reader sample for reading title keys

This commit is contained in:
Alex Barney 2018-07-14 15:36:47 -05:00
parent c44659ca17
commit 5c3e4af4be
19 changed files with 885 additions and 3 deletions

6
NandReaderGui/App.config Normal file
View file

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6" />
</startup>
</configuration>

12
NandReaderGui/App.xaml Normal file
View file

@ -0,0 +1,12 @@
<Application x:Class="NandReaderGui.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:viewModel="clr-namespace:NandReaderGui.ViewModel"
StartupUri="MainWindow.xaml"
mc:Ignorable="d">
<Application.Resources>
<viewModel:ViewModelLocator x:Key="Locator" d:IsDataSource="True" />
</Application.Resources>
</Application>

View file

@ -0,0 +1,9 @@
namespace NandReaderGui
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App
{
}
}

View file

@ -0,0 +1,163 @@
using System;
using System.IO;
using System.Runtime.InteropServices;
using Microsoft.Win32.SafeHandles;
namespace NandReaderGui
{
public class DeviceStream : Stream
{
public const short FileAttributeNormal = 0x80;
public const short InvalidHandleValue = -1;
public const uint GenericRead = 0x80000000;
public const uint GenericWrite = 0x40000000;
public const uint CreateNew = 1;
public const uint CreateAlways = 2;
public const uint OpenExisting = 3;
// Use interop to call the CreateFile function.
// For more information about CreateFile,
// see the unmanaged MSDN reference library.
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
private static extern IntPtr CreateFile(string lpFileName, uint dwDesiredAccess,
uint dwShareMode, IntPtr lpSecurityAttributes, uint dwCreationDisposition,
uint dwFlagsAndAttributes, IntPtr hTemplateFile);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool ReadFile(
IntPtr hFile, // handle to file
byte[] lpBuffer, // data buffer
int nNumberOfBytesToRead, // number of bytes to read
ref int lpNumberOfBytesRead, // number of bytes read
IntPtr lpOverlapped
//
// ref OVERLAPPED lpOverlapped // overlapped buffer
);
private SafeFileHandle _handleValue;
private FileStream _fs;
public DeviceStream(string device, long length)
{
Load(device);
Length = length;
}
private void Load(string path)
{
if (string.IsNullOrEmpty(path))
{
throw new ArgumentNullException("path");
}
// Try to open the file.
IntPtr ptr = CreateFile(path, GenericRead, 0, IntPtr.Zero, OpenExisting, 0, IntPtr.Zero);
_handleValue = new SafeFileHandle(ptr, true);
_fs = new FileStream(_handleValue, FileAccess.Read);
// If the handle is invalid,
// get the last Win32 error
// and throw a Win32Exception.
if (_handleValue.IsInvalid)
{
Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
}
}
public override bool CanRead { get; } = true;
public override bool CanSeek => true;
public override bool CanWrite => false;
public override void Flush() { }
public override long Length { get; }
public override long Position
{
get => _fs.Position;
set => _fs.Position = value;
}
public override int Read(byte[] buffer, int offset, int count)
{
int bytesRead = 0;
var bufBytes = new byte[count];
if (!ReadFile(_handleValue.DangerousGetHandle(), bufBytes, count, ref bytesRead, IntPtr.Zero))
{
Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
}
for (int i = 0; i < bytesRead; i++)
{
buffer[offset + i] = bufBytes[i];
}
return bytesRead;
}
public override int ReadByte()
{
int bytesRead = 0;
var lpBuffer = new byte[1];
if (!ReadFile(
_handleValue.DangerousGetHandle(), // handle to file
lpBuffer, // data buffer
1, // number of bytes to read
ref bytesRead, // number of bytes read
IntPtr.Zero
))
{ Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error()); }
return lpBuffer[0];
}
public override long Seek(long offset, SeekOrigin origin) => _fs.Seek(offset, origin);
public override void SetLength(long value)
{
throw new NotSupportedException();
}
public override void Write(byte[] buffer, int offset, int count)
{
throw new NotSupportedException();
}
public override void Close()
{
_handleValue.Close();
_handleValue.Dispose();
_handleValue = null;
base.Close();
}
private bool _disposed;
private new void Dispose()
{
Dispose(true);
base.Dispose();
GC.SuppressFinalize(this);
}
private new void Dispose(bool disposing)
{
// Check to see if Dispose has already been called.
if (!_disposed)
{
if (disposing)
{
if (_handleValue != null)
{
_fs.Dispose();
_handleValue.Close();
_handleValue.Dispose();
_handleValue = null;
}
}
// Note disposing has been done.
_disposed = true;
}
}
}
}

View file

@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<Weavers>
<Costura />
</Weavers>

View file

@ -0,0 +1,12 @@
<Window x:Class="NandReaderGui.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:view="clr-namespace:NandReaderGui.View"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<view:Nand></view:Nand>
</Grid>
</Window>

View file

@ -0,0 +1,13 @@
namespace NandReaderGui
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow
{
public MainWindow()
{
InitializeComponent();
}
}
}

View file

@ -0,0 +1,126 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{3CBD38B0-6575-4768-8E94-A8AF2D2C9F43}</ProjectGuid>
<OutputType>WinExe</OutputType>
<RootNamespace>NandReaderGui</RootNamespace>
<AssemblyName>NandReaderGui</AssemblyName>
<TargetFrameworkVersion>v4.6</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<ProjectTypeGuids>{60dc8134-eba5-43b8-bcc9-bb4bc16c2548};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
<WarningLevel>4</WarningLevel>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Data" />
<Reference Include="System.Management" />
<Reference Include="System.Xml" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Xaml">
<RequiredTargetFramework>4.0</RequiredTargetFramework>
</Reference>
<Reference Include="WindowsBase" />
<Reference Include="PresentationCore" />
<Reference Include="PresentationFramework" />
</ItemGroup>
<ItemGroup>
<ApplicationDefinition Include="App.xaml">
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</ApplicationDefinition>
<Compile Include="DeviceStream.cs" />
<Compile Include="ViewModel\NandViewModel.cs" />
<Compile Include="ViewModel\ViewModelLocator.cs" />
<Compile Include="View\Nand.xaml.cs">
<DependentUpon>Nand.xaml</DependentUpon>
</Compile>
<Page Include="MainWindow.xaml">
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</Page>
<Compile Include="App.xaml.cs">
<DependentUpon>App.xaml</DependentUpon>
<SubType>Code</SubType>
</Compile>
<Compile Include="MainWindow.xaml.cs">
<DependentUpon>MainWindow.xaml</DependentUpon>
<SubType>Code</SubType>
</Compile>
<Page Include="View\Nand.xaml">
<SubType>Designer</SubType>
<Generator>MSBuild:Compile</Generator>
</Page>
</ItemGroup>
<ItemGroup>
<Compile Include="Properties\AssemblyInfo.cs">
<SubType>Code</SubType>
</Compile>
<Compile Include="Properties\Resources.Designer.cs">
<AutoGen>True</AutoGen>
<DesignTime>True</DesignTime>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
<Compile Include="Properties\Settings.Designer.cs">
<AutoGen>True</AutoGen>
<DependentUpon>Settings.settings</DependentUpon>
<DesignTimeSharedInput>True</DesignTimeSharedInput>
</Compile>
<EmbeddedResource Include="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
</EmbeddedResource>
<None Include="Properties\Settings.settings">
<Generator>SettingsSingleFileGenerator</Generator>
<LastGenOutput>Settings.Designer.cs</LastGenOutput>
</None>
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Costura.Fody">
<Version>3.1.0</Version>
</PackageReference>
<PackageReference Include="MvvmLightLibs">
<Version>5.4.1</Version>
</PackageReference>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\libhac.Nand\libhac.Nand.csproj">
<Project>{ab503d24-f702-4e6e-b615-a9c7bda218d1}</Project>
<Name>libhac.Nand</Name>
</ProjectReference>
<ProjectReference Include="..\libhac\libhac.csproj">
<Project>{ffca6c31-d9d4-4ed8-a06d-0cc6b94422b8}</Project>
<Name>libhac</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>

View file

@ -0,0 +1,53 @@
using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("RawNandReader")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("RawNandReader")]
[assembly: AssemblyCopyright("Copyright © 2018")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

View file

@ -0,0 +1,63 @@
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace NandReaderGui.Properties {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "15.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("NandReaderGui.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
}
}

View file

@ -0,0 +1,117 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View file

@ -0,0 +1,26 @@
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace NandReaderGui.Properties {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "15.7.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default {
get {
return defaultInstance;
}
}
}
}

View file

@ -0,0 +1,7 @@
<?xml version='1.0' encoding='utf-8'?>
<SettingsFile xmlns="uri:settings" CurrentProfile="(Default)">
<Profiles>
<Profile Name="(Default)" />
</Profiles>
<Settings />
</SettingsFile>

View file

@ -0,0 +1,15 @@
<UserControl x:Class="NandReaderGui.View.Nand"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
DataContext="{Binding Main, Source={StaticResource Locator}}"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800">
<Grid>
<StackPanel Orientation="Vertical">
<ListBox ItemsSource="{Binding Disks}" DisplayMemberPath="Display" Height="150" SelectedItem="{Binding SelectedDisk}"/>
<Button Content="Open" Width="100" HorizontalAlignment="Left" Command="{Binding OpenCommand}"></Button>
</StackPanel>
</Grid>
</UserControl>

View file

@ -0,0 +1,13 @@
namespace NandReaderGui.View
{
/// <summary>
/// Interaction logic for Nand.xaml
/// </summary>
public partial class Nand
{
public Nand()
{
InitializeComponent();
}
}
}

View file

@ -0,0 +1,124 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Management;
using System.Windows.Input;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using libhac;
using libhac.Nand;
using libhac.XTSSharp;
namespace NandReaderGui.ViewModel
{
public class NandViewModel : ViewModelBase
{
public List<DiskInfo> Disks { get; } = new List<DiskInfo>();
public ICommand OpenCommand { get; set; }
public DiskInfo SelectedDisk { get; set; }
public NandViewModel()
{
OpenCommand = new RelayCommand(Open);
var query = new WqlObjectQuery("SELECT * FROM Win32_DiskDrive");
using (var searcher = new ManagementObjectSearcher(query))
{
foreach (var drive in searcher.Get())
{
if (drive.GetPropertyValue("Size") == null) continue;
var info = new DiskInfo();
info.PhysicalName = (string)drive.GetPropertyValue("Name");
info.Name = (string)drive.GetPropertyValue("Caption");
info.Model = (string)drive.GetPropertyValue("Model");
info.Length = (long)((ulong)drive.GetPropertyValue("Size"));
info.SectorSize = (int)((uint)drive.GetPropertyValue("BytesPerSector"));
info.DisplaySize = Util.GetBytesReadable((long)((ulong)drive.GetPropertyValue("Size")));
Disks.Add(info);
}
}
}
public void Open()
{
var disk = SelectedDisk;
var stream = new RandomAccessSectorStream(new SectorStream(new DeviceStream(disk.PhysicalName, disk.Length), disk.SectorSize * 100));
var keyset = OpenKeyset();
var nand = new Nand(stream, keyset);
var prodinfo = nand.OpenProdInfo();
var calibration = new Calibration(prodinfo);
keyset.eticket_ext_key_rsa = Crypto.DecryptRsaKey(calibration.EticketExtKeyRsa, keyset.eticket_rsa_kek);
var tickets = GetTickets(nand);
using (var outStream = new StreamWriter("titlekeys.txt"))
{
foreach (var ticket in tickets)
{
var key = ticket.GetTitleKey(keyset);
outStream.WriteLine($"{ticket.RightsId.ToHexString()},{key.ToHexString()}");
}
}
}
private static Ticket[] GetTickets(Nand nand, IProgressReport logger = null)
{
var tickets = new List<Ticket>();
var system = nand.OpenSystemPartition();
logger?.LogMessage("Searching save 80000000000000E1");
var saveE1 = system.OpenFile("save\\80000000000000E1", FileMode.Open, FileAccess.Read);
tickets.AddRange(Ticket.SearchTickets(saveE1, logger));
logger?.LogMessage("Searching save 80000000000000E2");
var saveE2 = system.OpenFile("save\\80000000000000E2", FileMode.Open, FileAccess.Read);
tickets.AddRange(Ticket.SearchTickets(saveE2, logger));
logger?.LogMessage($"Found {tickets.Count} tickets");
return tickets.ToArray();
}
private static Keyset OpenKeyset()
{
var home = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
var homeKeyFile = Path.Combine(home, ".switch", "prod.keys");
var homeTitleKeyFile = Path.Combine(home, ".switch", "title.keys");
var homeConsoleKeyFile = Path.Combine(home, ".switch", "console.keys");
string keyFile = null;
string titleKeyFile = null;
string consoleKeyFile = null;
if (File.Exists(homeKeyFile))
{
keyFile = homeKeyFile;
}
if (File.Exists(homeTitleKeyFile))
{
titleKeyFile = homeTitleKeyFile;
}
if (File.Exists(homeConsoleKeyFile))
{
consoleKeyFile = homeConsoleKeyFile;
}
return ExternalKeys.ReadKeyFile(keyFile, titleKeyFile, consoleKeyFile);
}
}
public class DiskInfo
{
public string PhysicalName { get; set; }
public string Name { get; set; }
public string Model { get; set; }
public long Length { get; set; }
public int SectorSize { get; set; }
public string DisplaySize { get; set; }
public string Display => $"{Name} ({DisplaySize})";
}
}

View file

@ -0,0 +1,48 @@
/*
In App.xaml:
<Application.Resources>
<vm:ViewModelLocatorTemplate xmlns:vm="clr-namespace:MvvmLight1.ViewModel"
x:Key="Locator" />
</Application.Resources>
In the View:
DataContext="{Binding Source={StaticResource Locator}, Path=ViewModelName}"
*/
using CommonServiceLocator;
using GalaSoft.MvvmLight.Ioc;
namespace NandReaderGui.ViewModel
{
/// <summary>
/// This class contains static references to all the view models in the
/// application and provides an entry point for the bindings.
/// <para>
/// See http://www.mvvmlight.net
/// </para>
/// </summary>
public class ViewModelLocator
{
static ViewModelLocator()
{
ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);
SimpleIoc.Default.Register<NandViewModel>();
}
/// <summary>
/// Gets the Main property.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance",
"CA1822:MarkMembersAsStatic",
Justification = "This non-static member is needed for data binding purposes.")]
public NandViewModel Main => ServiceLocator.Current.GetInstance<NandViewModel>();
/// <summary>
/// Cleans up all the resources.
/// </summary>
public static void Cleanup()
{
}
}
}

View file

@ -7,9 +7,11 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "libhac", "libhac\libhac.csp
EndProject EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "hactoolnet", "hactoolnet\hactoolnet.csproj", "{B1633A64-125F-40A3-9E15-654B4DE5FD98}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "hactoolnet", "hactoolnet\hactoolnet.csproj", "{B1633A64-125F-40A3-9E15-654B4DE5FD98}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "libhac.Nand", "libhac.Nand\libhac.Nand.csproj", "{AB503D24-F702-4E6E-B615-A9C7BDA218D1}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "libhac.Nand", "libhac.Nand\libhac.Nand.csproj", "{AB503D24-F702-4E6E-B615-A9C7BDA218D1}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NandReader", "NandReader\NandReader.csproj", "{9889C467-284F-4061-B4DB-EC94051C29C0}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "NandReader", "NandReader\NandReader.csproj", "{9889C467-284F-4061-B4DB-EC94051C29C0}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NandReaderGui", "NandReaderGui\NandReaderGui.csproj", "{3CBD38B0-6575-4768-8E94-A8AF2D2C9F43}"
EndProject EndProject
Global Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution GlobalSection(SolutionConfigurationPlatforms) = preSolution
@ -33,6 +35,10 @@ Global
{9889C467-284F-4061-B4DB-EC94051C29C0}.Debug|Any CPU.Build.0 = Debug|Any CPU {9889C467-284F-4061-B4DB-EC94051C29C0}.Debug|Any CPU.Build.0 = Debug|Any CPU
{9889C467-284F-4061-B4DB-EC94051C29C0}.Release|Any CPU.ActiveCfg = Release|Any CPU {9889C467-284F-4061-B4DB-EC94051C29C0}.Release|Any CPU.ActiveCfg = Release|Any CPU
{9889C467-284F-4061-B4DB-EC94051C29C0}.Release|Any CPU.Build.0 = Release|Any CPU {9889C467-284F-4061-B4DB-EC94051C29C0}.Release|Any CPU.Build.0 = Release|Any CPU
{3CBD38B0-6575-4768-8E94-A8AF2D2C9F43}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{3CBD38B0-6575-4768-8E94-A8AF2D2C9F43}.Debug|Any CPU.Build.0 = Debug|Any CPU
{3CBD38B0-6575-4768-8E94-A8AF2D2C9F43}.Release|Any CPU.ActiveCfg = Release|Any CPU
{3CBD38B0-6575-4768-8E94-A8AF2D2C9F43}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection EndGlobalSection
GlobalSection(SolutionProperties) = preSolution GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE HideSolutionNode = FALSE

View file

@ -25,6 +25,7 @@
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System; using System;
using System.Collections.Generic;
using System.IO; using System.IO;
namespace libhac.XTSSharp namespace libhac.XTSSharp
@ -34,7 +35,7 @@ namespace libhac.XTSSharp
/// </summary> /// </summary>
public class RandomAccessSectorStream : Stream public class RandomAccessSectorStream : Stream
{ {
private readonly byte[] _buffer; private byte[] _buffer;
private readonly int _bufferSize; private readonly int _bufferSize;
private readonly SectorStream _s; private readonly SectorStream _s;
private readonly bool _keepOpen; private readonly bool _keepOpen;
@ -43,6 +44,15 @@ namespace libhac.XTSSharp
private int _bufferPos; private int _bufferPos;
private int _currentBufferSize; private int _currentBufferSize;
private long PhysicalRead { get; set; }
private long VirtualRead { get; set; }
private int CacheMisses { get; set; }
private int CacheHits { get; set; }
// List should work just fine for a tiny cache
private List<Sector> Cache { get; }
private const int CacheSize = 4;
/// <summary> /// <summary>
/// Creates a new stream /// Creates a new stream
/// </summary> /// </summary>
@ -63,6 +73,17 @@ namespace libhac.XTSSharp
_keepOpen = keepOpen; _keepOpen = keepOpen;
_buffer = new byte[s.SectorSize]; _buffer = new byte[s.SectorSize];
_bufferSize = s.SectorSize; _bufferSize = s.SectorSize;
Cache = new List<Sector>(CacheSize);
for (int i = 0; i < CacheSize; i++)
{
Cache.Add(new Sector
{
Position = -1,
Data = new byte[_bufferSize]
});
}
} }
/// <summary> /// <summary>
@ -246,6 +267,8 @@ namespace libhac.XTSSharp
ReadSector(); ReadSector();
} }
VirtualRead += totalBytesRead;
return totalBytesRead; return totalBytesRead;
} }
@ -291,7 +314,37 @@ namespace libhac.XTSSharp
return; return;
} }
var sectorPosition = _s.Position;
for (int i = 0; i < CacheSize; i++)
{
var sector = Cache[i];
if (sector.Position == sectorPosition)
{
if (i != 0)
{
Cache.RemoveAt(i);
Cache.Insert(0, sector);
}
_buffer = sector.Data;
_bufferLoaded = true;
_bufferPos = 0;
_bufferDirty = false;
_currentBufferSize = sector.Length;
CacheHits++;
_s.Position += _bufferSize;
return;
}
}
var item = Cache[CacheSize - 1];
Cache.RemoveAt(CacheSize - 1);
_buffer = item.Data;
var bytesRead = _s.Read(_buffer, 0, _buffer.Length); var bytesRead = _s.Read(_buffer, 0, _buffer.Length);
PhysicalRead += bytesRead;
//clean the end of it //clean the end of it
if (bytesRead != _bufferSize) if (bytesRead != _bufferSize)
@ -301,6 +354,11 @@ namespace libhac.XTSSharp
_bufferPos = 0; _bufferPos = 0;
_bufferDirty = false; _bufferDirty = false;
_currentBufferSize = bytesRead; _currentBufferSize = bytesRead;
item.Position = sectorPosition;
item.Length = bytesRead;
Cache.Insert(0, item);
CacheMisses++;
} }
/// <summary> /// <summary>
@ -321,5 +379,12 @@ namespace libhac.XTSSharp
_bufferPos = 0; _bufferPos = 0;
Array.Clear(_buffer, 0, _bufferSize); Array.Clear(_buffer, 0, _bufferSize);
} }
private class Sector
{
public long Position { get; set; }
public byte[] Data { get; set; }
public int Length { get; set; }
}
} }
} }