SlideShare uma empresa Scribd logo
1 de 54
Baixar para ler offline
WebView security on iOS
Łukasz Pilorz"
!
OWASP Poland meeting, 29 Jan 2014
Thank you:
browser-shredders.blogspot.com

Mike Tigas
Theory
[webView loadRequest:
[NSURLRequest requestWithURL:
[NSURL URLWithString:@“http://example.com“]
]
];
!
- loadRequest:
!
- loadHTMLString:baseURL:
!
- loadData:MIMEType:

textEncodingName:baseURL:
!
- stringByEvaluatingJavaScriptFromString:
!
- goBack
!
- goForward
!
- stopLoading
!
- reload
!
id<UIWebViewDelegate> delegate"
!
NSURLRequest request"
!
UIDataDetectorTypes dataDetectorTypes"
!
enum {
UIDataDetectorTypePhoneNumber = 1 << 0,
UIDataDetectorTypeLink = 1 << 1,
UIDataDetectorTypeAddress = 1 << 2,
UIDataDetectorTypeCalendarEvent = 1 << 3,
UIDataDetectorTypeNone = 0,
UIDataDetectorTypeAll = NSUIntegerMax
}
!
…
!
https://developer.apple.com/library/ios/documentation/
uikit/reference/UIWebView_Class/Reference/
Reference.html
UIWebViewDelegate
– webView:shouldStartLoadWithRequest:navigationType:
– webViewDidStartLoad:
– webViewDidFinishLoad:
– webView:didFailLoadWithError:
Questions:

How to recognize whether navigation happened in top document or a frame?

How to block images or JavaScript?

Can webViewDidFinishLoad not happen after webViewDidStartLoad?

Can webViewDidStartLoad not happen before webViewDidFinishLoad?
Limitations
• Lack of Nitro
• HTTP 401 not supported natively
• No option to turn off JavaScript
• [Also applies to Mobile Safari]

Content-Disposition: attachment; filename=“download.html”

Content-Type: text/plain

- guess how will UIWebView behave (see CVE-2011-3426, CVE-2013-5151)
• Blocks JavaScript on scrolling
• Limited support for target attribute and window.open() ~ document.location.assign()
• Does not support RSS
Practice
Advantages
• Content update without App Store update
• HTML5 + JavaScript + CSS
• Possibility to re-use code on many platforms

(+ Apache Cordova / PhoneGap)
• .html / .key / .numbers / .pages / .xls / .pdf / .ppt / .doc / .rftd.zip / .rtf
• Automatic SSL certificate verification
• Same Origin Policy… non-standard one
Security guidelines
• “Ensure that all UIWebView calls do not execute without proper input validation. Apply filters
for dangerous JavaScript characters if possible, using a whitelist over blacklist character
policy before rendering. If possible call mobile Safari instead of rending inside of UIWebView
which has access to your application.” (OWASP Mobile Top 10)
• “[…] maintain control of all UIWebView content and pages, and prevent the user from
accessing arbitrary, untrusted web content.” (OWASP iOS Developer Cheat Sheet)
• “Inspect remote content via the use of the NSData class method dataWithContentsOfURL
in an attempt to prohibit the loading of malicious script into a UIWebview. Do not load
content remotely and then process the data returned before passing to a UIWebview (if
at all avoidable) otherwise you grant local file system access to any malicious script that
smuggles itself past your content inspectors.” (MWR Labs blog)
• Sounds dangerous… :-)
UIWebView in iOS applications
• Chrome
• Coast
• Facebook
• SkyDrive
• Skype
• WinZip
• and hundreds of others
Secure UIWebView - how to start?
Requirements:
• without reducing planned functionality
• without spending weeks on building content filters

(and further ones on maintenance and fixes)
• minimal amount of code added
• efficiently
Step 1
Probably NO, if it’s mobile banking:

http://blog.ioactive.com/2014/01/personal-banking-apps-leak-info-
through.html
Is UIWebView needed in your application?
YES
!
NO



These aren't the droids we're looking for.
You can go about your business.
Step 2
Do the documents, which you intend to display,
need to be displayed in your application?
YES
!
!
!
NO
!
Use Safari,

Chrome (x-callback-url?)

or another available browser
Step 3
Is the presented document loaded directly through HTTP?
YES
- loadRequest(…)
!
Use https://
!
Don’t turn off SSL

certificate validation
NO
- data passed locally

!
!
!
Remember to set baseURL"
!
- loadRequest:
!
- loadHTMLString:baseURL:
!
- loadData:MIMEType:

textEncodingName:baseURL:
!
- stringByEvaluatingJavaScriptFromString:
!
- goBack
!
- goForward
!
- stopLoading
!
- reload
baseURL vs Same Origin Policy
• file:/// can read local files and any URLs - dangerous!
• nil/NULL == applewebdata:

same privileges as file: - dangerous!
• by default UIWebView assumes file://

(@“test” == @“file://test”)
• for http(s):// standard Same Origin Policy applies
• for about: and data: also, but with separate origin context
<script>

a = document.location.href.split('/');

if(a[0]==='file:') {

path = ‘file:///'+a[3]+'/'+a[4]+'/'+a[5]+'/'+a[6]+'/'+a[7]

+'/Library/Cookies/Cookies.binarycookies';

x = new XMLHttpRequest();

x.open('GET', path, false);

x.send();

alert(x.responseText);

}

</script>
[webView

loadHTMLString:

[NSString stringWithContentsOfFile:@“/sciezka/do/pliku.html”

encoding:NSUTF8StringEncoding

error:&error]

baseURL:[NSURL URLWithString:@“about:blank”]];
!
Potential problem: images, CSS etc. won’t be loaded from file:///
Example: Chrome for iOS
<!-- CVE-2012-2899 -->
!
<script>
function test() {
pop = window.open('about:blank', '_blank');
pop.document.write(
'<script>document.write(document.location)</scr'
+'ipt><br><iframe src=“http://example.com/“'
+'onload="alert(this.contentDocument.body.innerHTML)"></iframe>'
);
}
</script>
<input type="button" onclick="test()" value=“Click">
Example: Coast by Opera
http://www.youtube.com/watch?v=_J-qe61_tAQ
Demo
Step 4
Do you have control over the content loaded to UIWebView?
YES
- I have control over content
!
Make sure the documents are not
vulnerable to XSS
NO
- I don’t have control over content
!
Can the user recognize origin?

!
Use CSP or HTML sandbox
User interface
• clear separation of trusted and untrusted content
• address bar with current URL



webView.request.mainDocumentURL.absoluteString

vs

[webView stringByEvaluatingJavaScriptFromString:@"window.location.href"]
• SSL indicator
• warning before first display of untrusted document
• other ideas?
Cross-Site Scripting
• Stored (server-side or in the application)
• Reflected (watch for URL scheme handlers)
• DOM-based (!)
• [webView stringByEvaluatingJavaScriptFromString:[NSString
stringWithFormat:@"document.body.innerText='%@'", input]];
Cross-Site Scripting/JavaScript Injection
input: ';alert(0)//🌙ꆁ
!
[webView stringByEvaluatingJavaScriptFromString:[NSString
stringWithFormat:@"document.body.innerText='%@'", input]];
!
document.body.innerText='';alert(0)//🌙ꆁ'
- (NSString*) escapeForJavaScript:(NSString*)fromString
{
NSString *toString = @"";
for(int i=0;i<fromString.length;i++) {
toString = [NSString stringWithFormat:@“%@u%04X",
toString, [fromString characterAtIndex:i]
];
}
return toString;
}
escapeForJavaScript
input: ‘;alert(0)//🌙ꆁ
!
[webView stringByEvaluatingJavaScriptFromString:[NSString

stringWithFormat:@"document.body.innerText='%@'",

[self escapeForJavaScript:input]
]];
document.body.innerText='u0027u003Bu0061u006C
u0065u0072u0074u0028u0030u0029u002Fu002FuD83C
uDF19uA181'
innerHTML
[webView stringByEvaluatingJavaScriptFromString:[NSString

stringWithFormat:@"document.body.innerHTML='%@'",

[self escapeForJavaScript:input]
]];
!
Question: why the above code is not secure?
innerHTML
input: <img src=x onerror=alert(0)>
!
[webView stringByEvaluatingJavaScriptFromString:[NSString

stringWithFormat:@"document.body.innerHTML='%@'",

[self escapeForJavaScript:input]
]];
document.body.innerHTML='u003Cu0069u006D
u0067u0020u0073u0072u0063u003Du0078u0020u006F
u006Eu0065u0072u0072u006Fu0072u003Du0061u006C
u0065u0072u0074u0028u0030u0029u003E'
Step 5
Additional security
Whitelisting allowed URLs
!
http
https
data
about
Turning off JavaScript

!
Content-Security-Policy
HTML5 Sandbox
!
What can go wrong?
[webView loadRequest:

[NSURLRequest requestWithURL:
[NSURL URLWithString:@“https://unknown.tld/untrusted.php“]

]

];
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response
{
NSMutableDictionary *mHeaders = [NSMutableDictionary dictionary];
NSString *CSP = @"default-src 'none'; img-src *;style-src 'unsafe-inline' *;child-src *;frame-src *;sandbox allow-
forms allow-top-navigation";
for(id h in response.allHeaderFields) {
if(![[h lowercaseString] isEqualToString:@"content-security-policy"]

&& ![[h lowercaseString] isEqualToString:@"x-webkit-csp"]) {
[mHeaders setObject:response.allHeaderFields[h] forKey:h];
}
}
[mHeaders setObject:CSP forKey:@"Content-Security-Policy"];
[mHeaders setObject:CSP forKey:@"X-Webkit-CSP"];
NSHTTPURLResponse *mResponse = [[NSHTTPURLResponse alloc]

initWithURL:response.URL statusCode:response.statusCode

HTTPVersion:@"HTTP/1.1" headerFields:mHeaders
];
[self.client URLProtocol:self didReceiveResponse:mResponse

cacheStoragePolicy:NSURLCacheStorageNotAllowed
];
}
?
//<UIWebViewDelegate>

- (BOOL)webView:(UIWebView *)webView

shouldStartLoadWithRequest:(NSURLRequest *)request 

navigationType:(UIWebViewNavigationType)navigationType

{

if([request.URL.scheme isEqualToString:@"http"

|| [request.URL.scheme isEqualToString:@"https"]

|| [request.URL.scheme isEqualToString:@"about"]

|| [request.URL.scheme isEqualToString:@“data”]) {

return YES;

}

return NO;

}
Question: Will the above code block javascript: URLs? Where?
Step 6
What did we forget?
Pentest
Cordova/PhoneGap
!
and other
Javascript/Objective-C bridges
…
Links
(OWASP)
• https://www.owasp.org/index.php/IOS_Application_Security_Testing_Cheat_Sheet
• https://www.owasp.org/index.php/IOS_Developer_Cheat_Sheet
!
(iOS)
• http://www.apple.com/business/accelerator/develop/security.html & https://developer.apple.com/videos/wwdc/2010/
• http://stackoverflow.com/questions/3496505/differences-between-uiwebview-and-mobile-safari
!
(CSP)
• https://www.owasp.org/images/2/2b/Oxdef_csp_poland.pdf & http://niebezpiecznik.pl/OWASP2013-Krakow-CSP.pdf
• http://lists.w3.org/Archives/Public/public-webappsec/2012Mar/0043.html
http://browser-shredders.blogspot.com
Teaser: Breaking iOS browsers (before it will be cool ;-)
lukasz.pilorz@runic.pl
WebView security on iOS (EN)

Mais conteúdo relacionado

Mais procurados

Mais procurados (20)

Chapter 2 c#
Chapter 2 c#Chapter 2 c#
Chapter 2 c#
 
javaScript.ppt
javaScript.pptjavaScript.ppt
javaScript.ppt
 
Autoboxing And Unboxing In Java
Autoboxing And Unboxing In JavaAutoboxing And Unboxing In Java
Autoboxing And Unboxing In Java
 
Introduction to the Web API
Introduction to the Web APIIntroduction to the Web API
Introduction to the Web API
 
Php sessions & cookies
Php sessions & cookiesPhp sessions & cookies
Php sessions & cookies
 
Security Vulnerabilities
Security VulnerabilitiesSecurity Vulnerabilities
Security Vulnerabilities
 
Oops concept on c#
Oops concept on c#Oops concept on c#
Oops concept on c#
 
Python sqlite3
Python sqlite3Python sqlite3
Python sqlite3
 
PHP Security
PHP SecurityPHP Security
PHP Security
 
Python :variable types
Python :variable typesPython :variable types
Python :variable types
 
Understanding java streams
Understanding java streamsUnderstanding java streams
Understanding java streams
 
Directory Traversal & File Inclusion Attacks
Directory Traversal & File Inclusion AttacksDirectory Traversal & File Inclusion Attacks
Directory Traversal & File Inclusion Attacks
 
Why TypeScript?
Why TypeScript?Why TypeScript?
Why TypeScript?
 
SQL Injection and Clickjacking Attack in Web security
SQL Injection and Clickjacking Attack in Web securitySQL Injection and Clickjacking Attack in Web security
SQL Injection and Clickjacking Attack in Web security
 
Packages In Python Tutorial
Packages In Python TutorialPackages In Python Tutorial
Packages In Python Tutorial
 
What’s wrong with WebSocket APIs? Unveiling vulnerabilities in WebSocket APIs.
What’s wrong with WebSocket APIs? Unveiling vulnerabilities in WebSocket APIs.What’s wrong with WebSocket APIs? Unveiling vulnerabilities in WebSocket APIs.
What’s wrong with WebSocket APIs? Unveiling vulnerabilities in WebSocket APIs.
 
PHP Functions & Arrays
PHP Functions & ArraysPHP Functions & Arrays
PHP Functions & Arrays
 
Java Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and StreamsJava Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and Streams
 
Swagger UI
Swagger UISwagger UI
Swagger UI
 
Sql Injection - Vulnerability and Security
Sql Injection - Vulnerability and SecuritySql Injection - Vulnerability and Security
Sql Injection - Vulnerability and Security
 

Destaque

WebView security on iOS (PL)
WebView security on iOS (PL)WebView security on iOS (PL)
WebView security on iOS (PL)lpilorz
 
Securing the client side web
Securing the client side webSecuring the client side web
Securing the client side webSC5.io
 
How to Secure Your iOs Device and Keep Client Data Safe
How to Secure Your iOs Device and Keep Client Data SafeHow to Secure Your iOs Device and Keep Client Data Safe
How to Secure Your iOs Device and Keep Client Data SafeRocket Matter, LLC
 
Legal and efficient web app testing without permission
Legal and efficient web app testing without permissionLegal and efficient web app testing without permission
Legal and efficient web app testing without permissionAbraham Aranguren
 
WKWebViewとUIWebView
WKWebViewとUIWebViewWKWebViewとUIWebView
WKWebViewとUIWebViewYuki Hirai
 
iOS-Application-Security-iAmPr3m
iOS-Application-Security-iAmPr3miOS-Application-Security-iAmPr3m
iOS-Application-Security-iAmPr3mPrem Kumar (OSCP)
 
How iOS and Android Handle Security Webinar
How iOS and Android Handle Security WebinarHow iOS and Android Handle Security Webinar
How iOS and Android Handle Security WebinarDenim Group
 
Pentesting iOS Applications
Pentesting iOS ApplicationsPentesting iOS Applications
Pentesting iOS Applicationsjasonhaddix
 

Destaque (9)

WebView security on iOS (PL)
WebView security on iOS (PL)WebView security on iOS (PL)
WebView security on iOS (PL)
 
Securing the client side web
Securing the client side webSecuring the client side web
Securing the client side web
 
How to Secure Your iOs Device and Keep Client Data Safe
How to Secure Your iOs Device and Keep Client Data SafeHow to Secure Your iOs Device and Keep Client Data Safe
How to Secure Your iOs Device and Keep Client Data Safe
 
Legal and efficient web app testing without permission
Legal and efficient web app testing without permissionLegal and efficient web app testing without permission
Legal and efficient web app testing without permission
 
WKWebViewとUIWebView
WKWebViewとUIWebViewWKWebViewとUIWebView
WKWebViewとUIWebView
 
Breaking iOS Apps using Cycript
Breaking iOS Apps using CycriptBreaking iOS Apps using Cycript
Breaking iOS Apps using Cycript
 
iOS-Application-Security-iAmPr3m
iOS-Application-Security-iAmPr3miOS-Application-Security-iAmPr3m
iOS-Application-Security-iAmPr3m
 
How iOS and Android Handle Security Webinar
How iOS and Android Handle Security WebinarHow iOS and Android Handle Security Webinar
How iOS and Android Handle Security Webinar
 
Pentesting iOS Applications
Pentesting iOS ApplicationsPentesting iOS Applications
Pentesting iOS Applications
 

Semelhante a WebView security on iOS (EN)

Client side production monitoring using - SyncApp Tool
Client side production monitoring using - SyncApp ToolClient side production monitoring using - SyncApp Tool
Client side production monitoring using - SyncApp ToolBhupesh Pant
 
Sherlock Homepage - A detective story about running large web services - WebN...
Sherlock Homepage - A detective story about running large web services - WebN...Sherlock Homepage - A detective story about running large web services - WebN...
Sherlock Homepage - A detective story about running large web services - WebN...Maarten Balliauw
 
Developing High Performance Web Apps - CodeMash 2011
Developing High Performance Web Apps - CodeMash 2011Developing High Performance Web Apps - CodeMash 2011
Developing High Performance Web Apps - CodeMash 2011Timothy Fisher
 
The top 10 security issues in web applications
The top 10 security issues in web applicationsThe top 10 security issues in web applications
The top 10 security issues in web applicationsDevnology
 
HTML5 on Mobile
HTML5 on MobileHTML5 on Mobile
HTML5 on MobileAdam Lu
 
[convergese] Adaptive Images in Responsive Web Design
[convergese] Adaptive Images in Responsive Web Design[convergese] Adaptive Images in Responsive Web Design
[convergese] Adaptive Images in Responsive Web DesignChristopher Schmitt
 
WinAppDriver - Windows Store Apps Test Automation
WinAppDriver - Windows Store Apps Test AutomationWinAppDriver - Windows Store Apps Test Automation
WinAppDriver - Windows Store Apps Test AutomationJeremy Kao
 
[Poland] It's only about frontend
[Poland] It's only about frontend[Poland] It's only about frontend
[Poland] It's only about frontendOWASP EEE
 
Browser Hacking For Fun and Profit | Null Bangalore Meetup 2019 | Divyanshu S...
Browser Hacking For Fun and Profit | Null Bangalore Meetup 2019 | Divyanshu S...Browser Hacking For Fun and Profit | Null Bangalore Meetup 2019 | Divyanshu S...
Browser Hacking For Fun and Profit | Null Bangalore Meetup 2019 | Divyanshu S...Divyanshu
 
[Serverless Meetup Tokyo #3] Serverless in Azure (Azure Functionsのアップデート、事例、デ...
[Serverless Meetup Tokyo #3] Serverless in Azure (Azure Functionsのアップデート、事例、デ...[Serverless Meetup Tokyo #3] Serverless in Azure (Azure Functionsのアップデート、事例、デ...
[Serverless Meetup Tokyo #3] Serverless in Azure (Azure Functionsのアップデート、事例、デ...Naoki (Neo) SATO
 
[CB16] Electron - Build cross platform desktop XSS, it’s easier than you thin...
[CB16] Electron - Build cross platform desktop XSS, it’s easier than you thin...[CB16] Electron - Build cross platform desktop XSS, it’s easier than you thin...
[CB16] Electron - Build cross platform desktop XSS, it’s easier than you thin...CODE BLUE
 
W3 conf hill-html5-security-realities
W3 conf hill-html5-security-realitiesW3 conf hill-html5-security-realities
W3 conf hill-html5-security-realitiesBrad Hill
 
JavaScript Performance (at SFJS)
JavaScript Performance (at SFJS)JavaScript Performance (at SFJS)
JavaScript Performance (at SFJS)Steve Souders
 
JavaScript Perfomance
JavaScript PerfomanceJavaScript Perfomance
JavaScript PerfomanceAnatol Alizar
 
Browser Horror Stories
Browser Horror StoriesBrowser Horror Stories
Browser Horror StoriesEC-Council
 
Modern Web Application Defense
Modern Web Application DefenseModern Web Application Defense
Modern Web Application DefenseFrank Kim
 

Semelhante a WebView security on iOS (EN) (20)

Client side production monitoring using - SyncApp Tool
Client side production monitoring using - SyncApp ToolClient side production monitoring using - SyncApp Tool
Client side production monitoring using - SyncApp Tool
 
Sherlock Homepage - A detective story about running large web services - WebN...
Sherlock Homepage - A detective story about running large web services - WebN...Sherlock Homepage - A detective story about running large web services - WebN...
Sherlock Homepage - A detective story about running large web services - WebN...
 
Always on! Or not?
Always on! Or not?Always on! Or not?
Always on! Or not?
 
Developing High Performance Web Apps - CodeMash 2011
Developing High Performance Web Apps - CodeMash 2011Developing High Performance Web Apps - CodeMash 2011
Developing High Performance Web Apps - CodeMash 2011
 
Node azure
Node azureNode azure
Node azure
 
Building Client-Side Attacks with HTML5 Features
Building Client-Side Attacks with HTML5 FeaturesBuilding Client-Side Attacks with HTML5 Features
Building Client-Side Attacks with HTML5 Features
 
The top 10 security issues in web applications
The top 10 security issues in web applicationsThe top 10 security issues in web applications
The top 10 security issues in web applications
 
HTML5 on Mobile
HTML5 on MobileHTML5 on Mobile
HTML5 on Mobile
 
[convergese] Adaptive Images in Responsive Web Design
[convergese] Adaptive Images in Responsive Web Design[convergese] Adaptive Images in Responsive Web Design
[convergese] Adaptive Images in Responsive Web Design
 
WinAppDriver - Windows Store Apps Test Automation
WinAppDriver - Windows Store Apps Test AutomationWinAppDriver - Windows Store Apps Test Automation
WinAppDriver - Windows Store Apps Test Automation
 
[Poland] It's only about frontend
[Poland] It's only about frontend[Poland] It's only about frontend
[Poland] It's only about frontend
 
Browser Hacking For Fun and Profit | Null Bangalore Meetup 2019 | Divyanshu S...
Browser Hacking For Fun and Profit | Null Bangalore Meetup 2019 | Divyanshu S...Browser Hacking For Fun and Profit | Null Bangalore Meetup 2019 | Divyanshu S...
Browser Hacking For Fun and Profit | Null Bangalore Meetup 2019 | Divyanshu S...
 
[Serverless Meetup Tokyo #3] Serverless in Azure (Azure Functionsのアップデート、事例、デ...
[Serverless Meetup Tokyo #3] Serverless in Azure (Azure Functionsのアップデート、事例、デ...[Serverless Meetup Tokyo #3] Serverless in Azure (Azure Functionsのアップデート、事例、デ...
[Serverless Meetup Tokyo #3] Serverless in Azure (Azure Functionsのアップデート、事例、デ...
 
[CB16] Electron - Build cross platform desktop XSS, it’s easier than you thin...
[CB16] Electron - Build cross platform desktop XSS, it’s easier than you thin...[CB16] Electron - Build cross platform desktop XSS, it’s easier than you thin...
[CB16] Electron - Build cross platform desktop XSS, it’s easier than you thin...
 
W3 conf hill-html5-security-realities
W3 conf hill-html5-security-realitiesW3 conf hill-html5-security-realities
W3 conf hill-html5-security-realities
 
Starwest 2008
Starwest 2008Starwest 2008
Starwest 2008
 
JavaScript Performance (at SFJS)
JavaScript Performance (at SFJS)JavaScript Performance (at SFJS)
JavaScript Performance (at SFJS)
 
JavaScript Perfomance
JavaScript PerfomanceJavaScript Perfomance
JavaScript Perfomance
 
Browser Horror Stories
Browser Horror StoriesBrowser Horror Stories
Browser Horror Stories
 
Modern Web Application Defense
Modern Web Application DefenseModern Web Application Defense
Modern Web Application Defense
 

Último

Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 

Último (20)

Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 

WebView security on iOS (EN)

  • 1. WebView security on iOS Łukasz Pilorz" ! OWASP Poland meeting, 29 Jan 2014
  • 4. [webView loadRequest: [NSURLRequest requestWithURL: [NSURL URLWithString:@“http://example.com“] ] ];
  • 5.
  • 6. ! - loadRequest: ! - loadHTMLString:baseURL: ! - loadData:MIMEType:
 textEncodingName:baseURL: ! - stringByEvaluatingJavaScriptFromString: ! - goBack ! - goForward ! - stopLoading ! - reload
  • 7. ! id<UIWebViewDelegate> delegate" ! NSURLRequest request" ! UIDataDetectorTypes dataDetectorTypes" ! enum { UIDataDetectorTypePhoneNumber = 1 << 0, UIDataDetectorTypeLink = 1 << 1, UIDataDetectorTypeAddress = 1 << 2, UIDataDetectorTypeCalendarEvent = 1 << 3, UIDataDetectorTypeNone = 0, UIDataDetectorTypeAll = NSUIntegerMax } ! … ! https://developer.apple.com/library/ios/documentation/ uikit/reference/UIWebView_Class/Reference/ Reference.html
  • 8. UIWebViewDelegate – webView:shouldStartLoadWithRequest:navigationType: – webViewDidStartLoad: – webViewDidFinishLoad: – webView:didFailLoadWithError: Questions:
 How to recognize whether navigation happened in top document or a frame?
 How to block images or JavaScript?
 Can webViewDidFinishLoad not happen after webViewDidStartLoad?
 Can webViewDidStartLoad not happen before webViewDidFinishLoad?
  • 9. Limitations • Lack of Nitro • HTTP 401 not supported natively • No option to turn off JavaScript • [Also applies to Mobile Safari]
 Content-Disposition: attachment; filename=“download.html”
 Content-Type: text/plain
 - guess how will UIWebView behave (see CVE-2011-3426, CVE-2013-5151) • Blocks JavaScript on scrolling • Limited support for target attribute and window.open() ~ document.location.assign() • Does not support RSS
  • 11. Advantages • Content update without App Store update • HTML5 + JavaScript + CSS • Possibility to re-use code on many platforms
 (+ Apache Cordova / PhoneGap) • .html / .key / .numbers / .pages / .xls / .pdf / .ppt / .doc / .rftd.zip / .rtf • Automatic SSL certificate verification • Same Origin Policy… non-standard one
  • 12. Security guidelines • “Ensure that all UIWebView calls do not execute without proper input validation. Apply filters for dangerous JavaScript characters if possible, using a whitelist over blacklist character policy before rendering. If possible call mobile Safari instead of rending inside of UIWebView which has access to your application.” (OWASP Mobile Top 10) • “[…] maintain control of all UIWebView content and pages, and prevent the user from accessing arbitrary, untrusted web content.” (OWASP iOS Developer Cheat Sheet) • “Inspect remote content via the use of the NSData class method dataWithContentsOfURL in an attempt to prohibit the loading of malicious script into a UIWebview. Do not load content remotely and then process the data returned before passing to a UIWebview (if at all avoidable) otherwise you grant local file system access to any malicious script that smuggles itself past your content inspectors.” (MWR Labs blog) • Sounds dangerous… :-)
  • 13. UIWebView in iOS applications • Chrome • Coast • Facebook • SkyDrive • Skype • WinZip • and hundreds of others
  • 14. Secure UIWebView - how to start? Requirements: • without reducing planned functionality • without spending weeks on building content filters
 (and further ones on maintenance and fixes) • minimal amount of code added • efficiently
  • 15. Step 1 Probably NO, if it’s mobile banking:
 http://blog.ioactive.com/2014/01/personal-banking-apps-leak-info- through.html Is UIWebView needed in your application? YES ! NO
 
 These aren't the droids we're looking for. You can go about your business.
  • 16. Step 2 Do the documents, which you intend to display, need to be displayed in your application? YES ! ! ! NO ! Use Safari,
 Chrome (x-callback-url?)
 or another available browser
  • 17. Step 3 Is the presented document loaded directly through HTTP? YES - loadRequest(…) ! Use https:// ! Don’t turn off SSL
 certificate validation NO - data passed locally
 ! ! ! Remember to set baseURL"
  • 18. ! - loadRequest: ! - loadHTMLString:baseURL: ! - loadData:MIMEType:
 textEncodingName:baseURL: ! - stringByEvaluatingJavaScriptFromString: ! - goBack ! - goForward ! - stopLoading ! - reload
  • 19. baseURL vs Same Origin Policy • file:/// can read local files and any URLs - dangerous! • nil/NULL == applewebdata:
 same privileges as file: - dangerous! • by default UIWebView assumes file://
 (@“test” == @“file://test”) • for http(s):// standard Same Origin Policy applies • for about: and data: also, but with separate origin context
  • 20. <script>
 a = document.location.href.split('/');
 if(a[0]==='file:') {
 path = ‘file:///'+a[3]+'/'+a[4]+'/'+a[5]+'/'+a[6]+'/'+a[7]
 +'/Library/Cookies/Cookies.binarycookies';
 x = new XMLHttpRequest();
 x.open('GET', path, false);
 x.send();
 alert(x.responseText);
 }
 </script>
  • 23. <!-- CVE-2012-2899 --> ! <script> function test() { pop = window.open('about:blank', '_blank'); pop.document.write( '<script>document.write(document.location)</scr' +'ipt><br><iframe src=“http://example.com/“' +'onload="alert(this.contentDocument.body.innerHTML)"></iframe>' ); } </script> <input type="button" onclick="test()" value=“Click">
  • 24.
  • 26.
  • 27.
  • 29.
  • 30.
  • 31. Step 4 Do you have control over the content loaded to UIWebView? YES - I have control over content ! Make sure the documents are not vulnerable to XSS NO - I don’t have control over content ! Can the user recognize origin?
 ! Use CSP or HTML sandbox
  • 32. User interface • clear separation of trusted and untrusted content • address bar with current URL
 
 webView.request.mainDocumentURL.absoluteString
 vs
 [webView stringByEvaluatingJavaScriptFromString:@"window.location.href"] • SSL indicator • warning before first display of untrusted document • other ideas?
  • 33.
  • 34.
  • 35. Cross-Site Scripting • Stored (server-side or in the application) • Reflected (watch for URL scheme handlers) • DOM-based (!) • [webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"document.body.innerText='%@'", input]];
  • 36. Cross-Site Scripting/JavaScript Injection input: ';alert(0)//🌙ꆁ ! [webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"document.body.innerText='%@'", input]]; ! document.body.innerText='';alert(0)//🌙ꆁ'
  • 37.
  • 38. - (NSString*) escapeForJavaScript:(NSString*)fromString { NSString *toString = @""; for(int i=0;i<fromString.length;i++) { toString = [NSString stringWithFormat:@“%@u%04X", toString, [fromString characterAtIndex:i] ]; } return toString; }
  • 39. escapeForJavaScript input: ‘;alert(0)//🌙ꆁ ! [webView stringByEvaluatingJavaScriptFromString:[NSString
 stringWithFormat:@"document.body.innerText='%@'",
 [self escapeForJavaScript:input] ]]; document.body.innerText='u0027u003Bu0061u006C u0065u0072u0074u0028u0030u0029u002Fu002FuD83C uDF19uA181'
  • 40.
  • 42. innerHTML input: <img src=x onerror=alert(0)> ! [webView stringByEvaluatingJavaScriptFromString:[NSString
 stringWithFormat:@"document.body.innerHTML='%@'",
 [self escapeForJavaScript:input] ]]; document.body.innerHTML='u003Cu0069u006D u0067u0020u0073u0072u0063u003Du0078u0020u006F u006Eu0065u0072u0072u006Fu0072u003Du0061u006C u0065u0072u0074u0028u0030u0029u003E'
  • 43.
  • 44. Step 5 Additional security Whitelisting allowed URLs ! http https data about Turning off JavaScript
 ! Content-Security-Policy HTML5 Sandbox ! What can go wrong?
  • 45. [webView loadRequest:
 [NSURLRequest requestWithURL: [NSURL URLWithString:@“https://unknown.tld/untrusted.php“]
 ]
 ];
  • 46. - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response { NSMutableDictionary *mHeaders = [NSMutableDictionary dictionary]; NSString *CSP = @"default-src 'none'; img-src *;style-src 'unsafe-inline' *;child-src *;frame-src *;sandbox allow- forms allow-top-navigation"; for(id h in response.allHeaderFields) { if(![[h lowercaseString] isEqualToString:@"content-security-policy"]
 && ![[h lowercaseString] isEqualToString:@"x-webkit-csp"]) { [mHeaders setObject:response.allHeaderFields[h] forKey:h]; } } [mHeaders setObject:CSP forKey:@"Content-Security-Policy"]; [mHeaders setObject:CSP forKey:@"X-Webkit-CSP"]; NSHTTPURLResponse *mResponse = [[NSHTTPURLResponse alloc]
 initWithURL:response.URL statusCode:response.statusCode
 HTTPVersion:@"HTTP/1.1" headerFields:mHeaders ]; [self.client URLProtocol:self didReceiveResponse:mResponse
 cacheStoragePolicy:NSURLCacheStorageNotAllowed ]; } ?
  • 47. //<UIWebViewDelegate>
 - (BOOL)webView:(UIWebView *)webView
 shouldStartLoadWithRequest:(NSURLRequest *)request 
 navigationType:(UIWebViewNavigationType)navigationType
 {
 if([request.URL.scheme isEqualToString:@"http"
 || [request.URL.scheme isEqualToString:@"https"]
 || [request.URL.scheme isEqualToString:@"about"]
 || [request.URL.scheme isEqualToString:@“data”]) {
 return YES;
 }
 return NO;
 } Question: Will the above code block javascript: URLs? Where?
  • 48. Step 6 What did we forget? Pentest Cordova/PhoneGap ! and other Javascript/Objective-C bridges
  • 49.
  • 50. Links (OWASP) • https://www.owasp.org/index.php/IOS_Application_Security_Testing_Cheat_Sheet • https://www.owasp.org/index.php/IOS_Developer_Cheat_Sheet ! (iOS) • http://www.apple.com/business/accelerator/develop/security.html & https://developer.apple.com/videos/wwdc/2010/ • http://stackoverflow.com/questions/3496505/differences-between-uiwebview-and-mobile-safari ! (CSP) • https://www.owasp.org/images/2/2b/Oxdef_csp_poland.pdf & http://niebezpiecznik.pl/OWASP2013-Krakow-CSP.pdf • http://lists.w3.org/Archives/Public/public-webappsec/2012Mar/0043.html
  • 51.
  • 52. http://browser-shredders.blogspot.com Teaser: Breaking iOS browsers (before it will be cool ;-)