-
Notifications
You must be signed in to change notification settings - Fork 217
/
BLAuthentication.m
executable file
·511 lines (414 loc) · 15.6 KB
/
BLAuthentication.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
// ====================================================================== //
// BLAuthentication.h //
// //
// Last Modified on Tuesday April 24 2001 //
// Copyright 2001 Ben Lachman //
// //
// Thanks to Brian R. Hill <http://personalpages.tds.net/~brian_hill/> //
// ====================================================================== //
#import "BLAuthentication.h"
#import <Security/AuthorizationTags.h>
#include <sys/stat.h>
OSStatus AuthorizationExecuteWithPrivilegesStdErrAndPid (
AuthorizationRef authorization,
const char *pathToTool,
AuthorizationFlags options,
char * const *arguments,
FILE **communicationsPipe,
FILE **errPipe,
pid_t* processid
)
{
[[NSFileManager defaultManager] changeCurrentDirectoryPath: @"/tmp/"];
char stderrpath[] = "/tmp/AuthorizationExecuteWithPrivilegesStdErrXXXXXXX.err" ;
const char* commandtemplate = "echo $$; \"$@\" 2>%s" ;
if (communicationsPipe == errPipe) {
commandtemplate = "echo $$; \"$@\" 2>1";
} else if (errPipe == 0) {
commandtemplate = "echo $$; \"$@\"";
}
char command[1024];
char ** args = nil;
OSStatus result;
int argcount = 0;
int i;
int stderrfd = 0;
FILE* commPipe = 0;
/* Create temporary file for stderr */
if (errPipe) {
stderrfd = mkstemps (stderrpath, strlen(".err"));
/* create a pipe on that path */
close(stderrfd); unlink(stderrpath);
if (mkfifo(stderrpath,S_IRWXU | S_IRWXG) != 0) {
fprintf(stderr,"Error mkfifo:%d\n",errno);
return errAuthorizationInternal;
}
if (stderrfd < 0)
return errAuthorizationInternal;
}
/* Create command to be executed */
for (argcount = 0; arguments[argcount] != 0; ++argcount) {}
args = (char**)malloc (sizeof(char*)*(argcount + 5));
args[0] = "-c";
snprintf (command, sizeof (command), commandtemplate, stderrpath);
args[1] = command;
args[2] = "";
args[3] = (char*)pathToTool;
for (i = 0; i < argcount; ++i) {
args[i+4] = arguments[i];
}
args[argcount+4] = 0;
/* for debugging: log the executed command */
/* printf ("Exec:\n%s", "/bin/sh"); for (i = 0; args[i] != 0; ++i) { printf (" \"%s\"", args[i]); } printf ("\n"); */
/* Execute command */
result = AuthorizationExecuteWithPrivileges(
authorization, "/bin/sh", options, args, &commPipe );
if (result != noErr) {
unlink (stderrpath);
free( args);
return result;
}
[NSThread sleepForTimeInterval: 0.2];
/* Read the first line of stdout => it's the pid */
{
int stdoutfd = fileno (commPipe);
char pidnum[1024];
pid_t pid = 0;
int i = 0;
char ch = 0;
while ((read(stdoutfd, &ch, sizeof(ch)) == 1) && (ch != '\n') && (i < sizeof(pidnum))) {
pidnum[i++] = ch;
}
pidnum[i] = 0;
if (ch != '\n') {
// we shouldn't get there
unlink (stderrpath);
return errAuthorizationInternal;
}
sscanf(pidnum, "%d", &pid);
if (processid) {
*processid = pid;
}
}
if (errPipe) {
stderrfd = open(stderrpath, O_RDONLY, 0);
*errPipe = fdopen(stderrfd, "r");
/* Now it's safe to unlink the stderr file, as the opened handle will be still valid */
unlink (stderrpath);
} else {
unlink(stderrpath);
}
if (communicationsPipe) {
*communicationsPipe = commPipe;
} else {
fclose (commPipe);
}
[[NSFileManager defaultManager] removeItemAtPath: [[[NSFileManager defaultManager] currentDirectoryPath] stringByAppendingPathComponent: @"1"] error: nil];
if( args)
free( args);
return noErr;
}
@implementation BLAuthentication
// returns an instace of itself, creating one if needed
+ sharedInstance {
static id sharedTask = nil;
if(sharedTask==nil) {
sharedTask = [[BLAuthentication alloc] init];
}
return sharedTask;
}
// initializes the super class and sets authorizationRef to NULL
- (id)init {
self = [super init];
authorizationRef = NULL;
return self;
}
// deauthenticates the user and deallocates memory
- (void)dealloc {
[self deauthenticate];
[super dealloc];
}
//============================================================================
// - (BOOL)isAuthenticated:(NSArray *)forCommands
//============================================================================
// Find outs if the user has the appropriate authorization rights for the
// commands listed in (NSArray *)forCommands.
// This should be called each time you need to know whether the user
// is authorized, since the AuthorizationRef can be invalidated elsewhere, or
// may expire after a short period of time.
//
- (BOOL)isAuthenticated:(NSArray *)forCommands {
AuthorizationRights rights;
AuthorizationRights *authorizedRights;
AuthorizationFlags flags;
int numItems = [forCommands count];
AuthorizationItem *items = malloc( sizeof(AuthorizationItem) * numItems );
char paths[20][128]; // only handles upto 20 commands with paths upto 128 characters in length
OSStatus err = 0;
BOOL authorized = NO;
int i = 0;
if(authorizationRef==NULL) {
rights.count=0;
rights.items = NULL;
flags = kAuthorizationFlagDefaults;
err = AuthorizationCreate(&rights, kAuthorizationEmptyEnvironment, flags, &authorizationRef);
}
if( numItems < 1 )
{
free( items);
return authorized;
}
while( i < numItems && i < 20 ) {
[[forCommands objectAtIndex:i] getCString:paths[i]];
items[i].name = kAuthorizationRightExecute;
items[i].value = paths[i];
items[i].valueLength = [[forCommands objectAtIndex:i] cStringLength];
items[i].flags = 0;
i++;
}
rights.count = numItems;
rights.items = items;
flags = kAuthorizationFlagExtendRights;
err = AuthorizationCopyRights(authorizationRef, &rights, kAuthorizationEmptyEnvironment, flags, &authorizedRights);
authorized = (errAuthorizationSuccess==err);
if(authorized)
AuthorizationFreeItemSet(authorizedRights);
if( items)
free(items);
return authorized;
}
//============================================================================
// - (void)deauthenticate
//============================================================================
// Deauthenticates the user by freeing their authorization.
//
- (void)deauthenticate {
if(authorizationRef) {
AuthorizationFree(authorizationRef, kAuthorizationFlagDestroyRights);
authorizationRef = NULL;
[[NSNotificationCenter defaultCenter]postNotificationName:BLDeauthenticatedNotification object:self];
}
}
//============================================================================
// - (BOOL)fetchPassword:(NSArray *)forCommands
//============================================================================
// Adds rights for commands specified in (NSArray *)forCommands.
// Commands should be passed as a NSString comtaining the path to the executable.
// Returns YES if rights were gained
//
- (BOOL)fetchPassword:(NSArray *)forCommands {
AuthorizationRights rights;
AuthorizationRights *authorizedRights;
AuthorizationFlags flags;
int numItems = [forCommands count];
AuthorizationItem *items = malloc( sizeof(AuthorizationItem) * numItems );
char paths[20][128];
OSStatus err = 0;
BOOL authorized = NO;
int i = 0;
if( numItems < 1 )
{
free( items);
return authorized;
}
while( i < numItems && i < 20 ) {
[[forCommands objectAtIndex:i] getCString:paths[i]];
items[i].name = kAuthorizationRightExecute;
items[i].value = paths[i];
items[i].valueLength = [[forCommands objectAtIndex:i] cStringLength];
items[i].flags = 0;
i++;
}
rights.count = numItems;
rights.items = items;
flags = kAuthorizationFlagInteractionAllowed | kAuthorizationFlagExtendRights;
err = AuthorizationCopyRights(authorizationRef, &rights, kAuthorizationEmptyEnvironment, flags, &authorizedRights);
authorized = (errAuthorizationSuccess == err);
if(authorized) {
AuthorizationFreeItemSet(authorizedRights);
[[NSNotificationCenter defaultCenter] postNotificationName:BLAuthenticatedNotification object:self];
}
free(items);
return authorized;
}
//============================================================================
// - (BOOL)authenticate:(NSArray *)forCommands
//============================================================================
// Authenticates the commands in the array (NSArray *)forCommands by calling
// fetchPassword.
//
- (BOOL)authenticate:(NSArray *)forCommands {
if( ![self isAuthenticated:forCommands] ) {
[self fetchPassword:forCommands];
}
return [self isAuthenticated:forCommands];
}
//============================================================================
// - (int)getPID:(NSString *)forProcess
//============================================================================
// Retrieves the PID (process ID) for the process specified in
// (NSString *)forProcess.
// The more specific forProcess is the better your accuracy will be, esp. when
// multiple versions of the process exist.
//
- (int)getPID:(NSString *)forProcess {
FILE* outpipe = NULL;
NSMutableData* outputData = [NSMutableData data];
NSString *commandOutput = nil;
NSString *scannerOutput = nil;
NSString *popenArgs = [[NSString alloc] initWithFormat:@"/bin/ps -axwwopid,command | grep \"%@\"",forProcess];
NSScanner *outputScanner = nil;
NSScanner *intScanner = nil;
int pid = 0;
int len = 0;
outpipe = popen([popenArgs UTF8String],"r");
[popenArgs release];
if(!outpipe) {
NSLog(@"Error opening pipe: %@",forProcess);
NSBeep();
return 0;
}
NSMutableData* tempData = [[NSMutableData alloc] initWithLength:512];
do {
[tempData setLength:512];
len = fread([tempData mutableBytes],1,512,outpipe);
if( len > 0 ) {
[tempData setLength:len];
[outputData appendData:tempData];
}
} while(len==512);
[tempData release];
pclose(outpipe);
commandOutput = [[NSString alloc] initWithData:outputData encoding:NSASCIIStringEncoding];
if( [commandOutput length] > 0 ) {
outputScanner = [NSScanner scannerWithString:commandOutput];
[commandOutput release];
[outputScanner setCharactersToBeSkipped:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
[outputScanner scanUpToString:forProcess intoString:&scannerOutput];
if( [scannerOutput rangeOfString:@"grep"].length != 0 ) {
return 0;
}
intScanner = [NSScanner scannerWithString:scannerOutput];
[intScanner scanInt:&pid];
if( pid ) {
return pid;
}
else {
return 0;
}
}
else {
[commandOutput release];
return 0;
}
}
//============================================================================
// -(void)executeCommand:(NSString *)pathToCommand withArgs:(NSArray *)arguments
//============================================================================
// Executes command in (NSString *)pathToCommand with the arguments listed in
// (NSArray *)arguments as root.
// pathToCommand should be a string contain the path to the command
// (eg., /usr/bin/more), arguments should be an array of strings each containing
// a single argument.
//
-(BOOL)executeCommand:(NSString *)pathToCommand withArgs:(NSArray *)arguments
{
#ifdef MACAPPSTORE
NSTask *task = [NSTask launchedTaskWithLaunchPath: pathToCommand arguments: arguments];
[task waitUntilExit];
return YES;
#else
char* args[30]; // can only handle 30 arguments to a given command
OSStatus err = 0;
int i = 0;
pid_t processid;
if(![self authenticate:[NSArray arrayWithObject:pathToCommand]])
return NO;
if( arguments == nil || [arguments count] < 1)
{
err = AuthorizationExecuteWithPrivilegesStdErrAndPid( authorizationRef,
[pathToCommand UTF8String],
kAuthorizationFlagDefaults,
nil,
nil,
nil,
&processid);
// err = AuthorizationExecuteWithPrivileges(authorizationRef, [pathToCommand UTF8String], 0, NULL, NULL);
}
else
{
while( i < [arguments count] && i < 19)
{
args[i] = (char*)[[arguments objectAtIndex:i] cString];
i++;
}
args[i] = NULL;
err = AuthorizationExecuteWithPrivilegesStdErrAndPid( authorizationRef,
[pathToCommand UTF8String],
kAuthorizationFlagDefaults,
args,
nil,
nil,
&processid);
// err = AuthorizationExecuteWithPrivileges(authorizationRef,
// [pathToCommand UTF8String],
// 0, args, NULL);
}
if( err != 0)
{
NSBeep();
NSLog(@"Error %d in AuthorizationExecuteWithPrivileges",(int)err);
return NO;
}
else
{
pid_t waitResult;
int junkStatus;
do
{
waitResult = waitpid( processid, &junkStatus, 0);
}
while((waitResult < 0) && (errno == EINTR));
return YES;
}
#endif
}
//============================================================================
// - (void)killProcess:(NSString *)commandFromPS
//============================================================================
// Finds and kills the process specified in (NSString *)commandFromPS using ps
// and kill. (by pid)
// The more specific (ie., closer to matching the actual listing in ps)
// commandFromPS is the better your accuracy will be, esp. when multiple
// versions of the process exist.
//
- (BOOL)killProcess:(NSString *)commandFromPS {
NSString *pid;
if( ![self isAuthenticated:[NSArray arrayWithObject:commandFromPS]] ) {
[self authenticate:[NSArray arrayWithObject:commandFromPS]];
}
pid = [NSString stringWithFormat:@"%d",[self getPID:commandFromPS]];
if( [pid intValue] > 0 ) {
[self executeCommand:@"/bin/kill" withArgs:[NSArray arrayWithObject:pid]];
return YES;
}
else {
NSBeep();
NSLog(@"Error killing process %@, invalid PID.",pid);
return NO;
}
}
@end
// BLAuthentication sends these notifications are sent when the user
// becomes authenticated or deauthenticated.
// Sample notification observer:
/*
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(userAuthenticated:)
name:BLAuthenticatedNotification
object:[BLAuthentication sharedInstance]];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(userDeauthenticated:)
name:BLDeauthenticatedNotification
object:[BLAuthentication sharedInstance]];
*/