Пример #1
0
def GetConfigSection(strFilename, strSection):
    """
    Keyword Arguments:
    strFilename -- configuration file to read
    strSection -- section searched
    
    This function reads a file and returns the content of a section. This was made in order to
    read the sections related with the behaviour mode in the configuration file artemisa.conf.
    """
    SectionData = []

    try:
        File = open(strFilename, "r")

        section_found = False

        for line in File:
            line = RemoveComments(line)
            line = line.strip()

            if line.find("[") != -1:
                section_found = False

            if section_found:
                if line != "":
                    SectionData.append(line)

            if line.find("[" + strSection + "]") != -1:
                section_found = True

        File.close()

    except Exception, e:
        logger.error("Error in GetConfigSection function. Details: " + str(e))
        return ""
Пример #2
0
def GetIPfromSIP(HeaderLine):
    """
    Keyword Arguments:
    HeaderLine -- a string containing a specific SIP header
    
    This function gets and returns the IP address from a SIP header field.
    """
    if HeaderLine == "": return ""

    try:
        if HeaderLine.find("sip:") != -1:
            IPaddr = HeaderLine.split("sip:")[1]
            if IPaddr.find("@") != -1:
                IPaddr = IPaddr.split("@")[1]
            IPaddr = IPaddr.split(">")[0]
            IPaddr = IPaddr.split(":")[0]

            return IPaddr.strip()

        IPaddr = HeaderLine.split(">")[0]
        if IPaddr.find("@") != -1:
            IPaddr = IPaddr.split("@")[1]
        IPaddr = IPaddr.split(";")[0]
        if IPaddr.find(" ") != -1:
            IPaddr = IPaddr.split(" ")[len(IPaddr.split(" ")) - 1]
        IPaddr = IPaddr.split(":")[0]
        IPaddr = IPaddr.split("<")[len(IPaddr.split("<")) - 1]
    except Exception, e:
        logger.error("Error in GetIPfromSIP function. Details: " + str(e))
        return ""
Пример #3
0
 def _get_content_from_page(self, url):
     logger.info(f"Requesting page... [PAGE: {url}")
     response = self._get_response(url)
     if response.status_code != 200:
         logger.error(f"Did not get proper response from server.\n"
                      f"Checked page: {url}. [CODE={response.status_code}]")
         sys.exit(1)
     else:
         self._current_page_content = BeautifulSoup(response.content,
                                                    features="html.parser")
Пример #4
0
def GetPortfromSIP(HeaderLine):
    """
    Keyword Arguments:
    HeaderLine -- a string containing a specific SIP header
    
    This function gets and returns the port number from a SIP header field.
    """
    if HeaderLine == "": return ""

    try:
        if HeaderLine.find("sip:") != -1:
            Port = HeaderLine.split("sip:")[1]
            Port = Port.split(" ")[0]
            Port = Port.split(";")[0]
            if Port.find("@") != -1:
                Port = Port.split("@")[1]
            Port = Port.split(">")[0]

            if Port.find(":") != -1:
                Port = Port.split(":")[1].strip()
            else:
                return ""

            return Port.strip()

        Port = HeaderLine.split(">")[0]
        if Port.find("@") != -1:
            Port = Port.split("@")[1]
        Port = Port.split(";")[0]
        if Port.find(" ") != -1:
            Port = Port.split(" ")[len(Port.split(" ")) - 1]

        if Port.find(":") != -1:
            Port = Port.split(":")[len(Port.split(":")) - 1].strip()
        else:
            return ""
    except Exception, e:
        logger.error("Error in GetPortfromSIP function. Details: " + str(e))
        return ""
Пример #5
0
def GetExtensionfromSIP(HeaderLine):
    """
    Keyword Arguments:
    HeaderLine -- a string containing a specific SIP header
    
    This function gets and returns the extension value from a SIP header field.
    """
    if HeaderLine == "": return ""

    try:
        if HeaderLine.find("@") == -1:
            return ""  # This means that there is not extension found

        if HeaderLine.find("sip:") == -1:
            return ""  # This means that there is not extension found

        Extension = HeaderLine.split("sip:")[1]
        Extension = Extension.split("@")[0]

    except Exception, e:
        logger.error("Error in GetExtensionfromSIP function. Details: " +
                     str(e))
        return ""
Пример #6
0
    def __init__(self):

        config = ConfigParser.ConfigParser()
        try:
            strTemp = config.read(CONFIG_FILE_PATH)
        except:
            logger.error(
                "The configuration file artemisa.conf cannot be read.")
            return

        if strTemp == []:
            logger.error(
                "The configuration file artemisa.conf cannot be read.")
            return
        else:
            try:

                if config.get("email", "enabled").lower() == "true":
                    self.Enabled = True
                else:
                    self.Enabled = False

                self.SMTP_IP = config.get("email", "smtp_server_ip")
                self.SMTP_PORT = config.get("email", "smtp_server_port")
                self.SMTP_USERNAME = config.get("email",
                                                "smtp_server_username")
                self.SMTP_PASSWORD = config.get("email",
                                                "smtp_server_password")
                self.From = config.get("email", "from_mail")
                self.Recipients = config.get("email", "recipients_mail")
                self.To_header = config.get("email", "to_header")
                self.Subject = config.get("email", "subject")

                if config.get("email",
                              "smtp_server_use_tsl_ssl").lower() == "true":
                    self.TSLSSL = True
                else:
                    self.TSLSSL = False

            except:
                logger.error(
                    "E-mail account configuration cannot be correctly read. E-mail reports will not be sent."
                )
                return

        del config
Пример #7
0
    def sendemail(self, strData):

        if not self.Enabled:
            logger.info("E-mail notification is disabled.")
            return
        if self.SMTP_IP == "":
            logger.info("No SMTP server address configured.")
            return
        if self.SMTP_PORT == "":
            logger.info("SMTP server port is not configured.")
            return
        if self.Recipients == "":
            logger.info("No recipient address is configured.")
            return

        msg = MIMEMultipart()
        msg['To'] = self.To_header
        msg['From'] = self.From
        msg['Subject'] = self.Subject

        msgText = MIMEText(strData, "html")
        msg.attach(msgText)

        # Read the logo
        try:
            fp = open(ARTEMISA_WEBLOGO_PATH, 'rb')
            msgImage = MIMEImage(fp.read())
            fp.close()
        except:
            logger.error("Cannot read file " + ARTEMISA_WEBLOGO_PATH)
            return

        # Define the image's ID as referenced above
        msgImage.add_header('Content-ID', '<weblogo>')
        msg.attach(msgImage)

        try:
            if self.TSLSSL:
                server = SMTP(self.SMTP_IP, int(self.SMTP_PORT))
                server.ehlo()
                server.starttls()
                server.ehlo()
                server.login(self.SMTP_USERNAME, self.SMTP_PASSWORD)
            else:
                server = SMTP(self.SMTP_IP, int(self.SMTP_PORT))
                server.ehlo()
                server.login(self.SMTP_USERNAME, self.SMTP_PASSWORD)

            server.sendmail(self.From, self.Recipients.split(","),
                            msg.as_string())
            server.quit()

            logger.info("E-mail notification sent.")

        except SMTPAuthenticationError:
            logger.warning(
                "E-mail account username and/or password refused by SMTP server."
            )
        except Exception, e:
            logger.error("E-mail notification couldn't be sent. Error: " +
                         str(e))
Пример #8
0
def main():
    # command line parsing
    cmd = argparse.ArgumentParser()
    cmd.add_argument("model",help="An ASLAn++ model")
    cmd.add_argument("--c",metavar="concre_file",help="The concretization file, needed for executing Abstract Attack Trace")
    cmd.add_argument("--debug",help="Print debug messages",action="store_true")
    cmd.add_argument("--mc-only",help="Run the model-checker only and exit",action="store_true")
    cmd.add_argument("--interactive", help="Ask input of every parameter", action="store_true")
    #cmd.add_argument("--merger",help="Use the specified file as a base file to merge with the given model", metavar="basefile")
    cmd.add_argument("--verbose", help="Increase the output verbosity",action="store_true")
    translator = cmd.add_argument_group('Translator')
    translator_versions = ["1.4.1","1.4.9","1.3"]
    translator.add_argument("--translator",help="Specify a jar translator to use. Allowed values are "+", ".join(translator_versions)+". Default (1.4.1)", metavar='',choices=translator_versions)

    requests = cmd.add_argument_group("HTTP(S) options")
    requests.add_argument("--proxy", metavar="ip:port", help="Use an HTTP proxy when executing requests")

    model_checker = cmd.add_argument_group("Cl-Atse options")
    model_checker.add_argument("--mc-options",help="String representing the options to pass to Cl-Atse. For more information on the available options check Cl-Atse manual")
    model_checker.add_argument("--mc-timeout", metavar="T", help="If Cl-Atse runs more than T seconds, abort (default: 600)", type=int)

    args = cmd.parse_args()
    load_model = args.model


    mc_options = args.mc_options.split(" ") if args.mc_options else []
    if args.mc_timeout:
        config.mc_timeout = args.mc_timeout

    if args.interactive:
        config.interactive = True

    # check if model file exists
    if not os.path.isfile(load_model):
        criticalMsg = "Error {} file not found".format(load_model)
        logger.critical(criticalMsg)
        exit()
    # check if concretization file exists only if --mc-only hasn't been specified
    if args.c == None and not args.mc_only:
        logger.critical("Concretization file not specified")
        exit()
    elif not args.mc_only and not os.path.isfile(args.c):
        criticalMsg = "Error: {} file not found".format(args.c)
        logger.critical(criticalMsg)
        exit()
    elif not args.mc_only and args.c != None and  os.path.isfile(args.c):
        config.concretization = args.c

    print(config.BANNER.format(config.VERSION,config.SITE))

    # register exiting cleanup function
    atexit.register(exitcleanup)

    # set global variables
    config.verbosity = args.verbose
    config.DEBUG = args.debug

    # create folders if they do not exists
    if not os.path.isdir(config.WFAST_HOME):
        logger.info("Creating {} home folder".format(config.TOOL_NAME))
        os.makedirs(config.WFAST_HOME)
    if not os.path.isdir(config.WFAST_EXTRACTED_FILES_DIR):
        logger.info("Creating {} extracted files folder".format(config.TOOL_NAME))
        os.makedirs(config.WFAST_EXTRACTED_FILES_DIR)

    if config.DEBUG:
        logger.setLevel(logging.DEBUG)
    else:
        logger.setLevel(logging.INFO)

    if args.proxy:
        proxy = args.proxy.split(":")
        if len(proxy) == 2 and proxy[0] and proxy[1].isdigit():
            config.proxy_ip = proxy[0]
            config.proxy_port = proxy[1]
        else:
            criticalMsg = "Invalid proxy format {}".format(args.proxy)
            logger.error(criticalMsg)
            exit(-1)
    if args.translator == "1.4.9":
        mc.connector = config.CONNECTOR_1_4_9
    if args.translator == "1.3":
        mc.connector = config.CONNECTOR_1_3

    # if args.merger:
    #     base_model = args.merger
    #     webapp = load_model
    #     load_model = "out.aslan++"
    #     # merge the files
    #     merger(webapp,base_model,load_model)

    # first thing is to confert the ASLan++ model in ASLan
    file_aslan_model, err = mc.aslanpp2aslan(load_model)

    # we can now run the model checker, by default we use Cl-Atse locally
    file_attack_trace = mc.local_cl_atse(file_aslan_model,mc_options)

    # translate the attack trace in msc
    msc_output = mc.generate_msc(file_attack_trace,file_aslan_model)


    if not args.mc_only:

        # read the output and parse it
        msc = mc.parse_msc(msc_output)

        logger.debug("Parsed MSC")
        for msg in msc:
            debugMsg = "{} {}:{}:{} {} > tag{}".format(msg.sender , msg.receiver, msg.params, msg.action, msg.action_params, msg.tag)
            logger.debug(debugMsg)

        # execute the attack trace
        execute_attack(msc)