Check if function returns true Objective-C - objective-c

I am wanting to check that when a function returns a true value then NSLog(#"hello!!!"); Just to confirm, I wish to check that validUrl returns true. I have declared the controller that it is inside, and this is the complete code:
NewInAppWebViewController *webViewController = [[NewInAppWebViewController alloc] init];
if([webViewController validUrl:(NSURL *)url] == true) {
NSLog(#"hello!!!");
}
else
{
[self showAlertForExternalURL:url];
}
Below is the function:
- (BOOL)validUrl:(NSURL*)url {
NSString *stringURL = [url absoluteString];
if([stringURL length]==0){
return false;
}
NSString *regExPattern = #"www-(test|testing[a-z]|newtest)\.testerer\.com";
NSRegularExpression *regEx = [[NSRegularExpression alloc] initWithPattern:regExPattern options:NSRegularExpressionCaseInsensitive error:nil];
NSUInteger regExMatches = [regEx numberOfMatchesInString:stringURL options:0 range:NSMakeRange(0, [stringURL length])];
NSLog(#"%i", regExMatches);
if (regExMatches == 0) {
return false;
} else {
return true;
}
}

Try below code:
Pass NSURL to method parameter and call method as follows:
NewInAppWebViewController *webViewController = [[NewInAppWebViewController alloc] init];
NSURL *url=yourNSURLHere;
if([webViewController validUrl:url]) {
NSLog(#"hello!!!");
}
else{
[self showAlertForExternalURL:url];
}

Related

NSPredicate - predicateWithFormat insecure

I have a predicate for query in core data base but i don't know what is the correct way to validate its params?
- (void) queryToDatabaseWithStoreId:(NSInteger) storeId {
[NSPredicate predicateWithFormat:#"store.storeId = %d", storeId];
}
My question is how can i validate storeId param or what i need to use for that vulnerability to dissapear?
And if i have a list:
- (void) queryToDataBaseWithListStore:(NSArray<Store *> *) storeList {
[NSPredicate predicateWithFormat:#"store.storeId IN %#", [storeList valueForObject:#"storeId"]];
}
https://developer.apple.com/library/archive/documentation/Security/Conceptual/SecureCodingGuide/Articles/ValidatingInput.html#//apple_ref/doc/uid/TP40007246-SW3
I need avoid that:
The following commonly-used functions and methods are subject to format-string attacks:
Standard C
printf and other functions listed on the printf(3) manual page
sscanf and other functions listed on the scanf(3) manual page
syslog and vsyslog
Carbon
AEBuildDesc and vAEBuildDesc
AEBuildParameters and vAEBuildParameters
AEBuildAppleEvent and vAEBuildAppleEvent
Core Foundation
CFStringCreateWithFormat
CFStringCreateWithFormatAndArguments
CFStringAppendFormat
CFStringAppendFormatAndArguments
Cocoa
stringWithFormat:, initWithFormat:, and other NSString methods that take formatted strings as arguments
appendFormat: in the NSMutableString class
alertWithMessageText:defaultButton:alternateButton:otherButton:informativeTextWithFormat: in NSAlert
predicateWithFormat:, predicateWithFormat:arguments:, and predicateWithFormat:argumentArray: in NSPredicate
raise:format: and raise:format:arguments: in NSException
NSRunAlertPanel and other AppKit functions that create or return panels or sheets
What is the best way to avoid this attack?
I have programmed this class but i don't know if it is enough.
#implementation StringUtils
+ (BOOL) isEmpty:(id) text {
if ([text isKindOfClass:[NSNull class]]) {
return YES;
} else {
if (text) {
if ([text isKindOfClass:[NSString class]]) {
NSString *textStr = [NSString stringWithFormat:#"%#", text];
return [textStr isEqualToString:#""];
}
return YES;
} else {
return YES;
}
}
}
+ (NSString *) validateField:(id) text {
NSInteger numErrors = 0;
NSString *pattern = #"[^A-Za-z0-9-]+";
NSError *error = nil;
NSString *textValidated = #"";
if ([text isKindOfClass:[NSNumber class]]) {
textValidated = [text stringValue];
} else if ([text isKindOfClass:[NSString class]]) {
textValidated = text;
} else {
#try {
textValidated = [text stringValue];
} #catch (NSException *exception) {
numErrors=+1;
}
}
//Only numbers && chars && -
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern options:0 error:&error];
NSRange textRange = NSMakeRange(0, textValidated.length);
NSRange matchRange = [regex rangeOfFirstMatchInString:textValidated options:NSMatchingReportProgress range:textRange];
if (matchRange.location != NSNotFound) {
numErrors+=1;
}
//Not empty string
if ([StringUtils isEmpty:textValidated]) {
numErrors+=1;
}
if (numErrors == 0) {
return textValidated;
}
return #"";
}
+ (NSArray *) validateArrayFields:(NSArray *) list {
NSInteger *numErrors = 0;
for (id obj in list) {
if ([StringUtils isEmpty:[StringUtils validateField:obj]]) {
numErrors+=1;
}
}
if (numErrors == 0) {
return list;
}
return [[NSArray alloc] init];
}
#end
For use normal:
[NSPredicate predicateWithFormat:#"store.storeId = %#", [StringUtils validateField:storeId]];
For use with array:
[NSPredicate predicateWithFormat:#"store.storeId IN %#", [StringUtils validateArrayFields:storeId]];

Does anyone know two NSString_s with the same hashes?

I want to test some cases in my app with strings which have the same hash, and I can't find it =(
I've found two strings with the same MD5. here But their hash are different. And googling didn't help me =(
NSString(MD5) category
Little story about NSDictionary
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
NSString *string1 = [self fileContentWithName:#"message1" encoding:NSUnicodeStringEncoding];
NSString *string2 = [self fileContentWithName:#"message2" encoding:NSUnicodeStringEncoding];
if (string1 != nil) {
if (string1.hash == string2.hash) {
NSLog(#"Hashes are the same");
} else {
if ([[string1 MD5Hash] isEqualToString:[string2 MD5Hash]]) {
NSLog(#"MD5 hases are equalfor:");
NSLog(#"lenght = %3ld - %#", string1.length, string1);
NSLog(#"lenght = %3ld - %#", string2.length, string2);
if ([string1 isEqualToString:string2]) {
NSLog(#"Strings are equal too");
} else {
NSLog(#"But strings are not equal");
}
}
}
}
}
#pragma mark -
- (NSString*)fileContentWithName:(NSString*)name encoding:(NSStringEncoding)enc
{
NSString *txtFilePath1 = [[NSBundle mainBundle] pathForResource:name ofType:#"bin"];
NSError *error = nil;
NSString *txtFileContents1 = [NSString stringWithContentsOfFile:txtFilePath1 encoding:enc error:&error];
return txtFileContents1;
}

NSMutableArray writeToURL:url atomically:YES

I'm trying to create a file with an NSMutableArray with just NSStrings stringWithFormat objects inside, this is what i got:
- (IBAction)CreateMod:(id)sender {
NSLog(#"Finished Button Pressed");
NSString* CustomScript = [NSString stringWithFormat:#"//Made with UltimateMM \n %#",self.CS ];
NSArray* fileTypes = [[NSArray alloc] initWithObjects:#"js", nil];
NSSavePanel *spanel = [NSSavePanel savePanel];
[spanel setCanCreateDirectories:YES];
[spanel setCanSelectHiddenExtension:YES];
[spanel setAllowedFileTypes:fileTypes];
[spanel setTreatsFilePackagesAsDirectories:YES];
[spanel beginSheetModalForWindow:self.SecondaryWindow completionHandler:^(NSInteger result) {
if (result == NSFileHandlingPanelOKButton)
{
NSURL *saveURL = [spanel URL];
NSLog(#"%#", saveURL);
NSError* error = nil;
if(_CST == true) {
NSLog(#"CustomScriptMade");
/*
BOOL didWrite = [CustomScript writeToURL:saveURL atomically:YES encoding:NSUTF8StringEncoding error:&error];
if (didWrite == NO)
{
NSLog(#"CustomScript Write Error");
}
*/
}
if(_TTT == true) {
NSLog(#"TopicMade");
BOOL didWrite = [_TopicPR writeToURL:saveURL atomically:YES];
if (didWrite == NO)
{
NSLog(#"Topic Write Error");
}
}
_CST = false;
_TTT = false;
}
}];
}
I have the CustomScript writeToURL out so i can see if it crates the TopicPR, but it doesn't even open the NSSavePanel, Please Help.
thanks in advance!..

How to check the NSString contains URL or string data?

I am fresher to iOS, i am getting problem at checking string object contains URL or string?
NSMutableArray *Arr=[NSMutableArray alloc]initWithObject:#"Welcome", #"http://abcd.com/Images/bus.png", nil];
int i;
i++;
NSString *str=[Arr objectAtIndex:i];
Now, i want to check condition, if string contains "Welcome", have to display on label or if it is URL , i need to display that URL image in ImageView. So how can i check it? Please help me in this problem.
Instead of initiating both as NSStrings, try differentiating between them by making urls a NSURL (special container specifically for urls):
NSMutableArray* Arr = [NSMutableArray alloc]initWithObject:#"Welcome", [NSURL URLWithString:#"http://abcd.com/Images/bus.png"], nil];
for(id object in Arr)
{
if([object isKindOfClass:[NSString class]])
{
NSString* string = object;
NSLog(#"String: %#", string);
}
else if([object isKindOfClass:[NSURL class]])
{
NSURL* url = object;
NSLog(#"URL: %#", url);
}
}
Try like this
NSMutableArray *Arr=[[NSMutableArray alloc]initWithObjects:#"Welcome", #"http://abcd.com/Images/bus.png",nil];
NSString *st=nil;
for(NSString *string in Arr)
{
NSArray *matches = [detector
matchesInString:string
options:0
range:NSMakeRange(0,
[string length])];
for (NSTextCheckingResult *match in
matches) {
if ([match resultType] ==
NSTextCheckingTypeLink) {
NSURL *url = [match URL];
} else
{
NSlog(#"it is a string");
}
}
}
Try this, it will help you:
NSMutableArray *Arr=[[NSMutableArray alloc]initWithObjects:#"Welcome", #"http://abcd.com/Images/bus.png", nil];
if([Arr count])
{
for (NSString *str in Arr)
{
if([str isEqualToString:#"Welcome"])
{
NSLog(#"str is %#",str);
//do whatever you want
}
if([str isEqualToString:#"http://abcd.com/Images/bus.png"])
{
NSLog(#"str is %#",str);
//do whatever you want
}
}
}
To check NSString is containing a URL You can Try This code
if ([stringName hasPrefix:#"http://"] || [stringName hasPrefix:#"https://"]) {
//show imageVivew
}

why is this code giving me EXC_BAD_ACCESS?

I get the bad access when followLink is called. This does not happen if I paste the openURL line into textContainsURL, so I'm assuming the object no longer exists once the method finishes? I'm new to this but I though ARC was supposed to handle this sort of thing for you?
#interface MyViewController : UIViewController
{
NSURL *newsURL;
}
#end
following is in the implementation:
- (void)followLink
{
[[UIApplication sharedApplication]openURL:newsURL];
}
- (BOOL)textContainsURL:(NSString*)text
{
NSError *error = NULL;
//scan text to see if there is a link and only set this up if there is
NSDataDetector *detector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypeLink error:&error];
NSArray *matches = [detector matchesInString:text
options:0
range:NSMakeRange(0, [text length])];
for (NSTextCheckingResult *match in matches)
{
//NSRange matchRange = [match range];
if ([match resultType] == NSTextCheckingTypeLink)
{
newsURL = [[NSURL alloc] init];
newsURL = [match URL];//what's the void state? retain it
return YES;
}
}
return NO;
}
You should copy the matched URL to your newsURL ivar or make your newsURL ivar a copy property and set the value through the accessor method. In your current code the URL is autoreleased.