Create a gist now

Instantly share code, notes, and snippets.

@SciresM /CMAC.py
Last active Jun 24, 2018

Embed
What would you like to do?
Script to decrypt/re-encrypt (resign) Splatoon 2 save files.
# -*- coding: utf-8 -*-
#
# Hash/CMAC.py - Implements the CMAC algorithm
#
# ===================================================================
# The contents of this file are dedicated to the public domain. To
# the extent that dedication to the public domain is not available,
# everyone is granted a worldwide, perpetual, royalty-free,
# non-exclusive license to exercise all rights associated with the
# contents of this file for any purpose whatsoever.
# No rights are reserved.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
# ===================================================================
"""CMAC (Cipher-based Message Authentication Code) algorithm
CMAC is a MAC defined in `NIST SP 800-38B`_ and in RFC4493_ (for AES only)
and constructed using a block cipher. It was originally known as `OMAC1`_.
The algorithm is sometimes named *X-CMAC* where *X* is the name
of the cipher (e.g. AES-CMAC).
This is an example showing how to *create* an AES-CMAC:
>>> from Crypto.Hash import CMAC
>>> from Crypto.Cipher import AES
>>>
>>> secret = b'Sixteen byte key'
>>> cobj = CMAC.new(secret, ciphermod=AES)
>>> cobj.update(b'Hello')
>>> print cobj.hexdigest()
And this is an example showing how to *check* an AES-CMAC:
>>> from Crypto.Hash import CMAC
>>> from Crypto.Cipher import AES
>>>
>>> # We have received a message 'msg' together
>>> # with its MAC 'mac'
>>>
>>> secret = b'Sixteen byte key'
>>> cobj = CMAC.new(secret, ciphermod=AES)
>>> cobj.update(msg)
>>> try:
>>> cobj.verify(mac)
>>> print "The message '%s' is authentic" % msg
>>> except ValueError:
>>> print "The message or the key is wrong"
.. _`NIST SP 800-38B`: http://csrc.nist.gov/publications/nistpubs/800-38B/SP_800-38B.pdf
.. _RFC4493: http://www.ietf.org/rfc/rfc4493.txt
.. _OMAC1: http://www.nuee.nagoya-u.ac.jp/labs/tiwata/omac/omac.html
"""
__all__ = ['new', 'digest_size', 'CMAC' ]
import sys
if sys.version_info[0] == 2 and sys.version_info[1] == 1:
from Crypto.Util.py21compat import *
from Crypto.Util.py3compat import *
from binascii import unhexlify
from Crypto.Util.strxor import strxor
from Crypto.Util.number import long_to_bytes, bytes_to_long
#: The size of the authentication tag produced by the MAC.
digest_size = None
def _shift_bytes(bs, xor_lsb=0):
num = (bytes_to_long(bs)<<1) ^ xor_lsb
return long_to_bytes(num, len(bs))[-len(bs):]
class _SmoothMAC(object):
"""Turn a MAC that only operates on aligned blocks of data
into a MAC with granularity of 1 byte."""
def __init__(self, block_size, msg=b(""), min_digest=0):
self._bs = block_size
#: Data waiting to be MAC-ed
self._buffer = []
self._buffer_len = 0
#: Data received via update()
self._total_len = 0
#: Minimum amount of bytes required by the final digest step
self._min_digest = min_digest
#: Block MAC object
self._mac = None
#: Cached digest
self._tag = None
if msg:
self.update(msg)
def can_reduce(self):
return (self._mac is not None)
def get_len(self):
return self._total_len
def zero_pad(self):
if self._buffer_len & (self._bs-1):
npad = self._bs - self._buffer_len & (self._bs-1)
self._buffer.append(bchr(0)*npad)
self._buffer_len += npad
def update(self, data):
# Optimization (try not to copy data if possible)
if self._buffer_len==0 and self.can_reduce() and\
self._min_digest==0 and len(data)%self._bs==0:
self._update(data)
self._total_len += len(data)
return
self._buffer.append(data)
self._buffer_len += len(data)
self._total_len += len(data)
# Feed data into MAC
blocks, rem = divmod(self._buffer_len, self._bs)
if rem<self._min_digest:
blocks -= 1
if blocks>0 and self.can_reduce():
aligned_data = blocks*self._bs
buf = b("").join(self._buffer)
self._update(buf[:aligned_data])
self._buffer = [ buf[aligned_data:] ]
self._buffer_len -= aligned_data
def _deep_copy(self, target):
# Copy everything by self._mac, since we don't know how to
target._buffer = self._buffer[:]
for m in [ '_bs', '_buffer_len', '_total_len', '_min_digest', '_tag' ]:
setattr(target, m, getattr(self, m))
def _update(self, data_block):
"""Delegate to the implementation the update
of the MAC state given some new *block aligned* data."""
raise NotImplementedError("_update() must be still implemented")
def _digest(self, left_data):
"""Delegate to the implementation the computation
of the final MAC given the current MAC state
and the last piece of data (not block aligned)."""
raise NotImplementedError("_digest() must be still implemented")
def digest(self):
if self._tag:
return self._tag
if self._buffer_len>0:
self.update(b(""))
left_data = b("").join(self._buffer)
self._tag = self._digest(left_data)
return self._tag
class CMAC(_SmoothMAC):
"""Class that implements CMAC"""
#: The size of the authentication tag produced by the MAC.
digest_size = None
def __init__(self, key, msg = None, ciphermod = None):
"""Create a new CMAC object.
:Parameters:
key : byte string
secret key for the CMAC object.
The key must be valid for the underlying cipher algorithm.
For instance, it must be 16 bytes long for AES-128.
msg : byte string
The very first chunk of the message to authenticate.
It is equivalent to an early call to `update`. Optional.
ciphermod : module
A cipher module from `Crypto.Cipher`.
The cipher's block size must be 64 or 128 bits.
It is recommended to use `Crypto.Cipher.AES`.
"""
if ciphermod is None:
raise TypeError("ciphermod must be specified (try AES)")
_SmoothMAC.__init__(self, ciphermod.block_size, msg, 1)
self._key = key
self._factory = ciphermod
# Section 5.3 of NIST SP 800 38B
if ciphermod.block_size==8:
const_Rb = 0x1B
elif ciphermod.block_size==16:
const_Rb = 0x87
else:
raise TypeError("CMAC requires a cipher with a block size of 8 or 16 bytes, not %d" %
(ciphermod.block_size,))
self.digest_size = ciphermod.block_size
# Compute sub-keys
cipher = ciphermod.new(key, ciphermod.MODE_ECB)
l = cipher.encrypt(bchr(0)*ciphermod.block_size)
if bord(l[0]) & 0x80:
self._k1 = _shift_bytes(l, const_Rb)
else:
self._k1 = _shift_bytes(l)
if bord(self._k1[0]) & 0x80:
self._k2 = _shift_bytes(self._k1, const_Rb)
else:
self._k2 = _shift_bytes(self._k1)
# Initialize CBC cipher with zero IV
self._IV = bchr(0)*ciphermod.block_size
self._mac = ciphermod.new(key, ciphermod.MODE_CBC, self._IV)
def update(self, msg):
"""Continue authentication of a message by consuming the next chunk of data.
Repeated calls are equivalent to a single call with the concatenation
of all the arguments. In other words:
>>> m.update(a); m.update(b)
is equivalent to:
>>> m.update(a+b)
:Parameters:
msg : byte string
The next chunk of the message being authenticated
"""
_SmoothMAC.update(self, msg)
def _update(self, data_block):
self._IV = self._mac.encrypt(data_block)[-self._mac.block_size:]
def copy(self):
"""Return a copy ("clone") of the MAC object.
The copy will have the same internal state as the original MAC
object.
This can be used to efficiently compute the MAC of strings that
share a common initial substring.
:Returns: A `CMAC` object
"""
obj = CMAC(self._key, ciphermod=self._factory)
_SmoothMAC._deep_copy(self, obj)
obj._mac = self._factory.new(self._key, self._factory.MODE_CBC, self._IV)
for m in [ '_tag', '_k1', '_k2', '_IV']:
setattr(obj, m, getattr(self, m))
return obj
def digest(self):
"""Return the **binary** (non-printable) MAC of the message that has
been authenticated so far.
This method does not change the state of the MAC object.
You can continue updating the object after calling this function.
:Return: A byte string of `digest_size` bytes. It may contain non-ASCII
characters, including null bytes.
"""
return _SmoothMAC.digest(self)
def _digest(self, last_data):
if len(last_data)==self._bs:
last_block = strxor(last_data, self._k1)
else:
last_block = strxor(last_data+bchr(128)+
bchr(0)*(self._bs-1-len(last_data)), self._k2)
tag = self._mac.encrypt(last_block)
return tag
def hexdigest(self):
"""Return the **printable** MAC of the message that has been
authenticated so far.
This method does not change the state of the MAC object.
:Return: A string of 2* `digest_size` bytes. It contains only
hexadecimal ASCII digits.
"""
return "".join(["%02x" % bord(x)
for x in tuple(self.digest())])
def verify(self, mac_tag):
"""Verify that a given **binary** MAC (computed by another party) is valid.
:Parameters:
mac_tag : byte string
The expected MAC of the message.
:Raises ValueError:
if the MAC does not match. It means that the message
has been tampered with or that the MAC key is incorrect.
"""
mac = self.digest()
res = 0
# Constant-time comparison
for x,y in zip(mac, mac_tag):
res |= bord(x) ^ bord(y)
if res or len(mac_tag)!=self.digest_size:
raise ValueError("MAC check failed")
def hexverify(self, hex_mac_tag):
"""Verify that a given **printable** MAC (computed by another party) is valid.
:Parameters:
hex_mac_tag : string
The expected MAC of the message, as a hexadecimal string.
:Raises ValueError:
if the MAC does not match. It means that the message
has been tampered with or that the MAC key is incorrect.
"""
self.verify(unhexlify(tobytes(hex_mac_tag)))
def new(key, msg = None, ciphermod = None):
"""Create a new CMAC object.
:Parameters:
key : byte string
secret key for the CMAC object.
The key must be valid for the underlying cipher algorithm.
For instance, it must be 16 bytes long for AES-128.
msg : byte string
The very first chunk of the message to authenticate.
It is equivalent to an early call to `CMAC.update`. Optional.
ciphermod : module
A cipher module from `Crypto.Cipher`.
The cipher's block size must be 64 or 128 bits.
Default is `Crypto.Cipher.AES`.
:Returns: A `CMAC` object
"""
return CMAC(key, msg, ciphermod)
import sys, os, struct, CMAC
from Crypto.Cipher import AES
def u32(x):
return (x & 0xFFFFFFFF)
class sead_rand:
'''Implements Splatoon 2's mersenne random generator.'''
def __init__(self, seed):
self.seed = u32(seed)
self.state = [self.seed]
for i in xrange(1, 5):
self.state.append(u32(0x6C078965 * (self.state[-1] ^ (self.state[-1] >> 30)) + i))
self.state = self.state[1:]
def load_state(self, state):
self.state = state[:]
def get_u32(self):
a = u32(self.state[0] ^ (self.state[0] << 11))
self.state[0] = self.state[1]
b = u32(self.state[3])
c = u32(a ^ (a >> 8) ^ b ^ (b >> 19))
self.state[1] = self.state[2]
self.state[2] = b
self.state[3] = c
return c
def check_body_size(vers, sz):
sizes = {0: 0x483A0, 2: 0x86800, 3: 0x88D50}
try:
if sizes[vers] != sz:
print 'Warning: Body is incorrect size for save version (expected %x, got %x).' % (sizes[vers], sz)
except KeyError:
raise ValueError('Invalid save version: %x!' % vers)
def get_keys(vers, seed):
if vers >= 2:
crypt_tab = [0xDFD0A132, 0x1537D7E5, 0xC8B0F6D5, 0x6C31FED3, 0xB7A1221A, 0x9B9DC40C, 0x44315579, 0xF239E05A, 0x87E4D9AF, 0x59EF5961, 0xF5AF2DC9, 0xD1521C02, 0x68405262, 0x9864C589, 0x98F5F8BE, 0x0C90FE24, 0x9B3FC02A, 0x31E4FD02, 0xEC747B2D, 0x5FC1C04E, 0x80D6B732, 0x32BA6CB7, 0x961A5683, 0x33025098, 0xD5676789, 0xAB622A5A, 0xF651F93A, 0x130D6D68, 0xEFFEDA48, 0x24E2C2D3, 0xEA89C5DD, 0xF04AFA58, 0x767D3A19, 0xBF67B888, 0x54218F00, 0x6F461AFF, 0x9A216E37, 0x5861AAD0, 0x3B44CEAE, 0xCD6C9A42, 0x0610ECD2, 0x2A894F76, 0x23D72BE9, 0x63FA2D93, 0x2ADC8A10, 0xFB0E9F6A, 0x3BE0CE91, 0x80BB93A1, 0xDB8D8FF3, 0x72E21DC7, 0x93B0C670, 0x2907C541, 0x3DBF1C6D, 0x62D8924F, 0x3205E36F, 0x041C44D5, 0xDACB2490, 0x01D905A9, 0x6C8C579B, 0xE3C54DC2, 0xF4583808, 0x76459488, 0x1E5F7C61, 0x2876F360]
else:
crypt_tab = [0x476BC5E7, 0x76DF4A26, 0x2BD714E2, 0x632623A5, 0xD36838ED, 0x7583042F, 0x32B3A6CE, 0x301180A2, 0x63479874, 0xB0EEF148, 0x4144F37F, 0x717EDD13, 0xA7C02D5F, 0xDF535C64, 0x1816AA04, 0xC3E911A8, 0x07E6D14A, 0xFAE665ED, 0xE0A4AA9E, 0xB271F407, 0xE57CCA4F, 0xD2CBFF86, 0x33AC5C1A, 0x10867E0A, 0x42E43493, 0x8CCBC746, 0x1E82ECBC, 0xFDE23A9C, 0x52A93E3D, 0x617A7898, 0x0753255C, 0xDFF1DEC9, 0x310E0F37, 0x1C4BA740, 0x8E02AB06, 0xDDBE8580, 0xC714785E, 0x0B24EB7B, 0xE6951F2F, 0x728EBF81, 0xA10ABBBF, 0x47F5244F, 0xF96AD9DA, 0x8B8472CD, 0xEE47B55B, 0xA1E97980, 0xF30B7FDA, 0xFD230EE1, 0x7BF84A0E, 0x705A2AFC, 0x6685E6A1, 0x98AAB220, 0x2B307047, 0x551804EB, 0x183A95BB, 0x4531F3E8, 0xFDCB1756, 0xF0387032, 0x1F27AC7D, 0x5AD014E2, 0x6508E3B3, 0xF13D7C92, 0xD7DA45D4, 0xA01D9485]
rnd = sead_rand(0)
rnd.load_state(list(struct.unpack('<IIII', seed)))
key = []
for _ in xrange(8):
k = u32(0)
for _ in xrange(4):
k <<= 8
k |= u32((crypt_tab[rnd.get_u32() >> 26] >> ((rnd.get_u32() >> 27) & 0x18)) & 0xFF)
key.append(k)
return struct.pack('<IIII', key[0], key[1], key[2], key[3]), struct.pack('<IIII', key[4], key[5], key[6], key[7])
def decrypt_save(path, out_path = None):
if not out_path:
out_path = '%s.dec' % path
with open(path, 'rb') as f:
sv = f.read()
header = sv[:0x10]
save_vers, unk = struct.unpack('<QQ', header)
if save_vers > 0x3:
raise ValueError('Error: Unknown save version: %x' % save_vers)
body = sv[0x10:-0x30]
iv = sv[-0x30:-0x20]
key_seed = sv[-0x20:-0x10]
mac = sv[-0x10:]
key, mac_key = get_keys(save_vers, key_seed)
check_body_size(save_vers, len(body))
print 'Save Version: %x' % save_vers
print 'Key: %s' % key.encode('hex')
print 'IV: %s' % iv.encode('hex')
print 'MAC Key: %s' % mac_key.encode('hex')
print 'MAC: %s' % mac.encode('hex')
dec_body = AES.new(key, AES.MODE_CBC, iv).decrypt(body)
if CMAC.new(mac_key, dec_body, AES).digest() != mac:
print 'Warning: Stored MAC is invalid, save may have been modified and decryption may produce garbage.'
with open(out_path, 'wb') as f:
f.write(header + dec_body)
print 'Decrypted %s to %s!' % (path, out_path)
def resign_save(path, out_path = None):
if not out_path:
out_path = '%s.dat' % path
with open(path, 'rb') as f:
sv = f.read()
header = sv[:0x10]
save_vers, unk = struct.unpack('<QQ', header)
if save_vers > 0x3:
raise ValueError('Error: Unknown save version: %x' % save_vers)
dec_body = sv[0x10:]
check_body_size(save_vers, len(dec_body))
key_seed = os.urandom(0x10)
iv = os.urandom(0x10)
key, mac_key = get_keys(save_vers, key_seed)
mac = CMAC.new(mac_key, dec_body, AES).digest()
body = AES.new(key, AES.MODE_CBC, iv).encrypt(dec_body)
with open(out_path, 'wb') as f:
f.write(header + body + iv + key_seed + mac)
print 'Resigned %s to %s!' % (path, out_path)
def main(argc, argv):
funcs = {'-d' : decrypt_save, '-e' : resign_save, '-r' : resign_save}
if argc not in (3, 4) or (argv[1] not in funcs and (len(argv[1]) < 1 or argv[1][1:] not in funcs)):
print 'Usage: %s mode in_file [out_file]' % argv[0]
print 'Mode is -d to decrypt a save, and -e or -r to re-encrypt a save.'
if argv[1] in funcs:
func = funcs[argv[1]]
else:
func = funcs[argv[1][1:]]
if argc == 3:
func(argv[2])
elif argc == 4:
func(argv[2], argv[3])
if __name__ == '__main__':
main(len(sys.argv), sys.argv)
@3096

This comment has been minimized.

Show comment
Hide comment
@3096

3096 Jun 21, 2018

That unk in the save header is a crc32 of decrypted save body.

3096 commented Jun 21, 2018

That unk in the save header is a crc32 of decrypted save body.

@WulfyStylez

This comment has been minimized.

Show comment
Hide comment
@WulfyStylez

WulfyStylez Jun 24, 2018

oh hey! nice to see someone else tackle their goofy prng-driven save crypto. i've got a c impl over here from a while back, when i felt it was... less of a good idea to redistribute their lookup tables, hehe

oh hey! nice to see someone else tackle their goofy prng-driven save crypto. i've got a c impl over here from a while back, when i felt it was... less of a good idea to redistribute their lookup tables, hehe

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment