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

Oracle10g unwrap技术分析

程序员文章站 2022-04-06 23:06:20
0x01 前言 Oracle为PL/SQL开发者提供的一种对他们所写的代码(oracle下的对象Package、Procedure、Function、Java Source等)进...
0x01 前言

Oracle为PL/SQL开发者提供的一种对他们所写的代码(oracle下的对象Package、Procedure、Function、Java Source等)进行加密的工具。当PL/SQL代码被加密以后,它就被描述为被“包装过”。使用wrap工具对代码进行包装,wrap工具会取出含有要包装的代码的文件名并输出下面的文件:
wrap iname=plain.sql oname=encrypted.plb
因为代码被加密了,所以其细节被隐藏了,而且Oracle不提供解包装设备。但是我们可以编写我们自己的unwrap程序。

0x02 对象加密

Oracle为了防止自己的对象程序源码泄露,也对其做了wrap处理。因为许多PACKAGE、PROCEDURE等程序本身可能存在SQL注入漏洞,但是如果得不到源码,对其进行审计是很困难的。这样wrap在一定程度上也起到了保护作用。
这里随便找一个Oracle的PACKAGE为实例,这里我们找到dbms_hs包程序,其代码如图所示:

Oracle10g unwrap技术分析

很明显代码被加密了。

0x03 Oracle Wrap的算法机制

Oracle加密的原理就是先对源码进行lz压缩lzstr,然后对压缩数据进行SHA-1运算得到40位的加密串shstr,然后将加密串与压缩串拼接得到shstr+lzstr,然后对拼接后的字符串进行Oracle双字符转换(转换表)。最后将转换后的字符串进行base64编码,最终得到wrap的加密串。
关于LZ压缩,这里用老外提供的一个JAVA包,代码如下:

 

create or replace java source named MY_COMPRESSas
import java.io.*;
import java.util.zip.*;
public class MY_COMPRESS
{
  public static String Inflate( byte[] src )
  {
    try
    {
      ByteArrayInputStream bis = new ByteArrayInputStream( src );
      InflaterInputStream iis = new InflaterInputStream( bis );
      StringBuffer sb = new StringBuffer();
      for( int c = iis.read(); c != -1; c = iis.read() )
      {
        sb.append( (char) c );
      }
      return sb.toString();
    } catch ( Exception e )
    {
    }
    return null;
  }
  public static byte[] Deflate( String src, int quality )
  {
    try
    {
      byte[] tmp = new byte[ src.length() + 100 ];
      Deflater defl = new Deflater( quality );
      defl.setInput( src.getBytes( "UTF-8" ) );
      defl.finish();
      int cnt = defl.deflate( tmp );
      byte[] res = new byte[ cnt ];
      for( int i = 0; i < cnt; i++ )
        res[i] = tmp[i];
      return res;
    } catch ( Exception e )
    {
    }
    return null;
  }
}
/

alter java source MY_COMPRESS compile
/

create or replace package mycompress
is
  function deflate( src in varchar2 )
  return raw;
--
  function deflate( src in varchar2, quality in number )
  return raw;
--
  function inflate( src in raw )
  return varchar2;
--
end;
/
create or replace package body mycompress
is
  function deflate( src in varchar2 )
  return raw
  is
  begin
    return deflate( src, 6 );
  end;
--
  function deflate( src in varchar2, quality in number )
  return raw
  as language java
  name 'MY_COMPRESS.Deflate( java.lang.String, int ) return byte[]';
--
  function inflate( src in raw )
  return varchar2
  as language java
  name 'MY_COMPRESS.Inflate( byte[] ) return java.lang.String';
--
end;
/


 

这里deflate函数实现LZ压缩,而inflate则实现解压。
首先,我们以一小段PL/SQL代码来测试分先加密字符串的结构,这里我先讲程序加密处理。如图所示,这里将create PACKAGE a代码wrap之后变成了如下代码

Oracle10g unwrap技术分析

为了进一步测试,分析其加密字符串中的结构,我们利用如下代码:

with src as
( select 'PACKAGE a' txt from dual )
, wrap as
( select src.txt, dbms_ddl.wrap( 'create ' || src.txt ) wrap from src )
Select rtrim( substr( wrap.wrap, instr(wrap.wrap, chr(10), 1, 20 ) + 1 ),chr(10) ) from wrap;

 

这段代码获得加密串,如图所示

Oracle10g unwrap技术分析

进一步对这段代码做base64解码,获得经过Oracle双字符转换后的字符串,如图所示:

Oracle10g unwrap技术分析

因为字符串是由两部分组成,先经过LZ压缩,然后经过SHA-1处理,然后再将SHA-1字符串和压缩字符串拼接得到,因为SHA-1总共40位,所以40位以后的全为经过Oracle双字符转换的压缩串,也就是308399B8F5339FF5BF5CB891A6A6CBBFE1DC

0x04 计算转换表

当wrap完成sha-1字符串和压缩字符串的拼接之后,紧接着会对照一个字符代替表进行Oracle双字符转换。这个表可能是Oracle的商业机密,所以官方没有给出该表的信息。
  但是,既然我们已经得到了经过字符转换之后的LZ压缩串,同时我们可以通过前面提到的JAVA包得到纯净的LZ压缩串,通过对比这两个字符串,我们便可以推算出这个转换表。
  在使用这个java包时,涉及到一个压缩级别参数,这个等级参数不一样,压缩得到的字符串完全一不样。有人可能要问,这样搞岂不是没法得到替换表了吗?是的,但也不完全正确。因为可供选择的等级参数有限,我们可以从0等级开始一个一个进行测试,经过测试发现,ORACLE用的是“9”等级。所以我们用以下代码对比两个字符串:

with src as
( select 'PACKAGE c' txt from dual )
, wrap as
( select src.txt, dbms_ddl.wrap( 'create ' || src.txt ) wrap from src )
, subst as
( select substr( utl_encode.base64_decode( utl_raw.cast_to_raw( rtrim( substr( wrap.wrap, instr(wrap.wrap, chr(10), 1, 20 ) + 1 ),chr(10) ) ) ), 41 ) x
, mycompress.deflate( wrap.txt || chr(0),9 ) d
from wrap )
select to_number( substr( x, r * 2 - 1, 2),'xx' ) wrapped
     , to_number( substr( d, r * 2 - 1, 2),'xx' ) zipped
from subst
    , ( select rownum r from dual connect by rownum < 19 );

 

结果如下:

Oracle10g unwrap技术分析

通过对结果的排序,没有出现同一个BASE64编码对应不同的十六进制的情况,因此我们知道了可以用这个SQL为基础,通过用不同的SOURCE串来产生替换表的内容。
根据上面的SQL首先建一个表来存储替换表的内容,

CREATE TABLE SYS.IDLTRANSLATE
(
    C_BASE64DECODE  VARCHAR2(2) NOT NULL,
    C_LZDEFLATECODE VARCHAR2(2)     NULL
    )

 

然后写一段PLSQL块来生成替换表的内容:

declare
  nCnt integer;
  nLoop integer;
  nSLoop integer;
  nCharmax integer;
  nCharmin  integer;
  vChar     Varchar2(3);
  cursor getchar is
    with src AS ( select 'PACKAGE '||vChar txt  from dual   ),
     wrap as   ( select src.txt , dbms_ddl.wrap( 'create ' || src.txt ) wrap  from src  ),
     subst as  (select substr( utl_encode.base64_decode( utl_raw.cast_to_raw(rtrim( substr( wrap.wrap, instr( wrap.wrap, chr( 10 ), 1, 20 ) + 1 ), chr(10) )  ) ), 41 ) x,
         mycompress.deflate( wrap.txt || chr(0), 9 ) d
       from wrap  )
    select  substr( x, r * 2 - 1, 2 )  xr ,
    substr( d, r * 2 - 1, 2 )  dr
            from subst  , ( select rownum r from dual connect by rownum <= ( select length( x ) / 2 from subst ) );
begin
    nCharmax:=97;
nCharmin:=122;

For nLoop In 97..122 Loop
  For nSloop In 0..99 Loop
   vChar := chr(nLoop)||to_char(nSloop);
   For abc In getchar Loop
    Select Count(*) Into nCnt From sys.idltranslate WHERE c_base64decode = abc.xr;
    If nCnt < 1 Then
     Insert INTO sys.idltranslate VALUES (abc.xr,abc.dr);
     Commit;
    Else
     Select Count(*) Into ncnt From sys.idltranslate WHERE c_base64decode = abc.xr AND c_lzdeflatecode=abc.dr;
     If nCnt < 1 Then
      DBMS_OUTPUT.PUT_LINE('wrong orginal char:'||vchar||'         hex base64:'||abc.xr);
     End If;
    End If;    
   End Loop;
  End Loop;
End Loop;
end;

 

运行上面这段SQL大概会产生100多条记录,还未达到00-FF总共256条记录的要求,建议替换select 'PACKAGE '||vChar txt  from dual中的PACKAGE关健字为procedure或者function类似的,继续运行直到替换表中有不重复的256条记录为止。有了替换表的内容,unwrap出明文也就不再困难了。
这里给出替换表的内容,我将其写到一个变量里,如下所示:

int charmap[] = {0x3d, 0x65, 0x85, 0xb3, 0x18, 0xdb, 0xe2, 0x87, 0xf1, 0x52, 0xab, 0x63, 0x4b, 0xb5, 0xa0, 0x5f, 0x7d, 0x68, 0x7b, 0x9b, 0x24, 0xc2, 0x28, 0x67, 0x8a, 0xde, 0xa4, 0x26, 0x1e, 0x03, 0xeb, 0x17, 0x6f, 0x34, 0x3e, 0x7a, 0x3f, 0xd2, 0xa9, 0x6a, 0x0f, 0xe9, 0x35, 0x56, 0x1f, 0xb1, 0x4d, 0x10, 0x78, 0xd9, 0x75, 0xf6, 0xbc, 0x41, 0x04, 0x81, 0x61, 0x06, 0xf9, 0xad, 0xd6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x74, 0x6b, 0x91, 0xfb, 0xfe, 0xc9, 0x01, 0xea, 0x1b, 0xf7, 0xce}

 

这里为256条记录,按顺序00~FF对应数组每一个元素。

0x05 破解程序

利用前面得出的JAVA包以及转换表,结合下面这段代码unwrap出明文,如下

set serveroutput on;
create or replace procedure unwrap(o in varchar,n in varchar, t in varchar)
as
        vWrappedtext                Varchar2(32767);                
        vtrimtext                Varchar2(32767);                
        vChar                                        Varchar2(2);
        vRepchar                                Varchar2(2);
        vLZinflatestr                        Varchar2(32767);
        nLen                Integer;
        nLoop        Integer;
        nCnt                Integer;
code varchar(512);
Begin
code:='3D6585B318DBE287F152AB634BB5A05F7D687B9B24C228678ADEA4261E03EB176F343E7A3FD2A96A0FE935561FB14D1078D975F6BC4104816106F9ADD6D5297E869E79E505BA84CC6E278EB05DA8F39FD0A271B858DD2C38994C480755E4538C46B62DA5AF322240DC50C3A1258B9C16605CCFFD0C981CD4376D3C3A30E86C3147F533DA43C8E35E1994ECE6A39514E09D64FA5915C52FCABB0BDFF297BF0A76B449445A1DF0009621807F1A82394FC1A7D70DD1D8FF139370EE5BEFBE09B97772E7B254B72AC7739066200E51EDF87C8F2EF412C62B83CDACCB3BC44EC069366202AE88FCAA4208A64557D39ABDE1238D924A1189746B91FBFEC901EA1BF7CE';--sys.idltranslate表内容存到字符数组

vtrimtext:='';
select count(*) into ncnt                         from DBA_SOURCE
                        Where owner=o
                        And Name = n
                        And Type=t ;
if ncnt >0 and ncnt <=5 then
for i in 1..ncnt loop
if i=1 then
select rtrim(substr(TEXT,instr(TEXT,chr(10),1,20)+1),chr(10))  --保存去掉前边20行的BASE64码正文
into vLZinflatestr
                        from DBA_SOURCE
                        Where owner=o
                        And Name = n
                        And Type=t and line=i;
else
select text into vLZinflatestr
                        from DBA_SOURCE
                        Where owner=o
                        And Name = n
                        And Type=t and line=i;
end if;
vtrimtext:=vtrimtext||vLZinflatestr;
end loop;
end if;
vtrimtext:=replace(vtrimtext,chr(10),'');
nLen := Length(vtrimtext)/256 ;
vWrappedtext :='';
for i in 0..nLen  loop  
--if i< nLen   then
vWrappedtext:=vWrappedtext||utl_encode.base64_decode( utl_raw.cast_to_raw(substrb(vtrimtext,256*i+1 , 256 ))) ;
-- else
--vWrappedtext:=vWrappedtext||utl_encode.base64_decode( utl_raw.cast_to_raw(substrb(vtrimtext,64*i+1  ))) ;
--end if;
        --DBMS_OUTPUT.PUT_LINE(vWrappedtext);
        End Loop;
--vWrappedtext:=substr(vWrappedtext,41);
    nLen := Length(vWrappedtext)/2 - 1;

        vLZinflatestr :='';

        For nLoop In 20..nLen Loop --从第41字节开始
                vChar := Substrb(vWrappedtext,nLoop*2+1,2);
                vLZinflatestr := vLZinflatestr ||substr(code,to_number(vChar,'XX')*2+1,2); --从字符串变量匹配
                --DBMS_OUTPUT.PUT_LINE(vLZinflatestr);
        End Loop;
        --DBMS_OUTPUT.PUT_LINE(vLZinflatestr);
        DBMS_OUTPUT.PUT_LINE(mycompress.inflate(vLZinflatestr));
End;
/
exec unwrap('SYS','AA','PROCEDURE');

 

这里将转换表IDLTRANSLATE的内容存储变量code当中,这样可以在unwrap的过程中不必再去创建IDLTRANSLATE这个表。
执行以上代码查看一下输出的内容,至此Oracle所有PACKAGE程序没有密码可言了,当然其他对象程序存储过程、函数等也可以得到明文了。
这里执行一段unwrap以后的程序,然后保存以上代码为code.sql,解码得到明文。

Oracle10g unwrap技术分析

Oracle10g unwrap技术分析


同时还收集了老外提供的一个python脚本,代码如下:

#!/usr/bin/python #
# This script unwraps Oracle wrapped plb packages, does not support 9g
# Contact: niels at teusink net / blog.teusink.net
#
# License: Public domain
#
import re
import base64
import zlib
import sys

# simple substitution table
charmap = [0x3d, 0x65, 0x85, 0xb3, 0x18, 0xdb, 0xe2, 0x87, 0xf1, 0x52, 0xab, 0x63, 0x4b, 0xb5, 0xa0, 0x5f, 0x7d, 0x68, 0x7b, 0x9b, 0x24, 0xc2, 0x28, 0x67, 0x8a, 0xde, 0xa4, 0x26, 0x1e, 0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2b, 0x83, 0xcd, 0xac, 0xcb, 0x3b, 0xc4, 0x4e, 0xc0, 0x69, 0x36, 0x62, 0x02, 0xae, 0x88, 0xfc, 0xaa, 0x42, 0x08, 0xa6, 0x45, 0x57, 0xd3, 0x9a, 0xbd, 0xe1, 0x23, 0x8d, 0x92, 0x4a, 0x11, 0x89, 0x74, 0x6b, 0x91, 0xfb, 0xfe, 0xc9, 0x01, 0xea, 0x1b, 0xf7, 0xce]
#print charmap[124]

def decode_base64_package(base64str):
    base64dec = base64.decodestring(base64str)[20:] # we strip the first 20 chars (SHA1 hash, I don't bother checking it at the moment)
    decoded = ''
    for byte in range(0, len(base64dec)):
        decoded += chr(charmap[ord(base64dec[byte])])
    return zlib.decompress(decoded)
    

sys.stderr.write("=== Oracle 10g/11g PL/SQL unwrapper 0.2 - by Niels Teusink - blog.teusink.net ===\n\n" )
if len(sys.argv) < 2:
    sys.stderr.write("Usage: %s infile.plb [outfile]\n" % sys.argv[0])
    sys.exit(1)

infile = open(sys.argv[1])
outfile = None
if len(sys.argv) == 3:
    outfile = open(sys.argv[2], 'w')

lines = infile.readlines()
for i in range(0, len(lines)):
    # this is really naive parsing, but works on every package I've thrown at it
    matches = re.compile(r"^[0-9a-f]+ ([0-9a-f]+)$").match(lines[i])
    #print matches
    if matches:
        base64len = int(matches.groups()[0], 16)
        base64str = ''
        j = 0
        while len(base64str) < base64len:
            j+=1
            base64str += lines[i+j]
        base64str = base64str.replace("\n","")
        if outfile:
            outfile.write(decode_base64_package(base64str) + "\n")
        else:
            print decode_base64_package(base64str)

 

执行结果,如图所示:

Oracle10g unwrap技术分析

0x06 总结

Oracle 10g PL/SQL的wrap过程是对源码先进行lz压缩lzstr,然后对压缩数据进行SHA-1运算得到40位的加密串shstr,然后将加密串与压缩串拼接得到shstr+lzstr,然后对拼接后的字符串进行Oracle双字符转换(转换表),最后将转换后的字符串进行base64编码,最终得到wrap的加密串。

而unwrap的过程正好相反,破解的关键是得到ORACLE的双字符转换表,因为在10g以后Oracle中无法查看转换表的内容。这里捎带提一下oracle 9i的wrap技术,它使用一种完全不同于10g的方法。9i wrap的时候,代码被转换为DIANA(ADA的中间描述语言),这是一个相当复杂的过程,具体细节请阅读Pete Finnegan的论文“How to Unwrap PL/SQL”,大家可以去http://www.blackhat.com/presentations/bh-usa-06/BH-US-06-Finnigan.pdf下载