Esempio n. 1
0
    def test_supported_protocols(self):
        #Kritierum 2.3.1
        for protocol in self.protocols:
            try:
                context = ssl.SSLContext(protocol[0])
                context.verify_mode = ssl.CERT_REQUIRED
                context.check_hostname = True
                context.load_default_certs()

                self.__connect_ssl_socket(context)
                if protocol[2]:
                    logger.info("Server unterstützt " + protocol[1] +
                                " Dieses Verhalten ist OK")
                else:
                    logger.error("Server unterstützt " + protocol[1] +
                                 " Das sollte nicht der Fall sein")

            except ssl.SSLError as err:
                if "SSLV3_ALERT_HANDSHAKE_FAILURE" in err.args[1]:
                    if not protocol[2]:
                        logger.info("Server unterstützt NICHT " + protocol[1] +
                                    " Dieses Verhalten ist OK")
                    else:
                        logger.error("Server unterstützt NICHT" + protocol[1] +
                                     " Das sollte nicht der Fall sein")
Esempio n. 2
0
    def check_cert_for_keyusage_ca(self):
        try:
            keyusage_extension = self.cert.extensions.get_extension_for_class(
                x509.KeyUsage)
            if keyusage_extension.critical and keyusage_extension.value.key_cert_sign and keyusage_extension.value.crl_sign:
                logger.info(
                    "Das Zertifikat hat die korrekten KeyUsage-Bits, das ist so OK."
                )
                logger.info("critical: " + str(keyusage_extension.critical))
                logger.info("key_cert_sign: " +
                            str(keyusage_extension.value.key_cert_sign))
                logger.info("crl_sign: " +
                            str(keyusage_extension.value.crl_sign))
            else:
                logger.error(
                    "Das Zertifikat hat abweichende KeyUsage-Bits, das ist nicht OK"
                )
                logger.warning("critical: " + str(keyusage_extension.critical))
                logger.warning("key_cert_sign: " +
                               str(keyusage_extension.value.key_cert_sign))
                logger.warning("crl_sign: " +
                               str(keyusage_extension.value.crl_sign))

        except Exception as err:
            if "No <class 'cryptography.x509.extensions.KeyUsage'> extension was found" in str(
                    err):
                logger.error("Es wurde keine keyUsage Extension gefunden")
            else:
                print err
Esempio n. 3
0
    def test_session_renegotiation(self):
        #Anforderung 2.5.1

        openssl_cmd_getcert = "sslyze --regular " + self.hostname + ":" + str(
            self.port) + self.sslyze_proxy_part
        proc = subprocess.Popen([openssl_cmd_getcert],
                                stdout=subprocess.PIPE,
                                stderr=subprocess.PIPE,
                                shell=True)
        (out, err) = proc.communicate()

        if "Client-initiated Renegotiation:    OK - Rejected" in out:
            logger.error(
                "Server unterstützt unsichere session renegotiation. Das sollte nicht der Fall sein."
            )
        else:
            logger.info(
                "Server unterstützt unsichere session renegotiation nicht. Das ist so OK"
            )

        if "Secure Renegotiation:              OK - Supported" in out:
            logger.error(
                "Der Server unterstützt die sichere Form der renegotiaion. Das sollte nicht der Fall sein."
            )
        else:
            logger.info(
                "Der Server unterstützt die sichere Form der renegotiaion nicht. Das ist so OK."
            )
Esempio n. 4
0
    def test_heartbeat_extension(self):
        #Anforderung 2.5.3
        #Thanks to  https://www.feistyduck.com/library/openssl-cookbook/online/ch-testing-with-openssl.html

        if self.ca_file:
            openssl_ca_opt = "-CAfile " + self.ca_file
        else:
            openssl_ca_opt = ""
        openssl_cmd_getcert = " echo Q | openssl s_client " + openssl_ca_opt + " -connect " + self.hostname + ":" + str(
            self.port) + " -tlsextdebug" + self.openssl_client_proxy_part

        proc = subprocess.Popen([openssl_cmd_getcert],
                                stdout=subprocess.PIPE,
                                stderr=subprocess.PIPE,
                                shell=True)
        (out, err) = proc.communicate()

        if "heartbeat" in out:
            logger.error(
                "Server unterstützt die Heartbeat-extension. Das sollte nicht der Fall sein."
            )
        else:
            logger.info(
                "Server unterstützt die Heartbeat-Extension nicht. Das ist so OK."
            )
Esempio n. 5
0
    def check_cert_for_revocation(self):

        tmp_file = tempfile.NamedTemporaryFile(delete=False)
        tmp_file.write(self.cert.public_bytes(serialization.Encoding.PEM))
        tmp_file.close()

        try:
            crl_extension = self.cert.extensions.get_extension_for_class(
                x509.CRLDistributionPoints)
            logger.info(
                "Das Zertifikat hat eine CRLDistributionPoint Extension")

            openssl_cmd_getcert = "openssl verify -crl_check_all -CAfile " + self.ca_file + " " + tmp_file.name

            proc = subprocess.Popen([openssl_cmd_getcert],
                                    stdout=subprocess.PIPE,
                                    stderr=subprocess.PIPE,
                                    shell=True)
            (out, err) = proc.communicate()

            logger.warning(
                "Die Prüfung des Zertifikats gegen die CRL hat folgendes Ergebnis ergeben:"
            )
            logger.warning(out)
            logger.warning(err)

        except Exception as err:
            logger.error(
                "Fehler bei der Prüfung des Revocation status. Existiert keine CRLDistributionPoint Extension? Es folgt die Ausgabe des Fehlers"
            )
            logger.error(err)
Esempio n. 6
0
    def __init__(self,
                 features,
                 targets,
                 split_fraction=0.8,
                 embed_size=300,
                 lstm_size=256,
                 lstm_layers=1,
                 batch_size=500,
                 learning_rate=0.001,
                 keep_prob=0.5,
                 epochs=15):

        split_idx = int(len(features) * split_fraction)
        self.train_x, self.val_x = features[:split_idx], features[split_idx:]
        self.train_y, self.val_y = targets[:split_idx], targets[split_idx:]

        test_idx = int(len(self.val_x) * 0.5)
        self.val_x, self.test_x = self.val_x[:test_idx], self.val_x[test_idx:]
        self.val_y, self.test_y = self.val_y[:test_idx], self.val_y[test_idx:]

        self.embed_size = embed_size
        self.lstm_size = lstm_size
        self.lstm_layers = lstm_layers
        self.batch_size = batch_size
        self.learning_rate = learning_rate
        self.keep_prob = keep_prob
        self.epochs = epochs

        path_vocab_to_int = "{}/vocab_to_int.npy".format("./data")
        if os.path.exists(path_vocab_to_int):
            self.vocab_to_int = np.load(path_vocab_to_int).item()
        else:
            logger.error(
                "No vocab_to_int data found, please re-run DataCenter.")
            exit()
Esempio n. 7
0
    def config(self, key, value):
        method = self.cfg.get_method(key)
        if method is None:
            logger.error("No method for key %s" % key)
            return False

        logger.info("Setting option %s to value %s" % (key, value))
        return method(value)
Esempio n. 8
0
def login_ldap_callback(form):
    if current.auth.is_logged_in():
        user_name = current.auth.user.username
        if current.db.user(username = user_name)['last_name'] == "":
            user_info = fetch_ldap_user(user_name)
            if user_info:
                create_or_update_user(user_info, True)
            else:
                logger.error('Unable To Update User Info!!!')
Esempio n. 9
0
def login_ldap_callback(form):
    if current.auth.is_logged_in():
        user_name = current.auth.user.username
        if current.db.user(username = user_name)['last_name'] == "":
            user_info = fetch_ldap_user(user_name)
            if user_info:
                create_or_update_user(user_info, True)
            else:
                logger.error('Unable To Update User Info!!!')
    def test_model(self):
        """
        Test the trained model on test data. Report its accuracy.
        """
        save_model_path = './savedModel/cnn-model'
        n_samples = 4
        top_n_predictions = 3
        test_features, test_labels = pickle.load(
            open('./ProcessedData/preprocess_test.p', mode='rb'))

        tf.reset_default_graph()
        with tf.Session(graph=tf.get_default_graph()) as sess:
            try:
                graph = self.__load_graph(sess, save_model_path)
                # Get accuracy in batches for memory limitations
                test_batch_acc_total = 0
                test_batch_count = 0

                for test_feature_batch, test_label_batch in helper.batch_features_labels(
                        test_features, test_labels, NeuralNetwork.batch_size):
                    test_batch_acc_total += sess.run(graph['accuracy'],
                                                     feed_dict={
                                                         graph['x']:
                                                         test_feature_batch,
                                                         graph['y']:
                                                         test_label_batch,
                                                         graph['keep_prob']:
                                                         1.0
                                                     })
                    test_batch_count += 1

                logger.info('Testing Accuracy: {}\n'.format(
                    test_batch_acc_total / test_batch_count))

                # Print Random Samples
                random_test_features, random_test_labels = tuple(
                    zip(*random.sample(list(zip(test_features, test_labels)),
                                       n_samples)))
                random_test_predictions = sess.run(
                    tf.nn.top_k(tf.nn.softmax(graph['logits']),
                                top_n_predictions),
                    feed_dict={
                        graph['x']: random_test_features,
                        graph['y']: random_test_labels,
                        graph['keep_prob']: 1.0
                    })

                helper.display_image_predictions(random_test_features,
                                                 random_test_labels,
                                                 random_test_predictions)

            except Exception as e:
                logger.error(
                    "Something is missing from the previous saved graph, remove it and regenerate graph"
                )
                exit()
Esempio n. 11
0
def fetch_ldap_user(username):
    ldap_url = config.get("LDAP_CONF","ldap_url")
    base_dn = config.get("LDAP_CONF","ldap_dn")

    import ldap
    try:
        l = ldap.open(ldap_url)
        l.protocol_version = ldap.VERSION3    
    except ldap.LDAPError, e:
        logger.error(e)
        return None
Esempio n. 12
0
def fetch_ldap_user(username):
    ldap_url = config.get("LDAP_CONF","ldap_url")
    base_dn = config.get("LDAP_CONF","ldap_dn")

    import ldap
    try:
        l = ldap.open(ldap_url)
        l.protocol_version = ldap.VERSION3    
    except ldap.LDAPError, e:
        logger.error(e)
        return None
Esempio n. 13
0
def main(hostname, port, ca_file, clientcert_file, server_certificates, proxy, insecure):

    print_h1("Überprüfe Systemvorraussetzungen")
    if which('openssl')==None:
        logger.error('Could not find openssl in the path. Please install openssl and add it to the path. The call this script again. Will exit now.')
        exit (1)
    
    if server_certificates is None and proxy is not None:                       
        if ssl.OPENSSL_VERSION_NUMBER < 9999999999: # TODO: ab welcher version von openssl wird --proxy unterstuetz
            logger.error('Your version of OpenSSL does not support proxy setting. Please install OpenSSL x.x.x or later or try --servercertificates argument.')
            exit(1)
    

    if ca_file is not None:
        if os.path.exists(ca_file):
            logger.info("Using the following ca certificate file: "+ca_file)
        else:
            logger.error("ca file not found")
            sys.exit()
    else:
        logger.info("No dedicated ca_file provided. Using system ca.")

    if clientcert_file is not None:
        if os.path.exists(clientcert_file):
            logger.info("Using the following client certificate file: "+clientcert_file)
        else:
            logger.info("client certificate file not found.")
            sys.exit()

    if which('sslyze')==None:
        logger.error('Could not find sslyze in the path. Please install sslyze and add it to the path. The call this script again. Will exit now.')
        exit (1)


    svr=Server(hostname,port,ca_file,clientcert_file,server_certificates, split_proxy(proxy), insecure)

    svr.test_server_for_protocol()

    svr.read_certificates(server_certificates)

    if len(svr.certs)<1:
        logger.error("Zertifikate konnten nicht gelesen werden.")
        exit (1)

    svr.certs[0].check_leaf_certificate()

    if len(svr.certs)>1:
        svr.certs[-1].check_root_certificate()

    if len(svr.certs)>2:
        for crt in svr.certs[1:-1]:
            crt.check_intermediate_certificate()
Esempio n. 14
0
    def check_basic_constraint(self):
        #Anforderung 2.2.5
        try:
            basic_constraint_extension = self.cert.extensions.get_extension_for_class(
                x509.BasicConstraints)
            logger.info("Das Zertifikat hat eine BasicContraint Extension")
            logger.warning("Der Inhalt der BasicContraint Extension ist: " +
                           str(basic_constraint_extension))

            #TODO: Die Extension könnte man noch nett auswerten.

        except Exception as err:
            logger.error("Das Zertifikat hat keine BasicContraint Extension")
 def __init__(self, data, num_embedding_features=200):
     """
     :param data: input data, already in batches with batch_size defined in DataCenter. This is a generator
     :param num_embedding_features:
     """
     self.data = data
     self.num_embedding_features = num_embedding_features
     try:
         self.int_to_word = np.load("data/int_to_word.npy").item()
         self.num_words = len(self.int_to_word)
     except:
         logger.error(
             "Cannot find int_to_word dict, run DataCenter again...")
         exit()
Esempio n. 16
0
def push_email(to_address,
               email_subject,
               email_message,
               reply_to_address,
               cc_addresses=[]):
    if config.getboolean("MAIL_CONF", "mail_active"):
        logger.debug("Sending mail to %s with subject %s" %
                     (to_address, email_subject))
        rtn = mail.send(to=to_address,
                        subject=email_subject,
                        message=email_message,
                        reply_to=reply_to_address,
                        cc=cc_addresses)
        logger.error("ERROR:: " + str(mail.error))
        logger.info("EMAIL STATUS:: " + str(rtn))
Esempio n. 17
0
    def check_cert_for_revocation(self):

        # cn auslesen
        for entry in self.cert.subject._attributes:
            for attr in entry:
                if attr.oid._name == "commonName":
                    cn = attr.value
                    break

        # cn in tmpfilenamen einbetten
        tmp_file = tempfile.NamedTemporaryFile(prefix="tmp.checklist.%s" %
                                               (cn),
                                               delete=False)
        tmp_file.write(self.cert.public_bytes(serialization.Encoding.PEM))
        tmp_file.close()

        try:
            crl_extension = self.cert.extensions.get_extension_for_class(
                x509.CRLDistributionPoints)
            logger.info(
                "Das Zertifikat hat eine CRLDistributionPoint Extension")

            if self.ca_file:
                openssl_ca_opt = "-CAfile " + self.ca_file
            else:
                openssl_ca_opt = ""

            # Download der crl und Prüfung auf Zertifikatablauf
            openssl_cmd_getcert = "openssl verify -crl_check_all -crl_download " + openssl_ca_opt + " " + tmp_file.name

            proc = subprocess.Popen([openssl_cmd_getcert],
                                    stdout=subprocess.PIPE,
                                    stderr=subprocess.PIPE,
                                    shell=True)
            (out, err) = proc.communicate()

            logger.warning(
                "Die Prüfung des Zertifikats gegen die CRL hat folgendes Ergebnis ergeben:"
            )
            logger.warning(out)
            logger.warning(err)

        except Exception as err:
            logger.error(
                "Fehler bei der Prüfung des Revocation status. Existiert keine CRLDistributionPoint Extension? Es folgt die Ausgabe des Fehlers"
            )
            logger.error(err)
Esempio n. 18
0
    def __connect_ssl_socket(self, context):
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

        if self.proxy is None:
            ssl_sock = context.wrap_socket(s, server_hostname=self.hostname)
            ssl_sock.connect((self.hostname, self.port))
        else:
            try:
                s.connect(self.proxy)
            except socket.error, e:
                logger.error("Unable to connect to " + self.proxy[0] + ":" +
                             str(self.proxy[1]) + " " + str(e))
                exit(-1)
            s.send("CONNECT %s:%s HTTP/1.0\n\n" % (self.hostname, self.port))
            s.recv(1024)
            # logger.info ("Proxy response: " + string.strip(s.recv(1024)))
            ssl_sock = context.wrap_socket(s, server_hostname=self.hostname)
    def train_on_whole_data(self):
        """
        Train the model on whole batches and save the session on disk
        """
        save_model_path = './savedModel/cnn-model'
        self.build_graph(save_model_path)

        tf.reset_default_graph()
        with tf.Session(graph=tf.get_default_graph()) as sess:
            try:
                graph = self.__load_graph(sess, save_model_path)
                self.__train_and_report(sess, graph, range(1, 6),
                                        save_model_path)
            except Exception as e:
                logger.error(
                    "Something is missing from the previous saved graph, remove it and regenerate graph"
                )
                shutil.rmtree("./savedModel")
                exit()
Esempio n. 20
0
    def test_truncated_hmac_extension(self):
        #Anforderung 2.5.4
        openssl_cmd_getcert = " echo Q | openssl s_client -CAfile " + self.ca_file + " -connect " + self.hostname + ":" + str(
            self.port) + " -tlsextdebug" + self.openssl_client_proxy_part
        proc = subprocess.Popen([openssl_cmd_getcert],
                                stdout=subprocess.PIPE,
                                stderr=subprocess.PIPE,
                                shell=True)
        (out, err) = proc.communicate()

        #TODO: wir brauchen mal einen Server mit einer truncated_hmac extension um zu sehen, ob das hier funktioniert.
        if "truncated_hmac" in out:
            logger.error(
                "Server unterstützt die truncated_hmac extension. Das sollte nicht der Fall sein."
            )
        else:
            logger.info(
                "Server unterstützt die truncated_hmac extension nicht. Das ist OK."
            )
    def __init__(self, data):
        path_meta = "./data/meta.npy"
        if os.path.exists(path_meta):
            meta_data = np.load(path_meta).item()
            print(meta_data)
            assert isinstance(meta_data, dict), "meta data is not python dict type, something wrong"
            self.num_seq = meta_data['num_seq']
            self.num_step = meta_data['num_step']
            self.len_vocabulary = meta_data['len_vocabulary']

            self.data = data

            self.lstm_size = 512         # Size of hidden layers in LSTMs
            self.num_layers = 2          # Number of LSTM layers
            self.learning_rate = 0.001   # Learning rate
            self.keep_prob = 0.5         # Dropout keep probability
        else:
            logger.error("Meta data is missing, please re-run DataCenter first!")
            exit()
Esempio n. 22
0
def create_schema():

    # do migration
    create_table_and_index = """
        CREATE TABLE IF NOT EXISTS tags 
        (image_id VARCHAR(40) NOT NULL, label VARCHAR(64) NOT NULL, 
        PRIMARY KEY (image_id, label),
        INDEX (image_id, label));
    """

    try:
        execute_statement(create_table_and_index)
        response = execute_statement("SHOW TABLES;")
        logger.info(f'List of tables: {response}')
    except Exception as e:
        logger.error(f'Something went wrong while creating table: {e}')
        raise e

    return True
Esempio n. 23
0
    def test_tls_compression(self):
        #Anforderung 2.5.2
        openssl_cmd_getcert = " echo " R" | openssl s_client -CAfile " + self.ca_file + " -connect " + self.hostname + ":" + str(
            self.port) + self.openssl_client_proxy_part

        proc = subprocess.Popen([openssl_cmd_getcert],
                                stdout=subprocess.PIPE,
                                stderr=subprocess.PIPE,
                                shell=True)
        (out, err) = proc.communicate()

        if "Compression: NONE" in out:
            logger.info(
                "Server unterstützt keine TLS compression. Das ist das erwartete Verhalten."
            )
        else:
            logger.error(
                "Server unterstützt TLS compression. Das sollte nicht der Fall sein."
            )
Esempio n. 24
0
    def test_supported_protocols(self):
        #Kritierum 2.3.1
        for protocol in self.protocols:

            context = ssl.SSLContext(protocol[0])
            if self.insecure:
                context.verify_mode = ssl.CERT_NONE
                context.check_hostname = False
            else:
                context.verify_mode = ssl.CERT_REQUIRED
                context.check_hostname = True

            if self.ca_file:
                context.load_verify_locations(cafile=self.ca_file)
            else:
                context.load_default_certs()

            if self.clientcert_file:
                context.load_cert_chain(certfile=self.clientcert_file)

            try:
                s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                ssl_sock = context.wrap_socket(s,
                                               server_hostname=self.hostname)
                ssl_sock.connect((self.hostname, self.port))

                if protocol[2]:
                    logger.info("Server unterstützt " + protocol[1] +
                                " Dieses Verhalten ist OK")
                else:
                    logger.error("Server unterstützt " + protocol[1] +
                                 " Das sollte nicht der Fall sein")

            except ssl.SSLError as err:
                if "SSLV3_ALERT_HANDSHAKE_FAILURE" in err.args[
                        1] or "EOF occurred in violation of protocol" in err.args[
                            1]:
                    if not protocol[2]:
                        logger.info("Server unterstützt NICHT " + protocol[1] +
                                    " Dieses Verhalten ist OK")
                    else:
                        logger.error("Server unterstützt NICHT " +
                                     protocol[1] +
                                     " Das sollte nicht der Fall sein")
                else:
                    logger.error("unbekannter Fehler bei Test von " +
                                 protocol[1])
                    print(err)

            except Exception as err:
                logger.error("unbekannter Fehler bei Test von " + protocol[1])
                print(err)
Esempio n. 25
0
    def check_for_wildcards(self):
        #TODO: Das ist in der Prüfung von CA Zertifkaten anders. Die Funktion hier steigt leider aus wenn es die AlternativeNames extension nich gitb und daher kann man sie eigentlich für ein CA-ZErt nicht verwenden. Und es müssen auch noch mehr Felder (subject) geprüft werden.
        for entry in self.cert.subject._attributes:
            for attr in entry:
                if attr.oid._name == "commonName":
                    logger.info(
                        "commonName im subject des Zertifikat hat den Wert: " +
                        attr.value)
                    # test auf stern in cn
                    if re.search(r"\*+", attr.value) != None:
                        logger.error(
                            "Der CN enthält mindestens ein *. Das ist nicht OK"
                        )

        try:
            name_extension = self.cert.extensions.get_extension_for_class(
                x509.SubjectAlternativeName)
            logger.info("Das Zertifikat hat eine AlternativeName Extension")

            # liste der san
            altname_list = name_extension.value.get_values_for_type(
                x509.DNSName)
            # keine san enthalten
            if len(altname_list) < 1:
                logger.warn("Die Liste der Alernative Names ist leer.")
                return

            # test auf stern in san
            for altname in altname_list:
                if re.search(r"\*+", altname) != None:
                    logger.error(
                        "Die AlternativeName-Extension enthält mindestens ein *. Das ist nicht OK"
                    )
                    return
            logger.info(
                "Die AlternativeName-Extension enthält keine Wildcards. Das ist  OK"
            )

        except Exception as err:
            # eine fehlende SAN-Extension an sich sollte kein Fehler sein
            # bitte prüfen
            logger.info("Es existiert keine AlternativeName-Extension")
    def train_on_one_batch(self):
        """
        Train the model on one batch and save the session on disk
        """
        save_model_path = './savedModel/cnn-model'
        self.build_graph(save_model_path)

        with tf.device('/gpu:0'):
            tf.reset_default_graph()
            with tf.Session(graph=tf.get_default_graph(
            )) as sess:  #config=tf.ConfigProto(log_device_placement=True)
                try:
                    graph = self.__load_graph(sess, save_model_path)
                    self.__train_and_report(sess, graph, range(1, 2),
                                            save_model_path)

                except Exception as e:
                    logger.error(
                        "Something is missing from the previous saved graph, remove it and regenerate graph"
                    )
                    shutil.rmtree("./savedModel")
                    exit()
Esempio n. 27
0
    def check_cert_for_keyusage(self):
        try:
            keyusage_extension = self.cert.extensions.get_extension_for_class(
                x509.KeyUsage)
            logger.info(
                "Das Zertifikat hat eine KeyUsage Extension mit den folgenden Eigenschaften"
            )
            logger.warning("digital_signature: " +
                           str(keyusage_extension.value.digital_signature))
            logger.warning("key_cert_sign: " +
                           str(keyusage_extension.value.key_cert_sign))
            logger.warning("crl_sign: " +
                           str(keyusage_extension.value.crl_sign))

            #TODO: Man könnte die Werte auch gleich prüfen, allerdings ist das für CA Zertifkate anders und daher etwas komplizierter.

        except Exception as err:
            if "No <class 'cryptography.x509.extensions.KeyUsage'> extension was found" in str(
                    err):
                logger.error("Es wurde keine keyUsage Extension gefunden")
            else:
                print err
Esempio n. 28
0
    def check_basic_constraint(self):
        #Anforderung 2.2.5
        try:
            basic_constraint_extension = self.cert.extensions.get_extension_for_class(
                x509.BasicConstraints)
            # test auf vorhandensein der critical constraint
            if basic_constraint_extension.critical:
                logger.info(
                    "Das Zertifikat hat eine als kritisch markierte BasicContraint Extension. Das ist so OK"
                )
                logger.info("Der Inhalt der BasicContraint Extension ist: " +
                            str(basic_constraint_extension))
            else:
                logger.error(
                    "Das Zertifikat hat eine nicht kritisch markierte BasicContraint Extension. Das ist nicht OK"
                )
                logger.warning(
                    "Der Inhalt der BasicContraint Extension ist: " +
                    str(basic_constraint_extension))

        except Exception as err:
            logger.error("Das Zertifikat hat keine BasicContraint Extension")
Esempio n. 29
0
    def __init__(self, data, para_dict):

        self.data_path = "data"
        self.lstm_size = para_dict['lstm_size']
        self.lstm_layers = para_dict['lstm_layers']
        self.embedding_size = para_dict['embedding_size']
        self.batch_size = para_dict['batch_size']
        self.epochs = para_dict['epochs']
        self.keep_prob = para_dict['keep_prob']
        self.learning_rate = para_dict['learning_rate']

        self.source_train, self.target_train = data[0][self.batch_size:], data[
            1][self.batch_size:]
        self.source_valid, self.target_valid = data[0][:self.batch_size], data[
            1][:self.batch_size]
        path_target_int_to_vocab = "{}/target_int_to_vocab.npy".format(
            self.data_path)
        path_target_vocab_to_int = "{}/target_vocab_to_int.npy".format(
            self.data_path)
        path_source_int_to_vocab = "{}/source_int_to_vocab.npy".format(
            self.data_path)
        path_source_vocab_to_int = "{}/source_vocab_to_int.npy".format(
            self.data_path)

        if os.path.exists(path_target_int_to_vocab) and os.path.exists(path_target_vocab_to_int) and \
                os.path.exists(path_source_vocab_to_int) and os.path.exists(path_source_int_to_vocab):
            self.target_int_to_vocab = np.load(path_target_int_to_vocab).item()
            self.target_vocab_to_int = np.load(path_target_vocab_to_int).item()
            self.source_vocab_to_int = np.load(path_source_vocab_to_int).item()
            self.source_int_to_vocab = np.load(path_source_int_to_vocab).item()
            assert isinstance(self.source_vocab_to_int, dict)
            self.source_vocab_size = len(self.source_vocab_to_int)
            assert isinstance(self.target_vocab_to_int, dict)
            self.target_vocab_size = len(self.target_vocab_to_int)
        else:
            logger.error(
                "No vocab_to_int data found, please re-run DataCenter.")
            exit()
Esempio n. 30
0
    def __init__(self, file_name):
        try:
            self.tree = self.parse(file_name)
        except ET.ParseError:
            logger.error(str(ET.ParseError))
            if os.path.getsize(file_name) > 0:
                raise Exception("Error parsing file %s" % file_name)
            #create a new tree if the file is empty
            self.create_tree()

        if self.tree is None:
            return

        self.root = self.tree.getroot()
        if self.root is None:
            self.create_tree()

        if self.root.tag != self.ROOT_TAG:
            raise Exception("Invalid root element")

        self.file_name = file_name

        self.save()
Esempio n. 31
0
    def run(self):

        #lock a tmp file to avoid starting multiple daemons
        self.lockf = open('/tmp/clipon-lock', 'w')
        try:
            fcntl.flock(self.lockf, fcntl.LOCK_EX | fcntl.LOCK_NB)
        except BlockingIOError:
            logger.error("Unable to lock file")
            return

        self.setup()

        self.cfg = CliponConfig(self.cfg_file)
        self.cfg.load()
        self.cfg.save()

        self.history = ClipHistory(self.cfg)

        self.monitor = ClipboardMonitor(self.history)
        self.monitor.start()

        dbus_loop = DBusGMainLoop()
        bus_name = dbus.service.BusName(CLIPON_BUS_NAME,
                        bus=dbus.SessionBus(mainloop=dbus_loop))
        dbus.service.Object.__init__(self, bus_name,
                                     CLIPON_OBJ_PATH)

        GObject.threads_init() #should be called before mainloop
        self.main_loop = GObject.MainLoop()

        self.status = 'active'
        try:
            logger.info("DBus service started")
            self.main_loop.run()
        except (KeyboardInterrupt, SystemExit):
            self.stop()
Esempio n. 32
0
    def check_cert_for_extended_keyusage(self):
        try:
            # liste der extended-keyusage extension auslesen
            keyusage_extension = self.cert.extensions.get_extension_for_class(
                x509.ExtendedKeyUsage)
            usg_list = []
            for usg in keyusage_extension.value._usages:
                usg_list.append(usg._name)

            # test auf serverAuth
            if "serverAuth" in usg_list:
                contains_serverauth = True
                logger.info(
                    "Das Zertifikat hat eine ExtendedKeyUsage Extension mit dem Eintrag serverAuth"
                )
            else:
                contains_serverauth = False
                logger.warning(
                    "Das Zertifikat hat eine ExtendedKeyUsage Extension mit den folgenden Eigenschaften:",
                    usg_list)

        except Exception as err:
            logger.error("Das Zertifikat hat keine ExtendedKeyUsage Extension")
            print err
Esempio n. 33
0
    def check_for_wildcards(self):
        #TODO: Das ist in der Prüfung von CA Zertifkaten anders. Die Funktion hier steigt leider aus wenn es die AlternativeNames extension nich gitb und daher kann man sie eigentlich für ein CA-ZErt nicht verwenden. Und es müssen auch noch mehr Felder (subject) geprüft werden.
        for entry in self.cert.subject._attributes:
            for attr in entry:
                if attr.oid._name == "commonName":
                    logger.info(
                        "commonName im subject des Zertifikat hat den Wert: " +
                        attr.value)
        try:
            name_extension = self.cert.extensions.get_extension_for_class(
                x509.SubjectAlternativeName)
            logger.info("Das Zertifikat hat eine AlternativeName Extension")

            if re.search(r"\*+", str(name_extension)) is not None:
                logger.error(
                    "Die AlternativeName-Extension enthält mindestens ein *. Das ist nicht OK"
                )
            else:
                logger.info(
                    "Die AlternativeName-Extension enthält keine Wildcards. Das ist  OK"
                )

        except Exception as err:
            logger.error("Es existiert keine AlternativeName-Extension")
Esempio n. 34
0
def main(hostname, port, ca_file, server_certificates, proxy):

    print_h1("Überprüfe Systemvorraussetzungen")
    if which('openssl') == None:
        logger.error(
            'Could not find openssl in the path. Please install openssl and add it to the path. The call this script again. Will exit now.'
        )
        exit(1)

    if server_certificates is None and proxy is not None:
        if ssl.OPENSSL_VERSION_NUMBER < 9999999999:  # TODO: ab welcher version von openssl wird --proxy unterstuetz
            logger.error(
                'Your version of OpenSSL does not support proxy setting. Please install OpenSSL x.x.x or later or try --servercertificates argument.'
            )
            exit(1)

    if ca_file is None:
        logger.info("No dedicated ca_file provided. Using default vaule.")
        ca_file = ssl.get_default_verify_paths().openssl_cafile

    logger.info("Using the follwing ca_file: " + ca_file)

    if which('sslyze') == None:
        logger.error(
            'Could not find sslyze in the path. Please install sslyze and add it to the path. The call this script again. Will exit now.'
        )
        exit(1)

    svr = Server(hostname, port, ca_file, server_certificates,
                 split_proxy(proxy))

    svr.test_server_for_protocol()

    svr.read_certificates(server_certificates)

    svr.certs[0].check_leaf_certificate()

    if len(svr.certs) > 1:
        svr.certs[-1].check_root_certificate()

    if len(svr.certs) > 2:
        for crt in svr.certs[1:-1]:
            crt.check_intermediate_certificate()
Esempio n. 35
0
    def check_certificate_key(self):
        if (type(self.cert.public_key()) is _RSAPublicKey):
            logger.info("This certificate has an RSA key")
            if self.cert.public_key().key_size >= 2048:
                logger.info(
                    "Die Groesse des Schluessels ist gleich oder groesser 2048. Das ist OK."
                )
            else:
                logger.error(
                    "Die Groesse des Schluessels ist kleiner 2048bit. Das sollte nicht der Fall sein."
                )

            # logger.info.("The key size is: "+str(cert.public_key().key_size))
        if (type(self.cert.public_key()) == DSAPublicKey):
            logger.error(
                "Das Zertifikat hat einen DSA key. Das sollte nicht der Fall sein. Das Skript wird hier beendet da die weiteren Tests nicht sinnvoll sind."
            )
            exit(1)
            #TODO: Der Fall muss noch getestet werden. Die genaue Bezeichnung des Types des public_key könnte leicht anders sein

        if (type(self.cert.public_key()) == EllipticCurvePublicKey):
            #TODO: Dieser Fall ist noch recht ungetestet

            logger.info("Das Zertifikat hat einen EllipticCurvePublicKey")

            allowed_curves = [
                "brainpoolPP256r1", "brainpoolP384r1", "brainpoolP512r1",
                "secp224r1", "secp256r1", "secp384r1", "secp521r1"
            ]
            correct_curve = False

            for crv in allowed_curves:
                if str(self.cert.public_key().curve.name) == crv:
                    logger.info("Es wird folgende Kurfe verwendet:" +
                                str(self.cert.public_key().curve.name) +
                                " Das ist OK")
                    correct_curve = True
            if correct_curve:
                logger.error(
                    "Es wird eine nicht zugelassene Kurve verwendet. Und zwar: "
                    + str(self.cert.public_key().curve.name))
Esempio n. 36
0
                                    user_info['last_name'] = vals[0][vals[0].index(' '):].lstrip()
#                             if k == 'altEmail':
#                                 if vals[0] != 'none':
#                                     user_info['email'] = vals[0]
 
#TODO: find role and organisation from ldap and set in db accordingly (current iitd ldap does not support this feature entirely) 
        user_info['email'] = username + config.get("MAIL_CONF", "email_domain")                                    
        user_info['roles'] = fetch_user_role(username)
        # If user has super admin rights; it is added to separate organization
        if current.ADMIN in user_info['roles']:
            user_info['organisation'] = 'ADMIN'
        else:
            user_info['organisation'] = 'IITD'

    except ldap.LDAPError, e:
        logger.error(e)

    logger.info(user_info)
    if 'first_name' in user_info:
        return user_info
    else: 
        return None

#This method is called only when user logs in for the first time or when faculty name is verified on 'request VM' screen
def create_or_update_user(user_info, update_session):

    user_name = user_info['user_name']
    user = current.db(current.db.user.username == user_name).select().first()
    
    if not user:
        #create user
Esempio n. 37
0
def push_email(to_address, email_subject, email_message, reply_to_address, cc_addresses=[]):
    if config.getboolean("MAIL_CONF","mail_active"):
        logger.debug("Sending mail to %s with subject %s" %(to_address, email_subject))
        rtn = mail.send(to=to_address, subject=email_subject, message = email_message, reply_to=reply_to_address, cc=cc_addresses)
        logger.error("ERROR:: " + str(mail.error))
        logger.info("EMAIL STATUS:: " + str(rtn))
Esempio n. 38
0
def get_vm_operations(vm_id):

    vm_operations = {'start_vm'              : ('user', 'on-off.png', 'Turn on this virtual machine'),
                     'suspend_vm'            : ('user', 'pause2.png', 'Suspend this Virtual Machine'),
                     'resume_vm'             : ('user', 'play2.png', 'Unpause this virtual machine'),
                     'stop_vm'               : ('user', 'shutdown2.png', 'Gracefully shut down this virtual machine'),
                     'destroy_vm'            : ('user', 'on-off.png', 'Forcefully power off this virtual machine'),
                     'clone_vm'              : ('user', 'clonevm.png', 'Request VM Clone'),
                     'attach_extra_disk'     : ('user', 'disk.jpg', 'Attach Extra Disk'),
                     'snapshot'              : ('user', 'snapshot.png', 'Take VM snapshot'),
                     'edit_vm_config'        : ('user', 'editme.png', 'Edit VM Config'),
                     'show_vm_performance'   : ('user', 'performance.jpg', 'Check VM Performance'),
                     'vm_history'            : ('user', 'history.png', 'Show VM History'),
                     'grant_vnc'             : ('user', 'vnc.jpg', 'Grant VNC Access'),
                     'confirm_vm_deletion()' : ( None, 'delete.png', 'Delete this virtual machine'),
                     'migrate_vm'            : ('admin', 'migrate.png', 'Migrate this virtual machine'),
                     'user_details'          : ('admin', 'user_add.png', 'Add User to VM'),
                     'save_vm_as_template'      : ('user', 'save.png', 'Save as Template'),
                     'mail_user'             : ('admin','email_icon.png','Send Mail to users of the VM'),
                     'affinity_host'         : ('admin','affinity.png','Set Affinity')}

    valid_operations_list = []
    
    vm_status = db.vm_data[vm_id].status
    
    if vm_status not in (VM_STATUS_UNKNOWN, VM_STATUS_IN_QUEUE):
        valid_operations = ['snapshot', 'show_vm_performance','affinity_host']

        if vm_status == VM_STATUS_RUNNING:
            valid_operations.extend(['suspend_vm' , 'stop_vm', 'destroy_vm'])
        elif vm_status == VM_STATUS_SUSPENDED:
            valid_operations.extend(['resume_vm'])
        elif vm_status == VM_STATUS_SHUTDOWN:
            #Start VM option is not valid if edit VM or attach disk option is in queue
            if not (is_request_in_queue(vm_id, VM_TASK_EDIT_CONFIG) | 
                    is_request_in_queue(vm_id, VM_TASK_ATTACH_DISK)):
                valid_operations.extend(['start_vm'])

            valid_operations.extend(['clone_vm', 'edit_vm_config', 'attach_extra_disk', 'save_vm_as_template'])

        if not is_vm_user():
            valid_operations.extend(['confirm_vm_deletion()'])
            if is_moderator():
                valid_operations.extend(['migrate_vm'])
                valid_operations.extend(['user_details'])
                valid_operations.extend(['mail_user'])

        valid_operations.extend(['grant_vnc', 'vm_history'])
        
        #Disable all links if Delete VM option is in queue
        link_disabled = True if is_request_in_queue(vm_id, VM_TASK_DELETE) else False
        for valid_operation in valid_operations:
            
            op_data = vm_operations[valid_operation]
            op_image = IMG(_src=URL('static','images/'+op_data[1]), _style='height:20px;weight:20px')
            
            if link_disabled:
                valid_operations_list.append(op_image)
            else:
                if op_data[0] != None:
                    valid_operations_list.append(A(op_image, _title=op_data[2], _alt=op_data[2], 
                                                   _href=URL(r=request, c = op_data[0] , f=valid_operation, args=[vm_id])))
                else:
                    valid_operations_list.append(A(op_image, _title=op_data[2], _alt=op_data[2], 
                                                   _onclick=valid_operation))
   
    else:
        logger.error("INVALID VM STATUS!!!")
        raise
    return valid_operations_list