Exemplo n.º 1
0
def choose_plural(amount, variants):
    """
    Choose proper case depending on amount

    @param amount: amount of objects
    @type amount: C{int} or C{long}

    @param variants: variants (forms) of object in such form:
        (1 object, 2 objects, 5 objects).
    @type variants: 3-element C{sequence} of C{unicode}
        or C{unicode} (three variants with delimeter ',')

    @return: proper variant
    @rtype: C{unicode}

    @raise L{pytils.err.InputParameterError}: input parameters' check failed
        (amount isn't C{int}, variants isn't C{sequence})
    @raise ValueError: variants' length lesser than 3
    """
    
    if isinstance(variants, unicode):
        variants = utils.split_values(variants)
    check_length(variants, 3)
    amount = abs(amount)
    
    if amount % 10 == 1 and amount % 100 != 11:
        variant = 0
    elif amount % 10 >= 2 and amount % 10 <= 4 and \
         (amount % 100 < 10 or amount % 100 >= 20):
        variant = 1
    else:
        variant = 2
    
    return variants[variant]
Exemplo n.º 2
0
 async def deck_topic(self, ctx: Context, *, new_topic: str = ''):
     if not new_topic:
         await self.deck_info(ctx)
         ctx.command.reset_cooldown(ctx)
         return
     deck = await DeckConverter().convert(ctx, str(ctx.channel.id))
     check_deck_manager(deck, ctx.author)
     check_length(new_topic, Deck.TOPIC_MAX_LENGTH)
     await self.edit_deck_topic(ctx, deck, new_topic)
Exemplo n.º 3
0
 async def deck_name(self, ctx: Context, *, new_name: str = ''):
     if not new_name:
         await self.deck_info(ctx)
         ctx.command.reset_cooldown(ctx)
         return
     deck = await DeckConverter().convert(ctx, str(ctx.channel.id))
     check_deck_manager(deck, ctx.author)
     check_length(new_name, Deck.NAME_MAX_LENGTH)
     literal = literals('deck_name')
     if (deck_with_same_name :=
             self.deck_handler.get_deck_by_name(new_name)) is not None:
         await ctx.send(literal['already'] % deck_with_same_name.name)
         ctx.command.reset_cooldown(ctx)
         return
Exemplo n.º 4
0
    def mutate(self, packets):
        numseg = self.numseg
        position = self.position
        # Not enough segments, Syn or Ack, return
        if (
            utils.check_length(numseg, packets)
            or utils.check_syn(packets[numseg - 1])
            or utils.check_ack(packets[numseg - 1])
        ):
            return packets

        forged = packets[numseg - 1].copy()
        forged = utils.tcp_bad_payload(forged)
        # calculate and modify chksum
        forged.chksum = scapy.checksum(forged) + 1

        """il frammento manipolato dovrebbe essere preso per buono da 
		snort -k notcp ma scartato da host vittima. """

        # insert forged segment
        if position == "after":
            packets.insert(numseg, forged)
        elif position == "before":
            packets.insert(numseg - 1, forged)
            # last position is for original packet, not the forged one!!!!
        elif position == "last":
            packets.append(packets[numseg - 1])
            del (packets[numseg - 1])
            packets.insert(numseg - 1, forged)

        return packets
Exemplo n.º 5
0
	def mutate(self, packets):
		numseg = self.numseg
		thl = self.thl
		position = self.position
				
		#Not enough segments, Syn or Ack, return
		if utils.check_length(numseg, packets) or utils.check_syn(packets[numseg-1]) or utils.check_ack(packets[numseg-1]):
			return packets
			
		forged = packets[numseg-1].copy()
		forged = utils.tcp_bad_payload(forged)
		
		#modify  data offset in tcp field
		forged.dataofs = thl
		
		#insert forged segment
		if position == "after":
			packets.insert(numseg, forged)
		elif position == "before":	
			packets.insert(numseg-1, forged)
		elif position == "last":
			packets.append(packets[numseg-1])
			del(packets[numseg-1])
			packets.insert(numseg-1, forged)
					
		return packets
Exemplo n.º 6
0
	def mutate(self, packets):
		result = []
		numseg = self.numseg
		position = self.position
		
		#Not enough segments, Syn or Ack, return
		if utils.check_length(numseg, packets) or utils.check_syn(packets[numseg-1]) or utils.check_ack(packets[numseg-1]):
			return packets
		#if numseg >= len(packets):
		#	return packets
			
		forged = packets[numseg-1].copy()
		forged = utils.tcp_bad_payload(forged)
		forged.flags = 0
		
		if position == "after":
			packets.insert(numseg, forged)
		elif position == "before":	
			packets.insert(numseg-1, forged)
		else:
			packets.append(packets[numseg-1])
			del(packets[numseg-1])
			packets.insert(numseg-1, forged)	
		
		return packets
Exemplo n.º 7
0
def check_all_noise():
    noise_dataset = dataset_info.NoiseDataset()
    noise_files = noise_dataset.files_from_pattern()
    audio_17s = "/home/dzubke/awni_speech/data/LibriSpeech/train-clean-100/19/198/19-198-0034.wav"
    audio_2s = "/home/dzubke/awni_speech/data/LibriSpeech/train-clean-100/19/198/19-198-0000.wav"
    test_audio = [audio_2s, audio_17s]
    print(f"\n Test All Noise: testing {len(noise_files)} noise files")
    for audio_file in test_audio:
        for noise_file in noise_files:
            try:
                utils.check_length(audio_file, noise_file)
            except AssertionError:
                raise AssertionError(
                    f"audio: {audio_file} and noise: {noise_file}")
            except FileNotFoundError:
                raise FileNotFoundError(
                    f"audio: {audio_file} and noise: {noise_file}")
Exemplo n.º 8
0
def test_dataset():
    json_path = "/home/dzubke/awni_speech/data/common-voice/validated-25-maxrepeat.json"
    corpus_name = "common-voice"
    # initializing the dataset object specified by dataset_name
    noise_path = "/home/dzubke/awni_speech/data/background_noise/388338__uminari__short-walk-thru-a-noisy-street-in-a-mexico-city.wav"
    with open(json_path) as fid:
        for line in fid:
            sample = json.loads(line)
            audio_file = sample.get("audio")
            if data_helpers.skip_file(corpus_name, audio_file):
                print(f"skipping: {audio_file}")
                continue
            try:
                utils.check_length(audio_file, noise_path)
            except:
                raise Exception(
                    f"error in audio: {audio_file} and noise: {noise_path}")
Exemplo n.º 9
0
def test_dataset():
    dataset_name = "Commonvoice"
    # initializing the dataset object specified by dataset_name
    dataset = eval("dataset_info."+dataset_name+"Dataset")()   
    audio_files = dataset.get_audio_files()
    noise_path = "/home/dzubke/awni_speech/data/background_noise/388338__uminari__short-walk-thru-a-noisy-street-in-a-mexico-city.wav"
    for audio_file in audio_files:
        if data_helpers.skip_file(dataset.corpus_name, audio_file):
            print(f"skipping: {audio_file}")
            continue            
        try:
            utils.check_length(audio_file, noise_path)
        except AssertionError:
            raise AssertionError(f"error in audio: {audio_file} and noise: {noise_path}")
        except FileNotFoundError:
            raise FileNotFoundError(f"audio: {audio_file} and noise: {noise_file}")
        except:
            raise Exception(f"audio: {audio_file}, noise: {noise_path}")
Exemplo n.º 10
0
def check_noise_level():
    """
    this test aims to test noise inject using a variety of noise levels
    across a selection of noise files and test audio files
    """
    noise_files = [
        "/home/dzubke/awni_speech/data/background_noise/100263_43834-lq.wav",
        "/home/dzubke/awni_speech/data/background_noise/101281_1148115-lq.wav",
        "/home/dzubke/awni_speech/data/background_noise/102547_1163166-lq.wav",
        "/home/dzubke/awni_speech/data/background_noise/elaborate_thunder-Mike_Koenig-1877244752.wav",
        "/home/dzubke/awni_speech/data/background_noise/violet_noise_2.wav",
        "/home/dzubke/awni_speech/data/background_noise/115418_8043-lq.wav"
    ]
    # first test audio is 17 s, second is 2 s, third is from separate dataset
    test_audio = [
        "/home/dzubke/awni_speech/data/LibriSpeech/train-clean-100/19/198/19-198-0034.wav",
        "/home/dzubke/awni_speech/data/LibriSpeech/train-clean-100/19/198/19-198-0000.wav",
        "/home/dzubke/awni_speech/data/tedlium/TEDLIUM_release-3/data/converted/wav/EmmanuelJal_2009G_104.wav.wav"
    ]
    # making a list of noise_levels form 0 to 1.15 in increments of 0.5
    noise_levels = [x / 100 for x in range(0, 120, 5)]

    print(f"\n Noise Level Test: testing {len(noise_files)} noise files")
    for audio_file in test_audio:
        for noise_file in noise_files:
            for noise_level in noise_levels:
                try:
                    utils.check_length(audio_file,
                                       noise_file,
                                       noise_level=noise_level)
                except AssertionError:
                    raise AssertionError(
                        f"audio:{audio_file}, noise:{noise_file}, noise_level:{noise_level}"
                    )
                except FileNotFoundError:
                    raise FileNotFoundError(
                        f"audio:{audio_file}, noise:{noise_file}, noise_level:{noise_level}"
                    )
                except:
                    raise Exception(
                        f"audio:{audio_file}, noise:{noise_file}, noise_level:{noise_level}"
                    )
Exemplo n.º 11
0
	def mutate(self, packets):
		numseg = self.numseg
		
		#Not enough segments, Syn or Ack, return
		if utils.check_length(numseg, packets) or utils.check_syn(packets[numseg-1]) or utils.check_ack(packets[numseg-1]):
			return packets
			
		packets.insert(numseg+1, packets[numseg-1])
		del(packets[numseg-1])
		
		return packets
Exemplo n.º 12
0
	def mutate(self, packets):
		BADMAC = self.BADMAC
		timer = self.timer	
		numframe = self.numframe
		#if packet is fragmented,SYN or ACK do nothing
		if utils.check_length(numframe, packets) or utils.check_syn(packets[numframe-1].payload.payload) or utils.check_ack(packets[numframe-1].payload.payload) or utils.check_fragmentation(packets[numframe-1].payload):
			return packets
		#create fake RST	
		forged = packets[numframe-1].copy()
		forged.payload.payload = utils.tcp_bad_payload(forged.payload.payload, utils.NOPAYLOAD)
		forged.dst=BADMAC
		#set reset flag
		forged.payload.payload.flags = 'R'
		#insert fake RST
		packets.insert(numframe-1, forged)
		#append original
		packets.append(packets[numframe])
		del(packets[numframe])
		#create fake SYN
		forged_syn = packets[numframe-1].copy()
		forged_syn.dst=BADMAC
		forged_syn.timeout = timer
		forged_syn.payload.payload.flags = 'S'
		forged_syn.payload.payload.seq += 103245
		forged_syn.payload.payload.ack = 0
		#insert fake SYN
		packets.insert(numframe, forged_syn)
		#create fake SYN/ACK
		forged_synack = packets[numframe-1].copy()
		forged_synack.dst=BADMAC
		forged_synack.payload.payload.sport = packets[numframe].payload.payload.dport
		forged_synack.payload.payload.dport = packets[numframe].payload.payload.sport
		forged_synack.payload.payload.flags = 'SA'
		forged_synack.payload.payload.seq += 207654
		forged_synack.payload.payload.ack = packets[numframe].payload.payload.seq + 1
		forged_synack.payload.dst = packets[numframe].payload.src
		forged_synack.payload.src = packets[numframe].payload.dst
		#insert fake SYN/ACK
		packets.insert(numframe+1, forged_synack)		
		#create fake ACK
		forged_ack = packets[numframe-1].copy()
		forged_ack.dst=BADMAC
		forged_ack.payload.payload.flags = 'A'
		forged_ack.payload.payload.seq = packets[numframe+1].payload.payload.ack
		forged_ack.payload.payload.ack = packets[numframe+1].payload.payload.seq + 1
		#insert fake SYN/ACK
		packets.insert(numframe+2, forged_ack)	
		
		#delete reset
		del(packets[numframe-1])

		return packets
Exemplo n.º 13
0
	def mutate(self, packets):
		result = []
		
		#Not enough segments, Syn or Ack, return
		if utils.check_length(self.numseg, packets) or utils.check_syn(packets[self.numseg-1]) or utils.check_ack(packets[self.numseg-1]):
			return packets
		
		count = 0
		for p in packets:
			if count == self.numseg:
				p.flags = 0
			result.append(p)
			count +=1
		return result
Exemplo n.º 14
0
    def mutate(self, packets):
        numseg = self.numseg
        timer = self.timer

        # Not enough segments, Syn or Ack, return
        if (
            utils.check_length(numseg, packets)
            or utils.check_syn(packets[numseg - 1])
            or utils.check_ack(packets[numseg - 1])
        ):
            return packets

        packets[numseg - 1].timeout = timer

        return packets
Exemplo n.º 15
0
	def mutate(self, packets):
		numfrag = self.numfrag
		
		if len(packets) == 1:
			return packets
		
		#Not enough fragments, Syn or Ack, return
		if utils.check_length(numfrag, packets) or utils.check_syn(packets[numfrag-1].payload) or utils.check_ack(packets[numfrag-1].payload):
			return packets
								
		frag_out = packets[numfrag-1]
		del(packets[numfrag-1])
		packets.insert(numfrag,frag_out)		
		
		return packets
Exemplo n.º 16
0
	def mutate(self, packets):
		numseg = self.numseg
		pos = self.pos
		
		#Not enough segments, Syn or Ack, return
		if utils.check_length(numseg, packets) or utils.check_syn(packets[numseg-1]) or utils.check_ack(packets[numseg-1]):
			return packets	
			
		if pos >= len(packets):
			packets.append(packets[numseg-1])
			return packets
		
		packets.insert(pos-1, packets[numseg-1])
				
		return packets
Exemplo n.º 17
0
	def mutate(self, packets):
		numseg = self.numseg
		timer = self.timer
		offset = self.offset
		
		#Not enough segments, Syn or Ack, return
		if utils.check_length(numseg, packets) or utils.check_syn(packets[numseg-1]) or utils.check_ack(packets[numseg-1]):
			return packets
			
		forged = packets[numseg-1].copy()
		forged = utils.tcp_bad_payload(forged, utils.NOPAYLOAD)
		forged.flags = 'R'
		#seq. number
		forged.seq += offset
		packets.insert(numseg-1, forged)
		packets[numseg].timeout = timer
						
		return packets
Exemplo n.º 18
0
	def mutate(self, packets):
		result = []
		numseg = self.numseg
		timer = self.timer
		
		#Not enough segments, Syn or Ack, return
		if utils.check_length(numseg, packets) or utils.check_syn(packets[numseg-1]) or utils.check_ack(packets[numseg-1]):
			return packets
			
		forged = packets[numseg-1].copy()
		forged = utils.tcp_bad_payload(forged, utils.NOPAYLOAD)
		forged.flags = 'R'
		#calculate and modify chksum
		forged.chksum = scapy.checksum(forged)+1
		packets.insert(numseg-1, forged)
		packets[numseg].timeout = timer
		
		return packets
Exemplo n.º 19
0
	def mutate(self, packets):
		numfrag = self.numfrag
		position = self.position
		
		#check there is enough fragments and if numfrag-1 is a fragment
		if utils.check_length(numfrag, packets) or not utils.check_fragmentation(packets[numfrag-1]):
			return packets 
		
		
		forged = packets[numfrag-1].copy()
		forged = utils.ip_bad_payload(forged)
		
		if position == "after":
			packets.insert(numfrag, forged)
		else:	
			packets.insert(numfrag-1, forged)

		return packets
Exemplo n.º 20
0
	def mutate(self, packets):
		numseg = self.numseg
		position = self.position
		option = self.opt
		#Not enough segments, Syn or Ack, return
		if utils.check_length(numseg, packets) or utils.check_syn(packets[numseg-1]) or utils.check_ack(packets[numseg-1]):
			return packets
					
		if option == "mss":
			forged=scapy.TCP(options=[("MSS",144)])/packets[numseg-1].load
		elif option == "timestamp":
			forged=scapy.TCP(options=[("Timestamp",(0,-1))])/packets[numseg-1].load
		elif option == "wscale":
			forged=scapy.TCP(options=[("WScale", 10)])/packets[numseg-1].load
		elif option == "sackok":
			forged=scapy.TCP(options=[("SAckOK", 1)])/packets[numseg-1].load
		
		
		forged.sport = packets[numseg-1].sport
		forged.dport = packets[numseg-1].dport
		forged.seq = packets[numseg-1].seq
		forged.ack = packets[numseg-1].ack
		forged.dataofs = packets[numseg-1].dataofs
		forged.reserverd = packets[numseg-1].reserved
		forged.flags = packets[numseg-1].flags
		if option =="timestamp":
			#disable ACK flag
			forged.flags = 0		
		forged.window = packets[numseg-1].window
		forged.urgptr = packets[numseg-1].urgptr
		'''nell elenco in __init__.py, mettere TCPBadOption prima di TCPFakeReset
		per non rischiare che operatore precedente abbia cancellato il payload'''
		forged = utils.tcp_bad_payload(forged)

		if position == "after":
			packets.insert(numseg, forged)
		elif position == "before":	
			packets.insert(numseg-1, forged)
		else:
			packets.append(packets[numseg-1])
			del(packets[numseg-1])
			packets.insert(numseg-1, forged)	
		
		return packets
Exemplo n.º 21
0
	def mutate(self, packets):
		numseg = self.numseg
		position = self.position
		
		#Not enough segments, Syn or Ack, return
		if utils.check_length(numseg, packets) or utils.check_syn(packets[numseg-1]) or utils.check_ack(packets[numseg-1]):
			return packets		
		
		forged = packets[numseg-1].copy()
		forged = utils.tcp_bad_payload(forged)
		
		if position == "after":
			#forged after original
			packets.insert(numseg, forged)
		else:	
			#forged one before original	
			packets.insert(numseg-1, forged)

		return packets
Exemplo n.º 22
0
	def mutate(self, packets):
			
		numframe = self.numframe
		BADMAC = self.BADMAC

		
		if utils.check_length(numframe, packets) or utils.check_syn(packets[numframe-1].payload.payload) or utils.check_ack(packets[numframe-1].payload.payload):
			return packets
				
		forged = packets[numframe-1].copy()
		forged.payload = utils.ip_bad_payload(forged.payload)
		forged.dst=BADMAC
		#insert forged frame
		packets.insert(0, forged)
		#append original
		packets.append(packets[numframe])
		del(packets[numframe])
		
		return packets
Exemplo n.º 23
0
	def mutate(self, packets):
		numfrag = self.numfrag
		bigsize = self.bigsize
		big_payload=""
		
		#check numfrag existence, and if it's a fragment
		if utils.check_length(numfrag, packets) or not utils.check_fragmentation(packets[numfrag-1]):
			return packets 

		#create big payload and load it		
		forged = packets[numfrag-1].copy()
		del(forged.payload)
		for i in range(bigsize):
			big_payload =big_payload + random.choice(string.ascii_letters)
		forged.add_payload(scapy.Raw(load=big_payload))
		forged.flags = ip.FLAG_DF
		#insert big packet	
		packets.insert(numfrag-1, forged)

		return packets
Exemplo n.º 24
0
	def mutate(self, packets):
		numfrag = self.numfrag
		
		#if not enough packets, syn or ack return
		if utils.check_length(numfrag, packets) or utils.check_syn(packets[numfrag-1].payload) or utils.check_ack(packets[numfrag-1].payload):
			return packets 
		
		forged = packets[numfrag-1].copy()
		forged = utils.ip_bad_payload(forged)
		
		#change IP version
		forged.version = 8
		#insert forged 
		packets.insert (0 ,forged)
		#append original
		packets.append(packets[numfrag])
		del(packets[numfrag])
				
		return packets
		
Exemplo n.º 25
0
	def mutate(self, packets):
		numfrag = self.numfrag
		ihl = self.ihl
				
		
		#Not enough fragments, Syn or Ack, return
		if utils.check_length(numfrag, packets) or utils.check_syn(packets[numfrag-1].payload) or utils.check_ack(packets[numfrag-1].payload):
			return packets
			
		forged = packets[numfrag-1].copy()
		forged = utils.ip_bad_payload(forged)
		
		#modify total length
		forged.ihl = ihl
		
		#insert fragment first pos
		packets.insert(0,forged)
		#move original fragment last pos
		packets.append(packets[numfrag])
		del(packets[numfrag])
			
		return packets
Exemplo n.º 26
0
	def mutate(self, packets):
		numseg = self.numseg
		position = self.position
		flags_ = self.flags
		#do nothing
		if utils.check_length(numseg, packets) or utils.check_syn(packets[numseg-1]) or utils.check_ack(packets[numseg-1]):
			return packets
			
		forged = packets[numseg-1].copy()
		forged = utils.tcp_bad_payload(forged)
		forged.flags = flags_
		
		if position == "after":
			packets.insert(numseg, forged)
		elif position == "before":	
			packets.insert(numseg-1, forged)
		else:
			packets.append(packets[numseg-1])
			del(packets[numseg-1])
			packets.insert(numseg-1, forged)	
		
		return packets
Exemplo n.º 27
0
	def mutate(self, packets):
		numfrag = self.numfrag

		#Not enough elements,  Syn or Ack return
		if utils.check_length(numfrag, packets) or utils.check_syn(packets[numfrag-1].payload) or utils.check_ack(packets[numfrag-1].payload):
			return packets
		
		#set self.TTL for each packet
		for i,f in enumerate(packets):
			packets[i].ttl=self.TTL		
		#create forged
		forged = packets[numfrag-1].copy()
		forged = utils.ip_bad_payload(forged)
		#set short TTL
		forged.ttl=self.shortTTL
		packets.insert(numfrag-1, forged)
		
		#append numfrag
		packets.append(packets[numfrag])
		del(packets[numfrag])
		
		return packets
Exemplo n.º 28
0
	def mutate(self, packets):
		numfrag = self.numfrag
		
		#Not enough fragments, Syn or Ack, return
		if utils.check_length(numfrag, packets) or utils.check_syn(packets[numfrag-1].payload) or utils.check_ack(packets[numfrag-1].payload):
			return packets

		forged = packets[numfrag-1].copy()
		forged = utils.ip_bad_payload(forged)
		#calculate and modify chksum
		forged.chksum = ip.scapy.checksum(forged)+1

		'''
		forged packet will be accepted by snort only if using -k noip option
		'''

		#insert fragment first pos
		packets.insert(0,forged)
		#move original fragment last pos
		packets.append(packets[numfrag])
		del(packets[numfrag])

		return packets
Exemplo n.º 29
0
            deck_embed = await self.get_deck_embed(deck)
            tasks = [
                message.edit(content=(done_str :=
                                      literal['done'] % description),
                             embed=deck_embed)
            ]
            if message.channel != partner_channel:
                tasks.append(partner_channel.send(done_str, embed=deck_embed))
            tasks.extend([
                manager.send(done_str, embed=deck_embed),
                deck.default_channel.send(literal['greeting'] %
                                          (manager.mention, deck.name))
            ])
            await asyncio.wait(tasks)
        else:
            check_length(description, Deck.TOPIC_MAX_LENGTH)
            await asyncio.wait([
                partner_channel.send(literal['pending'] %
                                     (author.mention, description)),
                ctx.send(literal['applied'] % description)
            ])

    @deck_.command(name='삭제', aliases=('폐쇄', '종료'))
    @guild_only()
    @wait_until_deck_handler_ready()
    async def deck_end(self, ctx: Context, *, deck: DeckConverter = None):
        literal = literals('deck_end')
        partner_role: Role = discord.utils.get(
            await self.deck_handler.guild.fetch_roles(),
            id=get_constant('partner_role'))
        partner_channel = await self.client.fetch_channel(