Search code examples
iosxcodesecurityxssnsurl

XSS vulnerability when sending an URL to Safari iOS



After my code got scanned, The report shows a XSS vulnerability happened when I try to open a web page in the Safari app.

[[UIApplication sharedApplication] openURL:[NSURL URLWithString:[event objectForKey:@"url"]]];

'event' is a NSDictionary where I got via NSURL from my server.

I understand to avoid XSS you should encode your output.
but that will messes up the URL and Safari can't open the correct webpage?

Or there's something else causing the issue?

I'm not familiar with security so any pointers will be appreciated.

Thanks in advance!


Solution

  • URL context based XSS can be appear when app try to reflect output inside href attribute.

    <a href="DATA_REFLECTS_HERE">DATA_REFLECTS_HERE</a>
    

    AS you can see same variable can be use 2 diffirent context. First one is inside of href, second one is directly HTML context.

    Most command XSS payloads(javascript:alert(1) etc) and mitigation can be found following example.

        /**
     * XSS protection function for URL context
     * @usecases
     * <a href="use this function if output reflects here">click</a>
     * <img src="use this function if output reflects here">
     * <iframe src="use this function if output reflects here">
     * @description
     * Only allows URLs that start with http(s) or ftp. e.g.,
     * https://www.google.com
     * Protection against JavaScript, VBScript and Data URI JavaScript code execution etc.
     * @author Ashar Javed
     * @Link https://twitter.com/soaj1664ashar
     * @demo http://xssplaygroundforfunandlearn.netai.net/final.html
     */
    function urlContextCleaner($url) {
        if(preg_match("#^(?:(?:https?|ftp):{1})\/\/[^\"\s\\\\]*.[^\"\s\\\\]*$#iu",(string)$url,$match))
        {
            return $match[0];
        }
        else {
            $noxss='javascript:void(0)';
            return $noxss;
        }
    }
    

    Grabbed from : https://github.com/symphonycms/xssfilter/blob/master/lib/xss.php

    Beside, you can solve this issue without having too much trouble. If you know url only can be http protocol, append http(s) prefix in-line at href attribute and encode all types of quotes .( single, double and back-tick )

    For HTML context, just use classic encoding methods.