Apple pia inapendekeza njia nyingine ya kuthibitisha ikiwa mchakato unaounganisha una idhini za kuita njia ya XPC iliyo wazi.
Wakati programu inahitaji kutekeleza vitendo kama mtumiaji mwenye mamlaka, badala ya kuendesha programu kama mtumiaji mwenye mamlaka, kawaida huweka kama root Tool ya Msaada kama huduma ya XPC ambayo inaweza kuitwa kutoka kwa programu ili kutekeleza vitendo hivyo. Hata hivyo, programu inayoiita huduma inapaswa kuwa na idhini ya kutosha.
ShouldAcceptNewConnection kila wakati YES
Mfano unaweza kupatikana katika EvenBetterAuthorizationSample. Katika App/AppDelegate.m inajaribu kuunganisha na Tool ya Msaada. Na katika HelperTool/HelperTool.m kazi shouldAcceptNewConnectionhaitaangalia yoyote ya mahitaji yaliyoelezwa hapo awali. Itarudisha kila wakati YES:
- (BOOL)listener:(NSXPCListener *)listener shouldAcceptNewConnection:(NSXPCConnection *)newConnection
// Called by our XPC listener when a new connection comes in. We configure the connection
// with our protocol and ourselves as the main object.
{
assert(listener == self.listener);
#pragma unused(listener)
assert(newConnection != nil);
newConnection.exportedInterface = [NSXPCInterface interfaceWithProtocol:@protocol(HelperToolProtocol)];
newConnection.exportedObject = self;
[newConnection resume];
return YES;
}
Kwa maelezo zaidi kuhusu jinsi ya kusanidi hii ipasavyo angalia:
Hata hivyo, kuna idhinisho linafanyika wakati njia kutoka kwa HelperTool inaitwa.
Kazi applicationDidFinishLaunching kutoka App/AppDelegate.m itaunda rejeleo tupu la idhini baada ya programu kuanza. Hii inapaswa kufanya kazi kila wakati.
Kisha, itajaribu kuongeza haki fulani kwa rejeleo hilo la idhini kwa kuita setupAuthorizationRights:
- (void)applicationDidFinishLaunching:(NSNotification *)note
{
[...]
err = AuthorizationCreate(NULL, NULL, 0, &self->_authRef);
if (err == errAuthorizationSuccess) {
err = AuthorizationMakeExternalForm(self->_authRef, &extForm);
}
if (err == errAuthorizationSuccess) {
self.authorization = [[NSData alloc] initWithBytes:&extForm length:sizeof(extForm)];
}
assert(err == errAuthorizationSuccess);
// If we successfully connected to Authorization Services, add definitions for our default
// rights (unless they're already in the database).
if (self->_authRef) {
[Common setupAuthorizationRights:self->_authRef];
}
[self.window makeKeyAndOrderFront:self];
}
The function setupAuthorizationRights from Common/Common.m itahifadhi katika hifadhidata ya uthibitisho /var/db/auth.db haki za programu. Kumbuka jinsi itakavyoongeza tu haki ambazo bado hazipo katika hifadhidata:
+ (void)setupAuthorizationRights:(AuthorizationRef)authRef
// See comment in header.
{
assert(authRef != NULL);
[Common enumerateRightsUsingBlock:^(NSString * authRightName, id authRightDefault, NSString * authRightDesc) {
OSStatus blockErr;
// First get the right. If we get back errAuthorizationDenied that means there's
// no current definition, so we add our default one.
blockErr = AuthorizationRightGet([authRightName UTF8String], NULL);
if (blockErr == errAuthorizationDenied) {
blockErr = AuthorizationRightSet(
authRef, // authRef
[authRightName UTF8String], // rightName
(__bridge CFTypeRef) authRightDefault, // rightDefinition
(__bridge CFStringRef) authRightDesc, // descriptionKey
NULL, // bundle (NULL implies main bundle)
CFSTR("Common") // localeTableName
);
assert(blockErr == errAuthorizationSuccess);
} else {
// A right already exists (err == noErr) or any other error occurs, we
// assume that it has been set up in advance by the system administrator or
// this is the second time we've run. Either way, there's nothing more for
// us to do.
}
}];
}
Kazi ya enumerateRightsUsingBlock ndiyo inayotumika kupata ruhusa za programu, ambazo zimefafanuliwa katika commandInfo:
static NSString * kCommandKeyAuthRightName = @"authRightName";
static NSString * kCommandKeyAuthRightDefault = @"authRightDefault";
static NSString * kCommandKeyAuthRightDesc = @"authRightDescription";
+ (NSDictionary *)commandInfo
{
static dispatch_once_t sOnceToken;
static NSDictionary * sCommandInfo;
dispatch_once(&sOnceToken, ^{
sCommandInfo = @{
NSStringFromSelector(@selector(readLicenseKeyAuthorization:withReply:)) : @{
kCommandKeyAuthRightName : @"com.example.apple-samplecode.EBAS.readLicenseKey",
kCommandKeyAuthRightDefault : @kAuthorizationRuleClassAllow,
kCommandKeyAuthRightDesc : NSLocalizedString(
@"EBAS is trying to read its license key.",
@"prompt shown when user is required to authorize to read the license key"
)
},
NSStringFromSelector(@selector(writeLicenseKey:authorization:withReply:)) : @{
kCommandKeyAuthRightName : @"com.example.apple-samplecode.EBAS.writeLicenseKey",
kCommandKeyAuthRightDefault : @kAuthorizationRuleAuthenticateAsAdmin,
kCommandKeyAuthRightDesc : NSLocalizedString(
@"EBAS is trying to write its license key.",
@"prompt shown when user is required to authorize to write the license key"
)
},
NSStringFromSelector(@selector(bindToLowNumberPortAuthorization:withReply:)) : @{
kCommandKeyAuthRightName : @"com.example.apple-samplecode.EBAS.startWebService",
kCommandKeyAuthRightDefault : @kAuthorizationRuleClassAllow,
kCommandKeyAuthRightDesc : NSLocalizedString(
@"EBAS is trying to start its web service.",
@"prompt shown when user is required to authorize to start the web service"
)
}
};
});
return sCommandInfo;
}
+ (NSString *)authorizationRightForCommand:(SEL)command
// See comment in header.
{
return [self commandInfo][NSStringFromSelector(command)][kCommandKeyAuthRightName];
}
+ (void)enumerateRightsUsingBlock:(void (^)(NSString * authRightName, id authRightDefault, NSString * authRightDesc))block
// Calls the supplied block with information about each known authorization right..
{
[self.commandInfo enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
#pragma unused(key)
#pragma unused(stop)
NSDictionary * commandDict;
NSString * authRightName;
id authRightDefault;
NSString * authRightDesc;
// If any of the following asserts fire it's likely that you've got a bug
// in sCommandInfo.
commandDict = (NSDictionary *) obj;
assert([commandDict isKindOfClass:[NSDictionary class]]);
authRightName = [commandDict objectForKey:kCommandKeyAuthRightName];
assert([authRightName isKindOfClass:[NSString class]]);
authRightDefault = [commandDict objectForKey:kCommandKeyAuthRightDefault];
assert(authRightDefault != nil);
authRightDesc = [commandDict objectForKey:kCommandKeyAuthRightDesc];
assert([authRightDesc isKindOfClass:[NSString class]]);
block(authRightName, authRightDefault, authRightDesc);
}];
}
Hii inamaanisha kwamba mwishoni mwa mchakato huu, ruhusa zilizotangazwa ndani ya commandInfo zitawekwa katika /var/db/auth.db. Angalia jinsi kuna kila njia ambayo itahitaji uthibitisho, jina la ruhusa na kCommandKeyAuthRightDefault. Ya mwisho inaonyesha ni nani anaweza kupata haki hii.
Kuna maeneo tofauti ya kuonyesha ni nani anaweza kupata haki. Baadhi yao zimefafanuliwa katika AuthorizationDB.h (unaweza kupata zote hapa), lakini kwa muhtasari:
Jina
Thamani
Maelezo
kAuthorizationRuleClassAllow
kuruhusu
Mtu yeyote
kAuthorizationRuleClassDeny
kukataa
Hakuna mtu
kAuthorizationRuleIsAdmin
ni-admin
Katumiaji wa sasa anahitaji kuwa admin (ndani ya kundi la admin)
kAuthorizationRuleAuthenticateAsSessionUser
uthibitisha-mmiliki-wa-sesheni
Muulize mtumiaji kuthibitisha.
kAuthorizationRuleAuthenticateAsAdmin
uthibitisha-admin
Muulize mtumiaji kuthibitisha. Anahitaji kuwa admin (ndani ya kundi la admin)
kAuthorizationRightRule
kanuni
Fafanua sheria
kAuthorizationComment
maoni
Fafanua maoni ya ziada kuhusu haki
Uthibitishaji wa Haki
Katika HelperTool/HelperTool.m kazi readLicenseKeyAuthorization inakagua ikiwa mpiga simu ameidhinishwa kutekeleza njia hiyo kwa kuita kazi checkAuthorization. Kazi hii itakagua authData iliyotumwa na mchakato wa kupiga simu ina muundo sahihi na kisha itakagua kila kinachohitajika kupata haki ya kuita njia maalum. Ikiwa kila kitu kinaenda vizuri error iliyorejeshwa itakuwa nil:
- (NSError *)checkAuthorization:(NSData *)authData command:(SEL)command
{
[...]
// First check that authData looks reasonable.
error = nil;
if ( (authData == nil) || ([authData length] != sizeof(AuthorizationExternalForm)) ) {
error = [NSError errorWithDomain:NSOSStatusErrorDomain code:paramErr userInfo:nil];
}
// Create an authorization ref from that the external form data contained within.
if (error == nil) {
err = AuthorizationCreateFromExternalForm([authData bytes], &authRef);
// Authorize the right associated with the command.
if (err == errAuthorizationSuccess) {
AuthorizationItem oneRight = { NULL, 0, NULL, 0 };
AuthorizationRights rights = { 1, &oneRight };
oneRight.name = [[Common authorizationRightForCommand:command] UTF8String];
assert(oneRight.name != NULL);
err = AuthorizationCopyRights(
authRef,
&rights,
NULL,
kAuthorizationFlagExtendRights | kAuthorizationFlagInteractionAllowed,
NULL
);
}
if (err != errAuthorizationSuccess) {
error = [NSError errorWithDomain:NSOSStatusErrorDomain code:err userInfo:nil];
}
}
if (authRef != NULL) {
junk = AuthorizationFree(authRef, 0);
assert(junk == errAuthorizationSuccess);
}
return error;
}
Note that to check the requirements to get the right to call that method the function authorizationRightForCommand will just check the previously comment object commandInfo. Then, it will call AuthorizationCopyRights to check if it has the rights to call the function (note that the flags allow interaction with the user).
In this case, to call the function readLicenseKeyAuthorization the kCommandKeyAuthRightDefault is defined to @kAuthorizationRuleClassAllow. So anyone can call it.
DB Information
Ilisemekana kwamba taarifa hii inahifadhiwa katika /var/db/auth.db. Unaweza kuorodhesha sheria zote zilizohifadhiwa kwa:
You can find all the permissions configurationsin here, but the combinations that won't require user interaction would be:
'authenticate-user': 'false'
Hii ni funguo ya moja kwa moja zaidi. Ikiwa imewekwa kuwa false, inaashiria kwamba mtumiaji hatahitaji kutoa uthibitisho ili kupata haki hii.
Hii inatumika kwa mchanganyiko na moja ya 2 hapa chini au kuashiria kundi ambalo mtumiaji lazima awe sehemu yake.
'allow-root': 'true'
Ikiwa mtumiaji anafanya kazi kama mtumiaji wa root (ambaye ana ruhusa za juu), na funguo hii imewekwa kuwa true, mtumiaji wa root anaweza kupata haki hii bila uthibitisho zaidi. Hata hivyo, kwa kawaida, kufikia hadhi ya mtumiaji wa root tayari kunahitaji uthibitisho, hivyo hii si hali ya "hakuna uthibitisho" kwa watumiaji wengi.
'session-owner': 'true'
Ikiwa imewekwa kuwa true, mmiliki wa kikao (mtumiaji aliyeingia sasa) atapata haki hii moja kwa moja. Hii inaweza kupita uthibitisho wa ziada ikiwa mtumiaji tayari ameingia.
'shared': 'true'
Funguo hii haitoi haki bila uthibitisho. Badala yake, ikiwa imewekwa kuwa true, inamaanisha kwamba mara haki hiyo itakapothibitishwa, inaweza kushirikiwa kati ya michakato mingi bila kila mmoja kuhitaji kuthibitishwa tena. Lakini utoaji wa awali wa haki hiyo bado utahitaji uthibitisho isipokuwa ikichanganywa na funguo nyingine kama 'authenticate-user': 'false'.
Ikiwa unapata kazi: [HelperTool checkAuthorization:command:] inawezekana kwamba mchakato unatumia mpangilio ulioelezwa hapo awali kwa ajili ya ruhusa:
Hii, ikiwa kazi hii inaita kazi kama AuthorizationCreateFromExternalForm, authorizationRightForCommand, AuthorizationCopyRights, AuhtorizationFree, inatumia EvenBetterAuthorizationSample.
Angalia /var/db/auth.db ili kuona kama inawezekana kupata ruhusa za kuita hatua fulani yenye mamlaka bila mwingiliano wa mtumiaji.
Protocol Communication
Kisha, unahitaji kupata mpangilio wa itifaki ili uweze kuanzisha mawasiliano na huduma ya XPC.
Kazi shouldAcceptNewConnection inaonyesha itifaki inayotolewa:
Katika kesi hii, tuna sawa na katika EvenBetterAuthorizationSample, angalia mstari huu.
Kujua, jina la itifaki inayotumika, inawezekana kudump ufafanuzi wa kichwa chake na: