2014-10-20 02:59:16 -04:00
//
// PairManager . m
2015-05-12 21:48:30 -04:00
// Moonlight
2014-10-20 02:59:16 -04:00
//
// Created by Diego Waxemberg on 10 / 19 / 14.
2015-05-12 21:48:30 -04:00
// Copyright ( c ) 2014 Moonlight Stream . All rights reserved .
2014-10-20 02:59:16 -04:00
//
# import "PairManager.h"
# import "CryptoManager.h"
2014-10-20 19:20:50 -04:00
# import "Utils.h"
2015-01-31 01:57:23 -05:00
# import "HttpResponse.h"
2015-02-01 04:26:47 -05:00
# import "HttpRequest.h"
# import "ServerInfoResponse.h"
2014-10-20 02:59:16 -04:00
# include < dispatch / dispatch . h >
@ implementation PairManager {
HttpManager * _httpManager ;
2018-12-22 00:05:48 -08:00
NSData * _clientCert ;
2014-10-20 13:35:42 -04:00
id < PairCallback > _callback ;
2014-10-20 02:59:16 -04:00
}
2018-12-22 00:05:48 -08:00
- ( id ) initWithManager : ( HttpManager * ) httpManager clientCert : ( NSData * ) clientCert callback : ( id < PairCallback > ) callback {
2014-10-20 02:59:16 -04:00
self = [ super init ] ;
_httpManager = httpManager ;
2018-12-22 00:05:48 -08:00
_clientCert = clientCert ;
2014-10-20 13:35:42 -04:00
_callback = callback ;
2014-10-20 02:59:16 -04:00
return self ;
}
- ( void ) main {
2019-11-04 21:41:42 -08:00
// We have to call startPairing before calling any other _callback functions
NSString * PIN = [ self generatePIN ] ;
[ _callback startPairing : PIN ] ;
2015-02-01 04:26:47 -05:00
ServerInfoResponse * serverInfoResp = [ [ ServerInfoResponse alloc ] init ] ;
2018-11-16 19:02:31 -08:00
[ _httpManager executeRequestSynchronously : [ HttpRequest requestForResponse : serverInfoResp withUrlRequest : [ _httpManager newServerInfoRequest : false ]
2015-07-08 23:03:23 -07:00
fallbackError : 401 fallbackRequest : [ _httpManager newHttpServerInfoRequest ] ] ] ;
2015-02-01 04:26:47 -05:00
if ( [ serverInfoResp isStatusOk ] ) {
2022-12-04 16:54:37 -06:00
if ( ! [ [ serverInfoResp getStringTag : @ "PairStatus" ] isEqual : @ "1" ] ) {
2016-03-31 11:20:18 -04:00
NSString * appversion = [ serverInfoResp getStringTag : @ "appversion" ] ;
if ( appversion = = nil ) {
[ _callback pairFailed : @ "Missing XML element" ] ;
return ;
}
2022-12-04 16:54:37 -06:00
[ self initiatePairWithPin : PIN forServerMajorVersion : [ [ appversion substringToIndex : 1 ] intValue ] withState : [ serverInfoResp getStringTag : @ "state" ] ] ;
2015-01-31 01:57:23 -05:00
} else {
[ _callback alreadyPaired ] ;
}
2014-10-20 13:35:42 -04:00
}
2019-10-12 16:41:32 -07:00
else {
[ _callback pairFailed : serverInfoResp . statusMessage ] ;
}
2014-10-20 02:59:16 -04:00
}
2019-10-12 16:41:32 -07:00
- ( void ) finishPairing : ( UIBackgroundTaskIdentifier ) bgId
forResponse : ( HttpResponse * ) resp
withFallbackError : ( NSString * ) errorMsg {
[ _httpManager executeRequestSynchronously : [ HttpRequest requestWithUrlRequest : [ _httpManager newUnpairRequest ] ] ] ;
2019-07-05 22:18:30 -07:00
if ( bgId ! = UIBackgroundTaskInvalid ) {
[ [ UIApplication sharedApplication ] endBackgroundTask : bgId ] ;
}
2019-10-12 16:41:32 -07:00
if ( ! [ resp isStatusOk ] ) {
// Use the response error if the request failed
errorMsg = resp . statusMessage ;
}
2019-07-05 22:18:30 -07:00
[ _callback pairFailed : errorMsg ] ;
}
- ( void ) finishPairing : ( UIBackgroundTaskIdentifier ) bgId withSuccess : ( NSData * ) derCertBytes {
if ( bgId ! = UIBackgroundTaskInvalid ) {
[ [ UIApplication sharedApplication ] endBackgroundTask : bgId ] ;
}
[ _callback pairSuccessful : derCertBytes ] ;
}
// All codepaths must call finishPairing exactly once before returning !
2022-12-04 16:54:37 -06:00
- ( void ) initiatePairWithPin : ( NSString * ) PIN forServerMajorVersion : ( int ) serverMajorVersion withState : ( NSString * ) state {
Log ( LOG_I , @ "Pairing with generation %d server in state %@" , serverMajorVersion , state ) ;
2016-03-31 11:20:18 -04:00
2019-07-05 22:18:30 -07:00
// Start a background task to help prevent the app from being killed
// while pairing is in progress .
UIBackgroundTaskIdentifier bgId = [ [ UIApplication sharedApplication ] beginBackgroundTaskWithName : @ "Pairing PC" expirationHandler : ^ {
Log ( LOG_W , @ "Background pairing time has expired!" ) ;
} ] ;
2020-04-17 14:45:46 +02:00
NSData * salt = [ Utils randomBytes : 16 ] ;
NSData * saltedPIN = [ self concatData : salt with : [ PIN dataUsingEncoding : NSUTF8StringEncoding ] ] ;
Log ( LOG_I , @ "PIN: %@, salt %@" , PIN , salt ) ;
2014-10-20 02:59:16 -04:00
2015-02-01 04:26:47 -05:00
HttpResponse * pairResp = [ [ HttpResponse alloc ] init ] ;
2018-12-22 00:05:48 -08:00
[ _httpManager executeRequestSynchronously : [ HttpRequest requestForResponse : pairResp withUrlRequest : [ _httpManager newPairRequest : salt clientCert : _clientCert ] ] ] ;
2015-01-31 01:57:23 -05:00
if ( ! [ self verifyResponseStatus : pairResp ] ) {
2022-12-04 16:54:37 -06:00
// GFE does not allow pairing while a server is busy , but Sunshine does . We give it a try and display the busy error if it fails .
if ( [ state hasSuffix : @ "_SERVER_BUSY" ] ) {
[ self finishPairing : bgId forResponse : pairResp withFallbackError : @ "You cannot pair while a previous session is still running on the host PC. Quit any running games or reboot the host PC, then try pairing again." ] ;
}
else {
[ self finishPairing : bgId forResponse : pairResp withFallbackError : @ "Pairing was declined by the target." ] ;
}
2014-10-20 02:59:16 -04:00
return ;
}
2015-02-01 04:26:47 -05:00
NSString * plainCert = [ pairResp getStringTag : @ "plaincert" ] ;
2016-10-21 12:07:29 -07:00
if ( [ plainCert length ] = = 0 ) {
2019-10-12 16:41:32 -07:00
[ self finishPairing : bgId forResponse : pairResp withFallbackError : @ "Another pairing attempt is already in progress." ] ;
2016-10-21 12:07:29 -07:00
return ;
}
2014-10-20 02:59:16 -04:00
2018-12-22 20:39:13 -08:00
// Pin the cert for TLS usage on this host
NSData * derCertBytes = [ CryptoManager pemToDer : [ Utils hexToBytes : plainCert ] ] ;
[ _httpManager setServerCert : derCertBytes ] ;
2014-10-20 02:59:16 -04:00
CryptoManager * cryptoMan = [ [ CryptoManager alloc ] init ] ;
2016-03-31 11:20:18 -04:00
NSData * aesKey ;
// Gen 7 servers use SHA256 to get the key
int hashLength ;
if ( serverMajorVersion >= 7 ) {
2020-04-17 14:45:46 +02:00
aesKey = [ cryptoMan createAESKeyFromSaltSHA256 : saltedPIN ] ;
2016-03-31 11:20:18 -04:00
hashLength = 32 ;
}
else {
2020-04-17 14:45:46 +02:00
aesKey = [ cryptoMan createAESKeyFromSaltSHA1 : saltedPIN ] ;
2016-03-31 11:20:18 -04:00
hashLength = 20 ;
}
2014-10-20 02:59:16 -04:00
2014-10-20 19:20:50 -04:00
NSData * randomChallenge = [ Utils randomBytes : 16 ] ;
2014-10-20 02:59:16 -04:00
NSData * encryptedChallenge = [ cryptoMan aesEncrypt : randomChallenge withKey : aesKey ] ;
2015-02-01 04:26:47 -05:00
HttpResponse * challengeResp = [ [ HttpResponse alloc ] init ] ;
[ _httpManager executeRequestSynchronously : [ HttpRequest requestForResponse : challengeResp withUrlRequest : [ _httpManager newChallengeRequest : encryptedChallenge ] ] ] ;
2019-10-12 16:41:32 -07:00
if ( ! [ self verifyResponseStatus : challengeResp ] ) {
[ self finishPairing : bgId forResponse : challengeResp withFallbackError : @ "Pairing stage #2 failed" ] ;
2014-10-20 02:59:16 -04:00
return ;
}
2015-02-01 04:26:47 -05:00
NSData * encServerChallengeResp = [ Utils hexToBytes : [ challengeResp getStringTag : @ "challengeresponse" ] ] ;
2014-10-20 02:59:16 -04:00
NSData * decServerChallengeResp = [ cryptoMan aesDecrypt : encServerChallengeResp withKey : aesKey ] ;
2016-03-31 11:20:18 -04:00
NSData * serverResponse = [ decServerChallengeResp subdataWithRange : NSMakeRange ( 0 , hashLength ) ] ;
NSData * serverChallenge = [ decServerChallengeResp subdataWithRange : NSMakeRange ( hashLength , 16 ) ] ;
2014-10-20 02:59:16 -04:00
2014-10-20 19:20:50 -04:00
NSData * clientSecret = [ Utils randomBytes : 16 ] ;
2018-12-22 00:05:48 -08:00
NSData * challengeRespHashInput = [ self concatData : [ self concatData : serverChallenge with : [ CryptoManager getSignatureFromCert : _clientCert ] ] with : clientSecret ] ;
2016-03-31 11:20:18 -04:00
NSData * challengeRespHash ;
if ( serverMajorVersion >= 7 ) {
challengeRespHash = [ cryptoMan SHA256HashData : challengeRespHashInput ] ;
}
else {
challengeRespHash = [ cryptoMan SHA1HashData : challengeRespHashInput ] ;
}
2020-06-09 01:13:30 -07:00
assert ( [ challengeRespHash length ] <= 32 ) ;
NSMutableData * paddedHash = [ NSMutableData dataWithData : challengeRespHash ] ;
[ paddedHash setLength : 32 ] ;
NSData * challengeRespEncrypted = [ cryptoMan aesEncrypt : paddedHash withKey : aesKey ] ;
2014-10-20 02:59:16 -04:00
2015-02-01 04:26:47 -05:00
HttpResponse * secretResp = [ [ HttpResponse alloc ] init ] ;
[ _httpManager executeRequestSynchronously : [ HttpRequest requestForResponse : secretResp withUrlRequest : [ _httpManager newChallengeRespRequest : challengeRespEncrypted ] ] ] ;
2019-10-12 16:41:32 -07:00
if ( ! [ self verifyResponseStatus : secretResp ] ) {
[ self finishPairing : bgId forResponse : secretResp withFallbackError : @ "Pairing stage #3 failed" ] ;
2014-10-20 02:59:16 -04:00
return ;
}
2015-02-01 04:26:47 -05:00
NSData * serverSecretResp = [ Utils hexToBytes : [ secretResp getStringTag : @ "pairingsecret" ] ] ;
2014-10-20 02:59:16 -04:00
NSData * serverSecret = [ serverSecretResp subdataWithRange : NSMakeRange ( 0 , 16 ) ] ;
2023-11-29 23:04:44 -06:00
NSData * serverSignature = [ serverSecretResp subdataWithRange : NSMakeRange ( 16 , serverSecretResp . length - 16 ) ] ;
2014-10-20 02:59:16 -04:00
2014-10-20 19:20:50 -04:00
if ( ! [ cryptoMan verifySignature : serverSecret withSignature : serverSignature andCert : [ Utils hexToBytes : plainCert ] ] ) {
2019-10-12 16:41:32 -07:00
[ self finishPairing : bgId forResponse : secretResp withFallbackError : @ "Server certificate invalid" ] ;
2014-10-20 02:59:16 -04:00
return ;
}
2016-03-31 11:20:18 -04:00
NSData * serverChallengeRespHashInput = [ self concatData : [ self concatData : randomChallenge with : [ CryptoManager getSignatureFromCert : [ Utils hexToBytes : plainCert ] ] ] with : serverSecret ] ;
NSData * serverChallengeRespHash ;
if ( serverMajorVersion >= 7 ) {
serverChallengeRespHash = [ cryptoMan SHA256HashData : serverChallengeRespHashInput ] ;
}
else {
serverChallengeRespHash = [ cryptoMan SHA1HashData : serverChallengeRespHashInput ] ;
}
2014-10-20 02:59:16 -04:00
if ( ! [ serverChallengeRespHash isEqual : serverResponse ] ) {
2019-10-12 16:41:32 -07:00
[ self finishPairing : bgId forResponse : secretResp withFallbackError : @ "Incorrect PIN" ] ;
2014-10-20 02:59:16 -04:00
return ;
}
NSData * clientPairingSecret = [ self concatData : clientSecret with : [ cryptoMan signData : clientSecret withKey : [ CryptoManager readKeyFromFile ] ] ] ;
2015-02-01 04:26:47 -05:00
HttpResponse * clientSecretResp = [ [ HttpResponse alloc ] init ] ;
[ _httpManager executeRequestSynchronously : [ HttpRequest requestForResponse : clientSecretResp withUrlRequest : [ _httpManager newClientSecretRespRequest : [ Utils bytesToHex : clientPairingSecret ] ] ] ] ;
2019-10-12 16:41:32 -07:00
if ( ! [ self verifyResponseStatus : clientSecretResp ] ) {
[ self finishPairing : bgId forResponse : clientSecretResp withFallbackError : @ "Pairing stage #4 failed" ] ;
2014-10-20 02:59:16 -04:00
return ;
}
2015-02-01 04:26:47 -05:00
HttpResponse * clientPairChallengeResp = [ [ HttpResponse alloc ] init ] ;
[ _httpManager executeRequestSynchronously : [ HttpRequest requestForResponse : clientPairChallengeResp withUrlRequest : [ _httpManager newPairChallenge ] ] ] ;
2019-10-12 16:41:32 -07:00
if ( ! [ self verifyResponseStatus : clientPairChallengeResp ] ) {
[ self finishPairing : bgId forResponse : clientPairChallengeResp withFallbackError : @ "Pairing stage #5 failed" ] ;
2014-10-20 02:59:16 -04:00
return ;
}
2018-12-22 00:05:48 -08:00
2019-07-05 22:18:30 -07:00
[ self finishPairing : bgId withSuccess : derCertBytes ] ;
2014-10-20 02:59:16 -04:00
}
2019-07-05 22:18:30 -07:00
// Caller calls finishPairing for us on failure
2015-01-31 01:57:23 -05:00
- ( BOOL ) verifyResponseStatus : ( HttpResponse * ) resp {
2019-10-12 16:41:32 -07:00
if ( ! [ resp isStatusOk ] ) {
2015-01-31 01:57:23 -05:00
return false ;
} else {
2019-10-21 17:05:03 -07:00
NSInteger pairedStatus ;
2019-10-12 16:41:32 -07:00
if ( ! [ resp getIntTag : @ "paired" value : & pairedStatus ] ) {
return false ;
}
return pairedStatus = = 1 ;
2015-01-31 01:57:23 -05:00
}
}
2014-10-20 02:59:16 -04:00
- ( NSData * ) concatData : ( NSData * ) data with : ( NSData * ) moreData {
NSMutableData * concatData = [ [ NSMutableData alloc ] initWithData : data ] ;
[ concatData appendData : moreData ] ;
return concatData ;
}
- ( NSString * ) generatePIN {
NSString * PIN = [ NSString stringWithFormat : @ "%d%d%d%d" ,
2020-07-12 11:40:31 -07:00
arc4random_uniform ( 10 ) , arc4random_uniform ( 10 ) ,
arc4random_uniform ( 10 ) , arc4random_uniform ( 10 ) ] ;
2014-10-20 02:59:16 -04:00
return PIN ;
}
@ end