[GH-ISSUE #1814] Blockchain v1 not cracking #1208

Closed
opened 2026-10-14 03:39:15 +07:00 by bsakaguchi · 17 comments
Owner

Originally created by @kost123 on GitHub (Oct 11, 2015).
Original GitHub issue: https://github.com/openwall/john/issues/1814

Originally assigned to: @kholia on GitHub.

Version 2 wallets crack fine but version 1 does not...

here is an example v1 wallet and password.

http://clicknupload.com/n7b2u5y4lmg3

Password: btcr-test-password

Originally created by @kost123 on GitHub (Oct 11, 2015). Original GitHub issue: https://github.com/openwall/john/issues/1814 Originally assigned to: @kholia on GitHub. Version 2 wallets crack fine but version 1 does not... here is an example v1 wallet and password. http://clicknupload.com/n7b2u5y4lmg3 Password: btcr-test-password
bsakaguchi 2026-10-14 03:39:15 +07:00
  • closed this issue
  • added the
    bug
    label
Author
Owner

@kost123 commented on GitHub (Oct 14, 2015):

Anybody know who the guy is who made the blockchain config?

<!-- gh-comment-id:147887868 --> @kost123 commented on GitHub (Oct 14, 2015): Anybody know who the guy is who made the blockchain config?
Author
Owner

@magnumripper commented on GitHub (Oct 14, 2015):

What do you mean with "config"?

<!-- gh-comment-id:147895197 --> @magnumripper commented on GitHub (Oct 14, 2015): What do you mean with "config"?
Author
Owner

@kost123 commented on GitHub (Oct 14, 2015):

The blockchain module that decrypts.. I don't know what to call it.

<!-- gh-comment-id:148031115 --> @kost123 commented on GitHub (Oct 14, 2015): The blockchain module that decrypts.. I don't know what to call it.
Author
Owner

@magnumripper commented on GitHub (Oct 14, 2015):

Are you talking about the blockchain format in JtR? It's written by @kholia

<!-- gh-comment-id:148104257 --> @magnumripper commented on GitHub (Oct 14, 2015): Are you talking about the blockchain format in JtR? It's written by @kholia
Author
Owner

@kholia commented on GitHub (Oct 14, 2015):

@ljx34 how did you generate / get this file?

I can't import it using the https://blockchain.info site (by using the "Import Wallet" option).

<!-- gh-comment-id:148108299 --> @kholia commented on GitHub (Oct 14, 2015): @ljx34 how did you generate / get this file? I can't import it using the https://blockchain.info site (by using the "Import Wallet" option).
Author
Owner

@kost123 commented on GitHub (Oct 14, 2015):

@kholia I just tried importing it and it worked fine...

EDIT: Hmm... this wallet has a second password on it for editing security info... maybe thats the reason.. I need to find a v1 wallet to try without, could be my bad.

<!-- gh-comment-id:148148513 --> @kost123 commented on GitHub (Oct 14, 2015): @kholia I just tried importing it and it worked fine... EDIT: Hmm... this wallet has a second password on it for editing security info... maybe thats the reason.. I need to find a v1 wallet to try without, could be my bad.
Author
Owner

@kost123 commented on GitHub (Oct 20, 2015):

@kholia I have confirmed it is not working... here is a wallet with a single password.

http://clicknupload.com/otrfc91fpzoc

Password: yueliaoli888

<!-- gh-comment-id:149418181 --> @kost123 commented on GitHub (Oct 20, 2015): @kholia I have confirmed it is not working... here is a wallet with a single password. http://clicknupload.com/otrfc91fpzoc Password: yueliaoli888
Author
Owner

@kost123 commented on GitHub (Oct 21, 2015):

From blockchains site:
...................
Encryption

Single Pass - By default all wallets are stored by AES encrypting the entire JSON payload with the users password which is then encoded as base64. A 16 byte iv is prepended to the wallet file used for PBKDF2 key stretching. The exact AES specifications are n rounds of PBKDF2 (Default 10 if not specified), Block Mode CBC ISO10126 padding.

var crypted = Crypto.AES.encrypt(json, password);
..........................

Is JTR trying to use 10round of PBKDF2 by default? or 1?

Should be 10 right?

<!-- gh-comment-id:149772786 --> @kost123 commented on GitHub (Oct 21, 2015): From blockchains site: ................... Encryption Single Pass - By default all wallets are stored by AES encrypting the entire JSON payload with the users password which is then encoded as base64. A 16 byte iv is prepended to the wallet file used for PBKDF2 key stretching. The exact AES specifications are n rounds of PBKDF2 (Default 10 if not specified), Block Mode CBC ISO10126 padding. var crypted = Crypto.AES.encrypt(json, password); .......................... Is JTR trying to use 10round of PBKDF2 by default? or 1? Should be 10 right?
Author
Owner

@magnumripper commented on GitHub (Oct 21, 2015):

Yes, our code seems to fall-back to 10.

<!-- gh-comment-id:150007628 --> @magnumripper commented on GitHub (Oct 21, 2015): Yes, our code seems to fall-back to 10.
Author
Owner

@magnumripper commented on GitHub (Oct 21, 2015):

@kholia this is a false-negative bug. At the very least we have to reject unsupported hashes in valid().

<!-- gh-comment-id:150008032 --> @magnumripper commented on GitHub (Oct 21, 2015): @kholia this is a false-negative bug. At the very least we have to reject unsupported hashes in valid().
Author
Owner

@kost123 commented on GitHub (Oct 21, 2015):

EDIT: Nvm, took a look at the code and it's a bit above me :3

<!-- gh-comment-id:150015208 --> @kost123 commented on GitHub (Oct 21, 2015): EDIT: Nvm, took a look at the code and it's a bit above me :3
Author
Owner

@magnumripper commented on GitHub (Oct 21, 2015):

It's this part of get_salt()

    ctcopy += TAG_LENGTH;
    p = strtokm(ctcopy, "$");
    if (!strcmp(p, "v2")) {
        p = strtokm(NULL, "$");
        cs->iter = atoi(p);
        p = strtokm(NULL, "$");
    } else
        cs->iter = 10;
<!-- gh-comment-id:150037973 --> @magnumripper commented on GitHub (Oct 21, 2015): It's this part of `get_salt()` ``` c ctcopy += TAG_LENGTH; p = strtokm(ctcopy, "$"); if (!strcmp(p, "v2")) { p = strtokm(NULL, "$"); cs->iter = atoi(p); p = strtokm(NULL, "$"); } else cs->iter = 10; ```
Author
Owner

@magnumripper commented on GitHub (Oct 21, 2015):

Here's the output from blockchain2john for that wallet:

warlet.aes.json:$blockchain$704$2b576c46724b7973614a564e6f3530312b53684d59526978615966452b61417563494337363947637831446a64434a666e6249516376747865744635644c396f3831624442493479566751635a6b432b754a4d765679736c7a6c577651372f3373565351616e2b33456b2b7a5a4a476b4e324e4b6d3945447531434b72374c6956702b7a414878426565637168555170315747567a4844485833723961746a487a316c737231627738337459507333486767424b47344d7a7756496a4c464a2b5a503658423664667358526356524f6d707970505145654e6d6b3163445134574f397768772f763567797132666f7a46413157346f6e545375575157436231625a326e6b7a522b4e3279736c7664354a6f68682b5731416a7258496669456d4d68666f6a7662544764454a36524f7356385758624451776d70687579556872617458306b59594f71636f76674559502b7a2f574b51656c37456f5a4471726c4c6178433767336231354537754c416344594362544a307451554f425a34312f696663416f706d476f6c30485a2f6178714845634c68517a624a3459565031617149616f79472b645a786d3157535038312f64506a2f3549414f7a4d6a6b76436a464d4e79365069412f682f4a336b4a627a61474e4736636f784644457675793331784a522f67614f64506c375436614752634b482b7067715a424c6f68793558796c34756a484176326f536b4b2b4d343055395a4c735a2b41574a4c5a79673837535a4e49576a39797a43494331787549346970415732437a314555647852586e5667626d2f384c4b697667514c74346b314b55532b5578305776672b7573614b70794b423071565862634f317870495a71355574504366515147674a6647583462384b4d2b323034693774566f447776436f554f4a6b74765862416e57365759496b7262616d35577173384c6b4f557671726f42715063506f304d6d572f4b

It says 704 iterations if I understand it correctly.

<!-- gh-comment-id:150038608 --> @magnumripper commented on GitHub (Oct 21, 2015): Here's the output from blockchain2john for that wallet: ``` warlet.aes.json:$blockchain$704$2b576c46724b7973614a564e6f3530312b53684d59526978615966452b61417563494337363947637831446a64434a666e6249516376747865744635644c396f3831624442493479566751635a6b432b754a4d765679736c7a6c577651372f3373565351616e2b33456b2b7a5a4a476b4e324e4b6d3945447531434b72374c6956702b7a414878426565637168555170315747567a4844485833723961746a487a316c737231627738337459507333486767424b47344d7a7756496a4c464a2b5a503658423664667358526356524f6d707970505145654e6d6b3163445134574f397768772f763567797132666f7a46413157346f6e545375575157436231625a326e6b7a522b4e3279736c7664354a6f68682b5731416a7258496669456d4d68666f6a7662544764454a36524f7356385758624451776d70687579556872617458306b59594f71636f76674559502b7a2f574b51656c37456f5a4471726c4c6178433767336231354537754c416344594362544a307451554f425a34312f696663416f706d476f6c30485a2f6178714845634c68517a624a3459565031617149616f79472b645a786d3157535038312f64506a2f3549414f7a4d6a6b76436a464d4e79365069412f682f4a336b4a627a61474e4736636f784644457675793331784a522f67614f64506c375436614752634b482b7067715a424c6f68793558796c34756a484176326f536b4b2b4d343055395a4c735a2b41574a4c5a79673837535a4e49576a39797a43494331787549346970415732437a314555647852586e5667626d2f384c4b697667514c74346b314b55532b5578305776672b7573614b70794b423071565862634f317870495a71355574504366515147674a6647583462384b4d2b323034693774566f447776436f554f4a6b74765862416e57365759496b7262616d35577173384c6b4f557671726f42715063506f304d6d572f4b ``` It says 704 iterations if I understand it correctly.
Author
Owner

@kholia commented on GitHub (Oct 21, 2015):

@magnumripper 704 is the data length, the code comes from my early days ;)

I can't maintain this format - I have too less free time these days.

@ljx34 the code is super easy to understand - submit patches please :-)

<!-- gh-comment-id:150041395 --> @kholia commented on GitHub (Oct 21, 2015): @magnumripper 704 is the data length, the code comes from my early days ;) I can't maintain this format - I have too less free time these days. @ljx34 the code is super easy to understand - submit patches please :-)
Author
Owner

@kost123 commented on GitHub (Oct 24, 2015):

I found this.. it may help... it's from a python blockchain cracker that find v0, v1 and v2 wallets

############### Blockchain ###############

@register_wallet_class
class WalletBlockchain(object):

    class __metaclass__(type):
        @property
        def data_extract_id(cls):    return b"bk"

    @staticmethod
    def is_wallet_file(wallet_file): return None  # there's no easy way to check this

    def __init__(self, iter_count, loading = False):
        assert loading, 'use load_from_* to create a ' + self.__class__.__name__
        pbkdf2_library_name = load_pbkdf2_library().__name__
        aes_library_name    = load_aes256_library().__name__
        self._iter_count           = iter_count
        self._passwords_per_second = 400000 if pbkdf2_library_name == "hashlib" else 100000
        if iter_count == 0:  # if it's a v0 wallet
            iter_count = 10
        self._passwords_per_second /= iter_count
        if aes_library_name != b"Crypto" and self._passwords_per_second > 2000:
            self._passwords_per_second = 2000

    def __setstate__(self, state):
        # (re-)load the required libraries after being unpickled
        load_pbkdf2_library()
        load_aes256_library()
        self.__dict__ = state

    def passwords_per_seconds(self, seconds):
        return max(int(round(self._passwords_per_second * seconds)), 1)

    # Load a Blockchain wallet file (the part of it we need)
    @classmethod
    def load_from_filename(cls, wallet_filename):
        with open(wallet_filename) as wallet_file:
            data, iter_count = cls._parse_encrypted_blockchain_wallet(wallet_file.read(1048576))  # up to 1M, typical size is a few k
        self = cls(iter_count, loading=True)
        self._salt_and_iv     = data[:16]    # only need the salt_and_iv plus
        self._encrypted_block = data[16:32]  # the first 16-byte encrypted block
        return self

    # Parse the contents of an encrypted blockchain wallet (either v0 or v2) returning two
    # values in a tuple: (encrypted_data_blob, iter_count) where iter_count == 0 for v0 wallets
    @staticmethod
    def _parse_encrypted_blockchain_wallet(data):
        iter_count = 0

        # Try to load a v2.0 wallet file (which contains an iter_count)
        if data[0] == "{":
            try:
                data = json.loads(data)
            except ValueError: pass
            else:
                if data[u"version"] != 2:
                    raise NotImplementedError("Unsupported Blockchain wallet version " + tstr(data[u"version"]))
                iter_count = data[u"pbkdf2_iterations"]
                if not isinstance(iter_count, int) or iter_count < 1:
                    raise ValueError("Invalid Blockchain pbkdf2_iterations " + tstr(iter_count))
                data = data[u"payload"]

        # Either the encrypted data was extracted from the "payload" field above, or
        # this is a v0.0 wallet file whose entire contents consist of the encrypted data
        try:
            data = base64.b64decode(data)
        except TypeError as e:
            raise ValueError("Can't base64-decode Blockchain wallet: "+tstr(e))
        if len(data) < 32:
            raise ValueError("Encrypted Blockchain data is too short")
        if len(data) % 16 != 0:
            raise ValueError("Encrypted Blockchain data length is not divisible by the encryption blocksize (16)")

        # If this is (possibly) a v0.0 (a.k.a. v1) wallet file, check that the encrypted data
        # looks random, otherwise this could be some other type of base64-encoded file such
        # as a MultiBit key file (it should be safe to skip this test for v2.0 wallets)
        if not iter_count:  # if this is a v0.0 wallet
            # The likelihood of of finding a valid encrypted blockchain wallet (even at its minimum length
            # of about 500 bytes) with less than 7.4 bits of entropy per byte is less than 1 in 10^6
            entropy_bits = est_entropy_bits(data)
            if entropy_bits < 7.4:
                raise ValueError("Doesn't look random enough to be an encrypted Blockchain wallet (only {:.1f} bits of entropy per byte)".format(entropy_bits))

        return data, iter_count  # iter_count == 0 for v0 wallets

    # Import extracted Blockchain file data necessary for main password checking
    @classmethod
    def load_from_data_extract(cls, file_data):
        # These are the same first encrypted block, salt_and_iv, iteration count retrieved above
        encrypted_block, salt_and_iv, iter_count = struct.unpack(b"< 16s 16s I", file_data)
        self = cls(iter_count, loading=True)
        self._encrypted_block = encrypted_block
        self._salt_and_iv     = salt_and_iv
        return self

    # This is the time-consuming function executed by worker thread(s). It returns a tuple: if a password
    # is correct return it, else return False for item 0; return a count of passwords checked for item 1
    def return_verified_password_or_false(self, passwords):
        # Copy a few globals into local for a small speed boost
        l_pbkdf2_hmac        = pbkdf2_hmac
        l_aes256_cbc_decrypt = aes256_cbc_decrypt
        l_aes256_ofb_decrypt = aes256_ofb_decrypt
        encrypted_block      = self._encrypted_block
        salt_and_iv          = self._salt_and_iv
        iter_count           = self._iter_count

        # Convert Unicode strings (lazily) to UTF-8 bytestrings
        if tstr == unicode:
            passwords = map(lambda p: p.encode("utf_8", "ignore"), passwords)

        v0 = not iter_count     # version 0.0 wallets don't specify an iter_count
        if v0: iter_count = 10  # the default iter_count for version 0.0 wallets
        for count, password in enumerate(passwords, 1):
            key = l_pbkdf2_hmac(b"sha1", password, salt_and_iv, iter_count, 32)          # iter_count iterations
            unencrypted_block = l_aes256_cbc_decrypt(key, salt_and_iv, encrypted_block)  # CBC mode
            # A bit fragile because it assumes the guid is in the first encrypted block,
            # although this has always been the case as of 6/2014 (since 12/2011)
            if unencrypted_block[0] == b"{" and b'"guid"' in unencrypted_block:
                return password if tstr == str else password.decode("utf_8", "replace"), count

        if v0:
            # Try the older encryption schemes possibly used in v0.0 wallets
            for count, password in enumerate(passwords, 1):
                key = l_pbkdf2_hmac(b"sha1", password, salt_and_iv, 1, 32)                   # only 1 iteration
                unencrypted_block = l_aes256_cbc_decrypt(key, salt_and_iv, encrypted_block)  # CBC mode
                if unencrypted_block[0] == b"{" and b'"guid"' in unencrypted_block:
                    return password if tstr == str else password.decode("utf_8", "replace"), count
                unencrypted_block = l_aes256_ofb_decrypt(key, salt_and_iv, encrypted_block)  # OFB mode
                if unencrypted_block[0] == b"{" and b'"guid"' in unencrypted_block:
                    return password if tstr == str else password.decode("utf_8", "replace"), count

        return False, count

@register_wallet_class
class WalletBlockchainSecondpass(WalletBlockchain):

    class __metaclass__(WalletBlockchain.__metaclass__):
        @property
        def data_extract_id(cls):    return b"bs"

    @staticmethod
    def is_wallet_file(wallet_file): return False  # never auto-detected as this wallet type

    # Load a Blockchain wallet file to get the "Second Password" hash,
    # decrypting the wallet if necessary
    @classmethod
    def load_from_filename(cls, wallet_filename, password = None, force_purepython = False):
        from uuid import UUID

        with open(wallet_filename) as wallet_file:
            data = wallet_file.read(1048576)  # up to 1M, typical size is a few k

        try:
            # Assuming the wallet is encrypted, get the encrypted data
            data, iter_count = cls._parse_encrypted_blockchain_wallet(data)
        except KeyError as e:
            # This is the one error to expect and ignore which occurs when the wallet isn't encrypted
            if e.args[0] == "version": pass
            else: raise
        except StandardError as e:
            error_exit(tstr(e))
        else:
            # If there were no problems getting the encrypted data, decrypt it
            if not password:
                password = prompt_unicode_password(
                    "Please enter the Blockchain wallet's main password: ",
                    "encrypted Blockchain files must be decrypted before searching for the second password")
            password = password.encode("utf_8")
            data, salt_and_iv = data[16:], data[:16]
            load_pbkdf2_library(force_purepython)
            load_aes256_library(force_purepython)
            #
            # These are a bit fragile in the interest of simplicity because they assume the guid is the first
            # name in the JSON object, although this has always been the case as of 6/2014 (since 12/2011)
            #
            # Encryption scheme used in newer wallets
            def decrypt_current(iter_count):
                key = pbkdf2_hmac(b"sha1", password, salt_and_iv, iter_count, 32)
                decrypted = aes256_cbc_decrypt(key, salt_and_iv, data)    # CBC mode
                padding   = ord(decrypted[-1:])                           # ISO 10126 padding length
                return decrypted[:-padding] if 1 <= padding <= 16 and re.match(b'{\s*"guid"', decrypted) else None
            #
            # Encryption scheme only used in version 0.0 wallets (N.B. this is untested)
            def decrypt_old():
                key = pbkdf2_hmac(b"sha1", password, salt_and_iv, 1, 32)  # only 1 iteration
                decrypted  = aes256_ofb_decrypt(key, salt_and_iv, data)   # OFB mode
                # The 16-byte last block, reversed, with all but the first byte of ISO 7816-4 padding removed:
                last_block = tuple(itertools.dropwhile(lambda x: x==b"\0", decrypted[:15:-1]))
                padding    = 17 - len(last_block)                         # ISO 7816-4 padding length
                return decrypted[:-padding] if 1 <= padding <= 16 and decrypted[-padding] == b"\x80" and re.match(b'{\s*"guid"', decrypted) else None
            #
            if iter_count:  # v2.0 wallets have a single possible encryption scheme
                data = decrypt_current(iter_count)
            else:           # v0.0 wallets have three different possible encryption schemes
                data = decrypt_current(10) or decrypt_current(1) or decrypt_old()
            if not data:
                error_exit("can't decrypt wallet (wrong main password?)")

        # Load and parse the now-decrypted wallet
        data = json.loads(data)
        if not data.get(u"double_encryption"):
            error_exit("double encryption with a second password is not enabled for this wallet")

        # Extract and save what we need to perform checking on the second password
        try:
            iter_count = data[u"options"][u"pbkdf2_iterations"]
            if not isinstance(iter_count, int) or iter_count < 1:
                raise ValueError("Invalid Blockchain second password pbkdf2_iterations " + tstr(iter_count))
        except KeyError:
            iter_count = 0
        self = cls(iter_count, loading=True)
        #
        self._password_hash = base64.b16decode(data[u"dpasswordhash"], casefold=True)
        if len(self._password_hash) != 32:
            raise ValueError("Blockchain second password hash is not 32 bytes long")
        #
        self._salt = data[u"sharedKey"].encode("ascii")
        if str(UUID(self._salt)) != self._salt:
            raise ValueError("Unrecognized Blockchain salt format")

        return self

    # Import extracted Blockchain file data necessary for second password checking
    @classmethod
    def load_from_data_extract(cls, file_data):
        from uuid import UUID
        # These are the same second password hash, salt, iteration count retrieved above
        password_hash, uuid_salt, iter_count = struct.unpack(b"< 32s 16s I", file_data)
        self = cls(iter_count, loading=True)
        self._salt          = str(UUID(bytes=uuid_salt))
        self._password_hash = password_hash
        return self

    # This is the time-consuming function executed by worker thread(s). It returns a tuple: if a password
    # is correct return it, else return False for item 0; return a count of passwords checked for item 1
    def return_verified_password_or_false(self, passwords):
        # Copy vars into locals for a small speed boost
        l_sha256 = hashlib.sha256
        password_hash = self._password_hash
        salt          = self._salt
        iter_count    = self._iter_count

        # Convert Unicode strings (lazily) to UTF-8 bytestrings
        if tstr == unicode:
            passwords = itertools.imap(lambda p: p.encode("utf_8", "ignore"), passwords)

        # Newer wallets specify an iter_count and use something similar to PBKDF1 with SHA-256
        if iter_count:
            for count, password in enumerate(passwords, 1):
                running_hash = salt + password
                for i in xrange(iter_count):
                    running_hash = l_sha256(running_hash).digest()
                if running_hash == password_hash:
                    return password if tstr == str else password.decode("utf_8", "replace"), count

        # Older wallets used one of three password hashing schemes
        else:
            for count, password in enumerate(passwords, 1):
                running_hash = l_sha256(salt + password).digest()
                # Just a single SHA-256 hash
                if running_hash == password_hash:
                    return password if tstr == str else password.decode("utf_8", "replace"), count
                # Exactly 10 hashes (the first of which was done above)
                for i in xrange(9):
                    running_hash = l_sha256(running_hash).digest()
                if running_hash == password_hash:
                    return password if tstr == str else password.decode("utf_8", "replace"), count
                # A single unsalted hash
                if l_sha256(password).digest() == password_hash:
                    return password if tstr == str else password.decode("utf_8", "replace"), count

        return False, count
<!-- gh-comment-id:150762935 --> @kost123 commented on GitHub (Oct 24, 2015): I found this.. it may help... it's from a python blockchain cracker that find v0, v1 and v2 wallets ############### Blockchain ############### ``` @register_wallet_class class WalletBlockchain(object): class __metaclass__(type): @property def data_extract_id(cls): return b"bk" @staticmethod def is_wallet_file(wallet_file): return None # there's no easy way to check this def __init__(self, iter_count, loading = False): assert loading, 'use load_from_* to create a ' + self.__class__.__name__ pbkdf2_library_name = load_pbkdf2_library().__name__ aes_library_name = load_aes256_library().__name__ self._iter_count = iter_count self._passwords_per_second = 400000 if pbkdf2_library_name == "hashlib" else 100000 if iter_count == 0: # if it's a v0 wallet iter_count = 10 self._passwords_per_second /= iter_count if aes_library_name != b"Crypto" and self._passwords_per_second > 2000: self._passwords_per_second = 2000 def __setstate__(self, state): # (re-)load the required libraries after being unpickled load_pbkdf2_library() load_aes256_library() self.__dict__ = state def passwords_per_seconds(self, seconds): return max(int(round(self._passwords_per_second * seconds)), 1) # Load a Blockchain wallet file (the part of it we need) @classmethod def load_from_filename(cls, wallet_filename): with open(wallet_filename) as wallet_file: data, iter_count = cls._parse_encrypted_blockchain_wallet(wallet_file.read(1048576)) # up to 1M, typical size is a few k self = cls(iter_count, loading=True) self._salt_and_iv = data[:16] # only need the salt_and_iv plus self._encrypted_block = data[16:32] # the first 16-byte encrypted block return self # Parse the contents of an encrypted blockchain wallet (either v0 or v2) returning two # values in a tuple: (encrypted_data_blob, iter_count) where iter_count == 0 for v0 wallets @staticmethod def _parse_encrypted_blockchain_wallet(data): iter_count = 0 # Try to load a v2.0 wallet file (which contains an iter_count) if data[0] == "{": try: data = json.loads(data) except ValueError: pass else: if data[u"version"] != 2: raise NotImplementedError("Unsupported Blockchain wallet version " + tstr(data[u"version"])) iter_count = data[u"pbkdf2_iterations"] if not isinstance(iter_count, int) or iter_count < 1: raise ValueError("Invalid Blockchain pbkdf2_iterations " + tstr(iter_count)) data = data[u"payload"] # Either the encrypted data was extracted from the "payload" field above, or # this is a v0.0 wallet file whose entire contents consist of the encrypted data try: data = base64.b64decode(data) except TypeError as e: raise ValueError("Can't base64-decode Blockchain wallet: "+tstr(e)) if len(data) < 32: raise ValueError("Encrypted Blockchain data is too short") if len(data) % 16 != 0: raise ValueError("Encrypted Blockchain data length is not divisible by the encryption blocksize (16)") # If this is (possibly) a v0.0 (a.k.a. v1) wallet file, check that the encrypted data # looks random, otherwise this could be some other type of base64-encoded file such # as a MultiBit key file (it should be safe to skip this test for v2.0 wallets) if not iter_count: # if this is a v0.0 wallet # The likelihood of of finding a valid encrypted blockchain wallet (even at its minimum length # of about 500 bytes) with less than 7.4 bits of entropy per byte is less than 1 in 10^6 entropy_bits = est_entropy_bits(data) if entropy_bits < 7.4: raise ValueError("Doesn't look random enough to be an encrypted Blockchain wallet (only {:.1f} bits of entropy per byte)".format(entropy_bits)) return data, iter_count # iter_count == 0 for v0 wallets # Import extracted Blockchain file data necessary for main password checking @classmethod def load_from_data_extract(cls, file_data): # These are the same first encrypted block, salt_and_iv, iteration count retrieved above encrypted_block, salt_and_iv, iter_count = struct.unpack(b"< 16s 16s I", file_data) self = cls(iter_count, loading=True) self._encrypted_block = encrypted_block self._salt_and_iv = salt_and_iv return self # This is the time-consuming function executed by worker thread(s). It returns a tuple: if a password # is correct return it, else return False for item 0; return a count of passwords checked for item 1 def return_verified_password_or_false(self, passwords): # Copy a few globals into local for a small speed boost l_pbkdf2_hmac = pbkdf2_hmac l_aes256_cbc_decrypt = aes256_cbc_decrypt l_aes256_ofb_decrypt = aes256_ofb_decrypt encrypted_block = self._encrypted_block salt_and_iv = self._salt_and_iv iter_count = self._iter_count # Convert Unicode strings (lazily) to UTF-8 bytestrings if tstr == unicode: passwords = map(lambda p: p.encode("utf_8", "ignore"), passwords) v0 = not iter_count # version 0.0 wallets don't specify an iter_count if v0: iter_count = 10 # the default iter_count for version 0.0 wallets for count, password in enumerate(passwords, 1): key = l_pbkdf2_hmac(b"sha1", password, salt_and_iv, iter_count, 32) # iter_count iterations unencrypted_block = l_aes256_cbc_decrypt(key, salt_and_iv, encrypted_block) # CBC mode # A bit fragile because it assumes the guid is in the first encrypted block, # although this has always been the case as of 6/2014 (since 12/2011) if unencrypted_block[0] == b"{" and b'"guid"' in unencrypted_block: return password if tstr == str else password.decode("utf_8", "replace"), count if v0: # Try the older encryption schemes possibly used in v0.0 wallets for count, password in enumerate(passwords, 1): key = l_pbkdf2_hmac(b"sha1", password, salt_and_iv, 1, 32) # only 1 iteration unencrypted_block = l_aes256_cbc_decrypt(key, salt_and_iv, encrypted_block) # CBC mode if unencrypted_block[0] == b"{" and b'"guid"' in unencrypted_block: return password if tstr == str else password.decode("utf_8", "replace"), count unencrypted_block = l_aes256_ofb_decrypt(key, salt_and_iv, encrypted_block) # OFB mode if unencrypted_block[0] == b"{" and b'"guid"' in unencrypted_block: return password if tstr == str else password.decode("utf_8", "replace"), count return False, count @register_wallet_class class WalletBlockchainSecondpass(WalletBlockchain): class __metaclass__(WalletBlockchain.__metaclass__): @property def data_extract_id(cls): return b"bs" @staticmethod def is_wallet_file(wallet_file): return False # never auto-detected as this wallet type # Load a Blockchain wallet file to get the "Second Password" hash, # decrypting the wallet if necessary @classmethod def load_from_filename(cls, wallet_filename, password = None, force_purepython = False): from uuid import UUID with open(wallet_filename) as wallet_file: data = wallet_file.read(1048576) # up to 1M, typical size is a few k try: # Assuming the wallet is encrypted, get the encrypted data data, iter_count = cls._parse_encrypted_blockchain_wallet(data) except KeyError as e: # This is the one error to expect and ignore which occurs when the wallet isn't encrypted if e.args[0] == "version": pass else: raise except StandardError as e: error_exit(tstr(e)) else: # If there were no problems getting the encrypted data, decrypt it if not password: password = prompt_unicode_password( "Please enter the Blockchain wallet's main password: ", "encrypted Blockchain files must be decrypted before searching for the second password") password = password.encode("utf_8") data, salt_and_iv = data[16:], data[:16] load_pbkdf2_library(force_purepython) load_aes256_library(force_purepython) # # These are a bit fragile in the interest of simplicity because they assume the guid is the first # name in the JSON object, although this has always been the case as of 6/2014 (since 12/2011) # # Encryption scheme used in newer wallets def decrypt_current(iter_count): key = pbkdf2_hmac(b"sha1", password, salt_and_iv, iter_count, 32) decrypted = aes256_cbc_decrypt(key, salt_and_iv, data) # CBC mode padding = ord(decrypted[-1:]) # ISO 10126 padding length return decrypted[:-padding] if 1 <= padding <= 16 and re.match(b'{\s*"guid"', decrypted) else None # # Encryption scheme only used in version 0.0 wallets (N.B. this is untested) def decrypt_old(): key = pbkdf2_hmac(b"sha1", password, salt_and_iv, 1, 32) # only 1 iteration decrypted = aes256_ofb_decrypt(key, salt_and_iv, data) # OFB mode # The 16-byte last block, reversed, with all but the first byte of ISO 7816-4 padding removed: last_block = tuple(itertools.dropwhile(lambda x: x==b"\0", decrypted[:15:-1])) padding = 17 - len(last_block) # ISO 7816-4 padding length return decrypted[:-padding] if 1 <= padding <= 16 and decrypted[-padding] == b"\x80" and re.match(b'{\s*"guid"', decrypted) else None # if iter_count: # v2.0 wallets have a single possible encryption scheme data = decrypt_current(iter_count) else: # v0.0 wallets have three different possible encryption schemes data = decrypt_current(10) or decrypt_current(1) or decrypt_old() if not data: error_exit("can't decrypt wallet (wrong main password?)") # Load and parse the now-decrypted wallet data = json.loads(data) if not data.get(u"double_encryption"): error_exit("double encryption with a second password is not enabled for this wallet") # Extract and save what we need to perform checking on the second password try: iter_count = data[u"options"][u"pbkdf2_iterations"] if not isinstance(iter_count, int) or iter_count < 1: raise ValueError("Invalid Blockchain second password pbkdf2_iterations " + tstr(iter_count)) except KeyError: iter_count = 0 self = cls(iter_count, loading=True) # self._password_hash = base64.b16decode(data[u"dpasswordhash"], casefold=True) if len(self._password_hash) != 32: raise ValueError("Blockchain second password hash is not 32 bytes long") # self._salt = data[u"sharedKey"].encode("ascii") if str(UUID(self._salt)) != self._salt: raise ValueError("Unrecognized Blockchain salt format") return self # Import extracted Blockchain file data necessary for second password checking @classmethod def load_from_data_extract(cls, file_data): from uuid import UUID # These are the same second password hash, salt, iteration count retrieved above password_hash, uuid_salt, iter_count = struct.unpack(b"< 32s 16s I", file_data) self = cls(iter_count, loading=True) self._salt = str(UUID(bytes=uuid_salt)) self._password_hash = password_hash return self # This is the time-consuming function executed by worker thread(s). It returns a tuple: if a password # is correct return it, else return False for item 0; return a count of passwords checked for item 1 def return_verified_password_or_false(self, passwords): # Copy vars into locals for a small speed boost l_sha256 = hashlib.sha256 password_hash = self._password_hash salt = self._salt iter_count = self._iter_count # Convert Unicode strings (lazily) to UTF-8 bytestrings if tstr == unicode: passwords = itertools.imap(lambda p: p.encode("utf_8", "ignore"), passwords) # Newer wallets specify an iter_count and use something similar to PBKDF1 with SHA-256 if iter_count: for count, password in enumerate(passwords, 1): running_hash = salt + password for i in xrange(iter_count): running_hash = l_sha256(running_hash).digest() if running_hash == password_hash: return password if tstr == str else password.decode("utf_8", "replace"), count # Older wallets used one of three password hashing schemes else: for count, password in enumerate(passwords, 1): running_hash = l_sha256(salt + password).digest() # Just a single SHA-256 hash if running_hash == password_hash: return password if tstr == str else password.decode("utf_8", "replace"), count # Exactly 10 hashes (the first of which was done above) for i in xrange(9): running_hash = l_sha256(running_hash).digest() if running_hash == password_hash: return password if tstr == str else password.decode("utf_8", "replace"), count # A single unsalted hash if l_sha256(password).digest() == password_hash: return password if tstr == str else password.decode("utf_8", "replace"), count return False, count ```
Author
Owner

@kost123 commented on GitHub (Oct 27, 2015):

This can be closed as I'm not sure what you did, but you changed blockchain2john.py and now it is cracking the hashes with --base64 option, which is odd seen as I thought it was decrypting with that beforehand, I only just noticed because I thought you would close the issue when fixed.

<!-- gh-comment-id:151453904 --> @kost123 commented on GitHub (Oct 27, 2015): This can be closed as I'm not sure what you did, but you changed blockchain2john.py and now it is cracking the hashes with --base64 option, which is odd seen as I thought it was decrypting with that beforehand, I only just noticed because I thought you would close the issue when fixed.
Author
Owner

@magnumripper commented on GitHub (Oct 27, 2015):

Cool!

<!-- gh-comment-id:151558009 --> @magnumripper commented on GitHub (Oct 27, 2015): Cool!
Sign in to join this conversation.
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference
openwall/john#1208
No description provided.