STPrivilegedTask ask for password for each task - macos

I would like to start a lot of NSTasks that require root privilege, I found that I should use Apple's Authorization Kit and I found STPrivilegedTask, which is designed for that.
The thing is, when I start a STPrivilegedTask, it will ask me for the root password each time. Is there a way to enter the root password for the first privileged task, and then for the other tasks, the application will remember the root password, so the user won't have to enter the password again and again and again?

Depending on your use case, you might be happy just replacing the initialization of authorizationRef in STPrivilegedTask -launch with something like...
// create authorization reference
static AuthorizationRef authorizationRef = NULL;
#synchronized(self) {
if (!authorizationRef) {
err = AuthorizationCreate(NULL, kAuthorizationEmptyEnvironment, kAuthorizationFlagDefaults, &authorizationRef);
if (err != errAuthorizationSuccess) { return err; }
}
}
... and then removing the AuthorizationFree:
// free the auth ref
AuthorizationFree(authorizationRef, kAuthorizationFlagDefaults);
That will allow you to launch tasks without the password prompt for five minutes.
If you need more control, create a Command Line Tool in Xcode that executes the desired commands using normal NSTask calls.
When you launch the tool using STPrivilegedTask or AuthorizationExecuteWithPrivileges, the NSTask commands will run with administrator privileges (euid = 0).
SMJobBless is the way to launch a tool going forward — especially if you need to perform privileged operations on a regular basis, without prompting for a password.
It's much harder to do that correctly using AuthorizationExecuteWithPrivileges.
Notes on SMJobBless
SMJobBless prompts for a password & installs the helper.
When you talk to the helper, there will be no password prompt.
Apple's own example on this is fairly convoluted, but there are other examples out there.
Some pages suggest that only your application is allowed to talk to your helper. Apple doesn't say that anywhere. After the helper is installed, I'm pretty sure anyone can talk to it.
You could probably enforce the code signing requirements (PROPERTY LISTS section of this document) yourself, but I couldn't find any examples that do that.
I used AuthorizationExecuteWithPrivileges a couple years ago to install a launchd daemon, but I have yet to tangle with SMJobBless myself.

Hi I found some work around for this issue. Here I am listing all steps, hope help someone facing same issue:
First step on application launch to check if our application has administration privileges.
// run a terminal command for admin privileges available or not
NSString* csPluginDirectoryPath = [NSString stringWithFormat:#"%#/supportFiles",[CommonMethods getResourceFolderPath]];
NSString* tapPathCommand = [NSString stringWithFormat:#"chown root %#/tap.kext", csPluginDirectoryPath];
//if app has not admin privileges then it return error text
// if application has admin privileges it will return empty message
NSString* csErrorMessage = [self ExecuteSudoTerminalCommand:tapPathCommand];
if(csErrorMessage && [csErrorMessage length] > 2)
{
// go for admin privileges
[self launchHelperTool];
}
-(NSString*) ExecuteSudoTerminalCommand:(NSString*) terminalCommands
{
NSString* resultOfScript = #"";
NSString* csScript = [NSString stringWithFormat:#"do shell script \"%#\"",terminalCommands];
NSDictionary* errors = [NSDictionary dictionary];
NSAppleScript* appleScript = [[NSAppleScript alloc] initWithSource:csScript];
NSAppleEventDescriptor* descriptor = [appleScript executeAndReturnError:&errors];
if(descriptor == nil)
{
resultOfScript = [errors objectForKey:#"NSAppleScriptErrorMessage"];
}
else
resultOfScript = [descriptor stringValue];
return resultOfScript;
}
-(void) launchHelperTool
{
helperToolPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingString:#"/Chameleon VPN"];
NSBundle *thisBundle = [NSBundle mainBundle];
NSString* commonDictionaryPath = [[thisBundle bundleURL] absoluteString];
commonDictionaryPath = [commonDictionaryPath substringToIndex:commonDictionaryPath.length - 1];
commonDictionaryPath = [commonDictionaryPath stringByReplacingOccurrencesOfString:#"file:/" withString:#""];
NSArray *args = [NSArray arrayWithObjects:helperToolPath, commonDictionaryPath, nil];
NSTask *task = [NSTask launchedTaskWithLaunchPath:helperToolPath arguments:args];
[task waitUntilExit];
int status = [task terminationStatus];
if (status == 0)
{
NSLog(#"Task succeeded.");
}
else
{
NSLog(#"Task failed.");
exit(0);
}
}

Related

Validating URL from drag and drop in a sandbox

With file access in a sandboxed osx app with swift in mind, does it work the same with URLs provided via Finder or other apps drops?
As there's no NSOpenPanel call to afford folder access as in this example, just urls - I think the folder access is implicit since the user dragged the file from the source / desktop "folder" much the same as implicit selection via the open dialog.
I have not begun the sandbox migration yet but wanted to verify my thinking was accurate, but here's a candidate routine that does not work in sandbox mode:
func performDragOperation(_ sender: NSDraggingInfo!) -> Bool {
let pboard = sender.draggingPasteboard()
let items = pboard.pasteboardItems
if (pboard.types?.contains(NSURLPboardType))! {
for item in items! {
if let urlString = item.string(forType: kUTTypeURL as String) {
self.webViewController.loadURL(text: urlString)
}
else
if let urlString = item.string(forType: kUTTypeFileURL as String/*"public.file-url"*/) {
let fileURL = NSURL.init(string: urlString)?.filePathURL
self.webViewController.loadURL(url: fileURL!)
}
else
{
Swift.print("items has \(item.types)")
}
}
}
else
if (pboard.types?.contains(NSPasteboardURLReadingFileURLsOnlyKey))! {
Swift.print("we have NSPasteboardURLReadingFileURLsOnlyKey")
}
return true
}
as no URL is acted upon or error thrown.
Yes, the file access is implicit. As the sandbox implementation is poorly documented and had/has many bugs, you want to work around URL and Filenames. The view should register itself for both types at initialisation. Code is in Objective-C, but API should be the same.
[self registerForDraggedTypes:[NSArray arrayWithObjects:NSFilenamesPboardType, NSURLPboardType, nil]];
Then on performDragOperation:
- (BOOL)performDragOperation:(id <NSDraggingInfo>)sender
{
BOOL dragPerformed = NO;
NSPasteboard *paste = [sender draggingPasteboard];
NSArray *typesWeRead = [NSArray arrayWithObjects:NSFilenamesPboardType, NSURLPboardType, nil];
//a list of types that we can accept
NSString *typeInPasteboard = [paste availableTypeFromArray:typesWeRead];
if ([typeInPasteboard isEqualToString:NSFilenamesPboardType]) {
NSArray *fileArray = [paste propertyListForType:#"NSFilenamesPboardType"];
//be careful since this method returns id.
//We just happen to know that it will be an array. and it contains strings.
NSMutableArray *urlArray = [NSMutableArray arrayWithCapacity:[fileArray count]];
for (NSString *path in fileArray) {
[urlArray addObject:[NSURL fileURLWithPath:path]];
}
dragPerformed = //.... do your stuff with the files;
} else if ([typeInPasteboard isEqualToString:NSURLPboardType]) {
NSURL *droppedURL = [NSURL URLFromPasteboard:paste];
if ([droppedURL isFileURL]) {
dragPerformed = //.... do your stuff with the files;
}
}
return dragPerformed;
}

OSX: Export system certificates from keychain in PEM format programmatically

How can I extract all root CA certificates from all the keychains on OSX programmatically in pem format?
Keychain programming services should allow this but how?
Any help would be appreciable.
security find-certificate -a -p /System/Library/Keychains/SystemRootCertificates.keychain >certs-roots.pem
security find-certificate -a -p /Library/Keychains/System.keychain >certs-system.pem
security find-certificate -a -p ~/Library/Keychains/login.keychain-db >certs-user.pem
BTW: You can see those paths in Keychain Access when you hover over the Keychains list (top/left).
You can combine system and user pems by using the default certificate source
security find-certificate -a -p >certs.pem
This is super useful for node.js, when you want to use require('https').request on typical corporate internal stuff without having to resort to hacks like accepting any certificate without checking. You don't need to include the system roots since nodejs has you covered already for those.
NODE_EXTRA_CA_CERTS=certs.pem node
Answering my own question:
On OSX you can invoke a NSTask to get response from the security command line utility:
security find-certificate -a -p /System/Library/Keychains/SystemCACertificates.keychain > allcerts.pem
Hey I know I'm late to this but I came across the same problem today and spent many hours figuring out how to do this. I know that the original poster might not need to know this anymore but hopefully this helps someone.
The following is my code to exactly replicate what you've done without using the command line.
+ (NSURL *)createCertsFileInDirectory:(NSURL *)directory {
NSString *outPath = [directory path];
if (!outPath) {
return nil;
}
outPath = [outPath stringByAppendingPathComponent:#"allcerts.pem"];
NSURL * outURL = [NSURL fileURLWithPath:outPath];
SecKeychainRef keychain;
if (SecKeychainOpen("/System/Library/Keychains/SystemCACertificates.keychain", &keychain) != errSecSuccess) {
return nil;
}
CFMutableArrayRef searchList = CFArrayCreateMutable(kCFAllocatorDefault, 1, &kCFTypeArrayCallBacks);
CFArrayAppendValue(searchList, keychain);
CFTypeRef keys[] = { kSecClass, kSecMatchLimit, kSecAttrCanVerify, kSecMatchSearchList };
CFTypeRef values[] = { kSecClassCertificate, kSecMatchLimitAll, kCFBooleanTrue, searchList };
CFDictionaryRef dict = CFDictionaryCreate(kCFAllocatorDefault, keys, values, 4, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
CFTypeRef results;
OSStatus status = SecItemCopyMatching(dict, &results);
CFArrayRef arr = (CFArrayRef) results;
NSLog(#"total item count = %ld", CFArrayGetCount(arr));
CFRelease(dict);
CFRelease(searchList);
CFRelease(keychain);
if (status != errSecSuccess) {
return nil;
}
CFDataRef certsData;
status = SecItemExport(results, kSecFormatPEMSequence, kSecItemPemArmour, NULL, &certsData);
CFRelease(results);
if (status != errSecSuccess) {
return nil;
}
NSData *topLevelData = (NSData *) CFBridgingRelease(certsData);
if (![topLevelData writeToURL:outURL atomically:YES]) {
return nil;
}
return outURL;
}

Get the Username(s) stored in Keychain, using only the ServiceName? OR: Where are you supposed to store the Username?

So the OS X Keychain has three pieces of information:
ServiceName (the name of my app)
Username
Password
I obviously always know the ServiceName. Is there a way to find any saved Username(s) for that ServiceName? (Finding the password is easy once you know the Username.)
I would much prefer to use a nice Cocoa wrapper such as EMKeychain to do this. But EMKeychain requires the UserName to get any keychain item!
+ (EMGenericKeychainItem *)genericKeychainItemForService:(NSString *)serviceNameString withUsername:(NSString *)usernameString;
How are you expected to fully utilize saving credentials in the Keychain, if you need the Username to find the credentials? Is the best practice to save the Username in the .plist file or something?
SecKeychainFindGenericPassword only returns a single keychain item. To find all generic passwords for a specific service, you need to run a query on the keychain. There are several ways to do this, based on what version of OS X you target.
If you need to run on 10.5 or below, you'll need to use SecKeychainSearchCreateFromAttributes. It's a rather horrible API. Here is a rough cut of a method that returns a dictionary mapping usernames to passwords.
- (NSDictionary *)genericPasswordsWithService:(NSString *)service {
OSStatus status;
// Construct a query.
const char *utf8Service = [service UTF8String];
SecKeychainAttribute attr = { .tag = kSecServiceItemAttr,
.length = strlen(utf8Service),
.data = (void *)utf8Service };
SecKeychainAttribute attrList = { .count = 1, .attr = &attr };
SecKeychainSearchRef *search = NULL;
status = SecKeychainSearchCreateFromAttributes(NULL, kSecGenericPasswordItemClass, &attrList, &search);
if (status) {
report(status);
return nil;
}
// Enumerate results.
NSMutableDictionary *result = [NSMutableDictionary dictionary];
while (1) {
SecKeychainItemRef item = NULL;
status = SecKeychainSearchCopyNext(search, &item);
if (status)
break;
// Find 'account' attribute and password value.
UInt32 tag = kSecAccountItemAttr;
UInt32 format = CSSM_DB_ATTRIBUTE_FORMAT_STRING;
SecKeychainAttributeInfo info = { .count = 1, .tag = &tag, .format = &format };
SecKeychainAttributeList *attrList = NULL;
UInt32 length = 0;
void *data = NULL;
status = SecKeychainItemCopyAttributesAndData(item, &info, NULL, &attrList, &length, &data);
if (status) {
CFRelease(item);
continue;
}
NSAssert(attrList->count == 1 && attrList->attr[0].tag == kSecAccountItemAttr, #"SecKeychainItemCopyAttributesAndData is messing with us");
NSString *account = [[[NSString alloc] initWithBytes:attrList->attr[0].data length:attrList->attr[0].length encoding:NSUTF8StringEncoding] autorelease];
NSString *password = [[[NSString alloc] initWithBytes:data length:length encoding:NSUTF8StringEncoding] autorelease];
[result setObject:password forKey:account];
SecKeychainItemFreeAttributesAndData(attrList, data);
CFRelease(item);
}
CFRelease(search);
return result;
}
For 10.6 and later, you can use the somewhat less inconvenient SecItemCopyMatching API:
- (NSDictionary *)genericPasswordsWithService:(NSString *)service {
NSDictionary *query = [NSDictionary dictionaryWithObjectsAndKeys:
kSecClassGenericPassword, kSecClass,
(id)kCFBooleanTrue, kSecReturnData,
(id)kCFBooleanTrue, kSecReturnAttributes,
kSecMatchLimitAll, kSecMatchLimit,
service, kSecAttrService,
nil];
NSArray *itemDicts = nil;
OSStatus status = SecItemCopyMatching((CFDictionaryRef)q, (CFTypeRef *)&itemDicts);
if (status) {
report(status);
return nil;
}
NSMutableDictionary *result = [NSMutableDictionary dictionary];
for (NSDictionary *itemDict in itemDicts) {
NSData *data = [itemDict objectForKey:kSecValueData];
NSString *password = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];
NSString *account = [itemDict objectForKey:kSecAttrAccount];
[result setObject:password forKey:account];
}
[itemDicts release];
return result;
}
For 10.7 or later, you can use my wonderful LKKeychain framework (PLUG!). It doesn't support building attribute-based queries, but you can simply list all passwords and filter out the ones you don't need.
- (NSDictionary *)genericPasswordsWithService:(NSString *)service {
LKKCKeychain *keychain = [LKKCKeychain defaultKeychain];
NSMutableDictionary *result = [NSMutableDictionary dictionary];
for (LKKCGenericPassword *item in [keychain genericPasswords]) {
if ([service isEqualToString:item.service]) {
[result setObject:item.password forKey:item.account];
}
}
return result;
}
(I didn't try running, or even compiling any of the above code samples; sorry for any typos.)
You don't need the username. You do with EMKeychain, but that's an artificial distinction that that class imposes; the underlying Keychain Services function does not require a username to find a keychain item.
When using SecKeychainFindGenericPassword directly, pass 0 and NULL for the username parameters. It will return a keychain item that exists on that service.
However, that will return only one item. If the user has multiple keychain items on the same service, you won't know that, or which one you got (the documentation says it returns the “first” matching item, with no specification of what it considers “first”). If you want any and all items for that service, you should create a search and use that.
Generic passwords have a unique key of the service name and the username. Thus, to fetch a single generic keychain entry, you will need to provide both. However, you can iterate over all generic keychain entries for your given service using the SecKeychainFindGenericPassword function.
(Disclaimer: I don't know anything about doing this in EMKeychain.)

Execute Applescript from Cocoa App with params

I would like to know how to execute an applescript from a cocoa application passing parameters.
I have seen how easy is to execute applescripts with no parameters in other questions here at stackoverflow, however the use NSAppleScript class, in which, i haven't seen no method that solve my problem. Does anyone have any idea.
I would like a Cocoa code with the same effect o this shell:
osascript teste.applescript "snow:Users:MyUser:Desktop:MyFolder" "snow:Users:MyUser:Desktop:Example:"
So it may run this AppleScript.
on run argv
set source to (item 1 of argv)
set destiny to (item 2 of argv)
tell application "Finder" to make new alias file at destiny to source
0
end run
Any help is appreciated. Thanks in advance.
Look at my GitHub repository, I have a category of NSAppleEventDescriptor that makes it much easier to create NSAppleEventDescriptor to call different AppleScript procedures with arguments, and coercion to and from many AppleScript typed.
NSAppleEventDescriptor-NDCoercion
I found easier to follow this piece code. I took a code from here and modified it to my purpose.
- (BOOL) executeScriptWithPath:(NSString*)path function:(NSString*)functionName andArguments:(NSArray*)scriptArgumentArray
{
BOOL executionSucceed = NO;
NSAppleScript * appleScript;
NSAppleEventDescriptor * thisApplication, *containerEvent;
NSURL * pathURL = [NSURL fileURLWithPath:path];
NSDictionary * appleScriptCreationError = nil;
appleScript = [[NSAppleScript alloc] initWithContentsOfURL:pathURL error:&appleScriptCreationError];
if (appleScriptCreationError)
{
NSLog([NSString stringWithFormat:#"Could not instantiate applescript %#",appleScriptCreationError]);
}
else
{
if (functionName && [functionName length])
{
/* If we have a functionName (and potentially arguments), we build
* an NSAppleEvent to execute the script. */
//Get a descriptor for ourself
int pid = [[NSProcessInfo processInfo] processIdentifier];
thisApplication = [NSAppleEventDescriptor descriptorWithDescriptorType:typeKernelProcessID
bytes:&pid
length:sizeof(pid)];
//Create the container event
//We need these constants from the Carbon OpenScripting framework, but we don't actually need Carbon.framework...
#define kASAppleScriptSuite 'ascr'
#define kASSubroutineEvent 'psbr'
#define keyASSubroutineName 'snam'
containerEvent = [NSAppleEventDescriptor appleEventWithEventClass:kASAppleScriptSuite
eventID:kASSubroutineEvent
targetDescriptor:thisApplication
returnID:kAutoGenerateReturnID
transactionID:kAnyTransactionID];
//Set the target function
[containerEvent setParamDescriptor:[NSAppleEventDescriptor descriptorWithString:functionName]
forKeyword:keyASSubroutineName];
//Pass arguments - arguments is expecting an NSArray with only NSString objects
if ([scriptArgumentArray count])
{
NSAppleEventDescriptor *arguments = [[NSAppleEventDescriptor alloc] initListDescriptor];
NSString *object;
for (object in scriptArgumentArray) {
[arguments insertDescriptor:[NSAppleEventDescriptor descriptorWithString:object]
atIndex:([arguments numberOfItems] + 1)]; //This +1 seems wrong... but it's not
}
[containerEvent setParamDescriptor:arguments forKeyword:keyDirectObject];
[arguments release];
}
//Execute the event
NSDictionary * executionError = nil;
NSAppleEventDescriptor * result = [appleScript executeAppleEvent:containerEvent error:&executionError];
if (executionError != nil)
{
NSLog([NSString stringWithFormat:#"error while executing script. Error %#",executionError]);
}
else
{
NSLog(#"Script execution has succeed. Result(%#)",result);
executionSucceed = YES;
}
}
else
{
NSDictionary * executionError = nil;
NSAppleEventDescriptor * result = [appleScript executeAndReturnError:&executionError];
if (executionError != nil)
{
NSLog([NSString stringWithFormat:#"error while executing script. Error %#",executionError]);
}
else
{
NSLog(#"Script execution has succeed. Result(%#)",result);
executionSucceed = YES;
}
}
}
[appleScript release];
return executionSucceed;
}
Technical Note TN2084
Using AppleScript Scripts in Cocoa Applications
Even though your application is written in Objective-C using Cocoa, you can use AppleScript scripts to perform certain operations. This Technical Note explains how to integrate and execute AppleScripts from within your Cocoa application. It discusses how to leverage the NSAppleScript class and the use of NSAppleEventDescriptor to send data to the receiver.
https://developer.apple.com/library/archive/technotes/tn2084/_index.html
https://applescriptlibrary.files.wordpress.com/2013/11/technical-note-tn2084-using-applescript-scripts-in-cocoa-applications.pdf
Swift 4 version, modified from the code here:
https://gist.github.com/chbeer/3666e4b7b2e71eb47b15eaae63d4192f
import Carbon
static func runAppleScript(_ url: URL) {
var appleScriptError: NSDictionary? = nil
guard let script = NSAppleScript(contentsOf: url, error: &appleScriptError) else {
return
}
let message = NSAppleEventDescriptor(string: "String parameter")
let parameters = NSAppleEventDescriptor(listDescriptor: ())
parameters.insert(message, at: 1)
var psn = ProcessSerialNumber(highLongOfPSN: UInt32(0), lowLongOfPSN: UInt32(kCurrentProcess))
let target = NSAppleEventDescriptor(descriptorType: typeProcessSerialNumber, bytes: &psn, length: MemoryLayout<ProcessSerialNumber>.size)
let handler = NSAppleEventDescriptor(string: "MyMethodName")
let event = NSAppleEventDescriptor.appleEvent(withEventClass: AEEventClass(kASAppleScriptSuite), eventID: AEEventID(kASSubroutineEvent), targetDescriptor: target, returnID: AEReturnID(kAutoGenerateReturnID), transactionID: AETransactionID(kAnyTransactionID))
event.setParam(handler, forKeyword: AEKeyword(keyASSubroutineName))
event.setParam(parameters, forKeyword: AEKeyword(keyDirectObject))
var executeError: NSDictionary? = nil
script.executeAppleEvent(event, error: &executeError)
if let executeError = executeError {
print("ERROR: \(executeError)")
}
}
For running the apple script:
on MyMethodName(theParameter)
display dialog theParameter
end MyMethodName
I'm not all too familiar with AppleScript, but I seem to remember that they are heavily based on (the rather crappy) Apple Events mechanism which dates back to the days where the 56k Modem was the coolest Gadget in your house.
Therefore I'd guess that you're looking for executeAppleEvent:error: which is part of NSAppleScript. Maybe you can find some information on how to encapsulate execution arguments in the instance of NSAppleEventDescriptor that you have to pass along with this function.

Keychain access required for displaying list of known Wifi Networks in OSX App

My OSX app needs to display a list of the user's known wifi networks. I've already figured out how to do this using the CoreWLAN framework. The code I'm using is:
CWInterface *interface = [[CWInterface alloc] init];
NSArray *knownNetworks = interface.configuration.preferredNetworks;
This works fine, except that when I do this, OSX prompts the user saying my app needs keychain access for each network that has a passphrase stored. The "preferredNetworks" property returns an array of CWWirelessProfile objects. One of the properties of this class is "passphrase". I believe this property is why my app needs keychain access.
I don't need, or even want, the passphrases for the user's known networks. All I care about is the SSID. Is there a way to query a list of known SSIDs without also pulling the passphrase? I would prefer it if my app didn't prompt the user that it needs keychain access. Also, the prompt is useless in my case because regardless if the user hits "Allow" or "Deny", I am still able to access the network's SSID.
It turns out that Bavarious was correct; I can utilize the System Configuration framework to retrieve a list of know wifi networks without prompting the user for admin access. Here is the class I ended up creating that handles this:
static NSString *configPath = #"/Library/Preferences/SystemConfiguration/preferences.plist";
#implementation KnownWifiNetworks
/**
This method reads the SystemConfiguration file located at configPath. Its schema is described in Apple's
Documentation at this url:
http://developer.apple.com/library/mac/#documentation/Networking/Conceptual/SystemConfigFrameworks/SC_Components/SC_Components.html
TODO: Cache the results so we don't have the read the file every time?
*/
+ (NSArray *)allKnownNetworks {
NSMutableArray *result = [NSMutableArray arrayWithCapacity:50];
#try {
NSDictionary *config = [NSDictionary dictionaryWithContentsOfFile:configPath];
NSDictionary *sets = [config objectForKey:#"Sets"];
for (NSString *setKey in sets) {
NSDictionary *set = [sets objectForKey:setKey];
NSDictionary *network = [set objectForKey:#"Network"];
NSDictionary *interface = [network objectForKey:#"Interface"];
for(NSString *interfaceKey in interface) {
NSDictionary *bsdInterface = [interface objectForKey:interfaceKey];
for(NSString *namedInterfaceKey in bsdInterface) {
NSDictionary *namedInterface = [bsdInterface objectForKey:namedInterfaceKey];
NSArray *networks = [namedInterface objectForKey:#"PreferredNetworks"];
for (NSDictionary *network in networks) {
NSString *ssid = [network objectForKey:#"SSID_STR"];
[result addObject:ssid];
}
}
}
}
} #catch (NSException * e) {
NSLog(#"Failed to read known networks: %#", e);
}
return result;
}
#end
I've been able to use the CoreWLAN framework classes to get a list of known network SSIDs without requiring keychain access like so:
NSMutableArray *result = [NSMutableArray arrayWithCapacity:50];
CWInterface *interface = [CWInterface interface];
NSEnumerator *profiles = [interface.configuration.networkProfiles objectEnumerator];
CWNetworkProfile *profile;
while (profile = [profiles nextObject]) {
[result addObject:profile.ssid];
}
return result;
It seems that CWInterface.configuration.preferredNetworks is deprecated but this solution works quite well.

Resources