Example #1
0
    def _xml_to_log_message(self, output):
        """
        author - string - the name of the author who committed the revision
        date - float time - the date of the commit
        message - string - the text of the log message for the commit
        revision - pysvn.Revision - the revision of the commit

        changed_paths - list of dictionaries. Each dictionary contains:
            path - string - the path in the repository
            action - string
            copyfrom_path - string - if copied, the original path, else None
            copyfrom_revision - pysvn.Revision - if copied, the revision of the original, else None
        """
        doc = ET.fromstring(output)
        entries = []

        for logentry in doc:
            entry = dict(
                revision=CommandLineRevision(logentry.get('revision')),
                author=logentry.findtext("author"),
                date=self._xmldate_to_timestamp(logentry.findtext("date")),
                message=logentry.findtext("msg"),
            )

            entry['changed_paths'] = []
            paths = logentry.find("paths")
            if paths:
                for path in paths:
                    cp = CommandLineChangedPath()
                    cp.kind = path.get('kind')
                    cp.action = path.get('action')
                    cp.path = path.text
                    entry['changed_paths'].append(cp)
            entries.append(entry)
        return entries
Example #2
0
    def get_background_image(self):
        """Get the background image from file.

        Returns:
            The first group element of the SVG image file.
        """
        scale = float(self.options['scale'])
        svg_ns = {'ns0': 'http://www.w3.org/2000/svg'}
        xloc = self.get_page_dimensions()[0]/2
        yloc = self.get_plaster_coord()
        image_file = os.path.expanduser(self.options['background-image'])
        image_tree = ET.parse(image_file)
        image_root = image_tree.getroot()
        image_group = image_root.find('ns0:g', svg_ns)
        image_group.set('transform', 'scale('+str(1/scale)+') '
                                     'translate('+str(xloc*scale)+' '+
                                     str(yloc*scale)+')')
        for path in image_group:
            path_class = path.get('class')
            if path.get('class') in reference.usitt_line_weights:
                weight = reference.usitt_line_weights[path_class]
            else:
                weight = 'line-weight-medium'
            path.set('stroke-width', 
                     str(float(self.options[weight])*scale))
            
        return image_group
Example #3
0
File: svn.py Project: B-Rich/ibid-1
    def _xml_to_log_message(self, output):
        """
        author - string - the name of the author who committed the revision
        date - float time - the date of the commit
        message - string - the text of the log message for the commit
        revision - pysvn.Revision - the revision of the commit

        changed_paths - list of dictionaries. Each dictionary contains:
            path - string - the path in the repository
            action - string
            copyfrom_path - string - if copied, the original path, else None
            copyfrom_revision - pysvn.Revision - if copied, the revision of the original, else None
        """
        doc = ET.fromstring(output)
        entries = []

        for logentry in doc:
            entry = dict(
                revision = CommandLineRevision(logentry.get('revision')),
                author = logentry.findtext("author"),
                date = self._xmldate_to_timestamp(logentry.findtext("date")),
                message = logentry.findtext("msg"),
            )

            entry['changed_paths'] = []
            paths = logentry.find("paths")
            if paths:
                for path in paths:
                    cp = CommandLineChangedPath()
                    cp.kind = path.get('kind')
                    cp.action = path.get('action')
                    cp.path = path.text
                    entry['changed_paths'].append(cp)
            entries.append(entry)
        return entries
Example #4
0
 def ResizePic():
     """缩放图像, 处理完成后弹出提示窗并打开图像所在文件夹
     """
     # 缩放图像并存储副本
     resize_pic(path.get(), int(entry_width.get()), int(entry_height.get()))
     # 处理完成后弹出提示窗
     messagebox.showinfo('提示', '图像缩放完成!')
     # 打开图像所在文件夹
     os.startfile(os.path.split(path.get())[0])
Example #5
0
 def open(self, path):
     '''
     Charger les actions du fichier
     @param path: Fichier d'entrée
     @author: Julien
     '''
     fichier = open(path.get(), 'r')
     self.actionlist = pickle.load(fichier)
     self.filesave = path.get()
     Publisher.sendMessage(Model.ACTIONLIST_CHANGED)
def process_file(f_path):
    # filter by content. only parse if the file actually contains any reource that we are intesrested in.
    # parse file contnents.
    # analize resource definitinon.
    # collect enpoints.
    log.debug("path: %s" % f_path)
    api_found = False
    api = API(name=f_path)
    pattern = re.compile(pattern='^\s*("?kind"?\s*:\s*"?([Ii]ngress)"?).*$',
                         flags=(re.I | re.M))
    resource_found = False
    with open(f_path) as file:
        line = file.readline()
        while line:
            # check if the file contains any type of resource of our interest
            result = pattern.match(line)
            resource_found = result != None and result.group(
                2).lower() in r_types
            if resource_found:
                break
            line = file.readline()
            continue
    if not resource_found:
        return
    # Parse contents
    if f_path.endswith('yaml') or f_path.endswith('yml'):
        resources = load_yaml_resource(f_path)
    elif f_path.endswith('json'):
        resources = load_json_resource(f_path)
    else:
        log.error("Unsupported file type. No parser found for file '%s'",
                  f_path)
        resources = None
        return
    for resource in resources:
        if not resource:
            continue
        try:
            # collect api paths
            # spec.rules.$
            rules = resource.get('spec', {}).get('rules')
            if not rules:
                return
            for rule in rules:
                host = rule.get('host', '*')
                for path in rule.get('http').get('paths'):
                    api_path = path.get('path', '/')
                    api_service = path.get('backend').get('serviceName')
                    api_service_port = path.get('backend').get('servicePort')
                    endpoint = host + '/' + api_path
                    api.add_endpoint(Endpoint(path=endpoint))
        except Exception as e:
            log.error(e, exc_info=True)
    if len(api.endpoints) > 0:
        return api
Example #7
0
    def get_fixture_icon(self, fixture):
        """Return an SVG group for a single fixture.

        Search the package data for a symbol for this fixture, then 
        transform as appropriate based on tags and plot scaling.

        Args:
            fixture: the fixture object to create an icon for.

        Returns:
            An ElementTree object representing an SVG 'g' element.
        """
        # Get the base SVG element
        symbol_name = fixture.data['symbol']
        tree = ET.parse(get_data('symbol/'+symbol_name+'.svg'))
        root = tree.getroot()
        svg_ns = {'ns0': 'http://www.w3.org/2000/svg'}
        symbol = root.find('ns0:g', svg_ns)
        # Transform based on scaling and data
        centre = self.get_page_dimensions()[0]/2
        plaster = self.get_plaster_coord()
        scale = float(self.options['scale'])
        plot_pos = lambda dim: (float(fixture.data['pos'+dim])*1000)
        rotation = fixture.get_rotation()
        colour = fixture.get_colour()
        symbol.set('transform', 'scale( '+str(1/scale)+' ) '
                   'translate('+str(centre*scale+plot_pos('X'))+' '+
                   str(plot_pos('Y')+plaster*scale)+') '
                   'rotate('+str(rotation)+')')
        for path in symbol:
            if path.get('class') == 'outer':
                path.set('fill', colour)
                path.set('stroke-width', 
                         str(float(self.options['line-weight-heavy'])*scale))
        return symbol
Example #8
0
def load_session(session):
	# session is useless, because path already defines which session is loaded
	global programs, scripts, aliases

	programs_ = _flatten_directory(path.get('/run/programs'))
	programs = set([
		Program(child) for child in programs_ if type(child) is path.File
	])
	scripts_ = _flatten_directory(path.get('/run/scripts'))
	scripts = set([
		Program(child) for child in scripts_ if type(child) is path.File
	])

	file = open(os.path.join('session', session, 'run.json'))
	aliases = json.load(file)['aliases']
	file.close()
Example #9
0
def create_user(admin_=False):
    global admin

    # TODO: make it so username prompt is repeated when the passwords don't match
    username = input('Username: '******'Username: '******'Password: '******'Confirm password: '******'Password: '******'Confirm password: '******'username': username, 'password': password})
    user_dir = path.get('/user').create(username, path.Directory)
    run_dir = user_dir.create('run', path.Directory)
    run_dir.create('scripts', path.Directory)
    run_dir.create('programs', path.Directory)

    if admin_:
        admin = username
        print(
            "*Congratulation! the system's admin account has been set to yours."
        )
    print("*Please restart for all services to work with your new account.",
          end=" ")
    input()
    internal.shutdown()
Example #10
0
	def execute(self, args, options, stdin, scope):	# I think the ``scope`` arg is pretty much irrelevant
		super().execute(args, options, stdin, scope)
		# statements = re.split(r'(?:\\\\)*(?!\\);', path.get(self.path, path.File).read())	# TODO: what if ; is in a string??
		# TODO: change to 'argv' list when/if lists are supported
		# The local scope (varname=>str, value=>str)
		local = EnvironmentDictionary()
		for i,arg in enumerate(args): local['arg%d'%i] = arg
		local['options'] = options
		local['stdin'] = stdin
		cli.process(path.get(self.path, path.File).read(), local)
Example #11
0
 def save(self, path):
     '''
     Enregistrer les actions dans un fichier
     @param path: Fichier de sortie
     @author: Julien
     '''
     fichier = open(path.get(), 'w')
     pickle.dump(self.actionlist, fichier)
     fichier.close()
     self.filesave = path
Example #12
0
	def execute(self, args, options, stdin, piped, scope):
		super().execute(args, options, stdin, piped, scope)
		try:
			fn = program.compile_fn(path.get(self.path, path.File).read())
			return fn(args, options, stdin, piped, scope)
		except ArgumentCountException as e: raise ArgumentCountException(self.usage)
		except Exception as e:
			if not isinstance(e, (cli.CliException, path.PathException, RunException)):
				print('An error occured during script execution:')
				traceback.print_exc()
			else: raise e
Example #13
0
 def listpeers(self):
     """List node peers"""
     peers = self.node.get_peer()
     print "200 listpeers <ztaddr> <paths> <latency> <version> <role>"
     for peer in peers:
         ztaddr = peer["address"]
         role = peer["role"]
         version = (
             peer.get("versionMajor", -1),
             peer.get("versionMinor", -1),
             peer.get("versionRev", -1),
         )
         if version[0] < 0 or version[1] < 0 or version[2] < 0:
             version = "-"
         else:
             version = "{}.{}.{}".format(*version)
         latency = peer.get("latency", 0)
         paths = []
         now = int(time.time() * 1000)
         for path in peer.get("paths", []):
             addr = path["address"]
             last_send = path.get("lastSend", 0)
             last_receive = path.get("lastReceive", 0)
             if last_send > 0:
                 last_send = now - last_send
             if last_receive > 0:
                 last_receive = now - last_receive
             if path.get("fixed"):
                 state = "fixed"
             elif path.get("active"):
                 state = "active"
             else:
                 state = "inactive"
             paths.append(
                 "{addr};{last_send};{last_receive};{state}".format(
                     **locals()))
         paths = ",".join(paths) or "-"
         print(
             "200 listpeers "
             "{ztaddr} {paths} {latency} {version} {role}").format(
                 **locals())
 def listpeers(self):
     """List node peers"""
     peers = self.node.get_peer()
     print "200 listpeers <ztaddr> <paths> <latency> <version> <role>"
     for peer in peers:
         ztaddr = peer["address"]
         role = peer["role"]
         version = (
             peer.get("versionMajor", -1),
             peer.get("versionMinor", -1),
             peer.get("versionRev", -1),
         )
         if version[0] < 0 or version[1] < 0 or version[2] < 0:
             version = "-"
         else:
             version = "{}.{}.{}".format(*version)
         latency = peer.get("latency", 0)
         paths = []
         now = int(time.time() * 1000)
         for path in peer.get("paths", []):
             addr = path["address"]
             last_send = path.get("lastSend", 0)
             last_receive = path.get("lastReceive", 0)
             if last_send > 0:
                 last_send = now - last_send
             if last_receive > 0:
                 last_receive = now - last_receive
             if path.get("fixed"):
                 state = "fixed"
             elif path.get("active"):
                 state = "active"
             else:
                 state = "inactive"
             paths.append(
                 "{addr};{last_send};{last_receive};{state}".format(
                     **locals()))
         paths = ",".join(paths) or "-"
         print (
             "200 listpeers "
             "{ztaddr} {paths} {latency} {version} {role}"
         ).format(**locals())
Example #15
0
 def get_fixture_group(self):
     """Return a transformed symbol g element."""
     posX_mm = float(self.fixture.data['posX'])*1000
     posY_mm = float(self.fixture.data['posY'])*1000
     rotation_deg = self.fixture.data['rotation']
     colour = self.fixture.data['colour']
     self.image_group.set('transform', 'translate('+
         str(posX_mm)+' '+str(posY_mm)+') rotate('+str(rotation_deg)+')')
     for path in self.image_group:
         if path.get('class') == 'outer':
             path.set('fill', colour)
     return self.image_group
Example #16
0
 def cleantext(path, file):
     file_to_open = os.path.join(path.get(), "no_emptyline.txt")
     fnew = open(file_to_open, 'w')
     fnew.truncate()  # clear the content of new file
     raw = file.replace('\n', ' ')
     #raw = raw.lower()
     sentences = sent_tokenize(raw)
     for sentence in sentences:
         lines = re.split('\n+', sentence)  # exclude extra empty lines
         for line in lines:
             newline = ' '.join(line.split())  # exclude extra spaces
             fnew.write(newline)
             fnew.write('\n')
     fnew.close()
Example #17
0
def get_svn_log(svn_branch_url):
    command = ['svn', 'log', '--non-interactive', '-v',
        '--xml', '--stop-on-copy', svn_branch_url]
    if username:
        command.extend(['--username', username])
    if password:
        command.extend(['--password', password])
    return_code, stdout = call(command)
    if return_code != 0:
        raise RuntimeError('svn log %s failed.' % svn_branch_url)
    root = xml.etree.ElementTree.fromstring(stdout)
    svn_log = []
    for logentry in root.findall('logentry'):
        log = {}
        log['revision'] = int(logentry.get('revision'))
        log['author'] = logentry.findtext('author')
        log['msg'] = logentry.findtext('msg')
        # date looks like this: 2010-10-11T11:03:25.847546Z
        log['date'] = logentry.findtext('date').split('.')[0].replace('T', ' ')
        svn_log.append(log)
    copyfrom = None
    for path in logentry.findall('paths/path'):
        if path.get('copyfrom-rev'):
            copyfrom_path = path.get('copyfrom-path')
            copyfrom_rev = path.get('copyfrom-rev')
            command = ['svn', 'log', '--xml', '--limit=1', '%s%s@%s' % (
                server_url, copyfrom_path, copyfrom_rev)]
            if username:
                command.extend(['--username', username])
            if password:
                command.extend(['--password', password])
            return_code, stdout = call(command)
            log = xml.etree.ElementTree.fromstring(stdout)
            copyfrom = int(log.find('logentry').get('revision'))
    svn_log.reverse()
    return svn_log, copyfrom
Example #18
0
def get(spec):
    """Convenience wrapper around ``spack.repo.get()``."""
    return path.get(spec)
Example #19
0
    {'path': 'h1_hesc/tests/code/fixtures/eukaryote_model.xlsx'},
    {'path': 'h1_hesc/tests/code/fixtures/mock_model.xlsx'},

    # rand_wc_model_gen
    {'path': 'rand_wc_model_gen/rand_wc_model_gen/model_gen/model.xlsx'},
    {'path': 'rand_wc_model_gen/rand_wc_model_gen/model_gen/model_2.xlsx'},
]

paths = [
{'path': 'wc_sim/tests/submodels/fixtures/test_next_reaction_method_submodel_2.xlsx'},
]

for i_path, path in enumerate(paths):
    print('Migrating path {} of {}: {}'.format(i_path + 1, len(paths), path['path']))

    abs_path = os.path.join(base_dir, path['path'])

    # migrate
    migration.transform(abs_path)

    # validate
    if path.get('validate', True):
        kwargs = copy.copy(path)
        kwargs.pop('path')
        if 'validate' in kwargs:
            kwargs.pop('validate')
        try:
            wc_lang.io.Reader().run(abs_path, **kwargs)
        except ValueError as err:
            warnings.warn('{} is invalid: {}'.format(path['path'], str(err)))
Example #20
0
    def on_message(self, message):
        global globalPath
        a=message.split(",")
        project=(a[0].split("/"))
        #batFileCmd = CypsaEnginePath+" " + project[len(project)-2] +" " + a[1]
        #print batFileCmd
        #from subprocess import Popen
        #p = Popen(batFileCmd, cwd=CypsaEngineRoot)
        #stdout, stderr = p.communicate()
        xmlfilepath=a[0]+"/pw_analysis_attack_graph_current.xml"
        csvfilepath=a[0]+"/patched.csv"
        percentage=0
        sumtotal=0
        counter=0
        assets = {}
        dup=0
        patched = []
        #read patched csv file and store elements already patched
        with open(csvfilepath) as csvfile:
            reader = csv.DictReader(csvfile)
            for row in reader:
                if(row['Patch']=="1"):
                    patched.append(row['IP Address'])
                else:
                    print row['Patch']
        #print patched[1]
        from xml.etree import ElementTree
        with open(xmlfilepath, 'rt') as f:
            tree = ElementTree.parse(f)
            for Nmap in tree.findall('NmapAnalysis'):
                source = Nmap.get('sourceNode')
                destination = Nmap.get('destinationNode')
                for path in Nmap.findall('Path'):
                    performanceIndex = path.get('performanceIndex')
                    securityIndex = path.get('securityIndex')
                    cyberCost = path.get('cyberCost')
                    for node in path.findall('Node'):
                        ipAddress = node.get('IPAddress')
                        vulID = node.get('vulnID')
                        if ipAddress == source:
                            type = "source"
                        elif ipAddress == destination:
                            type = "destination"
                        else:
                            type = "intermediate"

                        for ip in assets:
                            if (assets[ip][1]==ipAddress and assets[ip][0]==type):
                                dupkey = ip
                                dup=1
                                break


                        if dup == 1:
                            assets[dupkey][2]+=float(performanceIndex)
                            assets[dupkey][3]+=float(securityIndex)
                            assets[dupkey][4]+=float(cyberCost)
                            assets[dupkey][5]+=1
                            assets[dupkey][10]+=","+vulID
                            percentage+=float(securityIndex)
                            sumtotal+=1
                            assets[dupkey][11]=percentage
                            assets[dupkey][12]=sumtotal

                        else:
                            arr = []
                            arr.append(type)
                            arr.append(ipAddress)
                            arr.append(float(performanceIndex))
                            arr.append(float(securityIndex))
                            arr.append(float(cyberCost))
                            arr.append(1)
                            arr.append(0)
                            arr.append(0)
                            arr.append(0)
                            arr.append(0)
                            arr.append(vulID)
                            percentage+=float(securityIndex)
                            sumtotal+=1
                            arr.append(percentage)
                            arr.append(sumtotal)
                            if(ipAddress in patched):
                                arr.append(1)
                            else:
                                arr.append(0)
                            assets[counter] = arr
                            counter+=1
                        dup=0
                        type=""
                        dupkey=""


            xmlfilepath1=a[0]+"/pw_analysis_attack_graph_previous.xml"
            if os.path.isfile(xmlfilepath1):
                from xml.etree import ElementTree
                with open(xmlfilepath1,'rt') as f:
                    tree = ElementTree.parse(f)
                    for Nmap in tree.findall('NmapAnalysis'):
                        source = Nmap.get('sourceNode')
                        destination=Nmap.get('destinationNode')
                        for path in Nmap.findall('Path'):
                            performanceIndex = path.get('performanceIndex')
                            securityIndex = path.get('securityIndex')
                            cyberCost = path.get('cyberCost')
                            for node in path.findall('Node'):
                                ipAddress = node.get('IPAddress')
                                vulID = node.get('vulnID')
                                if ipAddress == source:
                                    type = "source"
                                elif ipAddress == destination:
                                    type = "destination"
                                else:
                                    type = "intermediate"


                                for ip in assets:
                                    if (assets[ip][1]==ipAddress and assets[ip][0]==type):
                                        dupkey = ip
                                        dup=1
                                        break

                                if dup == 1:
                                    assets[dupkey][6]+=float(performanceIndex)
                                    assets[dupkey][7]+=float(securityIndex)
                                    assets[dupkey][8]+=float(cyberCost)
                                    assets[dupkey][9]+=1
                                    assets[dupkey][10]+=","+vulID
                                    assets[dupkey][11]=percentage
                                    assets[dupkey][12]=sumtotal
                                    print assets[dupkey]


                                else:
                                    arr = []
                                    arr.append(type)
                                    arr.append(ipAddress)
                                    arr.append(0)
                                    arr.append(0)
                                    arr.append(0)
                                    arr.append(0)
                                    arr.append(float(performanceIndex))
                                    arr.append(float(securityIndex))
                                    arr.append(float(cyberCost))
                                    arr.append(1)
                                    arr.append(vulID)
                                    arr.append(percentage)
                                    arr.append(sumtotal)
                                    if(ipAddress in patched):
                                        arr.append(1)
                                    else:
                                        arr.append(0)
                                    assets[counter] = arr
                                    counter+=1
                                dup=0
                                type=""
                                dupkey=""



            for ip in assets:
                assets[ip][11]=percentage
                assets[ip][12]=sumtotal
            json_data = json.dumps(assets)
            event_handler = MyHandler()
            args = a[0]
            if args:
                print args[0]
            else:
                print "helo"
            observer = Observer()
            observer.schedule(event_handler, path=a[0], recursive=False)
            observer.start()
            globalPath=a[0]
            print globalPath+" This is intializing"
            self.write_message(json_data)


        def on_close(self):
            pass
Example #21
0
def selectPath():
    global path_
    path_ = askdirectory()

    path.set(path_)
    return path.get()
Example #22
0
    def on_message(self, message):
        global flag
        s=""
        #self.write_message("hello")
        if flag == "b":
            #read PID's
            #save them in an array
            filepath=globalPath+"/pw_analysis_attack_graph_current.xml"
            prevfilepath=globalPath+"/pw_analysis_attack_graph_previous.xml"
            print "This is csvfile path timer "+filepath
            percentage=0
            sumtotal=0
            counter=0
            assets = {}
            dup=0
            csvfilepath=globalPath+"/patched.csv"
            print "This is csvfile path timer"+csvfilepath
            patched = []
            #read patched csv file and store elements already patched
            if os.path.isfile(csvfilepath):
                with open(csvfilepath) as csvfile:
                    reader = csv.DictReader(csvfile)
                    for row in reader:
                        if(row['Patch']=="1"):
                            patched.append(row['IP Address'])
                    #else:
                    #    print row['Patch']
            #print patched[1]
            if os.path.isfile(filepath):
                tree = ET.parse(filepath)
                for Nmap in tree.findall('NmapAnalysis'):
                    source = Nmap.get('sourceNode')
                    destination = Nmap.get('destinationNode')
                    for path in Nmap.findall('Path'):
                        performanceIndex = path.get('performanceIndex')
                        securityIndex = path.get('securityIndex')
                        cyberCost = path.get('cyberCost')
                        for node in path.findall('Node'):
                            ipAddress = node.get('IPAddress')
                            vulID = node.get('vulnID')
                            if ipAddress == source:
                                type = "source"
                            elif ipAddress == destination:
                                type = "destination"
                            else:
                                type = "intermediate"
                            for ip in assets:
                                if (assets[ip][1]==ipAddress and assets[ip][0]==type):
                                    dupkey = ip
                                    dup=1
                                    break
                            if dup == 1:
                                assets[dupkey][2]+=float(performanceIndex)
                                assets[dupkey][3]+=float(securityIndex)
                                assets[dupkey][4]+=float(cyberCost)
                                assets[dupkey][5]+=1
                                assets[dupkey][10]+=","+vulID
                                percentage+=float(securityIndex)
                                sumtotal+=1
                                assets[dupkey][11]=percentage
                                assets[dupkey][12]=sumtotal
                            else:
                                arr = []
                                arr.append(type)
                                arr.append(ipAddress)
                                arr.append(float(performanceIndex))
                                arr.append(float(securityIndex))
                                arr.append(float(cyberCost))
                                arr.append(1)
                                arr.append(0)
                                arr.append(0)
                                arr.append(0)
                                arr.append(0)
                                arr.append(vulID)
                                percentage+=float(securityIndex)
                                sumtotal+=1
                                arr.append(percentage)
                                arr.append(sumtotal)
                                if(ipAddress in patched):
                                    arr.append(1)
                                else:
                                    arr.append(0)
                                assets[counter] = arr
                                counter+=1
                            dup=0
                            type=""
                            dupkey=""
            if os.path.isfile(prevfilepath):
                tree = ET.parse(prevfilepath)
                for Nmap in tree.findall('NmapAnalysis'):
                    source = Nmap.get('sourceNode')
                    destination=Nmap.get('destinationNode')
                    for path in Nmap.findall('Path'):
                        performanceIndex = path.get('performanceIndex')
                        securityIndex = path.get('securityIndex')
                        cyberCost = path.get('cyberCost')
                    for node in path.findall('Node'):
                        ipAddress = node.get('IPAddress')
                        vulID = node.get('vulnID')
                        if ipAddress == source:
                            type = "source"
                        elif ipAddress == destination:
                            type = "destination"
                        else:
                            type = "intermediate"


                        for ip in assets:
                            if (assets[ip][1]==ipAddress and assets[ip][0]==type):
                                dupkey = ip
                                dup=1
                                break

                        if dup == 1:
                            assets[dupkey][6]+=float(performanceIndex)
                            assets[dupkey][7]+=float(securityIndex)
                            assets[dupkey][8]+=float(cyberCost)
                            assets[dupkey][9]+=1
                            assets[dupkey][10]+=","+vulID
                            assets[dupkey][11]=percentage
                            assets[dupkey][12]=sumtotal
                            print assets[dupkey]


                        else:
                            arr = []
                            arr.append(type)
                            arr.append(ipAddress)
                            arr.append(0)
                            arr.append(0)
                            arr.append(0)
                            arr.append(0)
                            arr.append(float(performanceIndex))
                            arr.append(float(securityIndex))
                            arr.append(float(cyberCost))
                            arr.append(1)
                            arr.append(vulID)
                            arr.append(percentage)
                            arr.append(sumtotal)
                            if(ipAddress in patched):
                                arr.append(1)
                            else:
                                arr.append(0)
                            assets[counter] = arr
                            counter+=1
                        dup=0
                        type=""
                        dupkey=""

            for ip in assets:
                assets[ip][11]=percentage
                assets[ip][12]=sumtotal
            json_data = json.dumps(assets)
            flag = "a"
            self.write_message(json_data)
        else:
            self.write_message(flag)
Example #23
0
    def on_message(self, message):
        global globalPath
        a = message.split(",")
        project = (a[0].split("/"))
        #batFileCmd = CypsaEnginePath+" " + project[len(project)-2] +" " + a[1]
        #print batFileCmd
        #from subprocess import Popen
        #p = Popen(batFileCmd, cwd=CypsaEngineRoot)
        #stdout, stderr = p.communicate()
        xmlfilepath = a[0] + "/pw_analysis_attack_graph_current.xml"
        csvfilepath = a[0] + "/patched.csv"
        percentage = 0
        sumtotal = 0
        counter = 0
        assets = {}
        dup = 0
        patched = []
        #read patched csv file and store elements already patched
        with open(csvfilepath) as csvfile:
            reader = csv.DictReader(csvfile)
            for row in reader:
                if (row['Patch'] == "1"):
                    patched.append(row['IP Address'])
                else:
                    print row['Patch']
        #print patched[1]
        from xml.etree import ElementTree
        with open(xmlfilepath, 'rt') as f:
            tree = ElementTree.parse(f)
            for Nmap in tree.findall('NmapAnalysis'):
                source = Nmap.get('sourceNode')
                destination = Nmap.get('destinationNode')
                for path in Nmap.findall('Path'):
                    performanceIndex = path.get('performanceIndex')
                    securityIndex = path.get('securityIndex')
                    cyberCost = path.get('cyberCost')
                    for node in path.findall('Node'):
                        ipAddress = node.get('IPAddress')
                        vulID = node.get('vulnID')
                        if ipAddress == source:
                            type = "source"
                        elif ipAddress == destination:
                            type = "destination"
                        else:
                            type = "intermediate"

                        for ip in assets:
                            if (assets[ip][1] == ipAddress
                                    and assets[ip][0] == type):
                                dupkey = ip
                                dup = 1
                                break

                        if dup == 1:
                            assets[dupkey][2] += float(performanceIndex)
                            assets[dupkey][3] += float(securityIndex)
                            assets[dupkey][4] += float(cyberCost)
                            assets[dupkey][5] += 1
                            assets[dupkey][10] += "," + vulID
                            percentage += float(securityIndex)
                            sumtotal += 1
                            assets[dupkey][11] = percentage
                            assets[dupkey][12] = sumtotal

                        else:
                            arr = []
                            arr.append(type)
                            arr.append(ipAddress)
                            arr.append(float(performanceIndex))
                            arr.append(float(securityIndex))
                            arr.append(float(cyberCost))
                            arr.append(1)
                            arr.append(0)
                            arr.append(0)
                            arr.append(0)
                            arr.append(0)
                            arr.append(vulID)
                            percentage += float(securityIndex)
                            sumtotal += 1
                            arr.append(percentage)
                            arr.append(sumtotal)
                            if (ipAddress in patched):
                                arr.append(1)
                            else:
                                arr.append(0)
                            assets[counter] = arr
                            counter += 1
                        dup = 0
                        type = ""
                        dupkey = ""

            xmlfilepath1 = a[0] + "/pw_analysis_attack_graph_previous.xml"
            if os.path.isfile(xmlfilepath1):
                from xml.etree import ElementTree
                with open(xmlfilepath1, 'rt') as f:
                    tree = ElementTree.parse(f)
                    for Nmap in tree.findall('NmapAnalysis'):
                        source = Nmap.get('sourceNode')
                        destination = Nmap.get('destinationNode')
                        for path in Nmap.findall('Path'):
                            performanceIndex = path.get('performanceIndex')
                            securityIndex = path.get('securityIndex')
                            cyberCost = path.get('cyberCost')
                            for node in path.findall('Node'):
                                ipAddress = node.get('IPAddress')
                                vulID = node.get('vulnID')
                                if ipAddress == source:
                                    type = "source"
                                elif ipAddress == destination:
                                    type = "destination"
                                else:
                                    type = "intermediate"

                                for ip in assets:
                                    if (assets[ip][1] == ipAddress
                                            and assets[ip][0] == type):
                                        dupkey = ip
                                        dup = 1
                                        break

                                if dup == 1:
                                    assets[dupkey][6] += float(
                                        performanceIndex)
                                    assets[dupkey][7] += float(securityIndex)
                                    assets[dupkey][8] += float(cyberCost)
                                    assets[dupkey][9] += 1
                                    assets[dupkey][10] += "," + vulID
                                    assets[dupkey][11] = percentage
                                    assets[dupkey][12] = sumtotal
                                    print assets[dupkey]

                                else:
                                    arr = []
                                    arr.append(type)
                                    arr.append(ipAddress)
                                    arr.append(0)
                                    arr.append(0)
                                    arr.append(0)
                                    arr.append(0)
                                    arr.append(float(performanceIndex))
                                    arr.append(float(securityIndex))
                                    arr.append(float(cyberCost))
                                    arr.append(1)
                                    arr.append(vulID)
                                    arr.append(percentage)
                                    arr.append(sumtotal)
                                    if (ipAddress in patched):
                                        arr.append(1)
                                    else:
                                        arr.append(0)
                                    assets[counter] = arr
                                    counter += 1
                                dup = 0
                                type = ""
                                dupkey = ""

            for ip in assets:
                assets[ip][11] = percentage
                assets[ip][12] = sumtotal
            json_data = json.dumps(assets)
            event_handler = MyHandler()
            args = a[0]
            if args:
                print args[0]
            else:
                print "helo"
            observer = Observer()
            observer.schedule(event_handler, path=a[0], recursive=False)
            observer.start()
            globalPath = a[0]
            print globalPath + " This is intializing"
            self.write_message(json_data)

        def on_close(self):
            pass
Example #24
0
    def on_message(self, message):
        global flag
        s = ""
        #self.write_message("hello")
        if flag == "b":
            #read PID's
            #save them in an array
            filepath = globalPath + "/pw_analysis_attack_graph_current.xml"
            prevfilepath = globalPath + "/pw_analysis_attack_graph_previous.xml"
            print "This is csvfile path timer " + filepath
            percentage = 0
            sumtotal = 0
            counter = 0
            assets = {}
            dup = 0
            csvfilepath = globalPath + "/patched.csv"
            print "This is csvfile path timer" + csvfilepath
            patched = []
            #read patched csv file and store elements already patched
            if os.path.isfile(csvfilepath):
                with open(csvfilepath) as csvfile:
                    reader = csv.DictReader(csvfile)
                    for row in reader:
                        if (row['Patch'] == "1"):
                            patched.append(row['IP Address'])
                    #else:
                    #    print row['Patch']
            #print patched[1]
            if os.path.isfile(filepath):
                tree = ET.parse(filepath)
                for Nmap in tree.findall('NmapAnalysis'):
                    source = Nmap.get('sourceNode')
                    destination = Nmap.get('destinationNode')
                    for path in Nmap.findall('Path'):
                        performanceIndex = path.get('performanceIndex')
                        securityIndex = path.get('securityIndex')
                        cyberCost = path.get('cyberCost')
                        for node in path.findall('Node'):
                            ipAddress = node.get('IPAddress')
                            vulID = node.get('vulnID')
                            if ipAddress == source:
                                type = "source"
                            elif ipAddress == destination:
                                type = "destination"
                            else:
                                type = "intermediate"
                            for ip in assets:
                                if (assets[ip][1] == ipAddress
                                        and assets[ip][0] == type):
                                    dupkey = ip
                                    dup = 1
                                    break
                            if dup == 1:
                                assets[dupkey][2] += float(performanceIndex)
                                assets[dupkey][3] += float(securityIndex)
                                assets[dupkey][4] += float(cyberCost)
                                assets[dupkey][5] += 1
                                assets[dupkey][10] += "," + vulID
                                percentage += float(securityIndex)
                                sumtotal += 1
                                assets[dupkey][11] = percentage
                                assets[dupkey][12] = sumtotal
                            else:
                                arr = []
                                arr.append(type)
                                arr.append(ipAddress)
                                arr.append(float(performanceIndex))
                                arr.append(float(securityIndex))
                                arr.append(float(cyberCost))
                                arr.append(1)
                                arr.append(0)
                                arr.append(0)
                                arr.append(0)
                                arr.append(0)
                                arr.append(vulID)
                                percentage += float(securityIndex)
                                sumtotal += 1
                                arr.append(percentage)
                                arr.append(sumtotal)
                                if (ipAddress in patched):
                                    arr.append(1)
                                else:
                                    arr.append(0)
                                assets[counter] = arr
                                counter += 1
                            dup = 0
                            type = ""
                            dupkey = ""
            if os.path.isfile(prevfilepath):
                tree = ET.parse(prevfilepath)
                for Nmap in tree.findall('NmapAnalysis'):
                    source = Nmap.get('sourceNode')
                    destination = Nmap.get('destinationNode')
                    for path in Nmap.findall('Path'):
                        performanceIndex = path.get('performanceIndex')
                        securityIndex = path.get('securityIndex')
                        cyberCost = path.get('cyberCost')
                    for node in path.findall('Node'):
                        ipAddress = node.get('IPAddress')
                        vulID = node.get('vulnID')
                        if ipAddress == source:
                            type = "source"
                        elif ipAddress == destination:
                            type = "destination"
                        else:
                            type = "intermediate"

                        for ip in assets:
                            if (assets[ip][1] == ipAddress
                                    and assets[ip][0] == type):
                                dupkey = ip
                                dup = 1
                                break

                        if dup == 1:
                            assets[dupkey][6] += float(performanceIndex)
                            assets[dupkey][7] += float(securityIndex)
                            assets[dupkey][8] += float(cyberCost)
                            assets[dupkey][9] += 1
                            assets[dupkey][10] += "," + vulID
                            assets[dupkey][11] = percentage
                            assets[dupkey][12] = sumtotal
                            print assets[dupkey]

                        else:
                            arr = []
                            arr.append(type)
                            arr.append(ipAddress)
                            arr.append(0)
                            arr.append(0)
                            arr.append(0)
                            arr.append(0)
                            arr.append(float(performanceIndex))
                            arr.append(float(securityIndex))
                            arr.append(float(cyberCost))
                            arr.append(1)
                            arr.append(vulID)
                            arr.append(percentage)
                            arr.append(sumtotal)
                            if (ipAddress in patched):
                                arr.append(1)
                            else:
                                arr.append(0)
                            assets[counter] = arr
                            counter += 1
                        dup = 0
                        type = ""
                        dupkey = ""

            for ip in assets:
                assets[ip][11] = percentage
                assets[ip][12] = sumtotal
            json_data = json.dumps(assets)
            flag = "a"
            self.write_message(json_data)
        else:
            self.write_message(flag)
Example #25
0
def fanbianyi():
    os.system("node" + " " + pwd + "\wxappUnpacker-master\wuWxapkg.js" + " " +
              path.get())