예제 #1
0
def tuak_testset_65():
    K = b'\x15t\xcaV\x88\x1d\x05\xc1\x89\xc8(\x80\xf7\x89\xc9\xcdBD\x95_D&\xaa+i\xc2\x9f\x15w\x0eZ\xa5'
    RAND = b'\xc5p\xaa\xc6\x8c\xdee\x1f\xb1\xe3\x08\x83"I\x8b\xef'
    SQN = b'\xc8\x9b\xb7\x1f:A'
    AMF = b')}'
    TOP = b'\xe5\x9fn\xb1\x0e\xa4\x06\x81?I\x91\xb0\xb9\xe0/\x18\x1e\xdfL~\x17\xb4\x80\xf6m4\xda5\xee\x88\xc9^'

    tuak = TUAK(TOP)
    tuak.LEN_MAC = 64
    TOPc = make_TOPc(K, TOP)
    tuak.set_topc(TOPc)

    return TOPc == b'<`R\xe4\x152\xa2\x8aG\xaa<\xbb\x89\xf2#\xe8\xf3\xaa\xa9v\xae\xcdH\xbc>}ae\xa5^\xffb' and \
    tuak.f1(K, RAND, SQN, AMF) == b'\xd74\r\xad\x02\xb4\xcb\x01' and \
    tuak.f1star(K, RAND, SQN, AMF) == b'\xc6\x02\x1e.f\xac\xcb\x15'
예제 #2
0
def tuak_testset_61():
    K = b'\xab\xab\xab\xab\xab\xab\xab\xab\xab\xab\xab\xab\xab\xab\xab\xab'
    RAND = b'BBBBBBBBBBBBBBBB'
    SQN = b'\x11\x11\x11\x11\x11\x11'
    AMF = b'\xff\xff'
    TOP = b'UUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUU'

    tuak = TUAK(TOP)
    tuak.LEN_MAC = 64
    TOPc = make_TOPc(K, TOP)
    tuak.set_topc(TOPc)

    return TOPc == b'\xbd\x04\xd9S\x0e\x87Q<]\x83z\xc2\xad\x95F#\xa8\xe23\x0c\x11S\x05\xa7>\xb4]\x1f@\xcc\xcb\xff' and \
    tuak.f1(K, RAND, SQN, AMF) == b'\xf9\xa5Nj\xea\xa8a\x8d' and \
    tuak.f1star(K, RAND, SQN, AMF) == b'\xe9KM\xc6\xc7)}\xf3'
예제 #3
0
def tuak_testset_64():
    K = b'\xb8\xda\x83zPe-j\xc7\xc9}\xa1Oj\xcca'
    RAND = b'h\x87\xe5T%\xa9f\xbd\x86\xc9f\x1a_\xa7+\xe8'
    SQN = b'\r\xea.\xe2\xc5\xaf'
    AMF = b'\xdf\x1e'
    TOP = b'\tR\xbe\x13Ul2\xeb\xc5\x81\x95\xd9\xdd\x93\x04\x93\xe1*\x90\x03f\x99\x88\xff\xde_\xa1\xf0\xfe5\xcc\x01'

    tuak = TUAK(TOP)
    tuak.LEN_MAC = 128
    TOPc = make_TOPc(K, TOP)
    tuak.set_topc(TOPc)

    return TOPc == b"+\xc1n\xb6W\xa6\x8e\x1fDo\x08\xf5|\x0e\xfb\x1dI5'\xa2\xe6R\xce(\x1e\xb6\xca\x0eD\x87v\n" and \
    tuak.f1(K, RAND, SQN, AMF) == b't\x92\x14\x08yX\xdd\x8fX\xbf\xcd\xf8i\xd8\xae?' and \
    tuak.f1star(K, RAND, SQN, AMF) == b'a\x9e\x86Z\xfe\x80\xe3\x82\xae\xe10c\xf9\xdf\xb5m'
예제 #4
0
def tuak_testset_63():
    K = b'\xff\xfe\xfd\xfc\xfb\xfa\xf9\xf8\xf7\xf6\xf5\xf4\xf3\xf2\xf1\xf0\xef\xee\xed\xec\xeb\xea\xe9\xe8\xe7\xe6\xe5\xe4\xe3\xe2\xe1\xe0'
    RAND = b'\x01#Eg\x89\xab\xcd\xef\x01#Eg\x89\xab\xcd\xef'
    SQN = b'\x01#Eg\x89\xab'
    AMF = b'\xab\xcd'
    TOP = b'\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9a\x9b\x9c\x9d\x9e\x9f'

    tuak = TUAK(TOP)
    tuak.LEN_MAC = 256
    TOPc = make_TOPc(K, TOP)
    tuak.set_topc(TOPc)

    return TOPc == b'0T%B~\x18\xc5\x03\xc8\xa4\xb2\x94\xear\xc9]\x0c6\xc6\xc6\xb2\x9d\x0ce\xdeYt\xd5\x97\x7f\x85$' and \
    tuak.f1(K, RAND, SQN, AMF) == b"\xd9{u\xa1w`e'\x1b\x1e!+\xc3\xb1\xbf\x17?C\x8b!\xe6\xc6JU\xa9l7.\x08^\\\xc5" and \
    tuak.f1star(K, RAND, SQN, AMF) == b'B{\xbf\x07\xc6\xe3\xa8lT\xf8\xc5!d\x99\xf3\x90\x9ao\xd4\xa1d\xc9\xfe#[\x15P%\x81\x11\xb8!'
예제 #5
0
def tuak_testset_62():
    K = b'\xff\xfe\xfd\xfc\xfb\xfa\xf9\xf8\xf7\xf6\xf5\xf4\xf3\xf2\xf1\xf0\xef\xee\xed\xec\xeb\xea\xe9\xe8\xe7\xe6\xe5\xe4\xe3\xe2\xe1\xe0'
    RAND = b'\x01#Eg\x89\xab\xcd\xef\x01#Eg\x89\xab\xcd\xef'
    SQN = b'\x01#Eg\x89\xab'
    AMF = b'\xab\xcd'
    TOP = b'\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9a\x9b\x9c\x9d\x9e\x9f'

    tuak = TUAK(TOP)
    tuak.LEN_MAC = 128
    TOPc = make_TOPc(K, TOP)
    tuak.set_topc(TOPc)

    return TOPc == b'0T%B~\x18\xc5\x03\xc8\xa4\xb2\x94\xear\xc9]\x0c6\xc6\xc6\xb2\x9d\x0ce\xdeYt\xd5\x97\x7f\x85$' and \
    tuak.f1(K, RAND, SQN, AMF) == b'\xc0\xb8\xc2\xd4\x14\x8e\xc7\xaa_\x1dx\xa9~M\x1dX' and \
    tuak.f1star(K, RAND, SQN, AMF) == b'\xef\x81\xafr\x90\xf7\x84,l\xea\xfaS\x7f\xa0t['
예제 #6
0
def tuak_testset_66():
    TUAK.KeccakIterations = 2
    K = b'\x15t\xcaV\x88\x1d\x05\xc1\x89\xc8(\x80\xf7\x89\xc9\xcdBD\x95_D&\xaa+i\xc2\x9f\x15w\x0eZ\xa5'
    RAND = b'\xc5p\xaa\xc6\x8c\xdee\x1f\xb1\xe3\x08\x83"I\x8b\xef'
    SQN = b'\xc8\x9b\xb7\x1f:A'
    AMF = b')}'
    TOP = b'\xe5\x9fn\xb1\x0e\xa4\x06\x81?I\x91\xb0\xb9\xe0/\x18\x1e\xdfL~\x17\xb4\x80\xf6m4\xda5\xee\x88\xc9^'

    tuak = TUAK(TOP)
    tuak.LEN_MAC = 256
    TOPc = make_TOPc(K, TOP)
    tuak.set_topc(TOPc)

    ret = ( TOPc == b'\xb0Jf\xf2lb\xfc\xd6\xc8-\xe2*\x17\x9a\xb6U\x06\xec\xf4\x7fV$\\\xd1I\x96l\xfa\x9c\xeczQ' and \
    tuak.f1(K, RAND, SQN, AMF) == b'\x90\xd2(\x9e\xd1\xca\x1c=\xbc"G\xbbH\rC\x1a\xc7\x1d.Jvw\xf6\xe9\x97\xcf\xdd\xb0\xcb\xad\x88\xb7' and \
    tuak.f1star(K, RAND, SQN, AMF) == b'BsU\xdb\xac0\xe8%\x06:\xbaa\xb5V\xe8u\x83\xab\xacc\x8e:\xb0\x1cL\x88J\xd9\xd4X\xdc/' )

    TUAK.KeccakIterations = 1
    return ret
예제 #7
0
class AuC:
    """3GPP Authentication Centre (AuC), ARPF and SIDF
    
    Use the AuC.db file with (IMSI, K, SQN[, OP]) records to then produce 2G, 3G, 
    4G or 5G authentication vectors, and resynchronize SQN. It supports all standard 
    authentication algorithms: comp123v1, v2, v3, Milenage and TUAK.
    Set SIDF home-network private keys for profile A and / or B and use it to decrypt
    concealed subscriber 5G identities.
    """
    
    # verbosity level: list of log types to be displayed
    DEBUG = ('ERR', 'WNG', 'INF', 'DBG')
    
    # path to the local AuC.db file, should be overwritten
    AUC_DB_PATH = os.path.dirname(os.path.abspath( __file__ )) + os.sep
    
    # when rewriting the AuC.db, do a back-up of the last version of the file
    DO_BACKUP = True
    
    # MNO OP (Milenage) and TOP (TUAK) diversification parameter
    # The AuC supports also a per-subscriber OP / TOP, to be set optionally in the AuC.db database
    OP  = b'ffffffffffffffff'
    TOP = b'ffffffffffffffffffffffffffffffff'
    
    # SQN incrementation when a resynch is required by a USIM card
    SQN_SYNCH_STEP = 2
    
    # PLMN restriction for returning 4G and 5G vectors
    # provide a list of allowed PLMN, or None for disabling the filter
    #PLMN_FILTER = ['20869']
    PLMN_FILTER = None
    
    # SIDF ECIES private keys dict, for decrypting SUCI
    # index: Home Network Public Key Identifier (0..255), according to TS 31.102, section 4.4.11.8
    # value: 2-tuple with Protection Scheme Identifier (profile 'A' or 'B') and 
    #        corresponding Home Network Private Key value
    # 
    # ECIES public / private keypairs must be generated according to the CryptoMobile.ECIES API
    #
    SIDF_ECIES_K = {
        #
        # X25519 example keypair (WARNING: use one you generated yourself):
        # pubkey: d6797fcf69c55e889e5bdf9fc4d300eff2aa5b539bb9e97efe14ca244727b029
        #0 : ('A', unhexlify('38859b29cbbdee43fda218968f8b96bb9a7326ec05b43343939220fa2ac1ec56')),
        #
        # secp256r1 example keypair (WARNING: use one you generated yourself):
        # pubkey: 02519c4707c3535eb5a86a66d056696a45537d4d76e8997375dcd7d30b1f37c6c5
        #1 : ('B', unhexlify('308187020100301306072a8648ce3d020106082a8648ce3d030107046d306b02'\
        #                    '01010420d633fa02b1808226c0a27ddf093e332751f10cb002e8236d3723bb44'\
        #                    '33a55d41a14403420004519c4707c3535eb5a86a66d056696a45537d4d76e899'\
        #                    '7375dcd7d30b1f37c6c50fb946aec017a332ff00e3993f35b54992004894f7d2'\
        #                    'fc1ee0df47fde0c91cf8')
        }
    
    def __init__(self):
        """start the AuC
        
        open AuC.db file
        parse it into self.db (dict), containing IMSI: (K, SQN [, OP])
            IMSI: string of digits
            K   : 16 bytes buffer
            ALG : integer (0, 1, 2, 3 or 4, identifies the auth algorithm)
            SQN : unsigned integer
            OP  : subscriber specific OP, distinct from self.OP, optional field
        """
        self.db = {}
        try:
            # get 3G authentication database AuC.db
            db_fd = open('%sAuC.db' % self.AUC_DB_PATH, 'r')
            # parse it into a dict object with IMSI as key
            for line in db_fd.readlines():
                if line[0] != '#' and line.count(';') >= 3:
                    fields = line[:-1].split(';')
                    IMSI   = str( fields[0] )
                    K      = unhexlify( fields[1].encode('ascii') )
                    ALG    = int( fields[2] )
                    SQN    = int( fields[3] )
                    if len(fields) > 4 and len(fields[4]) == 32:
                        OP = unhexlify( fields[4].encode('ascii') )
                    else:
                        OP = None
                    self.db[IMSI] = [ K, ALG, SQN, OP ]
            self._log('INF', 'AuC.db file opened: %i record(s) found' % len(self.db))
            # close the file
            db_fd.close()
        except Exception as err:
            self._log('ERR', 'unable to read AuC.db, path: %s' % self.AUC_DB_PATH)
            raise(err)
        self._save_required = False
        #
        # initialize the Milenage algo with the AuC-defined OP
        self.Milenage = Milenage(self.OP)
        # initialize the TUAK algo with the AuC-defined TOP
        self.TUAK     = TUAK(self.TOP)
        # initialize the SIDF function
        self._init_sidf()
        #
        self._log('DBG', 'AuC / ARPF / SIDF started')
    
    def _init_sidf(self):
        self._SIDF_ECIES = {}
        for ind, (prof, key) in self.SIDF_ECIES_K.items():
            self._SIDF_ECIES[ind] = ECIES_HN(hn_priv_key=key, profile=prof)
    
    def _log(self, logtype='DBG', msg=''):
        if logtype in self.DEBUG:
            log('[%s] [AuC] %s' % (logtype, msg))
    
    def save(self):
        """
        optionally save old AuC.db with timestamp suffix (if self.DO_BACKUP is set)
        write the current content of self.db dict into AuC.db, with updated SQN
        values
        """
        if not self._save_required:
            return
        
        T = timemod.strftime( '20%y%m%d_%H%M', timemod.gmtime() )
        
        # get header from original file AuC.db
        header = []
        file_db = open('%sAuC.db' % self.AUC_DB_PATH)
        for line in file_db:
            if line[0] == '#':
                header.append( line )
            else:
                break
        header = ''.join(header) + '\n'
        file_db.close()
        
        if self.DO_BACKUP:
            # save the last current version of AuC.db
            os.rename( '%sAuC.db' % self.AUC_DB_PATH,
                       '%sAuC.%s.db' % (self.AUC_DB_PATH, T) )
            self._log('DBG', 'old AuC.db saved with timestamp')
        
        # save the current self.db into a new AuC.db file
        file_db = open('%s/AuC.db' % self.AUC_DB_PATH, 'w')
        file_db.write( header )
        indexes = list(self.db.keys())
        indexes.sort()
        for IMSI in indexes:
            K, ALG, SQN, OP = self.db[IMSI]
            if OP is not None:
                # OP additional parameter
                file_db.write('%s;%s;%i;%i;%s;\n'\
                    % (IMSI, hexlify(K).decode('ascii'), ALG, SQN, hexlify(OP).decode('ascii')))
            else:
                file_db.write('%s;%s;%i;%i;\n'\
                    % (IMSI, hexlify(K).decode('ascii'), ALG, SQN))
        file_db.close()
        self._log('INF', 'current db saved to AuC.db file')
    
    stop = save
    
    def make_2g_vector(self, IMSI, RAND=None):
        """
        return a 2G authentication vector "triplet":
        RAND [16 bytes], RES [4 bytes], Kc [8 bytes]
        or None if the IMSI is not defined in the db or ALG is invalid
        
        RAND can be passed as argument
        """
        # lookup db for authentication Key and algorithm id for IMSI
        try:
            K_ALG_SQN_OP = self.db[IMSI]
        except KeyError:
            self._log('WNG', '[make_2g_vector] IMSI %s not present in AuC.db' % IMSI)
            return None
        if len(K_ALG_SQN_OP) == 4:
            K, ALG, SQN, OP = K_ALG_SQN_OP
        else:
            K, ALG, SQN = K_ALG_SQN_OP
            OP = None
        #
        if not RAND:
            RAND = genrand(16)
        #
        if ALG == 0:
            # Milenage, adapted to 2G
            if OP is not None:
                XRES, CK, IK, AK = self.Milenage.f2345(RAND, K, OP)
            else:
                XRES, CK, IK, AK = self.Milenage.f2345(RAND, K)
            RES, Kc = conv_102_C2(XRES), conv_102_C3(CK, IK)
        elif ALG == 4:
            # TUAK, adapted to 2G
            if OP is not None:
                # which is actually TOP, for TUAK
                XRES, CK, IK, AK = self.TUAK.f2345(RAND, K, OP)
            else:
                XRES, CK, IK, AK = self.TUAK.f2345(RAND, K)
            RES, Kc = conv_102_C2(XRES), conv_102_C3(CK, IK)
        else:
            # COMP128
            if ALG == 1:
                RES, Kc = comp128v1(K, RAND)
            elif ALG == 2:
                RES, Kc = comp128v2(K, RAND)
            elif ALG == 3:
                RES, Kc = comp128v3(K, RAND)
            else:
                # invalid ALG
                return None
        #
        # return auth vector
        self._log('DBG', '[make_2g_vector] IMSI %s: RAND %s, RES %s, Kc %s'\
                  % (IMSI, hexlify(RAND).decode('ascii'), hexlify(RES).decode('ascii'), 
                     hexlify(Kc).decode('ascii')))
        return RAND, RES, Kc
    
    def make_3g_vector(self, IMSI, AMF=b'\0\0', RAND=None):
        '''
        return a 3G authentication vector "quintuplet":
        RAND [16 bytes], XRES [8 bytes], AUTN [16 bytes], CK [16 bytes], IK [16 bytes]
        or None if the IMSI is not defined in the db or does not support Milenage or TUAK
        
        RAND can be passed as argument
        '''
        # lookup db for authentication Key and counter for IMSI
        try:
            K_ALG_SQN_OP = self.db[IMSI]
        except Exception:
            self._log('WNG', '[make_3g_vector] IMSI %s not present in AuC.db' % IMSI)
            return None
        if len(K_ALG_SQN_OP) == 4:
            K, ALG, SQN, OP = K_ALG_SQN_OP
        else:
            K, ALG, SQN = K_ALG_SQN_OP
            OP = None
        #
        if SQN == -1:
            # Milenage / TUAK not supported
            self._log('WNG', '[make_3g_vector] IMSI %s does not support Milenage / TUAK' % IMSI)
            return None
        #
        # increment SQN counter in the db
        K_ALG_SQN_OP[2] += 1
        self._save_required = True
        #
        # pack SQN from integer to a 48-bit buffer
        SQNb = pack('>Q', SQN)[2:]
        #
        # generate challenge if necessary
        if RAND is None:
            RAND = genrand(16)
        #
        if ALG == 0:
            # compute Milenage functions
            if OP is not None:
                XRES, CK, IK, AK = self.Milenage.f2345( K, RAND, OP )
                MAC_A            = self.Milenage.f1( K, RAND, SQNb, AMF, OP )
            else:
                XRES, CK, IK, AK = self.Milenage.f2345( K, RAND )
                MAC_A            = self.Milenage.f1( K, RAND, SQNb, AMF )
        elif ALG == 4:
            # compute TUAK functions
            if OP is not None:
                XRES, CK, IK, AK = self.TUAK.f2345( K, RAND, OP )
                MAC_A            = self.TUAK.f1( K, RAND, SQNb, AMF, OP )
            else:
                XRES, CK, IK, AK = self.TUAK.f2345( K, RAND )
                MAC_A            = self.TUAK.f1( K, RAND, SQNb, AMF )
        else:
            # invalid ALG
            return None
        #
        AUTN = xor_buf( SQNb, AK ) + AMF + MAC_A
        #
        # return auth vector
        self._log('DBG', '[make_3g_vector] IMSI %s, SQN %i: RAND %s, XRES %s, AUTN %s, CK %s, IK %s'\
                  % (IMSI, SQN, hexlify(RAND).decode('ascii'), hexlify(XRES).decode('ascii'),
                     hexlify(AUTN).decode('ascii'), hexlify(CK).decode('ascii'), 
                     hexlify(IK).decode('ascii')))
        return RAND, XRES, AUTN, CK, IK
    
    def make_4g_vector(self, IMSI, SN_ID, AMF=b'\x80\x00', RAND=None):
        """
        return a 4G authentication vector "quadruplet":
        RAND [16 bytes], XRES [8 bytes], AUTN [16 bytes], KASME [32 bytes]
        or None if the IMSI is not defined in the db or does not support Milenage or TUAK
        or SN_ID is invalid or not allowed
        
        SN_ID is the serving network identity, bcd-encoded buffer
        RAND can be passed as argument
        """
        if not isinstance(SN_ID, bytes_types) or len(SN_ID) != 3:
            self._log('WNG', '[make_4g_vector] SN_ID invalid, %s' % hexlify(SN_ID).decode('ascii'))
            return None
        elif self.PLMN_FILTER is not None and SN_ID not in self.PLMN_FILTER:
            self._log('WNG', '[make_4g_vector] SN_ID not allowed, %s' % hexlify(SN_ID).decode('ascii'))
            return None
        #
        # lookup db for authentication Key and counter for IMSI
        try:
            K_ALG_SQN_OP = self.db[IMSI]
        except Exception:
            self._log('WNG', '[make_4g_vector] IMSI %s not present in AuC.db' % IMSI)
            return None
        if len(K_ALG_SQN_OP) == 4:
            K, ALG, SQN, OP = K_ALG_SQN_OP
        else:
            K, ALG, SQN = K_ALG_SQN_OP
            OP = None
        #
        if ALG not in (0, 4):
            # Milenage / TUAK not supported
            self._log('WNG', '[make_4g_vector] IMSI %s does not support Milenage or TUAK' % IMSI)
            return None
        #
        # increment SQN counter in the db
        if SQN >= 0:
            K_ALG_SQN_OP[2] += 1
            self._save_required = True
        #
        # pack SQN from integer to a 48-bit buffer
        SQNb = pack('>Q', SQN)[2:]
        #
        # generate challenge
        if RAND is None:
            RAND = genrand(16)
        #
        if ALG == 0:
            # compute Milenage functions
            if OP is not None:
                XRES, CK, IK, AK = self.Milenage.f2345( K, RAND, OP )
                MAC_A            = self.Milenage.f1( K, RAND, SQNb, AMF, OP )
            else:
                XRES, CK, IK, AK = self.Milenage.f2345( K, RAND )
                MAC_A            = self.Milenage.f1( K, RAND, SQNb, AMF )
        else:
            # ALG == 4, compute TUAK functions
            if OP is not None:
                XRES, CK, IK, AK = self.TUAK.f2345( K, RAND, OP )
                MAC_A            = self.TUAK.f1( K, RAND, SQNb, AMF, OP )
            else:
                XRES, CK, IK, AK = self.TUAK.f2345( K, RAND )
                MAC_A            = self.TUAK.f1( K, RAND, SQNb, AMF )
        #
        SQN_X_AK = xor_buf( SQNb, AK )
        AUTN = SQN_X_AK + AMF + MAC_A
        # convert to LTE master key
        KASME = conv_401_A2(CK, IK, SN_ID, SQN_X_AK)
        #
        # return auth vector
        self._log('DBG', '[make_4g_vector] IMSI %s, SQN %i, SN_ID %s: RAND %s, XRES %s, AUTN %s, KASME %s'\
                  % (IMSI, SQN, hexlify(SN_ID).decode('ascii'), hexlify(RAND).decode('ascii'), 
                     hexlify(XRES).decode('ascii'), hexlify(AUTN).decode('ascii'), 
                     hexlify(KASME).decode('ascii')))
        return RAND, XRES, AUTN, KASME
    
    def make_5g_vector(self, IMSI, SNName, AMF=b'\x80\x00', RAND=None):
        """
        return a 5G authentication vector "quadruplet":
        RAND [16 bytes], XRES* [8 bytes], AUTN [16 bytes], KAUSF [32 bytes]
        or None if the IMSI is not defined in the db or does not support Milenage or TUAK
        or SNName is invalid or not allowed
        
        SNName is the serving network name, ascii-encoded bytes buffer
        RAND can be passed as argument
        """
        if not isinstance(SNName, bytes_types) or not 32 <= len(SNName) <= 255:
            self._log('WNG', '[make_5g_vector] SNName invalid, %s' % SNName.decode('ascii'))
            return None
        elif self.PLMN_FILTER is not None:
            # extract MCC, MNC from SNName (e.g. "5G:mnc012.mcc345.3gppnetwork.org")
            snname_parts = SNName.split(':')[1].split('.')
            mcc, mnc =  snname_parts[1][3:], snname_parts[0][3:]
            if mcc + mnc not in self.PLMN_FILTER:
                self._log('WNG', '[make_5g_vector] SNName not allowed, %s' % SNName.decode('ascii'))
                return None
        #
        # lookup db for authentication Key and counter for IMSI
        try:
            K_ALG_SQN_OP = self.db[IMSI]
        except Exception:
            self._log('WNG', '[make_5g_vector] IMSI %s not present in AuC.db' % IMSI)
            return None
        if len(K_ALG_SQN_OP) == 4:
            K, ALG, SQN, OP = K_ALG_SQN_OP
        else:
            K, ALG, SQN = K_ALG_SQN_OP
            OP = None
        #
        if ALG not in (0, 4):
            # Milenage / TUAK not supported
            self._log('WNG', '[make_4g_vector] IMSI %s does not support Milenage or TUAK' % IMSI)
            return None
        #
        # increment SQN counter in the db
        if SQN >= 0:
            K_ALG_SQN_OP[2] += 1
            self._save_required = True
        #
        # pack SQN from integer to a 48-bit buffer
        SQNb = pack('>Q', SQN)[2:]
        #
        # generate challenge
        if RAND is None:
            RAND = genrand(16)
        #
        if ALG == 0:
            # compute Milenage functions
            if OP is not None:
                XRES, CK, IK, AK = self.Milenage.f2345( K, RAND, OP )
                MAC_A            = self.Milenage.f1( K, RAND, SQNb, AMF, OP )
            else:
                XRES, CK, IK, AK = self.Milenage.f2345( K, RAND )
                MAC_A            = self.Milenage.f1( K, RAND, SQNb, AMF )
        else:
            # ALG == 4, compute TUAK functions
            if OP is not None:
                XRES, CK, IK, AK = self.TUAK.f2345( K, RAND, OP )
                MAC_A            = self.TUAK.f1( K, RAND, SQNb, AMF, OP )
            else:
                XRES, CK, IK, AK = self.TUAK.f2345( K, RAND )
                MAC_A            = self.TUAK.f1( K, RAND, SQNb, AMF )
        #
        SQN_X_AK = xor_buf( SQNb, AK )
        AUTN = SQN_X_AK + AMF + MAC_A
        # convert to AUSF master key
        KAUSF = conv_501_A2(CK, IK, SNName, SQN_X_AK)
        XRESstar = conv_501_A4(CK, IK, SNName, RAND, XRES)
        #
        # return auth vector
        self._log('DBG', '[make_4g_vector] IMSI %s, SQN %i, SNName %s: RAND %s, XRES* %s, AUTN %s, KASME %s'\
                  % (IMSI, SQN, hexlify(SNName).decode('ascii'), hexlify(RAND).decode('ascii'), 
                     hexlify(XRESstar).decode('ascii'), hexlify(AUTN).decode('ascii'), 
                     hexlify(KAUSF).decode('ascii')))
        return RAND, XRESstar, AUTN, KAUSF
    
    def synch_sqn(self, IMSI, RAND, AUTS):
        """
        synchronize the local counter SQN with AUTS provided by the USIM
        in response to a given 3G or 4G authentication challenge (RAND, AMF)
        
        return 0 on successful synch, 1 on unsuccessful synch due to invalid AUTS
        or None if the IMSI is not defined in the db
        """
        # lookup db for authentication Key and counter for IMSI
        try:
            K_ALG_SQN_OP = self.db[IMSI]
        except Exception:
            self._log('WNG', '[synch_sqn] IMSI %s not present in AuC.db' % IMSI)
            return None
        if len(K_ALG_SQN_OP) == 4:
            K, ALG, SQN, OP = K_ALG_SQN_OP
        else:
            K, ALG, SQN = K_ALG_SQN_OP
            OP = None
        #
        if ALG not in (0, 4):
            # Milenage not supported
            self._log('WNG', '[make_3g_vector] IMSI %s does not support Milenage or TUAK' % IMSI)
            return None
        #
        # 33.102, section 6.3.3, for resynch, AMF is always null (0x0000)
        AMF = b'\0\0'
        #
        if ALG == 0:
            # compute Milenage functions
            if OP is not None:
                AK      = self.Milenage.f5star( K, RAND, OP )
                SQN_MS  = xor_buf( AUTS[0:6], AK )
                MAC_S   = self.Milenage.f1star( K, RAND, SQN_MS, AMF, OP )
            else:
                AK      = self.Milenage.f5star( K, RAND )
                SQN_MS  = xor_buf( AUTS[0:6], AK )
                MAC_S   = self.Milenage.f1star( K, RAND, SQN_MS, AMF )
        else:
            # ALG == 4, compute TUAK functions
            if OP is not None:
                AK      = self.TUAK.f5star( K, RAND, OP )
                SQN_MS  = xor_buf( AUTS[0:6], AK )
                MAC_S   = self.TUAK.f1star( K, RAND, SQN_MS, AMF, OP )
            else:
                AK      = self.TUAK.f5star( K, RAND )
                SQN_MS  = xor_buf( AUTS[0:6], AK )
                MAC_S   = self.TUAK.f1star( K, RAND, SQN_MS, AMF )
        #
        # unmask SQN
        SQN_MSi = unpack('>Q', b'\0\0' + SQN_MS)[0]
        #
        self._log('DBG', '[synch_sqn] USIM resynchronization, SQN_MS %i, MAC_S %s'\
                  % (SQN_MSi, hexlify(MAC_S).decode('ascii')))
        #
        # authenticate the USIM
        if MAC_S != AUTS[6:14]:
            self._log('WNG', '[synch_sqn] IMSI %s, USIM authentication failure' % IMSI)
            return 1
        #
        # resynchronize local SQN value
        K_ALG_SQN_OP[2] = SQN_MSi + self.SQN_SYNCH_STEP
        self._save_required = True
        self._log('DBG', '[synch_sqn] IMSI %s, SQN resynchronized to %i' % (IMSI, K_ALG_SQN_OP[2]))
        return 0
    
    def sidf_unconceal(self, hnkid, ephpubk, cipht, mac):
        """
        unconceal the cipher text `cipht` according to ECIES profile A or B (which
        is implicitly depending on `hnkid`).
        Use the home network private key index `hnkid`, ephemeral public key 
        `ephpubk`, after verifying the `mac`. All parameters are part of the
        SUCI.
        
        return None on error or the unconceal clear-text value bytes buffer (i.e.
        the clear-text 5G subscriber identity)
        """
        if hnkid not in self._SIDF_ECIES or not 32 <= len(ephpubk) <= 33 or len(mac) != 8:
            self._log('WNG', '[sidf_unconceal] invalid parameter')
            return None
        #
        try:
            cleart = self._SIDF_ECIES[hnkid].unprotect(ephpubk, cipht, mac)
        except Exception as err:
            self._log('ERR', '[sidf_unconceal] EC processing error: %s' % err)
            return None
        else:
            self._log('DBG', '[sidf_unconceal] SUCI ciphertext %s decrypted to %s'\
                      % (hexlify(cipht).decode('ascii'), hexlify(cleart).decode('ascii')))
            return cleart