Add object detection, tracking, mobile notifications, and search to any security camera.
start key prompt
roryclear7f2487e25757
diff --git a/clearcam/FileServer.m b/clearcam/FileServer.mindex 424f417..cfdac61 100644--- a/clearcam/FileServer.m+++ b/clearcam/FileServer.m@@ -11,6 +11,7 @@#import "PortScanner.h"#import "AppDelegate.h"#import <CoreData/CoreData.h>+#import "SecretManager.h"@interface FileServer ()@property (nonatomic, strong) NSString *basePath;@@ -39,6 +40,7 @@}if ([SettingsManager sharedManager].delete_on_launch) {+ [[SecretManager sharedManager] deleteAllKeysWithError:&error];for (NSString *file in contents) {if ([file hasPrefix:@"batch_req"]) continue;NSString *filePath = [documentsPath stringByAppendingPathComponent:file];diff --git a/clearcam/SceneDelegate.m b/clearcam/SceneDelegate.mindex 8f96503..5ba00bd 100644--- a/clearcam/SceneDelegate.m+++ b/clearcam/SceneDelegate.m@@ -2,6 +2,7 @@#import "ViewController.h" // Import your main view controller#import <UIKit/UIKit.h>#import <CommonCrypto/CommonCryptor.h>+#import "SecretManager.h"@interface SceneDelegate () <UIDocumentInteractionControllerDelegate>@@ -113,7 +114,7 @@}- (void)handleAESFile:(NSURL *)aesFileURL {- NSError *error = nil; // Declare error as a local variable+ NSError *error = nil;NSFileManager *fileManager = [NSFileManager defaultManager];// Log the file path for debugging@@ -126,7 +127,7 @@// Check the download statusNSString *downloadStatus = nil;- NSError *downloadError = nil; // Temporary error variable for getResourceValue+ NSError *downloadError = nil;[aesFileURL getResourceValue:&downloadStatus forKey:NSURLUbiquitousItemDownloadingStatusKey error:&downloadError];if (downloadError) {NSLog(@"Error checking iCloud download status: %@", downloadError.localizedDescription);@@ -139,7 +140,7 @@if (![downloadStatus isEqualToString:NSURLUbiquitousItemDownloadingStatusCurrent]) {// File is not downloaded locally, initiate downloadNSLog(@"File is not downloaded locally. Starting download...");- NSError *downloadStartError = nil; // Temporary error variable for startDownloading+ NSError *downloadStartError = nil;[fileManager startDownloadingUbiquitousItemAtURL:aesFileURL error:&downloadStartError];if (downloadStartError) {NSLog(@"Failed to start downloading iCloud file: %@", downloadStartError.localizedDescription);@@ -162,13 +163,13 @@// Use NSFileCoordinator to safely read the fileNSFileCoordinator *fileCoordinator = [[NSFileCoordinator alloc] initWithFilePresenter:nil];- NSError *coordinationError = nil; // Temporary error variable for coordination+ NSError *coordinationError = nil;[fileCoordinator coordinateReadingItemAtURL:aesFileURLoptions:0error:&coordinationErrorbyAccessor:^(NSURL *newURL) {// Read the .aes file data securely- NSError *readError = nil; // Temporary error variable for reading+ NSError *readError = nil;NSData *encryptedData = [NSData dataWithContentsOfURL:newURL options:0 error:&readError];if (!encryptedData) {NSLog(@"Failed to read .aes file: %@", readError.localizedDescription);@@ -177,53 +178,131 @@}NSLog(@"Read .aes file successfully. Size: %lu bytes", (unsigned long)encryptedData.length);- // Decrypt the data- NSString *key = @"opensesame"; // Hardcoded key (insecure, consider using Keychain)- NSData *decryptedData = [self decryptData:encryptedData withKey:key];+ // Attempt to decrypt the data using stored keys+ NSArray<NSString *> *storedKeys = [[SecretManager sharedManager] getAllStoredKeys];+ __block NSData *decryptedData = nil; // Add __block specifier+ __block NSString *successfulKey = nil; // Add __block specifier++ // Try each stored key+ for (NSString *key in storedKeys) {+ decryptedData = [self decryptData:encryptedData withKey:key];+ if (decryptedData) {+ successfulKey = key;+ break;+ }+ }++ // If no stored key worked, prompt the user for a keyif (!decryptedData) {- NSLog(@"Failed to decrypt data.");- [self showErrorAlertWithMessage:@"Failed to decrypt the file. The key or file may be incorrect."];- return;+ [self promptUserForKeyWithCompletion:^(NSString *userProvidedKey) {+ if (userProvidedKey) {+ decryptedData = [self decryptData:encryptedData withKey:userProvidedKey];+ if (decryptedData) {+ // Save the correct key to the secret manager+ NSError *saveError = nil;+ if (![[SecretManager sharedManager] saveKey:userProvidedKey error:&saveError]) {+ NSLog(@"Failed to save key to SecretManager: %@", saveError.localizedDescription);+ }+ successfulKey = userProvidedKey;+ } else {+ NSLog(@"Failed to decrypt data with user-provided key.");+ [self showErrorAlertWithMessage:@"Failed to decrypt the file. The key or file may be incorrect."];+ return;+ }+ } else {+ NSLog(@"User canceled key entry.");+ [self showErrorAlertWithMessage:@"Decryption canceled. A valid key is required to decrypt the file."];+ return;+ }++ // Proceed with file handling if decryption succeeded+ [self handleDecryptedData:decryptedData fromURL:aesFileURL];+ }];+ return; // Exit the accessor block to wait for user input}- NSLog(@"Decrypted data successfully. Size: %lu bytes", (unsigned long)decryptedData.length);- // Remove only the .aes extension- NSString *fileName = [aesFileURL lastPathComponent];- if ([fileName hasSuffix:@".aes"]) {- fileName = [fileName stringByReplacingOccurrencesOfString:@".aes" withString:@"" options:NSBackwardsSearch range:NSMakeRange(0, fileName.length)];+ // If decryption succeeded with a stored key, proceed immediately+ if (decryptedData) {+ [self handleDecryptedData:decryptedData fromURL:aesFileURL];}- //todo, can be any file type- NSURL *jpgFileURL = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask][0] URLByAppendingPathComponent:fileName];+ }];+ if (coordinationError) {+ NSLog(@"File coordination failed: %@", coordinationError.localizedDescription);+ [self showErrorAlertWithMessage:[NSString stringWithFormat:@"File access failed: %@", coordinationError.localizedDescription]];+ }+}- NSError *writeError = nil; // Temporary error variable for writing- [decryptedData writeToURL:jpgFileURL options:NSDataWritingAtomic error:&writeError];- if (writeError) {- NSLog(@"Failed to save .jpg file: %@", writeError.localizedDescription);- [self showErrorAlertWithMessage:[NSString stringWithFormat:@"Failed to save the decrypted file: %@", writeError.localizedDescription]];- return;- }+// Helper method to handle decrypted data+- (void)handleDecryptedData:(NSData *)decryptedData fromURL:(NSURL *)aesFileURL {+ NSFileManager *fileManager = [NSFileManager defaultManager];+ NSLog(@"Decrypted data successfully. Size: %lu bytes", (unsigned long)decryptedData.length);- NSLog(@"Decrypted and saved .jpg file: %@", jpgFileURL);+ // Remove only the .aes extension+ NSString *fileName = [aesFileURL lastPathComponent];+ if ([fileName hasSuffix:@".aes"]) {+ fileName = [fileName stringByReplacingOccurrencesOfString:@".aes" withString:@"" options:NSBackwardsSearch range:NSMakeRange(0, fileName.length)];+ }+ // todo: can be any file type+ NSURL *jpgFileURL = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask][0] URLByAppendingPathComponent:fileName];++ NSError *writeError = nil;+ [decryptedData writeToURL:jpgFileURL options:NSDataWritingAtomic error:&writeError];+ if (writeError) {+ NSLog(@"Failed to save .jpg file: %@", writeError.localizedDescription);+ [self showErrorAlertWithMessage:[NSString stringWithFormat:@"Failed to save the decrypted file: %@", writeError.localizedDescription]];+ return;+ }- // Open the .jpg file in the system's photo viewer- [self openImageInPhotoViewer:jpgFileURL];+ NSLog(@"Decrypted and saved .jpg file: %@", jpgFileURL);- // Delete the .aes file after successful decryption and saving- NSError *deleteError = nil;- [fileManager removeItemAtURL:aesFileURL error:&deleteError];- if (deleteError) {- NSLog(@"Failed to delete .aes file: %@", deleteError.localizedDescription);- [self showErrorAlertWithMessage:[NSString stringWithFormat:@"Failed to delete the original file: %@", deleteError.localizedDescription]];- } else {- NSLog(@"Successfully deleted .aes file: %@", aesFileURL.path);- }+ // Open the .jpg file in the system's photo viewer+ [self openImageInPhotoViewer:jpgFileURL];++ // Delete the .aes file after successful decryption and saving+ NSError *deleteError = nil;+ [fileManager removeItemAtURL:aesFileURL error:&deleteError];+ if (deleteError) {+ NSLog(@"Failed to delete .aes file: %@", deleteError.localizedDescription);+ [self showErrorAlertWithMessage:[NSString stringWithFormat:@"Failed to delete the original file: %@", deleteError.localizedDescription]];+ } else {+ NSLog(@"Successfully deleted .aes file: %@", aesFileURL.path);+ }+}++// Method to prompt the user for a key+- (void)promptUserForKeyWithCompletion:(void (^)(NSString *))completion {+ UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Enter Decryption Key"+ message:@"Please provide the key to decrypt the file."+ preferredStyle:UIAlertControllerStyleAlert];++ [alert addTextFieldWithConfigurationHandler:^(UITextField *textField) {+ textField.placeholder = @"Decryption Key";+ textField.secureTextEntry = YES; // Hide input for security}];- if (coordinationError) {- NSLog(@"File coordination failed: %@", coordinationError.localizedDescription);- [self showErrorAlertWithMessage:[NSString stringWithFormat:@"File access failed: %@", coordinationError.localizedDescription]];+ UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"OK"+ style:UIAlertActionStyleDefault+ handler:^(UIAlertAction * _Nonnull action) {+ NSString *key = alert.textFields.firstObject.text;+ completion(key);+ }];++ UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"Cancel"+ style:UIAlertActionStyleCancel+ handler:^(UIAlertAction * _Nonnull action) {+ completion(nil); // User canceled+ }];++ [alert addAction:okAction];+ [alert addAction:cancelAction];++ // Present the alert (assumes this is called from a view controller)+ UIViewController *topController = [UIApplication sharedApplication].keyWindow.rootViewController;+ while (topController.presentedViewController) {+ topController = topController.presentedViewController;}+ [topController presentViewController:alert animated:YES completion:nil];}- (void)openImageInPhotoViewer:(NSURL *)imageURL {@@ -311,6 +390,7 @@[self.window.rootViewController presentViewController:alert animated:YES completion:nil];}+#pragma mark - UIDocumentInteractionControllerDelegate- (UIViewController *)documentInteractionControllerViewControllerForPreview:(UIDocumentInteractionController *)controller {diff --git a/clearcam/SceneState.m b/clearcam/SceneState.mindex f409bff..2a8cad2 100644--- a/clearcam/SceneState.m+++ b/clearcam/SceneState.m@@ -169,7 +169,7 @@}- (void)sendEmailWithImageAtPath:(NSString *)imagePath encryptImage:(BOOL)encryptImage {- NSString *server = @"http://192.168.1.100:8080";+ NSString *server = @"http://192.168.1.113:8080";NSString *endpoint = @"/";NSString *toEmail = [[NSUserDefaults standardUserDefaults] stringForKey:@"user_email"];if (!toEmail) return;diff --git a/clearcam/SecretManager.h b/clearcam/SecretManager.hnew file mode 100644index 0000000..2692104--- /dev/null+++ b/clearcam/SecretManager.h@@ -0,0 +1,25 @@+#ifndef SecretManager_h+#define SecretManager_h++#import <Foundation/Foundation.h>++@interface SecretManager : NSObject++// Singleton instance++ (instancetype)sharedManager;++// Retrieve all stored keys from the Keychain+- (NSArray<NSString *> *)getAllStoredKeys;++// Save a key to the Keychain+- (BOOL)saveKey:(NSString *)key error:(NSError **)error;++// Delete a specific key from the Keychain using its identifier+- (BOOL)deleteKeyWithIdentifier:(NSString *)identifier error:(NSError **)error;++// Delete all keys from the Keychain+- (BOOL)deleteAllKeysWithError:(NSError **)error;++@end++#endif /* SecretManager_h */diff --git a/clearcam/SecretManager.m b/clearcam/SecretManager.mnew file mode 100644index 0000000..cb9a456--- /dev/null+++ b/clearcam/SecretManager.m@@ -0,0 +1,170 @@+#import "SecretManager.h"+#import <Security/Security.h>++static NSString *const kServiceIdentifier = @"com.yourapp.aeskeys"; // Replace with your app's unique identifier++@implementation SecretManager++#pragma mark - Singleton+++ (instancetype)sharedManager {+ static SecretManager *sharedInstance = nil;+ static dispatch_once_t onceToken;+ dispatch_once(&onceToken, ^{+ sharedInstance = [[SecretManager alloc] init];+ });+ return sharedInstance;+}++#pragma mark - Key Retrieval++- (NSArray<NSString *> *)getAllStoredKeys {+ NSMutableArray<NSString *> *keys = [NSMutableArray array];++ // Query the Keychain for all stored keys+ NSDictionary *query = @{+ (__bridge id)kSecClass: (__bridge id)kSecClassGenericPassword,+ (__bridge id)kSecAttrService: kServiceIdentifier,+ (__bridge id)kSecReturnAttributes: @YES,+ (__bridge id)kSecReturnData: @YES,+ (__bridge id)kSecMatchLimit: (__bridge id)kSecMatchLimitAll+ };++ CFTypeRef result = NULL;+ OSStatus status = SecItemCopyMatching((__bridge CFDictionaryRef)query, &result);+ if (status == errSecSuccess) {+ NSArray *items = (__bridge_transfer NSArray *)result;+ for (NSDictionary *item in items) {+ NSData *keyData = item[(__bridge id)kSecValueData];+ if (keyData) {+ NSString *key = [[NSString alloc] initWithData:keyData encoding:NSUTF8StringEncoding];+ if (key) {+ [keys addObject:key];+ }+ }+ }+ } else if (status != errSecItemNotFound) {+ NSLog(@"Failed to retrieve keys from Keychain: %d", (int)status);+ }++ return [keys copy];+}++#pragma mark - Key Storage++- (BOOL)saveKey:(NSString *)key error:(NSError **)error {+ if (!key) {+ if (error) {+ *error = [NSError errorWithDomain:@"SecretManagerErrorDomain"+ code:-1+ userInfo:@{NSLocalizedDescriptionKey: @"Key cannot be nil."}];+ }+ return NO;+ }++ // Convert key to data+ NSData *keyData = [key dataUsingEncoding:NSUTF8StringEncoding];++ // Create a unique identifier for the key (e.g., UUID)+ NSString *keyIdentifier = [[NSUUID UUID] UUIDString];++ // Keychain query to add the key+ NSDictionary *query = @{+ (__bridge id)kSecClass: (__bridge id)kSecClassGenericPassword,+ (__bridge id)kSecAttrService: kServiceIdentifier,+ (__bridge id)kSecAttrAccount: keyIdentifier,+ (__bridge id)kSecValueData: keyData,+ (__bridge id)kSecAttrAccessible: (__bridge id)kSecAttrAccessibleWhenUnlocked // Restrict access to when device is unlocked+ };++ // Delete any existing item with the same identifier (optional, to avoid duplicates)+ SecItemDelete((__bridge CFDictionaryRef)query);++ // Add the key to the Keychain+ OSStatus status = SecItemAdd((__bridge CFDictionaryRef)query, NULL);+ if (status != errSecSuccess) {+ NSLog(@"Failed to save key to Keychain: %d", (int)status);+ if (error) {+ *error = [NSError errorWithDomain:@"SecretManagerErrorDomain"+ code:status+ userInfo:@{NSLocalizedDescriptionKey: [self errorMessageForStatus:status]}];+ }+ return NO;+ }++ NSLog(@"Successfully saved key to Keychain with identifier: %@", keyIdentifier);+ return YES;+}++#pragma mark - Key Deletion++- (BOOL)deleteKeyWithIdentifier:(NSString *)identifier error:(NSError **)error {+ if (!identifier) {+ if (error) {+ *error = [NSError errorWithDomain:@"SecretManagerErrorDomain"+ code:-1+ userInfo:@{NSLocalizedDescriptionKey: @"Identifier cannot be nil."}];+ }+ return NO;+ }++ // Keychain query to delete the key+ NSDictionary *query = @{+ (__bridge id)kSecClass: (__bridge id)kSecClassGenericPassword,+ (__bridge id)kSecAttrService: kServiceIdentifier,+ (__bridge id)kSecAttrAccount: identifier+ };++ OSStatus status = SecItemDelete((__bridge CFDictionaryRef)query);+ if (status != errSecSuccess && status != errSecItemNotFound) {+ NSLog(@"Failed to delete key from Keychain: %d", (int)status);+ if (error) {+ *error = [NSError errorWithDomain:@"SecretManagerErrorDomain"+ code:status+ userInfo:@{NSLocalizedDescriptionKey: [self errorMessageForStatus:status]}];+ }+ return NO;+ }++ NSLog(@"Successfully deleted key from Keychain with identifier: %@", identifier);+ return YES;+}++- (BOOL)deleteAllKeysWithError:(NSError **)error {+ // Keychain query to delete all keys for this service+ NSDictionary *query = @{+ (__bridge id)kSecClass: (__bridge id)kSecClassGenericPassword,+ (__bridge id)kSecAttrService: kServiceIdentifier+ };++ OSStatus status = SecItemDelete((__bridge CFDictionaryRef)query);+ if (status != errSecSuccess && status != errSecItemNotFound) {+ NSLog(@"Failed to delete all keys from Keychain: %d", (int)status);+ if (error) {+ *error = [NSError errorWithDomain:@"SecretManagerErrorDomain"+ code:status+ userInfo:@{NSLocalizedDescriptionKey: [self errorMessageForStatus:status]}];+ }+ return NO;+ }++ NSLog(@"Successfully deleted all keys from Keychain.");+ return YES;+}++#pragma mark - Helper Methods++- (NSString *)errorMessageForStatus:(OSStatus)status {+ switch (status) {+ case errSecDuplicateItem:+ return @"A key with this identifier already exists.";+ case errSecItemNotFound:+ return @"The requested key was not found.";+ case errSecAuthFailed:+ return @"Authentication failed.";+ default:+ return [NSString stringWithFormat:@"Keychain error %d occurred.", (int)status];+ }+}++@end