macos: update AFS prefs pane

modify afshelper to just run what it's told instead
of offering fixed operations. this avoids having a setuid
tool around. in spite of apple's suggestion this is correct,
it's actually more dangerous. instead, elevate privilege only
to run a small set of commands, then drop. allow
unlocking of the prefs pane, but make the menu extra prompt
for authentication when needed.
deactivate controls in the prefs pane when locked.

Change-Id: I0e2510efc98605f464e04d26cc8f2ce2bfe116f4
Reviewed-on: http://gerrit.openafs.org/7196
Tested-by: BuildBot <buildbot@rampaginggeek.com>
Reviewed-by: Derrick Brashear <shadow@dementix.org>
This commit is contained in:
Derrick Brashear 2012-04-18 11:57:10 -04:00
parent 0debf2d227
commit 0524e0d191
16 changed files with 1682 additions and 2323 deletions

View File

@ -65,7 +65,6 @@
- (NSImage*)getImageFromBundle:(NSString*)fileName fileExt:(NSString*)ext; - (NSImage*)getImageFromBundle:(NSString*)fileName fileExt:(NSString*)ext;
- (NSImage*)imageToRender; - (NSImage*)imageToRender;
- (void)menuNeedsUpdate:(NSMenu *)menu; - (void)menuNeedsUpdate:(NSMenu *)menu;
- (void)repairHelperTool;
- (void) afsVolumeMountChange:(NSNotification *)notification; - (void) afsVolumeMountChange:(NSNotification *)notification;
- (void) updateLinkModeStatusWithpreferenceStatus:(BOOL)status; - (void) updateLinkModeStatusWithpreferenceStatus:(BOOL)status;
-(NSStatusItem*)statusItem; -(NSStatusItem*)statusItem;

View File

@ -335,22 +335,26 @@
- (void)startStopAfs:(id)sender - (void)startStopAfs:(id)sender
{ {
@try { @try {
BOOL currentAfsState = NO; BOOL currentAfsState = NO;
OSErr status = [[AuthUtil shared] autorize];
if(status == noErr){
currentAfsState = [afsMngr checkAfsStatus]; currentAfsState = [afsMngr checkAfsStatus];
// make the parameter to call the root helper app // make the parameter to call the root helper app
if(currentAfsState){ if(currentAfsState){
//shutdown afs //shutdown afs
NSLog(@"Shutting down afs"); NSLog(@"Shutting down afs");
[afsMngr shutdown]; [afsMngr shutdown];
} else { } else {
//Start afs //Start afs
NSLog(@"Starting up afs"); NSLog(@"Starting up afs");
[afsMngr startup]; [afsMngr startup];
} }
}
}@catch (NSException * e) { }@catch (NSException * e) {
NSLog(@"error %@", [e reason]); NSLog(@"error %@", [e reason]);
}@finally { }@finally {
[self updateAfsStatus:nil]; [self updateAfsStatus:nil];
[[AuthUtil shared] deautorize];
//Send notification to preferencepane //Send notification to preferencepane
[[NSDistributedNotificationCenter defaultCenter] postNotificationName:kAfsCommanderID object:kMenuExtraEventOccured]; [[NSDistributedNotificationCenter defaultCenter] postNotificationName:kAfsCommanderID object:kMenuExtraEventOccured];
} }
@ -525,53 +529,6 @@
else return NSOffState; else return NSOffState;
} }
// -------------------------------------------------------------------------------
// repairHelperTool:
// -------------------------------------------------------------------------------
- (void) repairHelperTool
{
struct stat st;
int fdTool;
int status = 0;
NSString *afshlpPath = [[NSBundle mainBundle] pathForResource:@"afshlp" ofType:nil];
// Open tool exclusively, so nobody can change it while we bless it.
fdTool = open([afshlpPath UTF8String], O_NONBLOCK | O_RDONLY | O_EXLOCK, 0);
if(fdTool == -1)
{
NSLog(@"Exclusive open while repairing tool failed: %d.", errno);
exit(-1);
}
if(fstat(fdTool, &st))
{
NSLog(@"fstat failed.");
exit(-1);
}
if(st.st_uid != 0)
{
status = [[AuthUtil shared] autorize];
if(status == noErr){
fchown(fdTool, 0, st.st_gid);
// Disable group and world writability and make setuid root.
fchmod(fdTool, (st.st_mode & (~(S_IWGRP | S_IWOTH)))/* | S_ISUID*/);
const char *args[] = {"root", [afshlpPath UTF8String],0L};
[[AuthUtil shared] execUnixCommand:"/usr/sbin/chown"
args:args
output:nil];
[[AuthUtil shared] deautorize];
}
} else NSLog(@"st_uid = 0");
close(fdTool);
NSLog(@"Self-repair done.");
}
#pragma mark accessor #pragma mark accessor
// ------------------------------------------------------------------------------- // -------------------------------------------------------------------------------
// statusItem // statusItem

View File

@ -52,6 +52,5 @@
- (NSImage*)getImageFromBundle:(NSString*)fileName fileExt:(NSString*)ext; - (NSImage*)getImageFromBundle:(NSString*)fileName fileExt:(NSString*)ext;
- (NSImage*)imageToRender; - (NSImage*)imageToRender;
- (void)updateMenu; - (void)updateMenu;
- (void)repairHelperTool;
- (void) afsVolumeMountChange:(NSNotification *)notification; - (void) afsVolumeMountChange:(NSNotification *)notification;
@end @end

View File

@ -176,62 +176,6 @@
[self updateAfsStatus:nil]; [self updateAfsStatus:nil];
} }
// -------------------------------------------------------------------------------
// -(void) readPreferenceFile
// -------------------------------------------------------------------------------
- (void)startStopAfs:(id)sender
{
if(!afsSysPath) return;
OSStatus status = noErr;
NSString *afsdPath = [TaskUtil searchExecutablePath:@"afsd"];
NSString *rootHelperApp = nil;
BOOL currentAfsState = NO;
@try {
if(afsdPath == nil) return;
AFSPropertyManager *afsMngr = [[AFSPropertyManager alloc] initWithAfsPath:afsSysPath];
currentAfsState = [afsMngr checkAfsStatus];
[afsMngr release];
rootHelperApp = [[self bundle] pathForResource:@"afshlp" ofType:@""];
//Check helper app
[self repairHelperTool];
// make the parameter to call the root helper app
status = [[AuthUtil shared] autorize];
if(status == noErr){
if(currentAfsState){
//shutdown afs
NSMutableString *afsKextPath = [[NSMutableString alloc] initWithCapacity:256];
[afsKextPath setString:afsSysPath];
[afsKextPath appendString:@"/etc/afs.kext"];
const char *stopAfsArgs[] = {"stop_afs", [afsKextPath UTF8String], [afsdPath UTF8String], 0L};
[[AuthUtil shared] execUnixCommand:[rootHelperApp UTF8String]
args:stopAfsArgs
output:nil];
} else {
const char *startAfsArgs[] = {[[[self bundle] pathForResource:@"start_afs" ofType:@"sh"] UTF8String], [afsSysPath UTF8String], [afsdPath UTF8String], 0L};
[[AuthUtil shared] execUnixCommand:[rootHelperApp UTF8String]
args:startAfsArgs
output:nil];
}
}
}
@catch (NSException * e) {
NSLog([e reason]);
}
@finally {
[[AuthUtil shared] deautorize];
[self updateAfsStatus:nil];
//Send notification to preferencepane
[[NSDistributedNotificationCenter defaultCenter] postNotificationName:afsCommanderID object:kMenuExtraEventOccured];
}
}
// ------------------------------------------------------------------------------- // -------------------------------------------------------------------------------
// -(void) getToken // -(void) getToken
// ------------------------------------------------------------------------------- // -------------------------------------------------------------------------------
@ -368,53 +312,4 @@
if(useAklogPrefValue) return [useAklogPrefValue intValue] == NSOnState; if(useAklogPrefValue) return [useAklogPrefValue intValue] == NSOnState;
else return NSOffState; else return NSOffState;
} }
@end
// -------------------------------------------------------------------------------
// repairHelperTool:
// -------------------------------------------------------------------------------
- (void) repairHelperTool
{
struct stat st;
int fdTool;
int status = 0;
NSString *afshlpPath = [[self bundle] pathForResource:@"afshlp" ofType:nil];
// Open tool exclusively, so nobody can change it while we bless it.
fdTool = open([afshlpPath UTF8String], O_NONBLOCK | O_RDONLY | O_EXLOCK, 0);
if(fdTool == -1)
{
NSLog(@"Exclusive open while repairing tool failed: %d.", errno);
exit(-1);
}
if(fstat(fdTool, &st))
{
NSLog(@"fstat failed.");
exit(-1);
}
if(st.st_uid != 0)
{
status = [[AuthUtil shared] autorize];
if(status == noErr){
fchown(fdTool, 0, st.st_gid);
// Disable group and world writability and make setuid root.
fchmod(fdTool, (st.st_mode & (~(S_IWGRP | S_IWOTH)))/* | S_ISUID*/);
const char *args[] = {"root", [afshlpPath UTF8String],0L};
[[AuthUtil shared] execUnixCommand:"/usr/sbin/chown"
args:args
output:nil];
[[AuthUtil shared] deautorize];
}
} else NSLog(@"st_uid = 0");
close(fdTool);
NSLog(@"Self-repair done.");
}@end

View File

@ -9,7 +9,7 @@
#import <Cocoa/Cocoa.h> #import <Cocoa/Cocoa.h>
#import "AFSBackgrounderDelegate.h" #import "AFSBackgrounderDelegate.h"
@interface AFSMenuExtraView : NSView { @interface AFSMenuExtraView : NSView <NSMenuDelegate> {
AFSBackgrounderDelegate *backgrounderDelegator; AFSBackgrounderDelegate *backgrounderDelegator;
NSStatusItem *statusItem; NSStatusItem *statusItem;
NSMenu *statusItemMenu; NSMenu *statusItemMenu;

View File

@ -7,6 +7,7 @@
// //
#import <PreferencePanes/PreferencePanes.h> #import <PreferencePanes/PreferencePanes.h>
#import <SecurityInterface/SFAuthorizationView.h>
#import "AFSPropertyManager.h" #import "AFSPropertyManager.h"
#import "global.h" #import "global.h"
#import "ViewUtility.h" #import "ViewUtility.h"
@ -20,12 +21,13 @@ int CoreMenuExtraRemoveMenuExtra(void *menuExtra, int whoCares);
@interface AFSCommanderPref : NSPreferencePane @interface AFSCommanderPref : NSPreferencePane <NSTableViewDataSource, NSTableViewDelegate>
{ {
//for check system version //for check system version
int prefStartUp; int prefStartUp;
// Main View // Main View
BOOL startAFSAtLogin; BOOL startAFSAtLogin;
IBOutlet SFAuthorizationView *authView;
IBOutlet NSView *afsCommanderView; IBOutlet NSView *afsCommanderView;
IBOutlet NSSearchField *textSearchField; IBOutlet NSSearchField *textSearchField;
IBOutlet NSTextField *afsDefaultCellLabel; IBOutlet NSTextField *afsDefaultCellLabel;
@ -104,6 +106,7 @@ int CoreMenuExtraRemoveMenuExtra(void *menuExtra, int whoCares);
NSLock *tokensLock; NSLock *tokensLock;
} }
- (BOOL)isUnlocked;
- (void) mainViewDidLoad; - (void) mainViewDidLoad;
- (void) willUnselect; - (void) willUnselect;
- (void) didSelect; - (void) didSelect;
@ -144,11 +147,8 @@ int CoreMenuExtraRemoveMenuExtra(void *menuExtra, int whoCares);
- (void) modifyCell:(DBCellElement*) cellElement; - (void) modifyCell:(DBCellElement*) cellElement;
- (void) modifyCellByIDX:(int) idx; - (void) modifyCellByIDX:(int) idx;
- (void) showMessage:(NSString*) message; - (void) showMessage:(NSString*) message;
- (void) tableViewCellmanageButtonState:(int) rowSelected;
- (void) tableViewLinkmanageButtonState:(NSIndexSet *) rowsSelectedIndex;
- (void) setAfsStatus; - (void) setAfsStatus;
- (void) refreshTokens:(NSTimer*)theTimer; - (void) refreshTokens:(NSTimer*)theTimer;
- (void) repairHelperTool;
- (void) writePreferenceFile; - (void) writePreferenceFile;
- (void) readPreferenceFile; - (void) readPreferenceFile;
- (void) refreshGui:(NSNotification *)notification; - (void) refreshGui:(NSNotification *)notification;
@ -157,6 +157,11 @@ int CoreMenuExtraRemoveMenuExtra(void *menuExtra, int whoCares);
- (void)tabView:(NSTabView *)tabView willSelectTabViewItem: (NSTabViewItem *)tabViewItem; - (void)tabView:(NSTabView *)tabView willSelectTabViewItem: (NSTabViewItem *)tabViewItem;
@end @end
@interface AFSCommanderPref (TableDelegate)
- (void) tableViewCellmanageButtonState:(int) rowSelected;
- (void) tableViewLinkmanageButtonState:(NSIndexSet *) rowsSelectedIndex;
@end;
@interface AFSCommanderPref (NSTableDataSource) @interface AFSCommanderPref (NSTableDataSource)
- (id) getTableTokensListValue:(int) colId row:(int)row; - (id) getTableTokensListValue:(int) colId row:(int)row;
- (id) getTableCelListValue:(int) colId row:(int)row; - (id) getTableCelListValue:(int) colId row:(int)row;

File diff suppressed because it is too large Load Diff

View File

@ -29,7 +29,7 @@
NSString *afsRootMountPoint; NSString *afsRootMountPoint;
int statCacheEntry; int statCacheEntry;
int dCacheDim; int dCacheDim;
int cacheDimension; int cacheDimension;
int daemonNumber; int daemonNumber;
int nVolEntry; int nVolEntry;
bool dynRoot; bool dynRoot;

View File

@ -92,7 +92,6 @@
if(cellList) {[cellList removeAllObjects];[cellList release];} if(cellList) {[cellList removeAllObjects];[cellList release];}
if(cellName) {[cellName release];} if(cellName) {[cellName release];}
if(futil) { if(futil) {
[futil endAutorization];
[futil release]; [futil release];
futil = nil; futil = nil;
} }
@ -360,7 +359,7 @@
NSCharacterSet *returnCS = [NSCharacterSet characterSetWithCharactersInString:@"\n"]; NSCharacterSet *returnCS = [NSCharacterSet characterSetWithCharactersInString:@"\n"];
NSFileHandle *fileH = [NSFileHandle fileHandleForReadingAtPath:filePath]; NSFileHandle *fileH = [NSFileHandle fileHandleForReadingAtPath:filePath];
if (!fileH) return nil; if (!fileH) return 0;
NSData *fileHData = [fileH readDataToEndOfFile]; NSData *fileHData = [fileH readDataToEndOfFile];
NSString *cacheInfoStrData = [[NSString alloc] initWithData:fileHData NSString *cacheInfoStrData = [[NSString alloc] initWithData:fileHData
encoding:NSASCIIStringEncoding]; encoding:NSASCIIStringEncoding];
@ -465,7 +464,7 @@
// ------------------------------------------------------------------------------- // -------------------------------------------------------------------------------
-(int) readOldAfsdOption:(NSString*)filePath -(int) readOldAfsdOption:(NSString*)filePath
{ {
if(!filePath) return nil; if(!filePath) return 0;
return [self readAFSDParamLineContent:[[NSString stringWithContentsOfFile:filePath return [self readAFSDParamLineContent:[[NSString stringWithContentsOfFile:filePath
encoding:NSUTF8StringEncoding encoding:NSUTF8StringEncoding
error:nil] stringByStandardizingPath]]; error:nil] stringByStandardizingPath]];
@ -475,7 +474,7 @@
// readAFSDParamLineContent: // readAFSDParamLineContent:
// ------------------------------------------------------------------------------- // -------------------------------------------------------------------------------
-(int) readAFSDParamLineContent:(NSString*) paramLine{ -(int) readAFSDParamLineContent:(NSString*) paramLine{
if (!paramLine) return nil; if (!paramLine) return 0;
NSString *tmpString = nil; NSString *tmpString = nil;
NSCharacterSet *space = [NSCharacterSet characterSetWithCharactersInString:@" "]; NSCharacterSet *space = [NSCharacterSet characterSetWithCharactersInString:@" "];
@ -537,16 +536,16 @@
// ------------------------------------------------------------------------------- // -------------------------------------------------------------------------------
-(int) readNewAfsdOption:(NSString*)filePath -(int) readNewAfsdOption:(NSString*)filePath
{ {
if(!filePath) return nil; if(!filePath) return 0;
NSString *currentLines = nil; NSString *currentLines = 0;
NSString *paramValue = nil; NSString *paramValue = 0;
NSScanner *lineScanner = nil; NSScanner *lineScanner = 0;
//Get file content //Get file content
NSString *newAFSDConfContent = [NSString stringWithContentsOfFile:filePath NSString *newAFSDConfContent = [NSString stringWithContentsOfFile:filePath
encoding:NSUTF8StringEncoding encoding:NSUTF8StringEncoding
error:nil]; error:nil];
if (!newAFSDConfContent) return nil; if (!newAFSDConfContent) return 0;
//get lines in array //get lines in array
NSArray *confLines = [newAFSDConfContent componentsSeparatedByString:@"\n"]; NSArray *confLines = [newAFSDConfContent componentsSeparatedByString:@"\n"];
@ -1078,23 +1077,18 @@
// ------------------------------------------------------------------------------- // -------------------------------------------------------------------------------
-(void) shutdown -(void) shutdown
{ {
@try { NSString *rootHelperApp = [[NSBundle bundleForClass:[self class]] pathForResource:@"afshlp" ofType:@""];
const char *stopArgs[] = {"stop", 0L}; @try {
if([[AuthUtil shared] autorize] == noErr) { const char *stopArgs[] = {AFS_DAEMON_STARTUPSCRIPT, "stop", 0L};
[[AuthUtil shared] execUnixCommand:AFS_DAEMON_STARTUPSCRIPT [[AuthUtil shared] execUnixCommand:[rootHelperApp fileSystemRepresentation]
args:stopArgs args:stopArgs
output:nil]; output:nil];
} }
@catch (NSException * e) {
} @throw e;
@catch (NSException * e) { }
@throw e; @finally {
} }
@finally {
}
} }
@ -1103,24 +1097,20 @@
// ------------------------------------------------------------------------------- // -------------------------------------------------------------------------------
-(void) startup -(void) startup
{ {
@try { NSString *rootHelperApp = [[NSBundle bundleForClass:[self class]] pathForResource:@"afshlp" ofType:@""];
const char *startArgs[] = {"start", 0L}; @try {
if([[AuthUtil shared] autorize] == noErr) { const char *startArgs[] = {AFS_DAEMON_STARTUPSCRIPT, "start", 0L};
[[AuthUtil shared] execUnixCommand:AFS_DAEMON_STARTUPSCRIPT [[AuthUtil shared] execUnixCommand:[rootHelperApp fileSystemRepresentation]
args:startArgs args:startArgs
output:nil]; output:nil];
} }
@catch (NSException * e) {
} @throw e;
@catch (NSException * e) { }
@throw e; @finally {
} }
@finally {
}
} }
// ------------------------------------------------------------------------------- // -------------------------------------------------------------------------------
// -(void) saveConfigurationFiles // -(void) saveConfigurationFiles
// ------------------------------------------------------------------------------- // -------------------------------------------------------------------------------
@ -1166,13 +1156,6 @@
encoding: NSUTF8StringEncoding encoding: NSUTF8StringEncoding
error:&err]; error:&err];
// backup original file
if([futil startAutorization] != noErr){
@throw [NSException exceptionWithName:@"saveConfigurationFiles:startAutorization"
reason:kUserNotAuth
userInfo:nil];
}
if(makeBackup) [self backupConfigurationFiles]; if(makeBackup) [self backupConfigurationFiles];
// install ThisCell // install ThisCell
@ -1220,12 +1203,6 @@
[self writeAfsdOption:useAfsdConfVersion?AFSD_TMP_NEW_PREFERENCE_FILE:AFSD_TMP_OLD_PREFERENCE_FILE]; [self writeAfsdOption:useAfsdConfVersion?AFSD_TMP_NEW_PREFERENCE_FILE:AFSD_TMP_OLD_PREFERENCE_FILE];
// backup original file // backup original file
if([futil startAutorization] != noErr){
@throw [NSException exceptionWithName:@"AFSPropertyManager:saveCacheConfigurationFiles:startAutorization"
reason:kUserNotAuth
userInfo:nil];
}
if(makeBackup) { if(makeBackup) {
//cacheinfo //cacheinfo
[self backupFile:@"/etc/cacheinfo"]; [self backupFile:@"/etc/cacheinfo"];
@ -1294,11 +1271,6 @@
{ {
@try{ @try{
if([futil startAutorization] != noErr){
@throw [NSException exceptionWithName:@"backupConfigurationFiles:startAutorization"
reason:kUserNotAuth
userInfo:nil];
}
//This cell //This cell
[self backupFile:@"/etc/ThisCell"]; [self backupFile:@"/etc/ThisCell"];
@ -1308,7 +1280,6 @@
//TheseCell //TheseCell
[self backupFile:@"/etc/TheseCells"]; [self backupFile:@"/etc/TheseCells"];
//[futil endAutorization];
} @catch (NSException *e) { } @catch (NSException *e) {
@throw e; @throw e;
} @finally { } @finally {
@ -1329,8 +1300,6 @@
//Check if the file at path exist //Check if the file at path exist
NSFileManager *fileManager = [NSFileManager defaultManager]; NSFileManager *fileManager = [NSFileManager defaultManager];
//check if th efile exist
if(![fileManager fileExistsAtPath:[filePath stringByExpandingTildeInPath]]) return; if(![fileManager fileExistsAtPath:[filePath stringByExpandingTildeInPath]]) return;
// store the source path // store the source path

View File

@ -16,8 +16,8 @@
// ------------------------------------------------------------------------------- // -------------------------------------------------------------------------------
- (void)awakeFromNib - (void)awakeFromNib
{ {
[((NSTableView*)tableViewCellIP) setDelegate:self]; [tableViewCellIP setDelegate:self];
[((NSTableView*)tableViewCellIP) setDataSource:self]; [tableViewCellIP setDataSource:self];
} }
// ------------------------------------------------------------------------------- // -------------------------------------------------------------------------------
@ -44,8 +44,8 @@
- (void) commitModify - (void) commitModify
{ {
//store the cell name //store the cell name
[cellElement setCellName:[((NSControl*) textFieldCellName) stringValue]]; [cellElement setCellName:[textFieldCellName stringValue]];
[cellElement setCellComment:[((NSControl*) textFieldComment) stringValue]]; [cellElement setCellComment:[textFieldComment stringValue]];
[bkIPArray removeAllObjects]; [bkIPArray removeAllObjects];
[bkIPArray setArray:workIPArray]; [bkIPArray setArray:workIPArray];
[workIPArray release]; [workIPArray release];
@ -81,8 +81,8 @@
[workIPArray addObject:ip]; [workIPArray addObject:ip];
[ip release]; [ip release];
currentSelectedIP = ip; currentSelectedIP = ip;
[((NSTableView*)tableViewCellIP) reloadData]; [tableViewCellIP reloadData];
[((NSTableView *) tableViewCellIP) scrollRowToVisible:[[cellElement getIp] count]-1]; [tableViewCellIP scrollRowToVisible:[[cellElement getIp] count]-1];
} }
// ------------------------------------------------------------------------------- // -------------------------------------------------------------------------------
@ -90,10 +90,10 @@
// ------------------------------------------------------------------------------- // -------------------------------------------------------------------------------
- (IBAction) cancelIP:(id) sender - (IBAction) cancelIP:(id) sender
{ {
[workIPArray removeObjectAtIndex:[((NSTableView*)tableViewCellIP) selectedRow]]; [workIPArray removeObjectAtIndex:[tableViewCellIP selectedRow]];
[((NSTableView*)tableViewCellIP) deselectAll:nil]; [tableViewCellIP deselectAll:nil];
[self manageTableSelection:-1]; [self manageTableSelection:-1];
[((NSTableView*)tableViewCellIP) reloadData]; [tableViewCellIP reloadData];
} }
@ -110,9 +110,9 @@
// ------------------------------------------------------------------------------- // -------------------------------------------------------------------------------
- (void) loadValueFromCellIPClass - (void) loadValueFromCellIPClass
{ {
[((NSTextField*)textFieldCellName) setStringValue:[cellElement getCellName]]; [textFieldCellName setStringValue:[cellElement getCellName]];
[((NSTextField*)textFieldComment) setStringValue:[cellElement getCellComment]]; [textFieldComment setStringValue:[cellElement getCellComment]];
[((NSTableView*)tableViewCellIP) reloadData]; [tableViewCellIP reloadData];
} }
// ------------------------------------------------------------------------------- // -------------------------------------------------------------------------------
@ -121,7 +121,7 @@
- (void) manageTableSelection:(int)row - (void) manageTableSelection:(int)row
{ {
//[((NSControl*) modifyButton) setEnabled:row>=0]; //[((NSControl*) modifyButton) setEnabled:row>=0];
[((NSControl*) deleteButton) setEnabled:row>=0]; [deleteButton setEnabled:row>=0];
} }
- (id) getPanel - (id) getPanel
@ -194,7 +194,7 @@
forTableColumn:(NSTableColumn *)aCol row:(int)aRow forTableColumn:(NSTableColumn *)aCol row:(int)aRow
{ {
CellIp *ipElement = (CellIp*)[workIPArray objectAtIndex:aRow]; CellIp *ipElement = (CellIp*)[workIPArray objectAtIndex:aRow];
switch([((NSNumber*)[aCol identifier]) intValue]) switch([[aCol identifier] intValue])
{ {
case 1: case 1:
[ipElement setCellIp:[aData description]]; [ipElement setCellIp:[aData description]];

View File

@ -40,7 +40,7 @@
@abstract Enable or disable the system to get kerberos ticket at login time @abstract Enable or disable the system to get kerberos ticket at login time
@discussion <#(comprehensive description)#> @discussion <#(comprehensive description)#>
*/ */
+(void) krb5TiketAtLoginTime:(BOOL)enable; +(void) krb5TiketAtLoginTime:(BOOL)enable helper:(NSString *)helper;
/*! /*!
@method checkKrb5AtLoginTimeLaunchdEnable @method checkKrb5AtLoginTimeLaunchdEnable
@ -80,9 +80,7 @@
@abstract exec the launchctl command on a particular plist job @abstract exec the launchctl command on a particular plist job
@discussion <#(comprehensive description)#> @discussion <#(comprehensive description)#>
*/ */
+(void) launchctlStringCommand:(NSString*)operation +(void) launchctlStringCommandAuth:(NSString*)operation option:(NSArray*)option plistName:(NSString*)plistName helper:(NSString *)helper withAuthRef:(AuthorizationRef)authRef;
option:(NSArray*)option
plistName:(NSString*)plistName;
/*! /*!
@method launchdJobState @method launchdJobState
@abstract check is a job has been submitted to launchd @abstract check is a job has been submitted to launchd

View File

@ -17,7 +17,8 @@
// ------------------------------------------------------------------------------- // -------------------------------------------------------------------------------
// krb5TiketAtLoginTime: // krb5TiketAtLoginTime:
// ------------------------------------------------------------------------------- // -------------------------------------------------------------------------------
+(void) krb5TiketAtLoginTime:(BOOL)enable{ +(void) krb5TiketAtLoginTime:(BOOL)enable helper:(NSString *)helper
{
NSData *plistData = nil; NSData *plistData = nil;
NSString *error = nil; NSString *error = nil;
NSString *toRemove = nil; NSString *toRemove = nil;
@ -112,16 +113,15 @@
//now we can move the file //now we can move the file
futil = [[FileUtil alloc] init]; futil = [[FileUtil alloc] init];
if([futil startAutorization] == noErr) { if(![[NSFileManager defaultManager] fileExistsAtPath:AUTH_FILE_BK]) {
if(![[NSFileManager defaultManager] fileExistsAtPath:AUTH_FILE_BK]) { //bk file doesn't exist so make it
//bk file doesn't exist so make it [futil autorizedCopy:AUTH_FILE toPath:AUTH_FILE_BK];
[futil autorizedCopy:AUTH_FILE toPath:AUTH_FILE_BK];
}
// chmod on tmp file
[futil autorizedChown:TMP_FILE owner:@"root" group:@"wheel"];
//move the file
[futil autorizedMoveFile:TMP_FILE toPath:AUTH_FILE_DIR];
} }
// chmod on tmp file
[futil autorizedChown:TMP_FILE owner:@"root" group:@"wheel"];
//move the file
[futil autorizedMoveFile:TMP_FILE toPath:AUTH_FILE_DIR];
[futil release]; [futil release];
} }
@ -223,9 +223,9 @@
// installAfsStartupLaunchdFile: // installAfsStartupLaunchdFile:
// ------------------------------------------------------------------------------- // -------------------------------------------------------------------------------
+(void) manageAfsStartupLaunchdFile:(BOOL)enable +(void) manageAfsStartupLaunchdFile:(BOOL)enable
afsStartupScript:(NSString*)afsStartupScript afsStartupScript:(NSString*)afsStartupScript
afsBasePath:(NSString*)afsBasePath afsBasePath:(NSString*)afsBasePath
afsdPath:(NSString*)afsdPath { afsdPath:(NSString*)afsdPath {
NSData *plistData = nil; NSData *plistData = nil;
NSMutableDictionary *launchdDic = nil; NSMutableDictionary *launchdDic = nil;
NSString *error = nil; NSString *error = nil;
@ -288,9 +288,10 @@
// launchctlCommand: // launchctlCommand:
// ------------------------------------------------------------------------------- // -------------------------------------------------------------------------------
+(void) launchctlCommand:(BOOL)enable +(void) launchctlCommand:(BOOL)enable
userDomain:(BOOL)userDomain userDomain:(BOOL)userDomain
option:(NSArray*)option option:(NSArray*)option
plistName:(NSString*)plistName { plistName:(NSString*)plistName
{
NSMutableArray *argument = [NSMutableArray array]; NSMutableArray *argument = [NSMutableArray array];
NSMutableString *commandPath = [NSMutableString stringWithCapacity:0]; NSMutableString *commandPath = [NSMutableString stringWithCapacity:0];
NSUInteger searchDomain = userDomain?NSUserDomainMask:NSSystemDomainMask; NSUInteger searchDomain = userDomain?NSUserDomainMask:NSSystemDomainMask;
@ -307,17 +308,21 @@
[commandPath appendFormat:@"/LaunchAgents/%@", plistName]; [commandPath appendFormat:@"/LaunchAgents/%@", plistName];
[argument addObject:commandPath]; [argument addObject:commandPath];
//exec the command //exec the command
[TaskUtil executeTaskSearchingPath:@"launchctl" [TaskUtil executeTask:@"/bin/launchctl"
args:argument]; arguments:argument];
} }
// ------------------------------------------------------------------------------- // -------------------------------------------------------------------------------
// launchctlCommand: // launchctlCommand:
// ------------------------------------------------------------------------------- // -------------------------------------------------------------------------------
+(void) launchctlStringCommand:(NSString*)operation +(void) launchctlStringCommandAuth:(NSString *)operation
option:(NSArray*)option option:(NSArray *)option
plistName:(NSString*)plistName { plistName:(NSString *)plistName
helper:(NSString *)helper
withAuthRef:(AuthorizationRef)authRef
{
NSMutableArray *argument = [NSMutableArray array]; NSMutableArray *argument = [NSMutableArray array];
//set the load unload //set the load unload
@ -330,8 +335,8 @@
[argument addObject: plistName]; [argument addObject: plistName];
//exec the command //exec the command
[TaskUtil executeTaskSearchingPath:@"launchctl" [TaskUtil executeTaskWithAuth:@"/bin/launchctl"
args:argument]; arguments:argument helper:helper withAuthRef:authRef];
} }
// ------------------------------------------------------------------------------- // -------------------------------------------------------------------------------

View File

@ -16,4 +16,5 @@
+(NSString*) executeTaskSearchingPath:(NSString*)unixCommand args:(NSArray*)args; +(NSString*) executeTaskSearchingPath:(NSString*)unixCommand args:(NSArray*)args;
+(NSString*) executeTask:(NSString*) taskName arguments:(NSArray *)args; +(NSString*) executeTask:(NSString*) taskName arguments:(NSArray *)args;
+(int) executeTaskWithAuth:(NSString*) taskName arguments:(NSArray *)args authExtForm:(NSData*)auth; +(int) executeTaskWithAuth:(NSString*) taskName arguments:(NSArray *)args authExtForm:(NSData*)auth;
+(int) executeTaskWithAuth:(NSString*) taskName arguments:(NSArray *)args helper:(NSString *)helper withAuthRef:(AuthorizationRef)authRef;
@end @end

View File

@ -7,6 +7,7 @@
// //
#import "TaskUtil.h" #import "TaskUtil.h"
#import "AuthUtil.h"
@implementation TaskUtil @implementation TaskUtil
@ -75,6 +76,36 @@
// ------------------------------------------------------------------------------- // -------------------------------------------------------------------------------
// executeTask: // executeTask:
// ------------------------------------------------------------------------------- // -------------------------------------------------------------------------------
+(int) executeTaskWithAuth:(NSString*) taskName arguments:(NSArray *)args helper:(NSString *)helper withAuthRef:(AuthorizationRef)authRef {
const char *rootHelperApp = [helper fileSystemRepresentation];
OSStatus status;
AuthorizationFlags flags = kAuthorizationFlagDefaults;
int count = [args count];
char **myArguments = calloc(count + 2, sizeof(char *));
int i=0;
myArguments[0] = strdup([taskName UTF8String]);
for(i=0;i < count;i++) {
const char *string = [[args objectAtIndex:i] UTF8String];
if(!string)
break;
myArguments[1+i] = strdup(string);
}
myArguments[1+i] = NULL;
// should use SMJobBless but we need to sign things...
status = AuthorizationExecuteWithPrivileges(authRef, rootHelperApp, flags, myArguments, NULL);
i = 0;
while (myArguments[i] != NULL) {
free(myArguments[i]);
i++;
}
free(myArguments);
return status;
}
+(int) executeTaskWithAuth:(NSString*) taskName arguments:(NSArray *)args authExtForm:(NSData*)auth { +(int) executeTaskWithAuth:(NSString*) taskName arguments:(NSArray *)args authExtForm:(NSData*)auth {
NSString *result = nil; NSString *result = nil;
int status = 0; int status = 0;

View File

@ -1,213 +1,11 @@
//
// afshlp.m
// AFSCommander
//
// Created by Claudio on 28/06/07.
//
#include <sys/types.h>
#include <unistd.h> #include <unistd.h>
#include <Security/Authorization.h> int
#include <Security/AuthorizationTags.h> main(int argc, char *argv[], char *envp[])
#include <sys/param.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <sys/fcntl.h>
#include <sys/errno.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <asl.h>
#include <sys/event.h>
#include <mach-o/dyld.h>
#import "TaskUtil.h"
#import "AuthUtil.h"
#import "PListManager.h"
#define AFS_DAEMON_STARTUPSCRIPT "/Library/OpenAFS/Tools/root.client/usr/vice/etc/afs.rc"
#define AFS_DAEMON_PATH "/Library/LaunchDaemons/org.openafs.filesystems.afs.plist"
void stopAfs(int argc, char *argv[]);
void getPath(char **selfPathPtr);
void selfRepair(char *selfPath);
void runWithSelfRepair(char *selfPath,int argc, char *argv[]);
int main(int argc, char *argv[])
{ {
if (argc < 2) int euid;
return 1; // nothing to do euid = geteuid();
NSString *cmdString = [NSString stringWithCString:(const char *)argv[1] encoding:NSUTF8StringEncoding]; if (setuid(euid) != 0)
return -1;
if(argc == 2 && [cmdString rangeOfString:@"stop_afs"].location!=NSNotFound ){ return execve(argv[1], &argv[1], envp);
if (setuid(0) == -1)
return 1;
const char *stopArgs[] = {"stop", 0L};
[[AuthUtil shared] execUnixCommand:AFS_DAEMON_STARTUPSCRIPT
args:stopArgs
output:nil];
} else if(argc == 2 && [cmdString rangeOfString:@"start_afs"].location!=NSNotFound){
if (setuid(0) == -1)
return 1;
const char *startArgs[] = {"start", 0L};
[[AuthUtil shared] execUnixCommand:AFS_DAEMON_STARTUPSCRIPT
args:startArgs
output:nil];
} else if(argc == 4 && [cmdString rangeOfString:@"enable_krb5_startup"].location!=NSNotFound) {
int olduid = getuid();
setuid(0);
int arg2 = atoi(argv[2]);
[PListManager krb5TiketAtLoginTime:[[NSNumber numberWithInt:arg2] boolValue]];
} else if(argc == 3 && [cmdString rangeOfString:@"start_afs_at_startup"].location!=NSNotFound){
if (setuid(0) == -1)
return 1;
BOOL enable = strcmp("enable", argv[2])==0;
NSLog(@"Manage start_afs_at_startup with option %s from helper", argv[2]);
[PListManager launchctlStringCommand:enable?@"load":@"unload"
option:[NSArray arrayWithObjects:@"-w", nil]
plistName:@AFS_DAEMON_PATH];
#if 0
} else if(argc == 2 && [cmdString rangeOfString:@"check_afs_daemon"].location!=NSNotFound) {
NSString *fsResult = [TaskUtil executeTaskSearchingPath:@"launchctl" args:[NSArray arrayWithObjects: @"list", nil]];
BOOL checkAfsDaemon = (fsResult?([fsResult rangeOfString:@"org.openafs.filesystems.afs"].location != NSNotFound):NO);
printf("afshlp:afs daemon registration result:%d",checkAfsDaemon);
#endif
}
return 0;
} }
#if 0
void stopAfs(int argc, char *argv[])
{
const char *umountArgs[] = {"-f", "/afs", 0L};
[[AuthUtil shared] execUnixCommand:"/sbin/umount"
args:umountArgs
output:nil];
const char *afsdArgs[] = {"-shutdown", 0L};
[[AuthUtil shared] execUnixCommand:argv[3]
args:afsdArgs
output:nil];
const char *kernelExtArgs[] = {argv[2], 0L};
[[AuthUtil shared] execUnixCommand:"/sbin/kextunload"
args:kernelExtArgs
output:nil];
[[AuthUtil shared] deautorize];
}
// Code to get the path to the executable using _NSGetExecutablePath.
void getPath(char **selfPathPtr)
{
uint32_t selfPathSize = MAXPATHLEN;
if(!(*selfPathPtr = malloc(selfPathSize)))
{
exit(-1);
}
if(_NSGetExecutablePath(*selfPathPtr, &selfPathSize) == -1)
{
// Try reallocating selfPath with the size returned by the function.
if(!(*selfPathPtr = realloc(*selfPathPtr, selfPathSize + 1)))
{
NSLog(@"Could not allocate memory to hold executable path.");
exit(-1);
}
if(_NSGetExecutablePath(*selfPathPtr, &selfPathSize) != 0)
{
NSLog(@"Could not get executable path.");
exit(-1);
}
}
}
int main(int argc, char *argv[])
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
char *selfPath;
NSLog(@"num of arguments %d", argc);
int status = [[AuthUtil shared] autorize];
if(status != noErr) exit(-1);
// Get the path to the tool's executable
getPath(&selfPath);
//selfRepair(selfPath);
// All done with the executable path
if(selfPath) free(selfPath);
// Now do the real work of running the command.
runCommand(argc, argv);
[[AuthUtil shared] deautorize];
[pool release];
return 0;
}
// Self-repair code. Found somehwere in internet
void selfRepair(char *selfPath)
{
struct stat st;
int fdTool;
printf("selfRepair");
// [[AuthUtil shared] autorize];
// Open tool exclusively, noone can touch it when we work on it, this idea i kepped somewhere in internet
fdTool = open(selfPath, O_NONBLOCK | O_RDONLY | O_EXLOCK, 0);
if(fdTool == -1)
{
NSLog(@"Open Filed: %d.", errno);
exit(-1);
}
if(fstat(fdTool, &st))
{
NSLog(@"fstat failed.");
exit(-1);
}
// Disable group and world writability and make setuid root.
if ((st.st_uid != 0) || (st.st_mode & S_IWGRP) || (st.st_mode & S_IWOTH) ||
!(st.st_mode & S_ISUID))
{
fchown(fdTool, 0, st.st_gid);
fchmod(fdTool, (st.st_mode & (~(S_IWGRP | S_IWOTH))) | S_ISUID);
} else NSLog(@"st_uid = 0");
close(fdTool);
NSLog(@"Self-repair done.");
}
// Code to execute the tool in self-repair mode.
void runWithSelfRepair(char *selfPath, int argc, char *argv[])
{
int status;
int pid;
// Make the qargs array for passing to child the same args of father
const char *arguments[] = {argv[1], argv[2], argv[3], "--self-repair", 0L};
// Get the privileged AuthorizationRef
[[AuthUtil shared] autorize];
[[AuthUtil shared] execUnixCommand:selfPath
args:arguments
output:nil];
pid = wait(&status);
if(pid == -1 || !WIFEXITED(status))
{
NSLog(@"Error returned from wait().");
exit(-1);
}
// Exit with the same exit code as the self-repair child
exit(WEXITSTATUS(status));
}
#endif