Example #1
0
 def cipher(self, data, key, alg=12):
     if alg not in self.enc_alg.keys(): 
         print '[WNG]: encryption algorithm not supported'
     if len(key) != self.enc_alg[alg][0]: 
         print '[WNG]: key must be %s bytes long' % self.enc_alg[alg][0]
     # adjust IV length
     self.iv.Len = self.enc_alg[alg][1]
     # manage IV automatically
     if self.iv.Pt is None: 
         self.iv.Pt = urandom( self.enc_alg[alg][1] )
     elif len(self.iv) != self.iv.Len: 
         self.iv.Pt += (self.iv.Len - len(self.iv)) * self.pad
     
     if len(data) >= 1:
         # pad data with padding bytes, adjust with the max padding length
         if alg != 11:
             pad_num = self.enc_alg[alg][2] - 1 - (len(data) % self.enc_alg[alg][2])
             data += pad_num * self.pad
             data += pack('!B', pad_num)
             # initialize algorithm
             if alg == 12: alg = AES.new(key=key, mode=2, IV=str(self.iv))
             elif alg == 2: alg = DES.new(key=key, mode=2, IV=str(self.iv))
             elif alg == 3: alg = DES3.new(key=key, mode=2, IV=str(self.iv))
             # add more algs to support here; taken from pycrypto
             ciph = alg.encrypt(data)
         else: ciph = data
         return ciph
     else: 
         print '[WNG]: .cipher(data, key): needs data of minimum length 1'
         return ''
Example #2
0
    def cipher(self, data, key, alg=12):
        if alg not in self.enc_alg.keys():
            print '[WNG]: encryption algorithm not supported'
        if len(key) != self.enc_alg[alg][0]:
            print '[WNG]: key must be %s bytes long' % self.enc_alg[alg][0]
        # adjust IV length
        self.iv.Len = self.enc_alg[alg][1]
        # manage IV automatically
        if self.iv.Pt is None:
            self.iv.Pt = urandom(self.enc_alg[alg][1])
        elif len(self.iv) != self.iv.Len:
            self.iv.Pt += (self.iv.Len - len(self.iv)) * self.pad

        if len(data) >= 1:
            # pad data with padding bytes, adjust with the max padding length
            if alg != 11:
                pad_num = self.enc_alg[alg][2] - 1 - (len(data) %
                                                      self.enc_alg[alg][2])
                data += pad_num * self.pad
                data += pack('!B', pad_num)
                # initialize algorithm
                if alg == 12: alg = AES.new(key=key, mode=2, IV=str(self.iv))
                elif alg == 2: alg = DES.new(key=key, mode=2, IV=str(self.iv))
                elif alg == 3: alg = DES3.new(key=key, mode=2, IV=str(self.iv))
                # add more algs to support here; taken from pycrypto
                ciph = alg.encrypt(data)
            else:
                ciph = data
            return ciph
        else:
            print '[WNG]: .cipher(data, key): needs data of minimum length 1'
            return ''
Example #3
0
def one_ear(whichEar,scale,tempo,output,duration):
	# define timing

	quarterNote = 60*zook.sec / float(tempo)

	# create the sound chain;  note that output["left"] and output["right"]
	# are connection syntax to isolate a single channel

	attack  =  10*zook.msec
	decay   = 150*zook.msec
	sustain = 0.2
	release = 150*zook.msec

	oscar = oscType(gain=gain)
	envy  = ADSR(adsr=(attack,decay,sustain,release))

	oscar >> envy >> output[whichEar]

	# generate a series of random notes

	prevFreq = 0.0
	startTime = now()
	while (now() < startTime + duration):
		noteStart = now()

		oscar.freq = freq = midi_to_freq(random_choice(scale))
		print "T=%.3f %-5s freq=%.1f" % (now()/zook.sec,whichEar,freq)

		envy.key_on(urandom(0.7,1.0))
		yield ("absolute", noteStart + (quarterNote*0.9) - envy._release)
		envy.key_off()
		yield ("absolute", noteStart + quarterNote)
Example #4
0
File: Hss.py Project: wnlUc3m/5G_CN
    def generate_authentication_info_answer_milenage(self, imsi, RAND=None):

        serving_network_id = PLMN(val=self.plmn).to_bytes()
        if len(serving_network_id) != 3:
            print "Invalid SN_ID %s" % hexlify(serving_network_id).decode(
                'ascii')

        # Get provided subscriber key (k), authentication management field (amf) and operator variant configuration field (op) if imsi is found
        K, AMF, OP, SQN, result = self.check_key_amf_op(imsi)

        # Pack SQN from integer to buffer
        SQNb = b'\0\0' + pack('>I', int(SQN))

        # Generate challenge
        if RAND is None or len(RAND) != 16:
            RAND = urandom(16)
        self.imsi_to_uecontext[imsi].set_rand(RAND)

        # Compute milenage functions
        milenage = Milenage(OP)
        XRES, CK, IK, AK = milenage.f2345(K, RAND, OP)
        MAC_A = milenage.f1(K, RAND, SQNb, AMF)
        SQN_X_AK = xor_buf(SQNb, AK)
        AUTN = SQN_X_AK + AMF + MAC_A
        K_ASME = conv_A2(CK, IK, serving_network_id, SQN_X_AK)
        # Store generated information
        self.imsi_to_uecontext[imsi].set_ik(IK)
        self.imsi_to_uecontext[imsi].set_ck(CK)
        self.imsi_to_uecontext[imsi].set_ak(AK)
        self.imsi_to_uecontext[imsi].set_xres(XRES)
        self.imsi_to_uecontext[imsi].set_autn(AUTN)

        print "\t [INFO] Generated Authentication vector for %s" % (imsi)
        return RAND, XRES, AUTN, K_ASME
Example #5
0
def echo_test(duration):
	filename = programName + ".wav"
	print >>stderr, "writing audio output to %s" % filename
	output = WavOut(filename=filename,channels=numChannels)

	# create sound chain;  basically we'll have
	#   voice >> envy >> echo >> output
	# but voice may be two different ugens, fed into the envelope's left and
	# right channels

	voice = TriOsc(gain=gain)
	if (numChannels == 1): voice2 = None
	else:                  voice2 = SinOsc(gain=gain)

	attack  =  10*zook.msec
	decay   = 150*zook.msec
	sustain = 0.2
	release = 150*zook.msec

	envy  = ADSR(adsr=(attack,decay,sustain,release),channels=numChannels)
	echo  = Echo(delay=delay,channels=numChannels,mix=mix)

	if (voice2 != None):
		voice  >> envy["left"]
		voice2 >> envy["right"]
	else:
		voice >> envy

	envy >> echo >> output

	# play random notes

	startTime = now()
	while (now() < startTime + duration):
		noteStart = now()

		voice.freq = midi_to_freq(urandom(50,80))
		if (voice2 != None): voice2.freq = midi_to_freq(urandom(50,80))

		envy.key_on(urandom(0.5,1.0))
		yield ("absolute", noteStart + (quarterNote*0.9) - release)
		envy.key_off()
		yield ("absolute", noteStart + quarterNote)

	output.close()
Example #6
0
def envelope_test(duration):
	filename = programName + ".wav"
	print >>stderr, "writing audio output to %s" % filename
	output = WavOut(filename=filename,channels=1)

	# set up scale

	Eb = 51                    # (51 is the midi note number for E-flat)
	minNote = 1
	maxNote = 29
	scale = build_scale("ionian",Eb,(minNote,maxNote))

	# set up chain

	if (showEnvelope): voice = None
	else:              voice = oscType(gain=gain)
	if (duty != None): voice.duty = duty
	if (envType == Envelope): envy = Envelope(ar=(attack,release))
	else:                     envy = ADSR(adsr=(attack,decay,sustain,release))
	master = PassThru()

	if (showEnvelope): envy >> master
	else:              voice >> envy >> master

	if (numDelays == None) or (numDelays <= 0):
		master >> output
	else:
		reverb = [None] * numDelays
		for ix in xrange(numDelays):
			reverb[ix] = Delay((60+20*ix)*zook.msec)
			master >> reverb[ix] >> reverb[ix] >> output
			reverb[ix].gain = 0.6

	# play random notes

	startTime = now()
	while (now() < startTime + duration):
		noteStart = now()

		degree = randint(minNote,maxNote)
		note   = scale[degree]
		freq   = midi_to_freq(note)
		if ("notes" in debug):
			print >>stderr, "%s\t%s\t%s" % (degree,note,freq)

		if (voice == None):
			envy.key_on(0.7)
		else:
			voice.freq = freq
			envy.key_on(urandom(0.5,1.0))
		yield ("absolute", noteStart + (quarterNote*0.9) - release)
		envy.key_off()
		yield ("absolute", noteStart + quarterNote)

	output.close()
Example #7
0
    def make_4g_vector(self, IMSI, SN_ID, AMF='\x80\x00'):
        '''
        produces a 4G authentication vector "quadruplet" for a given IMSI and
        network (MCC / MNC)
        
        requests self.db for the authentication key corresponding to the IMSI
        and returns RAND, XRES, AUTN, Kasme obtained from the Milenage 
        and key derivation function functions
        '''
        # lookup AuC_db for authentication key and SQN from IMSI
        if IMSI not in self.db.keys():
            self._log('[ERR] IMSI is not present in AuC.db')
            return -1
        if len(SN_ID) != 3:
            self._log('[ERR] incorrect Serving Network ID')
            return -1
        
        # WNG : there is an issue when retrieving SQN from 2 parallel threads
        #       (almost) at the same time
        # -> both threads can get the same SQN value
        # TODO: we would need a Queue / Lock mechanism so that MM & GMM stacks
        # never get the same SQN value
        
        # get Key and counter
        K, SQN = self.db[IMSI][0], self.db[IMSI][1]
        # increment counter
        self.db[IMSI][1] += 1
        
        # pack SQN from integer to buffer
        SQN = '\0\0' + pack('!I', SQN)
        
        # generate challenge
        RAND = urandom(16)
        
        # compute Milenage functions
        Mil = Milenage( self.OP )
        XRES, CK, IK, AK = Mil.f2345( K, RAND )
        MAC_A = Mil.f1( K, RAND, SQN, AMF ) # pack SQN
        AUTN = xor_string( SQN, AK ) + AMF + MAC_A # pack SQN
        
        # convert to LTE master key
        Kasme = conv_A2(CK=CK, IK=IK, sn_id=SN_ID, sqn_x_ak=AUTN[:6])
        
        # return auth vector
        self._log('Returning 4G authentication vector RAND, XRES, AUTN, KASME'\
                  ' for IMSI %s with SQN %s and SN ID %s' \
                  % (IMSI, hexlify(SQN), hexlify(SN_ID)))
        return RAND, XRES, AUTN, Kasme
#
Example #8
0
    def make_4g_vector(self, IMSI, SN_ID, AMF='\x80\x00'):
        '''
        produces a 4G authentication vector "quadruplet" for a given IMSI and
        network (MCC / MNC)
        
        requests self.db for the authentication key corresponding to the IMSI
        and returns RAND, XRES, AUTN, Kasme obtained from the Milenage 
        and key derivation function functions
        '''
        # lookup AuC_db for authentication key and SQN from IMSI
        if IMSI not in self.db.keys():
            self._log('[ERR] IMSI is not present in AuC.db')
            return -1
        if len(SN_ID) != 3:
            self._log('[ERR] incorrect Serving Network ID')
            return -1

        # WNG : there is an issue when retrieving SQN from 2 parallel threads
        #       (almost) at the same time
        # -> both threads can get the same SQN value
        # TODO: we would need a Queue / Lock mechanism so that MM & GMM stacks
        # never get the same SQN value

        # get Key and counter
        K, SQN = self.db[IMSI][0], self.db[IMSI][1]
        # increment counter
        self.db[IMSI][1] += 1

        # pack SQN from integer to buffer
        SQN = '\0\0' + pack('!I', SQN)

        # generate challenge
        RAND = urandom(16)

        # compute Milenage functions
        Mil = Milenage(self.OP)
        XRES, CK, IK, AK = Mil.f2345(K, RAND)
        MAC_A = Mil.f1(K, RAND, SQN, AMF)  # pack SQN
        AUTN = xor_string(SQN, AK) + AMF + MAC_A  # pack SQN

        # convert to LTE master key
        Kasme = conv_A2(CK=CK, IK=IK, sn_id=SN_ID, sqn_x_ak=AUTN[:6])

        # return auth vector
        self._log('Returning 4G authentication vector RAND, XRES, AUTN, KASME'\
                  ' for IMSI %s with SQN %s and SN ID %s' \
                  % (IMSI, hexlify(SQN), hexlify(SN_ID)))
        return RAND, XRES, AUTN, Kasme
Example #9
0
    def make_4g_vector(self, IMSI, SN_ID, AMF='\x80\x00', RAND=None):
        '''
        produces a 4G authentication vector "quadruplet" for a given IMSI and
        network (MCC / MNC)
        
        requests self.db for the authentication key corresponding to the IMSI
        and returns RAND, XRES, AUTN, Kasme obtained from the Milenage 
        and key derivation function functions
        '''
        # lookup AuC_db for authentication key and SQN from IMSI
        if IMSI not in self.db.keys():
            self._log('WNG', '[make_4g_vector] IMSI {0} not present in '\
                      'AuC.db'.format(IMSI))
            return -1
        if len(SN_ID) != 3:
            self._log('ERR', '[make_4g_vector] incorrect Serving Network ID:'\
                      ' {0}'.format(hexlify(SN_ID)))
            return -1
        
        # get Key and counter
        K, SQN = self.db[IMSI][0], self.db[IMSI][1]
        # increment counter
        self.db[IMSI][1] += 1
        
        # pack SQN from integer to buffer
        SQN = '\0\0' + pack('!I', SQN)
        
        # generate challenge
        if not isinstance(RAND, bytes) or len(RAND) != 16:
            RAND = urandom(16)
        
        # compute Milenage functions
        Mil = Milenage( self.OP )
        XRES, CK, IK, AK = Mil.f2345( K, RAND )
        MAC_A = Mil.f1( K, RAND, SQN, AMF ) # pack SQN
        AUTN = xor_string( SQN, AK ) + AMF + MAC_A # pack SQN
        
        # convert to LTE master key
        Kasme = conv_A2(CK=CK, IK=IK, sn_id=SN_ID, sqn_x_ak=AUTN[:6])
        
        # return auth vector
        self._log('DBG', '[make_4g_vector] returning 4G authentication vector:'\
                  ' RAND, XRES, AUTN, KASME for IMSI {0} with SQN {1} and SN '\
                  'ID {2}'.format(IMSI, hexlify(SQN), hexlify(SN_ID)))
        return RAND, XRES, AUTN, Kasme
#
Example #10
0
    def make_4g_vector(self, IMSI, SN_ID, AMF='\x80\x00', RAND=None):
        '''
        produces a 4G authentication vector "quadruplet" for a given IMSI and
        network (MCC / MNC)
        
        requests self.db for the authentication key corresponding to the IMSI
        and returns RAND, XRES, AUTN, Kasme obtained from the Milenage 
        and key derivation function functions
        '''
        # lookup AuC_db for authentication key and SQN from IMSI
        if IMSI not in self.db.keys():
            self._log('WNG', '[make_4g_vector] IMSI {0} not present in '\
                      'AuC.db'.format(IMSI))
            return -1
        if len(SN_ID) != 3:
            self._log('ERR', '[make_4g_vector] incorrect Serving Network ID:'\
                      ' {0}'.format(hexlify(SN_ID)))
            return -1

        # get Key and counter
        K, SQN = self.db[IMSI][0], self.db[IMSI][1]
        # increment counter
        self.db[IMSI][1] += 1

        # pack SQN from integer to buffer
        SQN = '\0\0' + pack('!I', SQN)

        # generate challenge
        if not isinstance(RAND, bytes) or len(RAND) != 16:
            RAND = urandom(16)

        # compute Milenage functions
        Mil = Milenage(self.OP)
        XRES, CK, IK, AK = Mil.f2345(K, RAND)
        MAC_A = Mil.f1(K, RAND, SQN, AMF)  # pack SQN
        AUTN = xor_string(SQN, AK) + AMF + MAC_A  # pack SQN

        # convert to LTE master key
        Kasme = conv_A2(CK=CK, IK=IK, sn_id=SN_ID, sqn_x_ak=AUTN[:6])

        # return auth vector
        self._log('DBG', '[make_4g_vector] returning 4G authentication vector:'\
                  ' RAND, XRES, AUTN, KASME for IMSI {0} with SQN {1} and SN '\
                  'ID {2}'.format(IMSI, hexlify(SQN), hexlify(SN_ID)))
        return RAND, XRES, AUTN, Kasme
Example #11
0
    def make_3g_vector(self, IMSI, AMF='\0\0', RAND=None):
        '''
        produces a 3G authentication vector "quintuplet" for a given IMSI
        
        requests self.db for the authentication key corresponding to the IMSI
        and returns RAND, XRES, CK, IK, AUTN obtained from the Milenage functions
        '''
        # lookup AuC_db for authentication key and SQN from IMSI
        if IMSI not in self.db.keys():
            self._log('WNG', '[make_3g_vector] IMSI {0} not present in '\
                      'AuC.db'.format(IMSI))
            return -1

        # WNG : there is an issue when retrieving SQN from 2 parallel threads
        #       (almost) at the same time
        # -> both threads can get the same SQN value
        # TODO: we would need a Queue / Lock mechanism so that MM & GMM stacks
        # never get the same SQN value

        # get Key and counter
        K, SQN = self.db[IMSI][0], self.db[IMSI][1]
        # increment counter
        self.db[IMSI][1] += 1

        # pack SQN from integer to buffer
        SQN = '\0\0' + pack('!I', SQN)

        # generate challenge
        if not isinstance(RAND, bytes) or len(RAND) != 16:
            RAND = urandom(16)

        # compute Milenage functions
        Mil = Milenage(self.OP)
        XRES, CK, IK, AK = Mil.f2345(K, RAND)
        MAC_A = Mil.f1(K, RAND, SQN, AMF)  # pack SQN
        AUTN = xor_string(SQN, AK) + AMF + MAC_A  # pack SQN

        # return auth vector
        self._log('DBG', '[make_3g_vector] returning 3G authentication vector:'\
                  ' RAND, XRES, CK, IK, AUTN for IMSI {0} with SQN {1}'.format(
                  IMSI, hexlify(SQN)))
        return RAND, XRES, CK, IK, AUTN
Example #12
0
 def make_3g_vector(self, IMSI, AMF='\0\0', RAND=None):
     '''
     produces a 3G authentication vector "quintuplet" for a given IMSI
     
     requests self.db for the authentication key corresponding to the IMSI
     and returns RAND, XRES, CK, IK, AUTN obtained from the Milenage functions
     '''
     # lookup AuC_db for authentication key and SQN from IMSI
     if IMSI not in self.db.keys():
         self._log('WNG', '[make_3g_vector] IMSI {0} not present in '\
                   'AuC.db'.format(IMSI))
         return -1
     
     # WNG : there is an issue when retrieving SQN from 2 parallel threads
     #       (almost) at the same time
     # -> both threads can get the same SQN value
     # TODO: we would need a Queue / Lock mechanism so that MM & GMM stacks
     # never get the same SQN value
     
     # get Key and counter
     K, SQN = self.db[IMSI][0], self.db[IMSI][1]
     # increment counter
     self.db[IMSI][1] += 1
     
     # pack SQN from integer to buffer
     SQN = '\0\0' + pack('!I', SQN)
     
     # generate challenge
     if not isinstance(RAND, bytes) or len(RAND) != 16:
         RAND = urandom(16)
     
     # compute Milenage functions
     Mil = Milenage( self.OP )
     XRES, CK, IK, AK = Mil.f2345( K, RAND )
     MAC_A = Mil.f1( K, RAND, SQN, AMF ) # pack SQN
     AUTN = xor_string( SQN, AK ) + AMF + MAC_A # pack SQN
     
     # return auth vector
     self._log('DBG', '[make_3g_vector] returning 3G authentication vector:'\
               ' RAND, XRES, CK, IK, AUTN for IMSI {0} with SQN {1}'.format(
               IMSI, hexlify(SQN)))
     return RAND, XRES, CK, IK, AUTN
Example #13
0
def envelope():
	output = WavOut(name="wave",filename="basic_envelope.ck.wav",channels=1)

	n = Noise(gain=1)                        # run white noise through envelope
	e = Envelope()
	n >> e >> output

	later = zook.now() + 5*zook.sec
	while (zook.now() < later):              # finite loop
		t = urandom(10,500) * zook.msec      # random choose rise/fall time
		#e.set(t,t)
		e.attack  = t
		e.release = t
		print "rise/fall: %s msec" % (t/zook.msec)

		e.keyOn()                            # key on - start attack
		yield 800*zook.msec                  # advance time by 800 ms
		e.keyOff()                           # key off - start release
		yield 800*zook.msec                  # advance time by 800 ms

	output.close()
Example #14
0
def inlet_test(duration):
	filename = programName + ".wav"
	print >>stderr, "writing audio output to %s" % filename
	output = WavOut(filename=filename,channels=1)

	# set up scale

	Eb = 51                    # (51 is the midi note number for E-flat)
	minNote = 1
	maxNote = 29
	scale = build_scale("ionian",Eb,(minNote,maxNote))

	# set up chain

	attack  =  10*zook.msec
	decay   = 150*zook.msec
	sustain = 0.2
	release = 150*zook.msec

	voice  = oscType(gain=gain)
	envy   = ADSR(adsr=(attack,decay,sustain,release))
	reverb = SimpleReverb(gain=reverbGain,delayTime=echos)

	voice >> envy >> reverb >> output

	# play random notes

	startTime = now()
	while (now() < startTime + duration):
		noteStart = now()
		voice.freq = midi_to_freq(scale[randint(minNote,maxNote)])
		envy.key_on(urandom(0.5,1.0))
		yield ("absolute", noteStart + (quarterNote*0.9) - release)
		envy.key_off()
		yield ("absolute", noteStart + quarterNote)

	output.close()
def triangle_wave_tooter(duration):
	filename = programName + ".wav"
	print >>stderr, "writing audio output to %s" % filename
	output = WavOut(filename=filename,channels=1)

	# create a scale, three octaves of a C ionian

	C = 48                     # (48 is the midi note number for C)
	threeOctaves = 3*7+1       # (three 7-note octaves plus root on both ends)
	scale = build_scale("ionian",C,threeOctaves)

	# create the sound chain;  this consists of an LFO to create a duty-cycle
	# that varies from .05 to .95, and a triangle wave (or a pulse wave) fed
	# through a standard ADSR envelope

	(dutyLow,dutyHigh) = (0.05,0.95)
	dutyContol = SinOsc(bias=(dutyHigh+dutyLow)/2.0,gain=(dutyHigh-dutyLow)/2.0)
	dutyContol.freq = lfoFreq

	tooter = oscType(gain=gain)
	envy   = ADSR(adsr=(attack,decay,sustain,release))

	dutyContol >> tooter["duty"] >> envy >> output

	# generate a series of random notes

	startTime = now()
	while (now() < startTime + duration):
		noteStart = now()

		tooter.freq = midi_to_freq(random_choice(scale))
		envy.key_on(urandom(0.5,1.0))
		envy.key_on()
		yield ("absolute", noteStart + (tootTime*0.9) - release)
		envy.key_off()
		yield ("absolute", noteStart + tootTime)
Example #16
0
 def __mutate_Str_4(self):
     # replace the whole self.elmt by urandom data
     # of maximum length Mutor.Str_type_4_max_len
     self.elmt.Val = urandom(randint(1, self.Str_type_4_max_len))
     self.state[4][0] += 1
Example #17
0
 def __init__(self):
     Layer.__init__(self)
     self.gmt_unix_time.PtFunc = lambda x: int(time.time())
     self.random_bytes.PtFunc = lambda x: urandom(28)
Example #18
0
 def __mutate_Str_4(self):
     # replace the whole self.elmt by urandom data 
     # of maximum length Mutor.Str_type_4_max_len
     self.elmt.Val = urandom( randint(1, self.Str_type_4_max_len) )
     self.state[4][0] += 1