diff --git a/SoObjects/SOGo/NSString+Utilities.h b/SoObjects/SOGo/NSString+Utilities.h index 636612dc4..19a6d33c9 100644 --- a/SoObjects/SOGo/NSString+Utilities.h +++ b/SoObjects/SOGo/NSString+Utilities.h @@ -76,6 +76,8 @@ /* OpenSSL multiline DN */ - (NSArray *) componentsFromMultilineDN; +/* XSS protection */ +- (NSString *) removeHTMLTagsExceptAnchorTags; - (NSString *) stringWithoutHTMLInjection: (BOOL)stripHTMLCode; #ifndef GNUSTEP_BASE_LIBRARY diff --git a/SoObjects/SOGo/NSString+Utilities.m b/SoObjects/SOGo/NSString+Utilities.m index d5b77c62d..31f6291be 100644 --- a/SoObjects/SOGo/NSString+Utilities.m +++ b/SoObjects/SOGo/NSString+Utilities.m @@ -903,6 +903,28 @@ static int cssEscapingCount; return result; } +/** + * Remove all HTML tags except for + * @return A clean string + */ +- (NSString *)removeHTMLTagsExceptAnchorTags { + NSError *error; + NSRegularExpression *regex; + NSString *stringWithoutHTML; + + error = nil; + + regex = [NSRegularExpression regularExpressionWithPattern: @"<(?!a|\\/a\\b)[^>]*>" options: NSRegularExpressionCaseInsensitive error: &error]; + stringWithoutHTML = [regex stringByReplacingMatchesInString: self options: 0 range: NSMakeRange(0, [self length]) withTemplate:@""]; + + if (error) { + [self logWithFormat: @"Error while removing tags : %@", [error localizedDescription]]; + return self; + } + + return stringWithoutHTML; +} + /** * Get the safe string avoiding HTML injection * @param stripHTMLCode Remove all HTML code from content diff --git a/Tests/Unit/TestNSString+Utilities.m b/Tests/Unit/TestNSString+Utilities.m index d1384932e..71ccd0825 100644 --- a/Tests/Unit/TestNSString+Utilities.m +++ b/Tests/Unit/TestNSString+Utilities.m @@ -118,5 +118,9 @@ testEquals([[NSString stringWithString:@"
"] cleanInvalidHTMLTags], @""); } +- (void) test_stringRemoveHTMLTagsExceptAnchorTags +{ + testEquals([[NSString stringWithString:@"