Added signature verification, info command now has WiiPy feature parity
Some checks are pending
Build rustii / build-linux-x86_64 (push) Waiting to run
Build rustii / build-macos-arm64 (push) Waiting to run
Build rustii / build-macos-x86_64 (push) Waiting to run
Build rustii / build-windows-x86_64 (push) Waiting to run

rustii CLI info command now displays the signing status of TMDs/Tickets/WADs like WiiPy does, and displays the ASCII TID for a title when applicable. This means that this command now has full feature parity with WiiPy.
This commit is contained in:
2025-03-27 21:06:59 -04:00
parent 444c3def54
commit edf3af0f7c
12 changed files with 817 additions and 47 deletions

View File

@@ -1,43 +1,44 @@
// Sample file for testing rustii library stuff.
use std::fs;
use rustii::title::{content, crypto, wad};
use rustii::title::{wad, cert};
use rustii::title;
fn main() {
let data = fs::read("boot2.wad").unwrap();
let mut title = title::Title::from_bytes(&data).unwrap();
let data = fs::read("sm.wad").unwrap();
let title = title::Title::from_bytes(&data).unwrap();
println!("Title ID from WAD via Title object: {}", hex::encode(title.tmd.title_id));
let wad = wad::WAD::from_bytes(&data).unwrap();
println!("size of tmd: {:?}", wad.tmd().len());
println!("num content records: {:?}", title.tmd.content_records.len());
println!("first record data: {:?}", title.tmd.content_records.first().unwrap());
if !title.tmd.is_fakesigned() {
title.tmd.fakesign().unwrap();
}
println!("TMD is fakesigned: {:?}",title.tmd.is_fakesigned());
println!("title version from ticket is: {:?}", title.ticket.title_version);
println!("title key (enc): {:?}", title.ticket.title_key);
println!("title key (dec): {:?}", title.ticket.dec_title_key());
if !title.ticket.is_fakesigned() {
title.ticket.fakesign().unwrap();
}
println!("ticket is fakesigned: {:?}", title.ticket.is_fakesigned());
println!("title is fakesigned: {:?}", title.is_fakesigned());
let content_region = content::ContentRegion::from_bytes(&wad.content(), title.tmd.content_records).unwrap();
assert_eq!(wad.content(), content_region.to_bytes().unwrap());
println!("content OK");
let content_dec = content_region.get_content_by_index(0, title.ticket.dec_title_key()).unwrap();
println!("content dec from index: {:?}", content_dec);
let content = content_region.get_enc_content_by_index(0).unwrap();
assert_eq!(content, crypto::encrypt_content(&content_dec, title.ticket.dec_title_key(), 0, content_region.content_records[0].content_size));
println!("content re-encrypted OK");
println!("wad header: {:?}", wad.header);
let cert_chain = &title.cert_chain;
println!("cert chain OK");
let result = cert::verify_ca_cert(&cert_chain.ca_cert()).unwrap();
println!("CA cert {} verified successfully: {}", cert_chain.ca_cert().child_cert_identity(), result);
let result = cert::verify_child_cert(&cert_chain.ca_cert(), &cert_chain.tmd_cert()).unwrap();
println!("TMD cert {} verified successfully: {}", cert_chain.tmd_cert().child_cert_identity(), result);
let result = cert::verify_tmd(&cert_chain.tmd_cert(), &title.tmd).unwrap();
println!("TMD verified successfully: {}", result);
let result = cert::verify_child_cert(&cert_chain.ca_cert(), &cert_chain.ticket_cert()).unwrap();
println!("Ticket cert {} verified successfully: {}", cert_chain.ticket_cert().child_cert_identity(), result);
let result = cert::verify_ticket(&cert_chain.ticket_cert(), &title.ticket).unwrap();
println!("Ticket verified successfully: {}", result);
let result = title.verify().unwrap();
println!("full title verified successfully: {}", result);
}

View File

@@ -5,13 +5,27 @@
use std::{str, fs};
use std::path::Path;
use rustii::{title, title::tmd, title::ticket, title::wad, title::versions};
use rustii::{title, title::cert, title::tmd, title::ticket, title::wad, title::versions};
use crate::filetypes::{WiiFileType, identify_file_type};
fn print_tmd_info(tmd: tmd::TMD) {
fn tid_to_ascii(tid: [u8; 8]) -> Option<String> {
let tid = String::from_utf8_lossy(&tid[4..]).trim_end_matches('\0').trim_start_matches('\0').to_owned();
if tid.len() == 4 {
Some(tid)
} else {
None
}
}
fn print_tmd_info(tmd: tmd::TMD, cert: Option<cert::Certificate>) {
// Print all important keys from the TMD.
println!("Title Info");
println!(" Title ID: {}", hex::encode(tmd.title_id).to_uppercase());
let ascii_tid = tid_to_ascii(tmd.title_id);
if ascii_tid.is_some() {
println!(" Title ID: {} ({})", hex::encode(tmd.title_id).to_uppercase(), ascii_tid.unwrap());
} else {
println!(" Title ID: {}", hex::encode(tmd.title_id).to_uppercase());
}
if hex::encode(tmd.title_id)[..8].eq("00000001") {
if hex::encode(tmd.title_id).eq("0000000100000001") {
println!(" Title Version: {} (boot2v{})", tmd.title_version, tmd.title_version);
@@ -67,7 +81,24 @@ fn print_tmd_info(tmd: tmd::TMD) {
println!(" vWii Title: {}", tmd.is_vwii != 0);
println!(" DVD Video Access: {}", tmd.check_access_right(tmd::AccessRight::DVDVideo));
println!(" AHB Access: {}", tmd.check_access_right(tmd::AccessRight::AHB));
println!(" Fakesigned: {}", tmd.is_fakesigned());
if cert.is_some() {
let signing_str = match cert::verify_tmd(&cert.unwrap(), &tmd) {
Ok(result) => match result {
true => "Valid (Unmodified TMD)",
false => {
if tmd.is_fakesigned() {
"Fakesigned"
} else {
"Invalid (Modified TMD)"
}
},
},
Err(_) => "Invalid (Modified TMD)"
};
println!(" Signature: {}", signing_str);
} else {
println!(" Fakesigned: {}", tmd.is_fakesigned());
}
println!("\nContent Info");
println!(" Total Contents: {}", tmd.num_contents);
println!(" Boot Content Index: {}", tmd.boot_index);
@@ -81,10 +112,15 @@ fn print_tmd_info(tmd: tmd::TMD) {
}
}
fn print_ticket_info(ticket: ticket::Ticket) {
fn print_ticket_info(ticket: ticket::Ticket, cert: Option<cert::Certificate>) {
// Print all important keys from the Ticket.
println!("Ticket Info");
println!(" Title ID: {}", hex::encode(ticket.title_id).to_uppercase());
let ascii_tid = tid_to_ascii(ticket.title_id);
if ascii_tid.is_some() {
println!(" Title ID: {} ({})", hex::encode(ticket.title_id).to_uppercase(), ascii_tid.unwrap());
} else {
println!(" Title ID: {}", hex::encode(ticket.title_id).to_uppercase());
}
if hex::encode(ticket.title_id)[..8].eq("00000001") {
if hex::encode(ticket.title_id).eq("0000000100000001") {
println!(" Title Version: {} (boot2v{})", ticket.title_version, ticket.title_version);
@@ -120,7 +156,24 @@ fn print_ticket_info(ticket: ticket::Ticket) {
println!(" Decryption Key: {}", key);
println!(" Title Key (Encrypted): {}", hex::encode(ticket.title_key));
println!(" Title Key (Decrypted): {}", hex::encode(ticket.dec_title_key()));
println!(" Fakesigned: {}", ticket.is_fakesigned());
if cert.is_some() {
let signing_str = match cert::verify_ticket(&cert.unwrap(), &ticket) {
Ok(result) => match result {
true => "Valid (Unmodified Ticket)",
false => {
if ticket.is_fakesigned() {
"Fakesigned"
} else {
"Invalid (Modified Ticket)"
}
},
},
Err(_) => "Invalid (Modified Ticket)"
};
println!(" Signature: {}", signing_str);
} else {
println!(" Fakesigned: {}", ticket.is_fakesigned());
}
}
fn print_wad_info(wad: wad::WAD) {
@@ -147,11 +200,28 @@ fn print_wad_info(wad: wad::WAD) {
}
println!(" Has Meta/Footer: {}", wad.meta_size() != 0);
println!(" Has CRL: {}", wad.crl_size() != 0);
println!(" Fakesigned: {}", title.is_fakesigned());
let signing_str = match title.verify() {
Ok(result) => match result {
true => "Legitimate (Unmodified TMD + Ticket)",
false => {
if title.is_fakesigned() {
"Fakesigned"
} else if cert::verify_tmd(&title.cert_chain.tmd_cert(), &title.tmd).unwrap() {
"Piratelegit (Unmodified TMD, Modified Ticket)"
} else if cert::verify_ticket(&title.cert_chain.ticket_cert(), &title.ticket).unwrap() {
"Edited (Modified TMD, Unmodified Ticket)"
} else {
"Illegitimate (Modified TMD + Ticket)"
}
},
},
Err(_) => "Illegitimate (Modified TMD + Ticket)"
};
println!(" Signing Status: {}", signing_str);
println!();
print_ticket_info(title.ticket);
print_ticket_info(title.ticket, Some(title.cert_chain.ticket_cert()));
println!();
print_tmd_info(title.tmd);
print_tmd_info(title.tmd, Some(title.cert_chain.tmd_cert()));
}
pub fn info(input: &str) {
@@ -162,11 +232,11 @@ pub fn info(input: &str) {
match identify_file_type(input) {
Some(WiiFileType::Tmd) => {
let tmd = tmd::TMD::from_bytes(fs::read(in_path).unwrap().as_slice()).unwrap();
print_tmd_info(tmd);
print_tmd_info(tmd, None);
},
Some(WiiFileType::Ticket) => {
let ticket = ticket::Ticket::from_bytes(fs::read(in_path).unwrap().as_slice()).unwrap();
print_ticket_info(ticket);
print_ticket_info(ticket, None);
},
Some(WiiFileType::Wad) => {
let wad = wad::WAD::from_bytes(fs::read(in_path).unwrap().as_slice()).unwrap();

View File

@@ -7,7 +7,7 @@ use std::{str, fs};
use std::path::{Path, PathBuf};
use clap::Subcommand;
use glob::glob;
use rustii::title::{tmd, ticket, content, wad};
use rustii::title::{cert, tmd, ticket, content, wad};
use rustii::title;
#[derive(Subcommand)]
@@ -59,7 +59,7 @@ pub fn pack_wad(input: &str, output: &str) {
} else if cert_files.len() > 1 {
panic!("Error: More than one Cert file found in the source directory.")
}
let cert_chain = fs::read(&cert_files[0]).expect("could not read cert chain file");
let cert_chain = cert::CertificateChain::from_bytes(&fs::read(&cert_files[0]).expect("could not read cert chain file")).unwrap();
// Read footer, if one exists (only accept one file).
let footer_files: Vec<PathBuf> = glob(&format!("{}/*.footer", in_path.display()))
.expect("failed to read glob pattern")
@@ -106,7 +106,7 @@ pub fn unpack_wad(input: &str, output: &str) {
let ticket_file_name = format!("{}.tik", tid);
fs::write(Path::join(out_path, ticket_file_name), title.ticket.to_bytes().unwrap()).expect("could not write Ticket file");
let cert_file_name = format!("{}.cert", tid);
fs::write(Path::join(out_path, cert_file_name), title.cert_chain()).expect("could not write Cert file");
fs::write(Path::join(out_path, cert_file_name), title.cert_chain.to_bytes().unwrap()).expect("could not write Cert file");
let meta_file_name = format!("{}.footer", tid);
fs::write(Path::join(out_path, meta_file_name), title.meta()).expect("could not write footer file");
// Iterate over contents, decrypt them, and write them out.

View File

@@ -3,4 +3,374 @@
//
// Implements the structures and methods required for validating the signatures of Wii titles.
use std::error::Error;
use std::fmt;
use std::io::{Cursor, Read, Write, SeekFrom, Seek};
use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
use rsa::pkcs8::DecodePublicKey;
use rsa::pkcs1v15::Pkcs1v15Sign;
use rsa::{RsaPublicKey, BigUint};
use sha1::{Digest, Sha1};
use crate::title::{tmd, ticket};
#[derive(Debug)]
pub enum CertificateError {
InvalidSignatureKeyType(u32),
InvalidContainedKeyType(u32),
UnknownCertificate,
MissingCertificate(String),
IncorrectCertificate(String),
NonMatchingCertificates,
IOError(std::io::Error),
}
impl fmt::Display for CertificateError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let description = match *self {
CertificateError::InvalidSignatureKeyType(_) => "The key type this certificate appears to be signed with is not valid.",
CertificateError::InvalidContainedKeyType(_) => "The key type contained in this certificate is not valid.",
CertificateError::UnknownCertificate => "An unknown certificate was found in the certificate chain.",
CertificateError::MissingCertificate(_) => "A required certificate was not found in the certificate chain.",
CertificateError::IncorrectCertificate(_) => "A provided certificate did not match the expected type.",
CertificateError::NonMatchingCertificates => "The provided certificate does not match the data you are attempting to verify with it.",
CertificateError::IOError(_) => "The provided certificate data was invalid.",
};
f.write_str(description)
}
}
impl Error for CertificateError {}
#[derive(Debug, Clone)]
pub enum CertificateKeyType {
Rsa4096,
Rsa2048,
ECC
}
#[derive(Debug, Clone)]
pub struct Certificate {
signer_key_type: CertificateKeyType,
signature: Vec<u8>,
signature_issuer: [u8; 64],
pub_key_type: CertificateKeyType,
child_cert_identity: [u8; 64],
pub_key_id: u32,
pub_key_modulus: Vec<u8>,
pub_key_exponent: u32
}
impl Certificate {
/// Creates a new Certificate instance from the binary data of a certificate file.
pub fn from_bytes(data: &[u8]) -> Result<Self, CertificateError> {
let mut buf = Cursor::new(data);
let signer_key_type_int = buf.read_u32::<BigEndian>().map_err(CertificateError::IOError)?;
let signer_key_type = match signer_key_type_int {
0x00010000 => CertificateKeyType::Rsa4096,
0x00010001 => CertificateKeyType::Rsa2048,
0x00010002 => CertificateKeyType::ECC,
_ => return Err(CertificateError::InvalidSignatureKeyType(signer_key_type_int))
};
let signature_len = match signer_key_type {
CertificateKeyType::Rsa4096 => 512,
CertificateKeyType::Rsa2048 => 256,
CertificateKeyType::ECC => 60,
};
let mut signature = vec![0u8; signature_len];
buf.read_exact(&mut signature).map_err(CertificateError::IOError)?;
// Skip past padding at the end of the signature.
buf.seek(SeekFrom::Start(0x40 + signature_len as u64)).map_err(CertificateError::IOError)?;
let mut signature_issuer = [0u8; 64];
buf.read_exact(&mut signature_issuer).map_err(CertificateError::IOError)?;
let pub_key_type_int = buf.read_u32::<BigEndian>().map_err(CertificateError::IOError)?;
let pub_key_type = match pub_key_type_int {
0x00000000 => CertificateKeyType::Rsa4096,
0x00000001 => CertificateKeyType::Rsa2048,
0x00000002 => CertificateKeyType::ECC,
_ => return Err(CertificateError::InvalidContainedKeyType(pub_key_type_int))
};
let mut child_cert_identity = [0u8; 64];
buf.read_exact(&mut child_cert_identity).map_err(CertificateError::IOError)?;
let pub_key_id = buf.read_u32::<BigEndian>().map_err(CertificateError::IOError)?;
let mut pub_key_modulus: Vec<u8>;
let mut pub_key_exponent: u32 = 0;
// The key size and exponent are different based on the key type. ECC has no exponent.
match pub_key_type {
CertificateKeyType::Rsa4096 => {
pub_key_modulus = vec![0u8; 512];
buf.read_exact(&mut pub_key_modulus).map_err(CertificateError::IOError)?;
pub_key_exponent = buf.read_u32::<BigEndian>().map_err(CertificateError::IOError)?;
},
CertificateKeyType::Rsa2048 => {
pub_key_modulus = vec![0u8; 256];
buf.read_exact(&mut pub_key_modulus).map_err(CertificateError::IOError)?;
pub_key_exponent = buf.read_u32::<BigEndian>().map_err(CertificateError::IOError)?;
},
CertificateKeyType::ECC => {
pub_key_modulus = vec![0u8; 60];
buf.read_exact(&mut pub_key_modulus).map_err(CertificateError::IOError)?;
}
}
Ok(Certificate {
signer_key_type,
signature,
signature_issuer,
pub_key_type,
child_cert_identity,
pub_key_id,
pub_key_modulus,
pub_key_exponent
})
}
/// Dumps the data in a Certificate back into binary data that can be written to a file.
pub fn to_bytes(&self) -> Result<Vec<u8>, std::io::Error> {
let mut buf: Vec<u8> = Vec::new();
match self.signer_key_type {
CertificateKeyType::Rsa4096 => { buf.write_u32::<BigEndian>(0x00010000)? },
CertificateKeyType::Rsa2048 => { buf.write_u32::<BigEndian>(0x00010001)? },
CertificateKeyType::ECC => { buf.write_u32::<BigEndian>(0x00010002)? },
}
buf.write_all(&self.signature)?;
// Pad to nearest 64 bytes after the signature.
buf.resize(0x40 + self.signature.len(), 0);
buf.write_all(&self.signature_issuer)?;
match self.pub_key_type {
CertificateKeyType::Rsa4096 => { buf.write_u32::<BigEndian>(0x0000000)? },
CertificateKeyType::Rsa2048 => { buf.write_u32::<BigEndian>(0x00000001)? },
CertificateKeyType::ECC => { buf.write_u32::<BigEndian>(0x00000002)? },
}
buf.write_all(&self.child_cert_identity)?;
buf.write_u32::<BigEndian>(self.pub_key_id)?;
buf.write_all(&self.pub_key_modulus)?;
// The key exponent is only used for the RSA keys and not ECC keys, so only write it out
// if this is one of those two key types.
if matches!(self.pub_key_type, CertificateKeyType::Rsa4096) ||
matches!(self.pub_key_type, CertificateKeyType::Rsa2048) {
buf.write_u32::<BigEndian>(self.pub_key_exponent)?;
}
// Pad the certificate data out to the nearest multiple of 64.
buf.resize((buf.len() + 63) & !63, 0);
Ok(buf)
}
pub fn signature_issuer(&self) -> String {
String::from_utf8_lossy(&self.signature_issuer).trim_end_matches('\0').to_owned()
}
pub fn child_cert_identity(&self) -> String {
String::from_utf8_lossy(&self.child_cert_identity).trim_end_matches('\0').to_owned()
}
pub fn pub_key_modulus(&self) -> Vec<u8> {
self.pub_key_modulus.clone()
}
pub fn pub_key_exponent(&self) -> u32 {
self.pub_key_exponent
}
}
#[derive(Debug)]
pub struct CertificateChain {
ca_cert: Certificate,
tmd_cert: Certificate,
ticket_cert: Certificate,
}
impl CertificateChain {
pub fn from_bytes(data: &[u8]) -> Result<CertificateChain, CertificateError> {
let mut buf = Cursor::new(data);
let mut offset: u64 = 0;
let mut ca_cert: Option<Certificate> = None;
let mut tmd_cert: Option<Certificate> = None;
let mut ticket_cert: Option<Certificate> = None;
// Iterate 3 times, because the chain should contain 3 certs.
for _ in 0..3 {
buf.seek(SeekFrom::Start(offset)).map_err(CertificateError::IOError)?;
let signer_key_type = buf.read_u32::<BigEndian>().map_err(CertificateError::IOError)?;
let signature_len = match signer_key_type {
0x00010000 => 512, // 0x200
0x00010001 => 256, // 0x100
0x00010002 => 60,
_ => return Err(CertificateError::InvalidSignatureKeyType(signer_key_type))
};
buf.seek(SeekFrom::Start(offset + 0x80 + signature_len)).map_err(CertificateError::IOError)?;
let pub_key_type = buf.read_u32::<BigEndian>().map_err(CertificateError::IOError)?;
let pub_key_len = match pub_key_type {
0x00000000 => 568, // 0x238
0x00000001 => 312, // 0x138
0x00000002 => 120,
_ => return Err(CertificateError::InvalidContainedKeyType(pub_key_type))
};
// Cert size is the base length (0xC8) + the signature length + the public key length.
// Like a lot of values, it needs to be rounded to the nearest multiple of 64.
let cert_size = (0xC8 + signature_len + pub_key_len + 63) & !63;
buf.seek(SeekFrom::End(0)).map_err(CertificateError::IOError)?;
buf.seek(SeekFrom::Start(offset)).map_err(CertificateError::IOError)?;
let mut cert_buf = vec![0u8; cert_size as usize];
buf.read_exact(&mut cert_buf).map_err(CertificateError::IOError)?;
let cert = Certificate::from_bytes(&cert_buf)?;
let issuer_name = String::from_utf8_lossy(&cert.signature_issuer).trim_end_matches('\0').to_owned();
if issuer_name.eq("Root") {
ca_cert = Some(cert.clone());
} else if issuer_name.contains("Root-CA") {
let child_name = String::from_utf8_lossy(&cert.child_cert_identity).trim_end_matches('\0').to_owned();
if child_name.contains("CP") {
tmd_cert = Some(cert.clone());
} else if child_name.contains("XS") {
ticket_cert = Some(cert.clone());
} else {
return Err(CertificateError::UnknownCertificate);
}
} else {
return Err(CertificateError::UnknownCertificate);
}
offset += cert_size;
}
if ca_cert.is_none() { return Err(CertificateError::MissingCertificate("CA".to_owned())) }
if tmd_cert.is_none() { return Err(CertificateError::MissingCertificate("TMD".to_owned())) }
if ticket_cert.is_none() { return Err(CertificateError::MissingCertificate("Ticket".to_owned())) }
Ok(CertificateChain {
ca_cert: ca_cert.unwrap(),
tmd_cert: tmd_cert.unwrap(),
ticket_cert: ticket_cert.unwrap(),
})
}
pub fn from_certs(ca_cert: Certificate, tmd_cert: Certificate, ticket_cert: Certificate) -> Result<Self, CertificateError> {
if String::from_utf8_lossy(&ca_cert.signature_issuer).trim_end_matches('\0').ne("Root") {
return Err(CertificateError::IncorrectCertificate("CA".to_owned()));
}
if !String::from_utf8_lossy(&tmd_cert.child_cert_identity).trim_end_matches('\0').contains("CP") {
return Err(CertificateError::IncorrectCertificate("TMD".to_owned()));
}
if !String::from_utf8_lossy(&ticket_cert.child_cert_identity).contains("XS") {
return Err(CertificateError::IncorrectCertificate("Ticket".to_owned()));
}
Ok(CertificateChain {
ca_cert,
tmd_cert,
ticket_cert,
})
}
pub fn to_bytes(&self) -> Result<Vec<u8>, std::io::Error> {
let mut buf: Vec<u8> = Vec::new();
buf.write_all(&self.ca_cert().to_bytes()?)?;
buf.write_all(&self.tmd_cert().to_bytes()?)?;
buf.write_all(&self.ticket_cert().to_bytes()?)?;
Ok(buf)
}
pub fn ca_cert(&self) -> Certificate {
self.ca_cert.clone()
}
pub fn tmd_cert(&self) -> Certificate {
self.tmd_cert.clone()
}
pub fn ticket_cert(&self) -> Certificate {
self.ticket_cert.clone()
}
}
/// Verifies a Wii CA certificate (either CA00000001 for retail or CA00000002 for development) using
/// the root keys.
pub fn verify_ca_cert(ca_cert: &Certificate) -> Result<bool, CertificateError> {
// Reject if the issuer isn't "Root" and this isn't one of the CA certs.
if String::from_utf8_lossy(&ca_cert.signature_issuer).trim_end_matches('\0').ne("Root") ||
!String::from_utf8_lossy(&ca_cert.child_cert_identity).contains("CA") {
return Err(CertificateError::IncorrectCertificate("CA".to_owned()));
}
let root_key = if String::from_utf8_lossy(&ca_cert.child_cert_identity).trim_end_matches('\0').eq("CA00000001") {
// Include key str from local file.
let retail_pem = include_str!("keys/retail-pub.pem");
RsaPublicKey::from_public_key_pem(retail_pem).unwrap()
} else if String::from_utf8_lossy(&ca_cert.child_cert_identity).trim_end_matches('\0').eq("CA00000002") {
// Include key str from local file.
let dev_pem = include_str!("keys/dev-pub.pem");
RsaPublicKey::from_public_key_pem(dev_pem).unwrap()
} else {
return Err(CertificateError::UnknownCertificate);
};
let mut hasher = Sha1::new();
let cert_body = ca_cert.to_bytes().unwrap();
hasher.update(&cert_body[576..]);
let cert_hash = hasher.finalize().as_slice().to_owned();
match root_key.verify(Pkcs1v15Sign::new::<Sha1>(), &cert_hash, ca_cert.signature.as_slice()) {
Ok(_) => Ok(true),
Err(_) => Ok(false),
}
}
/// Verifies a TMD or Ticket signing certificate using a CA certificate. The CA certificate and
/// child certificate being verified must match, or this function will return an error without
/// attempting signature verification.
pub fn verify_child_cert(ca_cert: &Certificate, child_cert: &Certificate) -> Result<bool, CertificateError> {
if ca_cert.signature_issuer().ne("Root") || !ca_cert.child_cert_identity().contains("CA") {
return Err(CertificateError::IncorrectCertificate("CA".to_owned()));
}
if format!("Root-{}", ca_cert.child_cert_identity()).ne(&child_cert.signature_issuer()) {
return Err(CertificateError::NonMatchingCertificates)
}
let mut hasher = Sha1::new();
let cert_body = child_cert.to_bytes().unwrap();
hasher.update(&cert_body[320..]);
let cert_hash = hasher.finalize().as_slice().to_owned();
let public_key_modulus = BigUint::from_bytes_be(&ca_cert.pub_key_modulus());
let public_key_exponent = BigUint::from(ca_cert.pub_key_exponent());
let root_key = RsaPublicKey::new(public_key_modulus, public_key_exponent).unwrap();
match root_key.verify(Pkcs1v15Sign::new::<Sha1>(), &cert_hash, child_cert.signature.as_slice()) {
Ok(_) => Ok(true),
Err(_) => Ok(false),
}
}
/// Verifies the signature of a TMD using a TMD signing certificate. The TMD certificate must match
/// the certificate used to sign the TMD, or this function will return an error without attempting
/// signature verification.
pub fn verify_tmd(tmd_cert: &Certificate, tmd: &tmd::TMD) -> Result<bool, CertificateError> {
if !tmd_cert.signature_issuer().contains("Root-CA") || !tmd_cert.child_cert_identity().contains("CP") {
return Err(CertificateError::IncorrectCertificate("TMD".to_owned()));
}
if format!("{}-{}", tmd_cert.signature_issuer(), tmd_cert.child_cert_identity()).ne(&tmd.signature_issuer()) {
return Err(CertificateError::NonMatchingCertificates)
}
let mut hasher = Sha1::new();
let tmd_body = tmd.to_bytes().unwrap();
hasher.update(&tmd_body[320..]);
let tmd_hash = hasher.finalize().as_slice().to_owned();
let public_key_modulus = BigUint::from_bytes_be(&tmd_cert.pub_key_modulus());
let public_key_exponent = BigUint::from(tmd_cert.pub_key_exponent());
let root_key = RsaPublicKey::new(public_key_modulus, public_key_exponent).unwrap();
match root_key.verify(Pkcs1v15Sign::new::<Sha1>(), &tmd_hash, tmd.signature.as_slice()) {
Ok(_) => Ok(true),
Err(_) => Ok(false),
}
}
/// Verifies the signature of a Ticket using a Ticket signing certificate. The Ticket certificate
/// must match the certificate used to sign the Ticket, or this function will return an error
/// without attempting signature verification.
pub fn verify_ticket(ticket_cert: &Certificate, ticket: &ticket::Ticket) -> Result<bool, CertificateError> {
if !ticket_cert.signature_issuer().contains("Root-CA") || !ticket_cert.child_cert_identity().contains("XS") {
return Err(CertificateError::IncorrectCertificate("Ticket".to_owned()));
}
if format!("{}-{}", ticket_cert.signature_issuer(), ticket_cert.child_cert_identity()).ne(&ticket.signature_issuer()) {
return Err(CertificateError::NonMatchingCertificates)
}
let mut hasher = Sha1::new();
let tmd_body = ticket.to_bytes().unwrap();
hasher.update(&tmd_body[320..]);
let tmd_hash = hasher.finalize().as_slice().to_owned();
let public_key_modulus = BigUint::from_bytes_be(&ticket_cert.pub_key_modulus());
let public_key_exponent = BigUint::from(ticket_cert.pub_key_exponent());
let root_key = RsaPublicKey::new(public_key_modulus, public_key_exponent).unwrap();
match root_key.verify(Pkcs1v15Sign::new::<Sha1>(), &tmd_hash, ticket.signature.as_slice()) {
Ok(_) => Ok(true),
Err(_) => Ok(false),
}
}

View File

@@ -0,0 +1,14 @@
-----BEGIN PUBLIC KEY-----
MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEA0B/hANQ1VrJLVtrpcbWl
04S5MAO+G78oojBbBgZFRn1bAlHSVhonT56fnOxkYVCrPSrjNmhmrKS66Brj15qm
sEqLy6fm+2SJRevf24W6CR/X0RS1o6eA46Iubs2HtaTG+RDkAyIIgUsM7qGhffc5
aV9hfvY1KNuUljegVgN/ezJBOJXAqPGYLhVl447twi5ZDuJne4YJ9IwuMD+8QFys
GAQvgiCE5JNoA9p/QTSSSFYrjuEvePgDJGMwvHvn7nJK9FikcuerRqGnwQwvGPoH
w93YmAahHJzBMLJHozyNR95n8p5Vd7EcQ0k9W7p2NKfk5xUxt99Zgf4koRRVTL2P
AFzh2zUIXM/HeAa23iVAaKJstUktRYBDj+Hlqe11xe1FHc54lDnMw7ooojEqG4cZ
7w9ztxOVDAJZGnRipgfzfAqnoY+pQ6NtdSpfQZLwE2EAqpy0G74UvrH5/Gkv36CU
Rt5and4spfaMHAwhQpKHyy2qo9JjdS9z4J+vRHnSgXQp9pgAr95rWS3BmIK99YHM
q/LLkQKe81xM/bv/ScH6Gy/jHeelYOy0frz+MkJblW+BtpkXSH47eJFR2y54sf0u
vn5iaz6hZbT7AMy3Ua9QcynEo5Oept2cUKDnOGsBRXlrQa9h94VVlE87wi3DvQ0A
+HmKQrGqoIMgZZrHOVq08ykCAwEAAQ==
-----END PUBLIC KEY-----

View File

@@ -0,0 +1,14 @@
-----BEGIN PUBLIC KEY-----
MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEA+CRsWLrnUAMB+7fC6+AB
BXHakiN48FFOwAMd0NIe09B+/IUgabXem7lRqLyQokSSbTeSla6UNqqmowJRDHsd
7dX7IIadfzAW9r5l04OhbbMyG5U1GJCxcAKTfuGT9X6ZokdOnTgkx67jhUH1Z+dR
jHoOOOfrr0EZG8/xe0KmtO3mzo3nMY9/UgSzmQ4iZ0Wv1IWyRJMAiwjH9rflawKz
6P4MnYWcuLaCI7irJ+5fZTgHiy25HioVPoWBgHKiO23ZMoEFT2+w9vWtKD7KC3rz
VFXgPae2gybz7INK8xQEisbfINKFCGc8q2Kix7wTGlM+C2aAaxwwZks3IzG9xLDK
2NEe57vZKFVIquwfZughs8igR2kAxeaI6AzOPGHWnLuhN8ZgT3py3Yx7Pj1RKQ2q
all7CB+dNjOjRno1YQmsp919Li+ywa644g9Ikti5+LRvTjwR9PR9i3V9/v6jiZwz
WVxe/evLq+hBPjqagDxpNW6ysq1cxMhYRV7197MGRLR8ZAaM34CfdgJaLbRG4D18
9i805wJFewKkz12d1TylOnymKXiMZ8oIv+zKQ6lXrRbJThzYdcoQfc5+ARjw32v+
5R3b2ZHCbmDNSFiqWSyCAHXyn1JskXxv5UA+p9SlDOw7c4TeiG6C0utNTkK18rFJ
qB6nznFE3CmUz8ROH5HL1JUCAwEAAQ==
-----END PUBLIC KEY-----

View File

@@ -17,10 +17,12 @@ use std::fmt;
#[derive(Debug)]
pub enum TitleError {
BadCertChain,
BadTicket,
BadTMD,
BadContent,
InvalidWAD,
CertificateError(cert::CertificateError),
TMDError(tmd::TMDError),
TicketError(ticket::TicketError),
WADError(wad::WADError),
@@ -30,10 +32,12 @@ pub enum TitleError {
impl fmt::Display for TitleError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let description = match *self {
TitleError::BadCertChain => "The provided certificate chain data was invalid.",
TitleError::BadTicket => "The provided Ticket data was invalid.",
TitleError::BadTMD => "The provided TMD data was invalid.",
TitleError::BadContent => "The provided content data was invalid.",
TitleError::InvalidWAD => "The provided WAD data was invalid.",
TitleError::CertificateError(_) => "An error occurred while processing certificate data.",
TitleError::TMDError(_) => "An error occurred while processing TMD data.",
TitleError::TicketError(_) => "An error occurred while processing ticket data.",
TitleError::WADError(_) => "A WAD could not be built from the provided data.",
@@ -47,7 +51,7 @@ impl Error for TitleError {}
#[derive(Debug)]
pub struct Title {
cert_chain: Vec<u8>,
pub cert_chain: cert::CertificateChain,
crl: Vec<u8>,
pub ticket: ticket::Ticket,
pub tmd: tmd::TMD,
@@ -57,11 +61,12 @@ pub struct Title {
impl Title {
pub fn from_wad(wad: &wad::WAD) -> Result<Title, TitleError> {
let cert_chain = cert::CertificateChain::from_bytes(&wad.cert_chain()).map_err(|_| TitleError::BadCertChain)?;
let ticket = ticket::Ticket::from_bytes(&wad.ticket()).map_err(|_| TitleError::BadTicket)?;
let tmd = tmd::TMD::from_bytes(&wad.tmd()).map_err(|_| TitleError::BadTMD)?;
let content = content::ContentRegion::from_bytes(&wad.content(), tmd.content_records.clone()).map_err(|_| TitleError::BadContent)?;
let title = Title {
cert_chain: wad.cert_chain(),
cert_chain,
crl: wad.crl(),
ticket,
tmd,
@@ -138,13 +143,26 @@ impl Title {
let title_size_bytes = self.title_size(absolute)?;
Ok((title_size_bytes as f64 / 131072.0).ceil() as usize)
}
pub fn cert_chain(&self) -> Vec<u8> {
self.cert_chain.clone()
/// Verifies entire certificate chain, and then the TMD and Ticket. Returns true if the title
/// is entirely valid, or false if any component of the verification fails.
pub fn verify(&self) -> Result<bool, TitleError> {
if !cert::verify_ca_cert(&self.cert_chain.ca_cert()).map_err(TitleError::CertificateError)? {
return Ok(false)
}
if !cert::verify_child_cert(&self.cert_chain.ca_cert(), &self.cert_chain.tmd_cert()).map_err(TitleError::CertificateError)? ||
!cert::verify_child_cert(&self.cert_chain.ca_cert(), &self.cert_chain.ticket_cert()).map_err(TitleError::CertificateError)? {
return Ok(false)
}
if !cert::verify_tmd(&self.cert_chain.tmd_cert(), &self.tmd).map_err(TitleError::CertificateError)? ||
!cert::verify_ticket(&self.cert_chain.ticket_cert(), &self.ticket).map_err(TitleError::CertificateError)? {
return Ok(false)
}
Ok(true)
}
pub fn set_cert_chain(&mut self, cert_chain: &[u8]) {
self.cert_chain = cert_chain.to_vec();
pub fn set_cert_chain(&mut self, cert_chain: cert::CertificateChain) {
self.cert_chain = cert_chain;
}
pub fn crl(&self) -> Vec<u8> {

View File

@@ -220,4 +220,8 @@ impl Ticket {
}
Ok(())
}
pub fn signature_issuer(&self) -> String {
String::from_utf8_lossy(&self.signature_issuer).trim_end_matches('\0').to_owned()
}
}

View File

@@ -337,4 +337,8 @@ impl TMD {
AccessRight::DVDVideo => (self.access_rights & (1 << 1)) != 0,
}
}
pub fn signature_issuer(&self) -> String {
String::from_utf8_lossy(&self.signature_issuer).trim_end_matches('\0').to_owned()
}
}

View File

@@ -8,7 +8,7 @@ use std::fmt;
use std::str;
use std::io::{Cursor, Read, Seek, SeekFrom, Write};
use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
use crate::title::{tmd, ticket, content};
use crate::title::{cert, tmd, ticket, content};
use crate::title::ticket::TicketError;
use crate::title::tmd::TMDError;
@@ -103,10 +103,10 @@ impl WADHeader {
}
impl WADBody {
pub fn from_parts(cert_chain: &[u8], crl: &[u8], ticket: &ticket::Ticket, tmd: &tmd::TMD,
pub fn from_parts(cert_chain: &cert::CertificateChain, crl: &[u8], ticket: &ticket::Ticket, tmd: &tmd::TMD,
content: &content::ContentRegion, meta: &[u8]) -> Result<WADBody, WADError> {
let body = WADBody {
cert_chain: cert_chain.to_vec(),
cert_chain: cert_chain.to_bytes().map_err(WADError::IOError)?,
crl: crl.to_vec(),
ticket: ticket.to_bytes().map_err(WADError::IOError)?,
tmd: tmd.to_bytes().map_err(WADError::IOError)?,
@@ -196,7 +196,7 @@ impl WAD {
Ok(wad)
}
pub fn from_parts(cert_chain: &[u8], crl: &[u8], ticket: &ticket::Ticket, tmd: &tmd::TMD,
pub fn from_parts(cert_chain: &cert::CertificateChain, crl: &[u8], ticket: &ticket::Ticket, tmd: &tmd::TMD,
content: &content::ContentRegion, meta: &[u8]) -> Result<WAD, WADError> {
let body = WADBody::from_parts(cert_chain, crl, ticket, tmd, content, meta)?;
let header = WADHeader::from_body(&body)?;