Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2,242 changes: 2,162 additions & 80 deletions Cargo.lock

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ openssl = { version = "*", features = ["vendored"] }
reqwest = { version = "0.12", features = ["json", "gzip", "deflate"] }
serde = { version = "1", features = ["derive"] }
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
anyhow = "1"
serde_json = "1"
gpapi = "6"
enum-iterator = "2"
Expand Down
373 changes: 373 additions & 0 deletions LICENSE-impactor

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,4 +29,5 @@ A guide on how to contribute and develop for Extendify is located [here](/docs/d
### Licenses:

- `crates/extendify-native/src/unix/preload.rs` is licensed under the [BSD 2-Clause "Simplified" License](/LICENSE-redhook).
- `crates/extendify-native/src/persistence/macos/macho.rs` is licensed under the [MPL 2.0 License](/LICENSE-impactor).
- All other code is licensed under the [GNU GPLv3](/LICENSE).
7 changes: 7 additions & 0 deletions crates/extendify-native/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,14 @@ features = [
"Win32_System_Diagnostics_Debug",
]

[target.'cfg(target_os = "macos")'.dependencies]
apple-codesign = { version = "0.29.0", default-features = false }
goblin = "0.10.7"
objc2 = "0.6.5"

[dependencies]
anyhow.workspace = true
ctor = "1.0.13"
reqwest = { workspace = true, features = ["blocking"] }

[build-dependencies]
Expand Down
30 changes: 30 additions & 0 deletions crates/extendify-native/src/consts.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
pub mod paths {
use std::{env, path::PathBuf};

pub fn extendify_root() -> PathBuf {
cfg_select! {
target_os = "macos" => env::home_dir().unwrap().join("Library/Application Support/Extendify"),
windows => PathBuf::from(env::var("LOCALAPPDATA").unwrap()).join("Extendify"),
unix => {
let config = env::var("XDG_CONFIG_HOME")
.map(|str| PathBuf::from(str))
.unwrap_or(env::home_dir().unwrap().join(".config"));

config.join("extendify")
},
}
}

pub fn extendify_dist() -> PathBuf {
extendify_root().join("dist")
}

#[cfg(unix)]
pub fn extendify_native() -> PathBuf {
let dist = extendify_dist();
cfg_select! {
target_os = "macos" => dist.join("extendify.dylib"),
unix => dist.join("libextendify.so"),
}
}
}
2 changes: 2 additions & 0 deletions crates/extendify-native/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ use std::fmt::Display;

mod callbacks;
mod cef;
mod consts;
mod persistence;
mod vtable_hooks;

#[cfg(unix)]
Expand Down
146 changes: 146 additions & 0 deletions crates/extendify-native/src/persistence/macos/macho.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
// Certain logic adapted from
// https://github.com/claration/impactor/blob/b13d99559febd63e3710dfdd0ef8cdd78d10ae13/crates/plume_core/src/utils/macho.rs

use std::io::Write;

use anyhow::{Result, ensure};
use apple_codesign::{AppleCodesignError, MachOSigner, SigningSettings};
use goblin::mach::{MachO as GoblinMachO, cputype::CPU_TYPE_ARM64, load_command::{CommandVariant, LC_LOAD_WEAK_DYLIB}};

pub struct MachO<'a> {
macho: GoblinMachO<'a>,
data: &'a [u8]
}

impl MachO<'_> {
pub fn parse<'a>(data: &'a Vec<u8>) -> MachO<'a> {
let macho = GoblinMachO::parse(data, 0).unwrap();
return MachO { macho, data }
}

pub fn has_dylib(&self, path: &str) -> bool {
self.macho.load_commands.iter().any(|load_cmd| {
if let CommandVariant::LoadDylib(dylib) = &load_cmd.command {
let name_offset = load_cmd.offset + dylib.dylib.name as usize;
let mut name_end = name_offset;

while self.data[name_end] != 0 {
name_end += 1;
}

let name = str::from_utf8(&self.data[name_offset..name_end]).unwrap();

return name == path;
}

false
})
}

pub fn add_dylib_load_path<'a>(&self, path: &str) -> Result<Vec<u8>> {
let read_u32_le = |data: &[u8], offset: usize| -> u32 {
u32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
])
};

let is_64 = self.macho.header.cputype == CPU_TYPE_ARM64;
let dylib_exists = self.has_dylib(path);
let current_sizeofcmds = read_u32_le(&self.data, 20);
let current_ncmds = read_u32_le(&self.data, 16);

// Create a mutable Vec<u8> so we can modify the Mach-O data in place
let mut data = self.data.to_vec();

// with macho.data we can clone, modify, then set the data
// for our modified binary, then using MachO struct we can make our universal bin

ensure!(!dylib_exists, "Dylib already exists in binary");

let header_size = if is_64 { 32 } else { 28 };

// Calculate new load command size (must be 8-byte aligned)
let dylib_path_len = path.len();
let padding = (8 - ((dylib_path_len + 1) % 8)) % 8; // +1 for null terminator
let dylib_command_size = 24 + dylib_path_len + 1 + padding; // sizeof(dylib_command) = 24

// Find the position to insert the new load command
let header_offset = 0;
let load_commands_offset = header_offset + header_size;
let sizeofcmds_offset = header_offset + 20;
let ncmds_offset = header_offset + 16;

// Find the minimum non-zero file offset from segments
let min_fileoff = self.macho
.load_commands
.iter()
.filter_map(|load_cmd| match &load_cmd.command {
CommandVariant::Segment64(seg) if seg.filesize > 0 && seg.fileoff > 0 => {
Some(seg.fileoff)
}
CommandVariant::Segment32(seg) if seg.filesize > 0 && seg.fileoff > 0 => {
Some(seg.fileoff as u64)
}
_ => None,
})
.min()
.unwrap_or(u64::MAX);

// Calculate available space
let load_commands_end = load_commands_offset + current_sizeofcmds as usize;
let data_start = if min_fileoff < u64::MAX {
min_fileoff as usize
} else {
data.len()
};

let available_space = data_start.saturating_sub(load_commands_end);

ensure!(dylib_command_size <= available_space, "Not enough space in binary to add dylib load command");

// Write the new load command into the available space (no splice needed!)
let insert_offset = load_commands_end;
let mut new_command = Vec::new();
new_command.extend_from_slice(&(LC_LOAD_WEAK_DYLIB as u32).to_le_bytes()); // cmd
new_command.extend_from_slice(&(dylib_command_size as u32).to_le_bytes()); // cmdsize

// dylib_command structure:
// struct dylib {
// uint32_t name; // offset from start of load command to start of name string
// uint32_t timestamp; // date/time stamp
// uint32_t current_version;
// uint32_t compatibility_version;
// };
new_command.extend_from_slice(&24u32.to_le_bytes()); // name.offset (sizeof dylib_command header = 8 + 16 = 24)
new_command.extend_from_slice(&2u32.to_le_bytes()); // timestamp
new_command.extend_from_slice(&0x00010000u32.to_le_bytes()); // current_version (1.0.0)
new_command.extend_from_slice(&0x00010000u32.to_le_bytes()); // compatibility_version (1.0.0)
new_command.extend_from_slice(path.as_bytes());
new_command.push(0); // null terminator
new_command.extend(vec![0u8; padding]); // padding

// Write directly into the existing padding space
data[insert_offset..insert_offset + dylib_command_size].copy_from_slice(&new_command);

// Update header fields
let new_sizeofcmds = current_sizeofcmds + dylib_command_size as u32;
let new_ncmds = current_ncmds + 1;

data[sizeofcmds_offset..sizeofcmds_offset + 4]
.copy_from_slice(&new_sizeofcmds.to_le_bytes());
data[ncmds_offset..ncmds_offset + 4].copy_from_slice(&new_ncmds.to_le_bytes());

Ok(data)
}

pub fn adhoc_sign(data: &[u8], writer: &mut impl Write) -> Result<(), AppleCodesignError> {
let signer = MachOSigner::new(data).unwrap();
let mut settings = SigningSettings::default();
settings.import_settings_from_macho(data).unwrap();

signer.write_signed_binary(&settings, writer)
}
}
124 changes: 124 additions & 0 deletions crates/extendify-native/src/persistence/macos/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
mod macho;

use std::{env::home_dir, ffi::{CStr, c_void}, fs::{self, File}, mem::transmute, path::PathBuf};
use anyhow::{Context, Result, bail, ensure};
use objc2::{ffi::{class_addMethod, class_getClassMethod, method_exchangeImplementations, method_getTypeEncoding, objc_getClass, objc_getMetaClass}, msg_send, runtime::{AnyObject, Bool, Imp, Sel}, sel};

use crate::{consts, log, persistence::{macos::macho::MachO, util::NotNull}};

// https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtTypeEncodings.html
const TYPE_ENCODING: &str = cfg_select! {
target_arch = "aarch64" => "B28@0:8r^v16B24",
target_arch = "x86_64" => "c28@0:8r^v16c24",
};

unsafe extern "C-unwind" fn swizzled_relaunch(
class: *mut AnyObject,
_sel: Sel,
available: *const c_void,
filter_action_arguments: Bool
) -> Bool {
patch_macho();

msg_send![class,
swizzled_relaunchForUpgradeIfAvailable:available,
filterActionArguments:filter_action_arguments
]
}

pub fn swizzle() -> Result<()> {
unsafe {
let name = c"SPTRelaunchUpgrader".as_ptr();
let class = objc_getClass(name).cast_mut()
.not_null("Failed to resolve SPTRelaunchUpgrader class")?;
let metaclass = objc_getMetaClass(name).cast_mut()
.not_null("Failed to resolve SPTRelaunchUpgrader metaclass")?;

// Note, these are class methods
let original_selector = sel!(relaunchForUpgradeIfAvailable:filterActionArguments:);
let swizzled_selector = sel!(swizzled_relaunchForUpgradeIfAvailable:filterActionArguments:);

let original_method = class_getClassMethod(class, original_selector).cast_mut()
.not_null("Failed to resolve original method")?;

let type_encoding = method_getTypeEncoding(original_method)
.not_null("Failed to get original method type encoding")?;

ensure!(
CStr::from_ptr(type_encoding).to_str()? == TYPE_ENCODING,
"Unexpected method type encoding. Extendify Native must be updated to fix this."
);

let swizzled_relaunch = transmute::<
unsafe extern "C-unwind" fn(*mut AnyObject, Sel, *const c_void, Bool) -> Bool,
Imp
>(swizzled_relaunch);

// When swizzling a class method, we need to use the metaclass here instead
let success = class_addMethod(
metaclass,
swizzled_selector,
swizzled_relaunch,
type_encoding
);
ensure!(success.as_bool(), "Failed to add method to SPTRelaunchUpgrader");

let swizzled_method = class_getClassMethod(class, swizzled_selector).cast_mut();

method_exchangeImplementations(original_method, swizzled_method);
}

Ok(())
}

/// Inject extendify.dylib into a Spotify binary.
fn inject(macho_path: &PathBuf) -> Result<bool> {
let dylib_path = consts::paths::extendify_native().into_string().unwrap();

let macho = fs::read(macho_path).context("Failed to read Spotify binary")?;
let macho = MachO::parse(&macho);

if macho.has_dylib(&dylib_path) { return Ok(false); }

let macho = macho.add_dylib_load_path(&dylib_path).context("Failed to add dylib load command")?;

let temp_macho_path = macho_path.with_added_extension("temp");
let write_res = || -> Result<()> {
let mut file = File::create(&temp_macho_path)?;
file.set_permissions(macho_path.metadata()?.permissions())?;

Ok(MachO::adhoc_sign(&macho, &mut file)?)
}();

match write_res {
Ok(_) => {
fs::rename(temp_macho_path, macho_path).context("Failed to rename file")?;
Ok(true)
},
Err(e) => {
fs::remove_file(temp_macho_path).context("Failed to cleanup after error")?;
bail!("Failed to patch Spotify binary: {e}")
},
}
}

fn patch_macho() {
let app_support = home_dir().unwrap().join("Library/Application Support");
let macho_path = app_support.join("Spotify/PersistentCache/Update/temp/Spotify.app/Contents/MacOS/Spotify");

if !macho_path.exists() { return; }

log("Patching Spotify update");

match inject(&macho_path) {
Ok(true) => {
log("Patched Spotify update");
},
Ok(false) => {
log("Spotify update already patched, skipping");
},
Err(err) => {
log(err.context("Failed to patch Spotify update"));
},
}
}
14 changes: 14 additions & 0 deletions crates/extendify-native/src/persistence/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
use ctor::ctor;

mod util;

#[cfg(target_os = "macos")]
mod macos;

#[ctor(unsafe)]
fn main() {
#[cfg(target_os = "macos")]
if let Err(e) = macos::swizzle() {
crate::log(e);
}
}
19 changes: 19 additions & 0 deletions crates/extendify-native/src/persistence/util.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
use anyhow::{Result, ensure};

#[cfg_attr(not(target_os = "macos"), allow(unused))]
pub trait NotNull: Sized {
fn not_null(self, msg: &'static str) -> Result<Self>;
}

impl<T: ?Sized> NotNull for *mut T {
fn not_null(self, msg: &'static str) -> Result<*mut T> {
ensure!(!self.is_null(), msg);
Ok(self)
}
}
impl<T: ?Sized> NotNull for *const T {
fn not_null(self, msg: &'static str) -> Result<*const T> {
ensure!(!self.is_null(), msg);
Ok(self)
}
}
Loading