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*)imageToRender;
- (void)menuNeedsUpdate:(NSMenu *)menu;
- (void)repairHelperTool;
- (void) afsVolumeMountChange:(NSNotification *)notification;
- (void) updateLinkModeStatusWithpreferenceStatus:(BOOL)status;
-(NSStatusItem*)statusItem;

View File

@ -336,6 +336,8 @@
{
@try {
BOOL currentAfsState = NO;
OSErr status = [[AuthUtil shared] autorize];
if(status == noErr){
currentAfsState = [afsMngr checkAfsStatus];
// make the parameter to call the root helper app
if(currentAfsState){
@ -347,10 +349,12 @@
NSLog(@"Starting up afs");
[afsMngr startup];
}
}
}@catch (NSException * e) {
NSLog(@"error %@", [e reason]);
}@finally {
[self updateAfsStatus:nil];
[[AuthUtil shared] deautorize];
//Send notification to preferencepane
[[NSDistributedNotificationCenter defaultCenter] postNotificationName:kAfsCommanderID object:kMenuExtraEventOccured];
}
@ -525,53 +529,6 @@
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
// -------------------------------------------------------------------------------
// statusItem

View File

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

View File

@ -176,62 +176,6 @@
[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
// -------------------------------------------------------------------------------
@ -368,53 +312,4 @@
if(useAklogPrefValue) return [useAklogPrefValue intValue] == NSOnState;
else return NSOffState;
}
// -------------------------------------------------------------------------------
// 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
@end

View File

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

View File

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

View File

@ -87,11 +87,16 @@
- (void) mainViewDidLoad
{
//CellServDB Table
[((NSTableView*)cellList) setDelegate:self];
[((NSTableView*)cellList) setTarget:self];
[((NSTableView*)cellList) setDoubleAction:@selector(tableDoubleAction:)];
[cellList setDelegate:self];
[cellList setTarget:self];
[cellList setDoubleAction:@selector(tableDoubleAction:)];
// Setup security.
AuthorizationItem items = {kAuthorizationRightExecute, 0, NULL, 0};
AuthorizationRights rights = {1, &items};
[authView setAuthorizationRights:&rights];
authView.delegate = self;
[authView updateStatus:nil];
}
// -------------------------------------------------------------------------------
@ -204,8 +209,8 @@
- (void)willUnselect
{
// remove self as datasource
[((NSTableView*)cellList) setDataSource:nil];
[((NSTableView*)tokensTable) setDataSource:nil];
[cellList setDataSource:nil];
[tokensTable setDataSource:nil];
//release the afs property manager
if(afsProperty) [afsProperty release];
@ -331,7 +336,6 @@
mutabilityOption:NSPropertyListMutableContainers
format:nil
errorDescription:nil];
}
// -------------------------------------------------------------------------------
@ -366,7 +370,7 @@
(CFStringRef)kAfsCommanderID, kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
//preference for renew time
NSLog(@"%d %d %d %d", [nsTextFieldKrb5RenewTimeD intValue],[nsTextFieldKrb5RenewTimeH intValue],[nsTextFieldKrb5RenewTimeM intValue],[nsTextFieldKrb5RenewTimeS intValue]);
//NSLog(@"%d %d %d %d", [nsTextFieldKrb5RenewTimeD intValue],[nsTextFieldKrb5RenewTimeH intValue],[nsTextFieldKrb5RenewTimeM intValue],[nsTextFieldKrb5RenewTimeS intValue]);
NSInteger totalSeconds = ([nsTextFieldKrb5RenewTimeD intValue]*24*60*60)+
([nsTextFieldKrb5RenewTimeH intValue]*60*60)+
([nsTextFieldKrb5RenewTimeM intValue]*60)+
@ -397,14 +401,11 @@
- (IBAction) saveConfiguration:(id) sender
{
@try{
//[afsProperty setCellName:[cellNameTextEdit stringValue]];
[afsProperty setCellName:[afsProperty getDefaultCellName]];
//save configurations
[afsProperty saveConfigurationFiles:YES];
//Reload all configuration
[self refreshConfiguration:nil];
@ -416,9 +417,8 @@
}@catch(NSException *e){
[self showMessage:[e reason]];
} @finally {
[((NSTableView*)cellList) reloadData];
[cellList reloadData];
}
}
// -------------------------------------------------------------------------------
@ -434,7 +434,7 @@
}@catch(NSException *e){
[self showMessage:[e reason]];
} @finally {
[((NSTableView*)cellList) reloadData];
[cellList reloadData];
}
}
@ -466,7 +466,7 @@
}@catch(NSException *e){
[self showMessage:[e reason]];
} @finally {
[((NSTableView*)cellList) reloadData];
[cellList reloadData];
}
}
@ -501,7 +501,6 @@
reason:kBadAfsRootMountPoint
userInfo:nil];
[afsProperty setDynRoot:[dynRoot state]==NSOnState];
[afsProperty setAfsDB:[afsDB state]==NSOnState];
[afsProperty setStatCacheEntry:[statCacheEntry intValue]];
@ -583,63 +582,10 @@
}
//Filter the cellServDb and allocate filtered array
[self searchCellTextEvent:nil];
[(NSTableView*)cellList deselectAll:nil];
[(NSTableView*)cellList reloadData];
[cellList deselectAll:nil];
[cellList reloadData];
}
// -------------------------------------------------------------------------------
// repairHelperTool:
// -------------------------------------------------------------------------------
- (void) repairHelperTool
{
struct stat st;
int fdTool;
int status = 0;
NSLog(@"repairHelperTool");
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.");
}
// -------------------------------------------------------------------------------
// startStopAfs:
// -------------------------------------------------------------------------------
@ -664,7 +610,6 @@
[self showMessage:[e reason]];
}
@finally {
[[AuthUtil shared] deautorize];
}
}
@ -689,8 +634,9 @@
// -------------------------------------------------------------------------------
// afsVolumeMountChange: Track the afs volume state change
// -------------------------------------------------------------------------------
// XXX should use mountdir not /afs
- (void) afsVolumeMountChange:(NSNotification *)notification{
// Cehck if is mounted or unmounted afs
// Check if is mounted or unmounted afs
if([[[notification userInfo] objectForKey:@"NSDevicePath"] isEqualToString:@"/afs"]){
[self setAfsStatus];
[self refreshTokens:nil];
@ -702,7 +648,7 @@
// -------------------------------------------------------------------------------
- (IBAction) info:(id) sender
{
[((InfoController*) infoController) showHtmlResource:[[self bundle] pathForResource:@"license" ofType:@"rtf"]];
[infoController showHtmlResource:[[self bundle] pathForResource:@"license" ofType:@"rtf"]];
[NSApp beginSheet: infoSheet
modalForWindow: [[self mainView] window]
@ -751,7 +697,7 @@
- (IBAction) unlog:(id) sender
{
int index = -1;
NSIndexSet *selectedIndex = [(NSTableView*)tokensTable selectedRowIndexes];
NSIndexSet *selectedIndex = [tokensTable selectedRowIndexes];
if( [selectedIndex count] > 0) {
index = [selectedIndex firstIndex];
do {
@ -766,7 +712,6 @@
[self refreshTokens:nil];
//Inform afs menuextra to updata afs status
[[NSDistributedNotificationCenter defaultCenter] postNotificationName:kAFSMenuExtraID object:kMExtraAFSStateChange];
}
@ -791,8 +736,6 @@
@catch (NSException * e) {
[self showMessage:[e reason]];
}
}
// -------------------------------------------------------------------------------
@ -809,13 +752,11 @@
NSString *rootHelperApp = [[self bundle] pathForResource:@"afshlp" ofType:@""];
//get the new state
startAFSAtLogin = [checkButtonAfsAtBootTime state];
const char *startupConfigureOption[] = {"start_afs_at_startup", startAFSAtLogin?"enable":"disable", 0L};
if([[AuthUtil shared] autorize] == noErr) {
//now disable the launchd configuration
[[AuthUtil shared] execUnixCommand:[rootHelperApp UTF8String]
args:startupConfigureOption
output:nil];
}
[PListManager launchctlStringCommandAuth:startAFSAtLogin?@"load":@"unload"
option:[NSArray arrayWithObjects:@"-w", nil]
plistName:@AFS_DAEMON_PATH
helper:rootHelperApp
withAuthRef:[[authView authorization] authorizationRef]];
}
@ -823,21 +764,12 @@
// afsMenuActivationEvent:
// -------------------------------------------------------------------------------
- (IBAction) krb5KredentialAtLoginTimeEvent:(id) sender {
//
NSString *rootHelperApp = [[self bundle] pathForResource:@"afshlp" ofType:@""];
const char *args[] = {"enable_krb5_startup", [[installKRB5AuthAtLoginButton stringValue] UTF8String], "", 0L};
//Check helper app
[self repairHelperTool];
if([[AuthUtil shared] autorize] == noErr) {
[[AuthUtil shared] execUnixCommand:[rootHelperApp UTF8String]
args:args
output:nil];
[PListManager krb5TiketAtLoginTime:[installKRB5AuthAtLoginButton state] helper:rootHelperApp];
//check if all is gone well
[installKRB5AuthAtLoginButton setState:[PListManager checkKrb5AtLoginTimeLaunchdEnable]];
}
}
// -------------------------------------------------------------------------------
// afsMenuActivationEvent:
@ -861,7 +793,6 @@
// -------------------------------------------------------------------------------
- (IBAction) searchCellTextEvent:(id) sender
{
NSString *searchText = [[textSearchField stringValue] lowercaseString]; //filter string
[self filterCellServDB:searchText];
[((NSTableView*)cellList) reloadData];
@ -912,7 +843,7 @@
// -------------------------------------------------------------------------------
- (DBCellElement*) getCurrentCellInDB
{
int rowSelected = [((NSTableView *) cellList) selectedRow];
int rowSelected = [cellList selectedRow];
return [self getCellByIDX:rowSelected];
}
@ -921,7 +852,6 @@
// -------------------------------------------------------------------------------
- (DBCellElement*) getCellByIDX:(int) idx
{
//NSMutableArray *cellArray = [afsProperty getCellList];
DBCellElement *cellElement = (DBCellElement*)[filteredCellDB objectAtIndex:idx];
return cellElement;
}
@ -945,41 +875,31 @@
// -------------------------------------------------------------------------------
-(void) setAfsStatus
{
BOOL afsIsUp = [afsProperty checkAfsStatus];
BOOL afsEnabledAtStartup = NO;
NSMutableString *commandOutput = [NSMutableString stringWithCapacity:20];
NSString *rootHelperApp = [[self bundle] pathForResource:@"afshlp" ofType:@""];
#if 0
// make the parameter to call the root helper app
const char *checkAFSDaemonParam[] = {"check_afs_daemon", 0L};
if([[AuthUtil shared] autorize] == noErr) {
//now disable the launchd configuration
[[AuthUtil shared] execUnixCommand:[rootHelperApp UTF8String]
args:checkAFSDaemonParam
output:commandOutput];
afsEnabledAtStartup = [commandOutput rangeOfString:@"afshlp:afs daemon registration result:1"].location!=NSNotFound;
if ([self isUnlocked]) {
afsEnabledAtStartup = (
[TaskUtil executeTaskWithAuth:@"/bin/launchctl"
arguments:[NSArray arrayWithObjects:@"list",
@"org.openafs.filesystems.afs", nil]
helper:rootHelperApp
withAuthRef:[[authView authorization] authorizationRef]
] == noErr)?YES:NO;
[checkButtonAfsAtBootTime setState:afsEnabledAtStartup];
}
#else
afsEnabledAtStartup = 1;
#endif
[startStopButton setTitle: (afsIsUp?kAfsButtonShutdown:kAfsButtonStartup)];
[((NSButton *)startStopButton) setTitle: (afsIsUp?kAfsButtonShutdown:kAfsButtonStartup)];
NSMutableAttributedString *colorTitle =[[NSMutableAttributedString alloc] initWithAttributedString:[((NSButton *)startStopButton) attributedTitle]];
NSMutableAttributedString *colorTitle =[[NSMutableAttributedString alloc] initWithAttributedString:[startStopButton attributedTitle]];
NSRange titleRange = NSMakeRange(0, [colorTitle length]);
[colorTitle addAttribute:NSForegroundColorAttributeName
value:(afsIsUp?[NSColor redColor]:[NSColor blackColor])
range:titleRange];
[((NSButton *)startStopButton) setAttributedTitle:colorTitle];
[checkButtonAfsAtBootTime setState:afsEnabledAtStartup];
[startStopButton setAttributedTitle:colorTitle];
if(afsIsUp) {
[self startTimer];
} else {
@ -998,7 +918,7 @@
}
tokenList = [afsProperty getTokenList];
[((NSTableView*)tokensTable) reloadData];
[tokensTable reloadData];
[tokensLock unlock];
}
@ -1013,7 +933,6 @@
modalDelegate: self
didEndSelector: @selector(didEndSymlinkSheet:returnCode:contextInfo:)
contextInfo: nil];
}
// -------------------------------------------------------------------------------
@ -1064,7 +983,7 @@
userDomain:YES
option:[NSArray arrayWithObjects:@"-S", @"Aqua", nil]
plistName:[NSString stringWithFormat:@"%@.plist", BACKGROUNDER_P_FILE]];
//re ad the status to check taht all is gone well
//read the status to check that all is gone well
[backgrounderActivationCheck setState:[PListManager launchdJobState:BACKGROUNDER_P_FILE]];
}
@ -1103,6 +1022,26 @@
// -------------------------------------------------------------------------------
- (IBAction) krb5RenewParamChange:(id) sender {
}
- (BOOL)isUnlocked {
return [authView authorizationState] == SFAuthorizationViewUnlockedState;
}
- (void)authorizationViewDidAuthorize:(SFAuthorizationView *)view {
// enable things
[startStopButton setEnabled:[self isUnlocked]];
[checkButtonAfsAtBootTime setEnabled:[self isUnlocked]];
[self setAfsStatus];
[installKRB5AuthAtLoginButton setEnabled:[self isUnlocked]];
}
- (void)authorizationViewDidDeauthorize:(SFAuthorizationView *)view {
// disable things
[startStopButton setEnabled:[self isUnlocked]];
[checkButtonAfsAtBootTime setEnabled:[self isUnlocked]];
[installKRB5AuthAtLoginButton setEnabled:[self isUnlocked]];
}
@end
@implementation AFSCommanderPref (NSTableDataSource)
@ -1138,7 +1077,6 @@
}
break;
}
}
@ -1150,7 +1088,6 @@
objectValueForTableColumn:(NSTableColumn *) aTableColumn
row:(int) rowIndex
{
id result = nil;
NSString *identifier = (NSString*)[aTableColumn identifier];
switch([aTableView tag]){
@ -1167,8 +1104,6 @@
case TABLE_LINK_LIST:
result = [self getTableLinkValue:[identifier intValue] row:rowIndex];
break;
}
return result;
}
@ -1243,22 +1178,18 @@
- (int)numberOfRowsInTableView:(NSTableView *)aTableView
{
int rowCount = 0;
//NSMutableArray *cellArray = nil;
switch([aTableView tag]){
case TABLE_TOKENS_LIST:
if(tokenList) rowCount = [tokenList count];
break;
case TABLE_CELL_LIST:
//cellArray = [afsProperty getCellList];
if(filteredCellDB) rowCount = [filteredCellDB count];
break;
case TABLE_LINK_LIST:
if(linkConfiguration) rowCount = [linkConfiguration count];
break;
}
return rowCount;
}
@ -1273,7 +1204,6 @@
{
switch([aTable tag]){
case TABLE_TOKENS_LIST:
break;
case TABLE_CELL_LIST:
@ -1296,7 +1226,6 @@
{
switch([aTable tag]){
case TABLE_TOKENS_LIST:
break;
case TABLE_CELL_LIST:
@ -1305,10 +1234,7 @@
case TABLE_LINK_LIST:
break;
}
return YES;
}
@ -1327,16 +1253,14 @@
case TABLE_LINK_LIST:
[self tableViewLinkmanageButtonState:[aTable selectedRowIndexes]];
break;
}
}
// -------------------------------------------------------------------------------
// manageButtonState:
// -------------------------------------------------------------------------------
-(void) tableViewCellmanageButtonState:(int) rowSelected {
[((NSControl*) cellIpButton) setEnabled:rowSelected >= 0];
[((NSControl*) removeCellButton) setEnabled:rowSelected >= 0];
[cellIpButton setEnabled:rowSelected >= 0];
[removeCellButton setEnabled:rowSelected >= 0];
}
// -------------------------------------------------------------------------------
@ -1357,7 +1281,7 @@
[sheet orderOut:self];
//Filter the cellServDb and allocate filtered array
[self searchCellTextEvent:nil];
[((NSTableView*)cellList) reloadData];
[cellList reloadData];
}
// -------------------------------------------------------------------------------
@ -1376,7 +1300,6 @@
[self refreshTokens:nil];
//Inform afs menuextra to updata afs status
[[NSDistributedNotificationCenter defaultCenter] postNotificationName:kAFSMenuExtraID object:kMExtraAFSStateChange];
}
// -------------------------------------------------------------------------------
@ -1395,6 +1318,5 @@
[lyncCreationSheet orderOut:self];
[self readPreferenceFile];
[tableViewLink reloadData];
}
@end

View File

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

View File

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

View File

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

View File

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

View File

@ -16,4 +16,5 @@
+(NSString*) executeTaskSearchingPath:(NSString*)unixCommand args:(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 helper:(NSString *)helper withAuthRef:(AuthorizationRef)authRef;
@end

View File

@ -7,6 +7,7 @@
//
#import "TaskUtil.h"
#import "AuthUtil.h"
@implementation TaskUtil
@ -75,6 +76,36 @@
// -------------------------------------------------------------------------------
// 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 {
NSString *result = nil;
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 <Security/Authorization.h>
#include <Security/AuthorizationTags.h>
#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[])
int
main(int argc, char *argv[], char *envp[])
{
if (argc < 2)
return 1; // nothing to do
NSString *cmdString = [NSString stringWithCString:(const char *)argv[1] encoding:NSUTF8StringEncoding];
if(argc == 2 && [cmdString rangeOfString:@"stop_afs"].location!=NSNotFound ){
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;
int euid;
euid = geteuid();
if (setuid(euid) != 0)
return -1;
return execve(argv[1], &argv[1], envp);
}
#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