1 dic 2015

Analizando software malicioso en Android con PHP. Parte 8

Buenas a todos, en el post de hoy de la cadena "Analizando software malicioso en Android con PHP", me gustaría compartir con vosotros una nueva evolución del programa, en la que añadiremos una página inicial para facilitar el análisis de los APKs, a través del script que implementamos en anteriores artículos.

El software lo he bautizado como Acube3 "Android APK Analyzer" y esta es su página inicial:


Para analizar un archivo basta con pulsar sobre Browse, y hacer clic en el botón "Upload":

Código del archivo "index.php":

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8"/>
        <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet">
        <link href="theme/css/fileinput.css" media="all" rel="stylesheet" type="text/css" />
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
        <script src="theme/js/fileinput.js" type="text/javascript"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js" type="text/javascript"></script>
    </head>
    <body>
        <div class="container kv-main">
            <div class="page-header" style="text-align:center">
                <img src="theme/img/acube.png" style="width:700px" />
            </div>
            <form enctype="multipart/form-data" method="post" action="analyze.php" >
                <div class="form-group">
                    <input id="file-2" type="file" name="file" multiple class="file" data-overwrite-initial="false" data-min-file-count="1">
                </div>
            </form>
        </div>
    </body>
</html>

Código del archivo "analyze.php":

<?php
   

    //******** GLOBAL VARIABLES ******************************************
    $rutaTemp="";$html_img="";$html_url="";$html_perm="";$html_manifest="";$extensiones=array();$bin="";$ext="";$name="";
    $x=0;

    //******** LOAD ******************************************************
    $obj_file=$_FILES["file"];
    if ($obj_file["error"] == 0)
    {
            $tmp_name = $obj_file["tmp_name"];
            move_uploaded_file($tmp_name, $obj_file["name"]);
        $name=$obj_file["name"];
        $parts_name = explode(".", $name);
        $bin=$parts_name[count($parts_name)-2];
        $ext='.'.$parts_name[count($parts_name)-1];
    }

    //******** REPEAT EXTENSIONS *****************************************
    function repeatExt($array, $returnWithNonRepeatedItems = false)
    {
        $repeated = array();
        foreach( (array)$array as $value )
        {
            $inArray = false;
            foreach( $repeated as $i => $rItem )
            {
                if( $rItem['value'] === $value )
                {
                    $inArray = true;
                    ++$repeated[$i]['count'];
                }
            }
   
            if( false === $inArray )
            {
                $i = count($repeated);
                $repeated[$i] = array();
                $repeated[$i]['value'] = $value;
                $repeated[$i]['count'] = 1;
            }
        }
   
        if( ! $returnWithNonRepeatedItems )
            foreach( $repeated as $i => $rItem )
                if($rItem['count'] === 1)
                    unset($repeated[$i]);
        sort($repeated);
        return $repeated;
    }

    //******** EXTRACT IMAGES ********************************************
    function showImages($ruta)
    {
        $extensions_img=array("png","jpg","jpeg","bmp","tiff","gif");
        global $rutaTemp,$x,$html_img,$extensiones;
        if (is_dir($ruta))
        {
            if ($aux = opendir($ruta))
            {
                while (($archivo = readdir($aux)) !== false)
                {
                    if ($archivo!="." && $archivo!="..")
                    {
                        $ruta_completa = $ruta . '/' . $archivo;
                        if (is_dir($ruta_completa))
                        {
                $rutaTemp=$rutaTemp.$ruta_completa . "/";
                            showImages($ruta_completa . "/");
                        }
                        else
                        {
                //Extensiones
                $porciones = explode(".", $archivo);
                array_push($extensiones,$porciones[count($porciones)-1]);

                foreach($extensions_img as $extension)
                {
                    if(strpos($archivo, $extension)!==false)
                    {
                                    $html_img.='<img src="' . $rutaTemp."/".$archivo . '" style="width:50px;height:50px;"/>';
                        $x++;
                    }
                }
                        }
                    }
                }
             $rutaTemp="";
                closedir($aux);
            }
        }
    }

    //******** SHELL COMMANDS *******************************************
    $com1='mkdir -p android';
    $com2='d2j-dex2jar '.$bin.$ext.' --force ';
    $com3='java -jar jd-core.jar '.$bin.'-dex2jar.jar android/apk ';
    $com4='find android/apk -type f -print0 | xargs -0 grep -1 "https:"';
    $com5='find android/apk -type f -print0 | xargs -0 grep -1 "http:"';
    $com6='apktool d -f '.getcwd().'/'.$bin.$ext.' '.getcwd().'/android/manifest';
    $commands=array($com1,$com2,$com3,$com4,$com5,$com6);
    foreach($commands as $com)
    {
        $output=array();
        exec($com, $output);
        foreach($output as $valor)
        {
            //http/s extract
            $pos = strpos($valor, '"http');
            if ($pos !== false)
            {
                $valor = substr($valor, $pos+1);
                $html_url.='<li>'.$valor.'</li>';
            }
        }
    }

    //******** EXTRACT IMAGES *******************************************
    showImages("./android/manifest");

    //******** EXTRACT MANIFEST *****************************************
    $a = getcwd().'/android/manifest/AndroidManifest.xml';
    $fp = fopen($a,'r');
    $html_manifest = fread($fp, filesize($a));
    $xml=simplexml_load_string(str_replace(":", "", $html_manifest));
   
    //******** EXTRACT PERMISSIONS **************************************
    $c=0;
    foreach ($xml->children() as $node)
        if($node->attributes()->{'androidname'}!="")
            {
                $prm=$node->attributes()->{'androidname'};
                    $html_perm.='<li>'.$prm.'</li>';
                $c++;
            }
    //******** CLEAN TEMP FILES *****************************************
    unlink($name);
    unlink($bin.'-dex2jar.jar');
    function rmdir_recursive($dir)
    {
        foreach(scandir($dir) as $file) {
            if ('.' === $file || '..' === $file) continue;
            if (is_dir("$dir/$file")) rmdir_recursive("$dir/$file");
            else unlink("$dir/$file");
        }
        rmdir($dir);
    }
    //rmdir_recursive('android');
?>


<html>
<head>
</head>
<body>
    <h1>General information</h1>
    <ul>
    <?php
        echo '<li>Package: '.$xml->attributes()->{'package'}.'</li>';
        echo '<li>Version code: '.$xml->attributes()->{'androidversionCode'}.'</li>';
        echo '<li>Version name: '.$xml->attributes()->{'androidversionName'}.'</li>';
        echo '<li>Size:'.filesize($bin.$ext).' bytes</li>';
        echo '<li>MD5:'.md5_file($bin.$ext).'</li>';
        echo '<li>SHA1:'.sha1_file($bin.$ext).'</li>';
        echo '<li>Permissions:'.$c.'</li>';
        echo '<li>Images:'.$x.'</li>';    
    ?>
    </ul>
    <h1>Files</h1>
    <ul> <?php foreach(repeatExt($extensiones) as $k) echo '<li>'.$k["value"].': '.$k["count"].'</li>'; ?> </ul>
    <h1>URLs</h1>
    <ul> <?php echo $html_url;?> </ul>
    <h1>Permissions</h1>
    <ul> <?php echo $html_perm; ?> </ul>
    <h1>Images</h1>
    <?php echo $html_img; ?>
    <h1>Android Manifest</h1>
    <textarea cols="100" rows="25">    <?php echo $html_manifest; ?> </textarea>
</body>
</html>


Cuando hayamos finalizado la herramienta la compartiremos con vosotros de forma completa. Por el momento falta mucho código por pulir, y funcionalidades que desarrollar. Así que nos vemos en el próximo post.

Saludos!

No hay comentarios:

Publicar un comentario