Valhalla Legends Forums Archive | Battle.net Bot Development | broken sha-1 in python?

AuthorMessageTime
aton
has someone ported the broken sha-1 used for hashing the cdkey in 0x51 to python?

May 3, 2009, 2:36 PM
Yegg
Not that I have nothing to do, but I feel like writing such a function since one doesn't exist. I should have something done that works today.
May 3, 2009, 9:11 PM
Quarantine
Just find a sha1 implementation and break it.
May 4, 2009, 12:12 AM
Yegg
[quote author=Warrior link=topic=17932.msg182585#msg182585 date=1241395946]
Just find a sha1 implementation and break it.
[/quote]

Python has a module called sha (has sha1 capabilities) that is built in.
May 4, 2009, 12:31 AM
aton
well whats the difference between normal sha-1 and blizzard's broken one?
May 6, 2009, 9:55 AM
Sveet
isnt the only difference the implementation of the ROL function? i remember reading that some dumbass at blizzard messed it up lol
May 6, 2009, 11:59 AM
xpeh
Yes, can some1 say where's the difference between sha-1 and bsha-1?
May 6, 2009, 12:09 PM
aton
yegg have you been able to use the builtin sha functionality of python to hash a cdkey?
May 6, 2009, 4:27 PM
Sveet
people don't listen to me? there is a function called ROL which is a bitwise rotate left. Its called during the SHA hashing algorithm, but the blizzard employee who was in charge of writing made a mistake so its not standard. go look at BN#'s source for it if you want a more specific.
May 6, 2009, 4:43 PM
Myndfyr
[quote author=Sveet link=topic=17932.msg182647#msg182647 date=1241628237]
people don't listen to me? there is a function called ROL which is a bitwise rotate left. Its called during the SHA hashing algorithm, but the blizzard employee who was in charge of writing made a mistake so its not standard. go look at BN#'s source for it if you want a more specific.
[/quote]

To be specific, look at this:
[quote author=Skywing] However, a more serious security problem remains: in SHA-1, there are a number of bit rotate left (``ROL'') operations. The Blizzard programmer responsible for implementing this apparently switched the two parameters in every call to ROL. That is, if there was a ``#define ROL(a, b) (...)'' macro, the programmer swapped the two arguments. This drastically reduces the security of Battle.net password hashes, as most of the data being hashed ends up being zero bits. Because of the problem of incompatibility with previously created accounts, this system is still in use today. [/quote]
May 6, 2009, 5:34 PM
idiat
Here is something I wrote. It's a very close port from either JBLS or BNCSutil, I forget which. It's pretty shitty, but, to my knowledge, it works, and perhaps you can improve upon it.

[code]from ctypes import c_byte, c_int32, c_uint32


def insert_byte(buf, loc, b):
    the_int = loc / 4
    the_byte = loc % 4

    replace_int = buf[the_int]

    new_byte = ord(b) << (8 * the_byte)

    if the_byte == 0:
        replace_int &= 0xFFFFFF00
    elif the_byte == 1:
        replace_int &= 0xFFFF00FF
    elif the_byte == 2:
        replace_int &= 0xFF00FFFF
    elif the_byte == 3:
        replace_int &= 0x00FFFFFF

    replace_int |= new_byte

    buf[the_int] = replace_int
   

def calc_hash_buffer(hash_data):
    hash_buffer = [0x67452301,
                   0xEFCDAB89,
                   0x98BADCFE,
                   0x10325476,
                   0xC3D2E1F0] + [0] * 0x10
    i = 0
    while i < len(hash_data):
        sub_len = len(hash_data) - i

        if sub_len > 0x40:
            sub_len = 0x40

        j = 0
        while j < sub_len:
            insert_byte(hash_buffer, j + 20, hash_data[j + i])
            j += 1

        if sub_len < 0x40:
            j = sub_len
            while j < 0x40:
                insert_byte(hash_buffer, j + 20, '\0')
                j += 1

        do_hash(hash_buffer)

        i += 0x40

    return hash_buffer[:5]

def do_hash(hash_buffer):
    buf = [0] * 0x50

    i = 0
    while i < 0x10:
        buf[i] = hash_buffer[i + 5]
        i += 1

    while i < 0x50:
        dw = buf[i - 0x3] ^ buf[i - 0x8] ^ buf[i - 0x10] ^ buf[i - 0xE]
        dw = c_byte(dw).value
        buf[i] = rol(1, dw)
        i += 1
                   
    a = c_uint32(hash_buffer[0]).value
    b = c_uint32(hash_buffer[1]).value
    c = c_uint32(hash_buffer[2]).value
    d = c_uint32(hash_buffer[3]).value
    e = c_uint32(hash_buffer[4]).value
    p = 0

    while p < 20:
        dw = rol(a, 5) + ((~b & d) | (c & b)) + e + buf[p] + 0x5a827999
        dw = c_uint32(dw).value
        e = d
        d = c
        c = c_uint32(rol(b, 0x1E)).value
        b = a
        a = dw
       
        p += 1
        i += 1

    while p < 40:
        dw = (d ^ c ^ b) + e + rol(a, 5) + buf[p] + 0x6ED9EBA1
        dw = c_uint32(dw).value
        e = d
        d = c
        c = c_uint32(rol(b, 0x1E)).value
        b = a
        a = dw

        p += 1

    while p < 60:
        dw = ((c & b) | (d & c) | (d & b)) + e + rol(a, 5) + buf[p] - 0x70E44324
        dw = c_uint32(dw).value
        e = d
        d = c
        c = c_uint32(rol(b, 0x1E)).value
        b = a
        a = dw

        p += 1

    while p < 80:
        dw = rol(a, 5) + e + (d ^ c ^ b) + buf[p] - 0x359D3E2A
        dw = c_uint32(dw).value
        e = d
        d = c
        c = c_uint32(rol(b, 0x1E)).value
        b = a
        a = dw

        p += 1

    hash_buffer[0] = c_int32(hash_buffer[0] + a).value
    hash_buffer[1] = c_int32(hash_buffer[1] + b).value
    hash_buffer[2] = c_int32(hash_buffer[2] + c).value
    hash_buffer[3] = c_int32(hash_buffer[3] + d).value
    hash_buffer[4] = c_int32(hash_buffer[4] + e).value


def rol(num, shift):
    shift &= 0x1F
    return lshift(num, shift) | rshift(num, 32 - shift)

def lshift(val, shift):
    if shift > 32:
        return 0
    elif shift < 0:
        return 0

    return val << shift

def rshift(val, shift):
    if shift > 32:
        return 0
    elif shift < 0:
        return 0

    return val >> shift
[/code]

I appear to have called it in this manner:
[code]    def single(self):
        a = xsha1.calc_hash_buffer(self.bot.connfig['login']['password'].lower())
        self.bot.status['new_pwhash'] = pack('<5l', *a)
        self.bot.events.call('hashing', 'recv', 'new_pwhash')

        return False

    def double(self):
        a = xsha1.calc_hash_buffer(self.bot.connfig['login']['password'].lower())
        bu = pack('<2L5l', self.bot.status['ctoken'],
                  self.bot.status['stoken'],
                  *a)
        b = xsha1.calc_hash_buffer(bu)
        self.bot.status['pwhash'] = pack('<5l', *b)
        self.bot.events.call('hashing', 'recv', 'pwhash')
       
        return False[/code]
May 7, 2009, 1:43 AM
Yegg
[quote author=aton link=topic=17932.msg182646#msg182646 date=1241627225]
yegg have you been able to use the builtin sha functionality of python to hash a cdkey?
[/quote]

Looking over Python 3.0 documentation (which replaces sha module with a module named hashlib), there is no way to change how SHA functions via the hashlib library. I imagine this library has its source available for free with every copy of Python 3.0. You could easily modify the code and add a new method to hashlib called "bsha" or whatever you prefer. I have no interest in this but it should be quite easy to accomplish. Let me know how it goes.

Since my work schedule changed a lot, I haven't had time to work on much of my projects. Tonight when I get out of work I may create Broken SHA in Python without using hashlib. I don't have work Friday, so I can just stay up all night, not sleep period, and get this over with. I'll post it here whenever that's complete.
May 7, 2009, 2:14 AM
aton
from the freenode python irc channel topic: "It's (seriously) too early to use python 3.x"

and i modified the sha-1 of python already, with help from rob (thanks!)

it does both, sha-1 and broken sha-1, depending on one argument. i think some people were interested in the differences between standard and broken, so here you can see them very clearly:

(its compliant to the python hashlib class calling conventions, i.e. .update() .hexdigest() etc)

[code]
import struct
import socket

def _long2bytesBigEndian(n, blocksize=0):
    """Convert a long integer to a byte string.

    If optional blocksize is given and greater than zero, pad the front
    of the byte string with binary zeros so that the length is a multiple
    of blocksize.
    """

    # After much testing, this algorithm was deemed to be the fastest.
    s = ''
    pack = struct.pack
    while n > 0:
        s = pack('>I', n & 0xffffffffL) + s
        n = n >> 32

    # Strip off leading zeros.
    for i in range(len(s)):
        if s[i] <> '\000':
            break
    else:
        # Only happens when n == 0.
        s = '\000'
        i = 0

    s = s[i:]

    # Add back some pad bytes. This could be done more efficiently
    # w.r.t. the de-padding being done above, but sigh...
    if blocksize > 0 and len(s) % blocksize:
        s = (blocksize - len(s) % blocksize) * '\000' + s

    return s


def _bytelist2longBigEndian(list):
    "Transform a list of characters into a list of longs."

    imax = len(list)/4
    hl = [0L] * imax

    j = 0
    i = 0
    while i < imax:
        b0 = long(ord(list[j])) << 24
        b1 = long(ord(list[j+1])) << 16
        b2 = long(ord(list[j+2])) << 8
        b3 = long(ord(list[j+3]))
        hl[i] = b0 | b1 | b2 | b3
        i = i+1
        j = j+4

    return hl


def _rotateLeft(x, n):
    "Rotate x (32 bit) left n bits circularly."

    return (x << n) | (x >> (32-n))

# ======================================================================
# The SHA transformation functions
#
# ======================================================================

def f0_19(B, C, D):
    return (B & C) | ((~ B) & D)

def f20_39(B, C, D):
    return B ^ C ^ D

def f40_59(B, C, D):
    return (B & C) | (B & D) | (C & D)

def f60_79(B, C, D):
    return B ^ C ^ D

f = [f0_19, f20_39, f40_59, f60_79]

# Constants to be used
K = [
    0x5A827999L, # ( 0 <= t <= 19)
    0x6ED9EBA1L, # (20 <= t <= 39)
    0x8F1BBCDCL, # (40 <= t <= 59)
    0xCA62C1D6L  # (60 <= t <= 79)
    ]

class bsha:
    "broken sha for blizzard stuff"

    digest_size = digestsize = 20

    def __init__(self, broken=True):
        "Initialisation."
        self.broken=broken
       
        # Initial message length in bits(!).
        #self.length = 0L
        self.count = [0, 0]

        # Initial empty message as a sequence of bytes (8 bit characters).
        self.input = []

        # Call a separate init function, that can be used repeatedly
        # to start from scratch on the same object.
        self.init()
       

    def init(self):
        "Initialize the message-digest and set all fields to zero."

        #self.length = 0L
        self.input = []

        # Initial 160 bit message digest (5 times 32 bit).
        self.H0 = 0x67452301L
        self.H1 = 0xEFCDAB89L
        self.H2 = 0x98BADCFEL
        self.H3 = 0x10325476L
        self.H4 = 0xC3D2E1F0L

    def _transform(self, W):
        if self.broken:
            for t in range(0, 16): W[t]=socket.htonl(W[t])
           
           
        for t in range(16, 80):
            if self.broken:
                W.append(_rotateLeft(1, (W[t-3] ^ W[t-8] ^ W[t-14] ^ W[t-16])&31) & 0xffffffffL)
            else:
                W.append(_rotateLeft(W[t-3] ^ W[t-8] ^ W[t-14] ^ W[t-16], 1) & 0xffffffffL)

        A = self.H0
        B = self.H1
        C = self.H2
        D = self.H3
        E = self.H4

        """
        This loop was unrolled to gain about 10% in speed
        for t in range(0, 80):
            TEMP = _rotateLeft(A, 5) + f[t/20] + E + W[t] + K[t/20]
            E = D
            D = C
            C = _rotateLeft(B, 30) & 0xffffffffL
            B = A
            A = TEMP & 0xffffffffL
        """

        for t in range(0, 20):
            TEMP = _rotateLeft(A, 5) + ((B & C) | ((~ B) & D)) + E + W[t] + K[0]
            E = D
            D = C
            C = _rotateLeft(B, 30) & 0xffffffffL
            B = A
            A = TEMP & 0xffffffffL

        for t in range(20, 40):
            TEMP = _rotateLeft(A, 5) + (B ^ C ^ D) + E + W[t] + K[1]
            E = D
            D = C
            C = _rotateLeft(B, 30) & 0xffffffffL
            B = A
            A = TEMP & 0xffffffffL

        for t in range(40, 60):
            TEMP = _rotateLeft(A, 5) + ((B & C) | (B & D) | (C & D)) + E + W[t] + K[2]
            E = D
            D = C
            C = _rotateLeft(B, 30) & 0xffffffffL
            B = A
            A = TEMP & 0xffffffffL

        for t in range(60, 80):
            TEMP = _rotateLeft(A, 5) + (B ^ C ^ D)  + E + W[t] + K[3]
            E = D
            D = C
            C = _rotateLeft(B, 30) & 0xffffffffL
            B = A
            A = TEMP & 0xffffffffL


        self.H0 = (self.H0 + A) & 0xffffffffL
        self.H1 = (self.H1 + B) & 0xffffffffL
        self.H2 = (self.H2 + C) & 0xffffffffL
        self.H3 = (self.H3 + D) & 0xffffffffL
        self.H4 = (self.H4 + E) & 0xffffffffL
   

    # Down from here all methods follow the Python Standard Library
    # API of the sha module.

    def update(self, inBuf):
        """Add to the current message.

        Update the md5 object with the string arg. Repeated calls
        are equivalent to a single call with the concatenation of all
        the arguments, i.e. m.update(a); m.update(b) is equivalent
        to m.update(a+b).

        The hash is immediately calculated for all full blocks. The final
        calculation is made in digest(). It will calculate 1-2 blocks,
        depending on how much padding we have to add. This allows us to
        keep an intermediate value for the hash, so that we only need to
        make minimal recalculation if we call update() to add more data
        to the hashed string.
        """

        leninBuf = long(len(inBuf))

        # Compute number of bytes mod 64.
        index = (self.count[1] >> 3) & 0x3FL

        # Update number of bits.
        self.count[1] = self.count[1] + (leninBuf << 3)
        if self.count[1] < (leninBuf << 3):
            self.count[0] = self.count[0] + 1
        self.count[0] = self.count[0] + (leninBuf >> 29)

        partLen = 64 - index

        if leninBuf >= partLen:
            self.input[index:] = list(inBuf[:partLen])
            self._transform(_bytelist2longBigEndian(self.input))
            i = partLen
            while i + 63 < leninBuf:
                self._transform(_bytelist2longBigEndian(list(inBuf[i:i+64])))
                i = i + 64
            else:
                self.input = list(inBuf[i:leninBuf])
        else:
            i = 0
            self.input = self.input + list(inBuf)


    def digest(self):
        """Terminate the message-digest computation and return digest.

        Return the digest of the strings passed to the update()
        method so far. This is a 20-byte string which may contain
        non-ASCII characters, including null bytes.
        """

        H0 = self.H0
        H1 = self.H1
        H2 = self.H2
        H3 = self.H3
        H4 = self.H4
        input = [] + self.input
        count = [] + self.count
       
        index = (self.count[1] >> 3) & 0x3fL
       
        if index < 56:
            padLen = 56 - index
        else:
            padLen = 120 - index

        if self.broken:
            padding = ['\000'] * 64
        else:
            padding = ['\200'] + ['\000'] * 63
       
        self.update(padding[:padLen])

       
        if self.broken:
            bits = _bytelist2longBigEndian(self.input[:56]) + [0L,0L]
        else:
            # Append length
            bits = _bytelist2longBigEndian(self.input[:56])+count
       
        self._transform(bits)

        # Store state in digest.
        digest = _long2bytesBigEndian(self.H0, 4) + \
                _long2bytesBigEndian(self.H1, 4) + \
                _long2bytesBigEndian(self.H2, 4) + \
                _long2bytesBigEndian(self.H3, 4) + \
                _long2bytesBigEndian(self.H4, 4)

        self.H0 = H0
        self.H1 = H1
        self.H2 = H2
        self.H3 = H3
        self.H4 = H4
        self.input = input
        self.count = count

        return digest


    def hexdigest(self):
        """Terminate and return digest in HEX form.

        Like digest() except the digest is returned as a string of
        length 32, containing only hexadecimal digits. This may be
        used to exchange the value safely in email or other non-
        binary environments.
        """
        return ''.join(['%02x' % ord(c) for c in self.digest()])




# ======================================================================
# Mimic Python top-level functions from standard library API
# for consistency with the md5 module of the standard library.
# ======================================================================

# These are mandatory variables in the module. They have constant values
# in the SHA standard.

digest_size = digestsize = 20
blocksize = 1
[/code]
May 7, 2009, 4:05 PM
Yegg
Nice work.
May 7, 2009, 6:09 PM

Search