XCode project for app, moved app project to folder

This commit is contained in:
Joe Mattiello
2023-03-01 22:07:19 -05:00
parent 365cadbb31
commit 4c9c5b1a56
371 changed files with 625 additions and 39 deletions

View File

@@ -0,0 +1,59 @@
//
// Use this file to import your target's public headers that you would like to expose to Swift.
//
#import <Foundation/Foundation.h>
// Shared
#import "ALTConstants.h"
#import "ALTConnection.h"
#import "NSError+ALTServerError.h"
#import "CFNotificationName+AltStore.h"
// libproc
int proc_pidpath(int pid, void * buffer, uint32_t buffersize);
// Security.framework
CF_ENUM(uint32_t) {
kSecCSInternalInformation = 1 << 0,
kSecCSSigningInformation = 1 << 1,
kSecCSRequirementInformation = 1 << 2,
kSecCSDynamicInformation = 1 << 3,
kSecCSContentInformation = 1 << 4,
kSecCSSkipResourceDirectory = 1 << 5,
kSecCSCalculateCMSDigest = 1 << 6,
};
OSStatus SecStaticCodeCreateWithPath(CFURLRef path, uint32_t flags, void ** __nonnull CF_RETURNS_RETAINED staticCode);
OSStatus SecCodeCopySigningInformation(void *code, uint32_t flags, CFDictionaryRef * __nonnull CF_RETURNS_RETAINED information);
NS_ASSUME_NONNULL_BEGIN
@interface AKDevice : NSObject
@property (class, readonly) AKDevice *currentDevice;
@property (strong, readonly) NSString *serialNumber;
@property (strong, readonly) NSString *uniqueDeviceIdentifier;
@property (strong, readonly) NSString *serverFriendlyDescription;
@end
@interface AKAppleIDSession : NSObject
- (instancetype)initWithIdentifier:(NSString *)identifier;
- (NSDictionary<NSString *, NSString *> *)appleIDHeadersForRequest:(NSURLRequest *)request;
@end
@interface LSApplicationWorkspace : NSObject
@property (class, readonly) LSApplicationWorkspace *defaultWorkspace;
- (BOOL)installApplication:(NSURL *)fileURL withOptions:(nullable NSDictionary<NSString *, id> *)options error:(NSError *_Nullable *)error;
- (BOOL)uninstallApplication:(NSString *)bundleIdentifier withOptions:(nullable NSDictionary *)options;
@end
NS_ASSUME_NONNULL_END

View File

@@ -0,0 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>application-identifier</key>
<string>$(DEVELOPMENT_TEAM).$(ORG_IDENTIFIER).AltDaemon</string>
<key>get-task-allow</key>
<true/>
<key>platform-application</key>
<true/>
<key>com.apple.authkit.client.private</key>
<true/>
<key>com.apple.private.mobileinstall.allowedSPI</key>
<array>
<string>Install</string>
<string>Uninstall</string>
<string>InstallForLaunchServices</string>
<string>UninstallForLaunchServices</string>
<string>InstallLocalProvisioned</string>
</array>
</dict>
</plist>

View File

@@ -0,0 +1,60 @@
//
// AnisetteDataManager.swift
// AltDaemon
//
// Created by Riley Testut on 6/1/20.
// Copyright © 2020 Riley Testut. All rights reserved.
//
import Foundation
import AltSign
private extension UserDefaults {
@objc var localUserID: String? {
get { string(forKey: #keyPath(UserDefaults.localUserID)) }
set { set(newValue, forKey: #keyPath(UserDefaults.localUserID)) }
}
}
struct AnisetteDataManager {
static let shared = AnisetteDataManager()
private let dateFormatter = ISO8601DateFormatter()
private init() {
dlopen("/System/Library/PrivateFrameworks/AuthKit.framework/AuthKit", RTLD_NOW)
}
func requestAnisetteData() throws -> ALTAnisetteData {
var request = URLRequest(url: URL(string: "https://developerservices2.apple.com/services/QH65B2/listTeams.action?clientId=XABBG36SBA")!)
request.httpMethod = "POST"
let akAppleIDSession = unsafeBitCast(NSClassFromString("AKAppleIDSession")!, to: AKAppleIDSession.Type.self)
let akDevice = unsafeBitCast(NSClassFromString("AKDevice")!, to: AKDevice.Type.self)
let session = akAppleIDSession.init(identifier: "com.apple.gs.xcode.auth")
let headers = session.appleIDHeaders(for: request)
let device = akDevice.current
let date = dateFormatter.date(from: headers["X-Apple-I-Client-Time"] ?? "") ?? Date()
var localUserID = UserDefaults.standard.localUserID
if localUserID == nil {
localUserID = UUID().uuidString
UserDefaults.standard.localUserID = localUserID
}
let anisetteData = ALTAnisetteData(machineID: headers["X-Apple-I-MD-M"] ?? "",
oneTimePassword: headers["X-Apple-I-MD"] ?? "",
localUserID: headers["X-Apple-I-MD-LU"] ?? localUserID ?? "",
routingInfo: UInt64(headers["X-Apple-I-MD-RINFO"] ?? "") ?? 0,
deviceUniqueIdentifier: device.uniqueDeviceIdentifier,
deviceSerialNumber: device.serialNumber,
deviceDescription: "<MacBookPro15,1> <Mac OS X;10.15.2;19C57> <com.apple.AuthKit/1 (com.apple.dt.Xcode/3594.4.19)>",
date: date,
locale: .current,
timeZone: .current)
return anisetteData
}
}

View File

@@ -0,0 +1,116 @@
//
// AppManager.swift
// AltDaemon
//
// Created by Riley Testut on 6/1/20.
// Copyright © 2020 Riley Testut. All rights reserved.
//
import Foundation
import AltSign
private extension URL {
static let profilesDirectoryURL = URL(fileURLWithPath: "/var/MobileDevice/ProvisioningProfiles", isDirectory: true)
}
private extension CFNotificationName {
static let updatedProvisioningProfiles = CFNotificationName("MISProvisioningProfileRemoved" as CFString)
}
struct AppManager {
static let shared = AppManager()
private let appQueue = DispatchQueue(label: "com.rileytestut.AltDaemon.appQueue", qos: .userInitiated)
private let profilesQueue = OperationQueue()
private let fileCoordinator = NSFileCoordinator()
private init() {
profilesQueue.name = "com.rileytestut.AltDaemon.profilesQueue"
profilesQueue.qualityOfService = .userInitiated
}
func installApp(at fileURL: URL, bundleIdentifier: String, activeProfiles _: Set<String>?, completionHandler: @escaping (Result<Void, Error>) -> Void) {
appQueue.async {
let lsApplicationWorkspace = unsafeBitCast(NSClassFromString("LSApplicationWorkspace")!, to: LSApplicationWorkspace.Type.self)
let options = ["CFBundleIdentifier": bundleIdentifier, "AllowInstallLocalProvisioned": NSNumber(value: true)] as [String: Any]
let result = Result { try lsApplicationWorkspace.default.installApplication(fileURL, withOptions: options) }
completionHandler(result)
}
}
func removeApp(forBundleIdentifier bundleIdentifier: String, completionHandler: @escaping (Result<Void, Error>) -> Void) {
appQueue.async {
let lsApplicationWorkspace = unsafeBitCast(NSClassFromString("LSApplicationWorkspace")!, to: LSApplicationWorkspace.Type.self)
lsApplicationWorkspace.default.uninstallApplication(bundleIdentifier, withOptions: nil)
completionHandler(.success(()))
}
}
func install(_ profiles: Set<ALTProvisioningProfile>, activeProfiles: Set<String>?, completionHandler: @escaping (Result<Void, Error>) -> Void) {
let intent = NSFileAccessIntent.writingIntent(with: .profilesDirectoryURL, options: [])
fileCoordinator.coordinate(with: [intent], queue: profilesQueue) { error in
do {
if let error = error {
throw error
}
let installingBundleIDs = Set(profiles.map(\.bundleIdentifier))
let profileURLs = try FileManager.default.contentsOfDirectory(at: intent.url, includingPropertiesForKeys: nil, options: [])
// Remove all inactive profiles (if active profiles are provided), and the previous profiles.
for fileURL in profileURLs {
// Use memory mapping to reduce peak memory usage and stay within limit.
guard let profile = try? ALTProvisioningProfile(url: fileURL, options: [.mappedIfSafe]) else { continue }
if installingBundleIDs.contains(profile.bundleIdentifier) || (activeProfiles?.contains(profile.bundleIdentifier) == false && profile.isFreeProvisioningProfile) {
try FileManager.default.removeItem(at: fileURL)
} else {
print("Ignoring:", profile.bundleIdentifier, profile.uuid)
}
}
for profile in profiles {
let destinationURL = URL.profilesDirectoryURL.appendingPathComponent(profile.uuid.uuidString.lowercased())
try profile.data.write(to: destinationURL, options: .atomic)
}
completionHandler(.success(()))
} catch {
completionHandler(.failure(error))
}
// Notify system to prevent accidentally untrusting developer certificate.
CFNotificationCenterPostNotification(CFNotificationCenterGetDarwinNotifyCenter(), .updatedProvisioningProfiles, nil, nil, true)
}
}
func removeProvisioningProfiles(forBundleIdentifiers bundleIdentifiers: Set<String>, completionHandler: @escaping (Result<Void, Error>) -> Void) {
let intent = NSFileAccessIntent.writingIntent(with: .profilesDirectoryURL, options: [])
fileCoordinator.coordinate(with: [intent], queue: profilesQueue) { error in
do {
let profileURLs = try FileManager.default.contentsOfDirectory(at: intent.url, includingPropertiesForKeys: nil, options: [])
for fileURL in profileURLs {
guard let profile = ALTProvisioningProfile(url: fileURL) else { continue }
if bundleIdentifiers.contains(profile.bundleIdentifier) {
try FileManager.default.removeItem(at: fileURL)
}
}
completionHandler(.success(()))
} catch {
completionHandler(.failure(error))
}
// Notify system to prevent accidentally untrusting developer certificate.
CFNotificationCenterPostNotification(CFNotificationCenterGetDarwinNotifyCenter(), .updatedProvisioningProfiles, nil, nil, true)
}
}
}

View File

@@ -0,0 +1,109 @@
//
// DaemonRequestHandler.swift
// AltDaemon
//
// Created by Riley Testut on 6/1/20.
// Copyright © 2019 Riley Testut. All rights reserved.
//
import Foundation
import Shared
import SideKit
typealias DaemonConnectionManager = ConnectionManager<DaemonRequestHandler>
private let connectionManager = ConnectionManager(requestHandler: DaemonRequestHandler(),
connectionHandlers: [XPCConnectionHandler()])
extension DaemonConnectionManager {
static var shared: ConnectionManager {
connectionManager
}
}
struct DaemonRequestHandler: RequestHandler {
func handleAnisetteDataRequest(_: AnisetteDataRequest, for _: Connection, completionHandler: @escaping (Result<AnisetteDataResponse, Error>) -> Void) {
do {
let anisetteData = try AnisetteDataManager.shared.requestAnisetteData()
let response = AnisetteDataResponse(anisetteData: anisetteData)
completionHandler(.success(response))
} catch {
completionHandler(.failure(error))
}
}
func handlePrepareAppRequest(_ request: PrepareAppRequest, for connection: Connection, completionHandler: @escaping (Result<InstallationProgressResponse, Error>) -> Void) {
guard let fileURL = request.fileURL else { return completionHandler(.failure(ALTServerError(.invalidRequest))) }
print("Awaiting begin installation request...")
connection.receiveRequest { result in
print("Received begin installation request with result:", result)
do {
guard case let .beginInstallation(request) = try result.get() else { throw ALTServerError(.unknownRequest) }
guard let bundleIdentifier = request.bundleIdentifier else { throw ALTServerError(.invalidRequest) }
AppManager.shared.installApp(at: fileURL, bundleIdentifier: bundleIdentifier, activeProfiles: request.activeProfiles) { result in
let result = result.map { InstallationProgressResponse(progress: 1.0) }
print("Installed app with result:", result)
completionHandler(result)
}
} catch {
completionHandler(.failure(error))
}
}
}
func handleInstallProvisioningProfilesRequest(_ request: InstallProvisioningProfilesRequest, for _: Connection,
completionHandler: @escaping (Result<InstallProvisioningProfilesResponse, Error>) -> Void) {
AppManager.shared.install(request.provisioningProfiles, activeProfiles: request.activeProfiles) { result in
switch result {
case let .failure(error):
print("Failed to install profiles \(request.provisioningProfiles.map { $0.bundleIdentifier }):", error)
completionHandler(.failure(error))
case .success:
print("Installed profiles:", request.provisioningProfiles.map { $0.bundleIdentifier })
let response = InstallProvisioningProfilesResponse()
completionHandler(.success(response))
}
}
}
func handleRemoveProvisioningProfilesRequest(_ request: RemoveProvisioningProfilesRequest, for _: Connection,
completionHandler: @escaping (Result<RemoveProvisioningProfilesResponse, Error>) -> Void) {
AppManager.shared.removeProvisioningProfiles(forBundleIdentifiers: request.bundleIdentifiers) { result in
switch result {
case let .failure(error):
print("Failed to remove profiles \(request.bundleIdentifiers):", error)
completionHandler(.failure(error))
case .success:
print("Removed profiles:", request.bundleIdentifiers)
let response = RemoveProvisioningProfilesResponse()
completionHandler(.success(response))
}
}
}
func handleRemoveAppRequest(_ request: RemoveAppRequest, for _: Connection, completionHandler: @escaping (Result<RemoveAppResponse, Error>) -> Void) {
AppManager.shared.removeApp(forBundleIdentifier: request.bundleIdentifier) { result in
switch result {
case let .failure(error):
print("Failed to remove app \(request.bundleIdentifier):", error)
completionHandler(.failure(error))
case .success:
print("Removed app:", request.bundleIdentifier)
let response = RemoveAppResponse()
completionHandler(.success(response))
}
}
}
}

View File

@@ -0,0 +1,84 @@
//
// XPCConnectionHandler.swift
// AltDaemon
//
// Created by Riley Testut on 9/14/20.
// Copyright © 2020 Riley Testut. All rights reserved.
//
import Foundation
import Security
class XPCConnectionHandler: NSObject, ConnectionHandler {
var connectionHandler: ((Connection) -> Void)?
var disconnectionHandler: ((Connection) -> Void)?
private let dispatchQueue = DispatchQueue(label: "io.altstore.XPCConnectionListener", qos: .utility)
private let listeners = XPCConnection.machServiceNames.map { NSXPCListener.makeListener(machServiceName: $0) }
deinit {
self.stopListening()
}
func startListening() {
for listener in listeners {
listener.delegate = self
listener.resume()
}
}
func stopListening() {
listeners.forEach { $0.suspend() }
}
}
private extension XPCConnectionHandler {
func disconnect(_ connection: Connection) {
connection.disconnect()
disconnectionHandler?(connection)
}
}
extension XPCConnectionHandler: NSXPCListenerDelegate {
func listener(_: NSXPCListener, shouldAcceptNewConnection newConnection: NSXPCConnection) -> Bool {
let maximumPathLength = 4 * UInt32(MAXPATHLEN)
let pathBuffer = UnsafeMutablePointer<CChar>.allocate(capacity: Int(maximumPathLength))
defer { pathBuffer.deallocate() }
proc_pidpath(newConnection.processIdentifier, pathBuffer, maximumPathLength)
let path = String(cString: pathBuffer)
let fileURL = URL(fileURLWithPath: path)
var code: UnsafeMutableRawPointer?
defer { code.map { Unmanaged<AnyObject>.fromOpaque($0).release() } }
var status = SecStaticCodeCreateWithPath(fileURL as CFURL, 0, &code)
guard status == 0 else { return false }
var signingInfo: CFDictionary?
defer { signingInfo.map { Unmanaged<AnyObject>.passUnretained($0).release() } }
status = SecCodeCopySigningInformation(code, kSecCSInternalInformation | kSecCSSigningInformation, &signingInfo)
guard status == 0 else { return false }
// Only accept connections from AltStore.
guard
let codeSigningInfo = signingInfo as? [String: Any],
let bundleIdentifier = codeSigningInfo["identifier"] as? String,
bundleIdentifier.contains(Bundle.Info.appbundleIdentifier)
else { return false }
let connection = XPCConnection(newConnection)
newConnection.invalidationHandler = { [weak self, weak connection] in
guard let self = self, let connection = connection else { return }
self.disconnect(connection)
}
connectionHandler?(connection)
return true
}
}

View File

@@ -0,0 +1,14 @@
//
// main.swift
// AltDaemon
//
// Created by Riley Testut on 6/2/20.
// Copyright © 2020 Riley Testut. All rights reserved.
//
import Foundation
autoreleasepool {
DaemonConnectionManager.shared.start()
RunLoop.current.run()
}

View File

@@ -0,0 +1,10 @@
Package: com.rileytestut.altdaemon
Name: AltDaemon
Depends:
Version: 1.0
Architecture: iphoneos-arm
Description: AltDaemon allows AltStore to install and refresh apps without a computer.
Maintainer: Riley Testut
Author: Riley Testut
Homepage: https://altstore.io
Section: System

View File

@@ -0,0 +1,2 @@
#!/bin/sh
launchctl load /Library/LaunchDaemons/com.rileytestut.altdaemon.plist

View File

@@ -0,0 +1,2 @@
#!/bin/sh
launchctl unload /Library/LaunchDaemons/com.rileytestut.altdaemon.plist >> /dev/null 2>&1

View File

@@ -0,0 +1,2 @@
#!/bin/sh
launchctl unload /Library/LaunchDaemons/com.rileytestut.altdaemon.plist

View File

@@ -0,0 +1,28 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>com.rileytestut.altdaemon</string>
<key>ProgramArguments</key>
<array>
<string>/usr/bin/env</string>
<string>_MSSafeMode=1</string>
<string>_SafeMode=1</string>
<string>/usr/bin/AltDaemon</string>
</array>
<key>UserName</key>
<string>mobile</string>
<key>KeepAlive</key>
<false/>
<key>RunAtLoad</key>
<false/>
<key>MachServices</key>
<dict>
<key>cy:io.altstore.altdaemon</key>
<true/>
<key>lh:io.altstore.altdaemon</key>
<true/>
</dict>
</dict>
</plist>

Binary file not shown.