示例#1
0
def download_http_cert(endpoint):
    """
    Scarica i certificati root e sub CA dall'endpoint
    :param endpoint: url del certificato da scaricare
    :return: restituisce il certificato scaricato
    """
    cert = None
    try:
        r = requests.get(endpoint)
        if r.status_code == 200:
            try:
                cert = crypto.load_certificate(crypto.FILETYPE_ASN1, r.content)
            except:
                cert = crypto.load_certificate(crypto.FILETYPE_PEM, r.content)
        else:
            LOG.error('Errore durante il download della CRL con endpoint = {}'.
                      format(endpoint),
                      extra=set_client_ip())
    except Exception as e:
        LOG.error(
            'Eccezione durante il download della CRL con endpoint = {}'.format(
                endpoint),
            extra=set_client_ip())
        LOG.error(str(e), extra=set_client_ip())
    return cert
示例#2
0
def init_county(request, file='province.csv'):
    """
    Popola le province
    :param request: request
    :param file: file province in formato csv
    :return: JsonResponse con statusCode
    """
    try:
        table = AddressMunicipality.objects.all()
        if table:
            table.delete()

        table = AddressCity.objects.all()
        if table:
            table.delete()
        with open(os.path.join(settings.DATA_FILES_PATH, file), encoding='utf-8') as csv_file:
            reader = csv.DictReader(csv_file, delimiter=';', skipinitialspace=True)
            sa = ''
            for row in reader:
                if sa != row["Sigla automobilistica"]:
                    sa = row["Sigla automobilistica"]
                    ac = AddressCity(name=row["Città"],
                                     code=row["Sigla automobilistica"])
                    ac.save()
        return JsonResponse({'statusCode': StatusCode.OK.value})
    except Exception as e:
        ype, value, tb = sys.exc_info()
        LOG.error("Exception: {}".format(str(e)), extra=set_client_ip(request))
        LOG.error('exception_value = %s, value = %s' % (value, type,), extra=set_client_ip(request))
        LOG.error('tb = %s' % traceback.format_exception(type, value, tb), extra=set_client_ip(request))
    return JsonResponse({'statusCode': StatusCode.BAD_REQUEST.value})
示例#3
0
def init_user(request):
    """
    Popola la tabella ruoli, inserisce il primo operatore e imposta il token di verifica a True
    :param request
    :return: JsonResponse con statusCode
    """
    try:
        response_role = populate_role()
        response_op = create_first_operator(request)
        if response_op and response_role:
            if request.session['activation_token']:
                vms = VerifyMail.objects.filter(token=request.session['activation_token']).last()
                vms.isVerified = True
                vms.save()
                return JsonResponse({'statusCode': StatusCode.OK.value})
            LOG.error("Errore durante la verifica dell'operatore activation_token")
            return JsonResponse({'statusCode': StatusCode.ERROR.value})
        else:
            LOG.error("Errore durante il popolamento tabella ruoli operatori")
            return JsonResponse({'statusCode': StatusCode.ERROR.value})
    except Exception as e:
        ype, value, tb = sys.exc_info()
        LOG.error("Exception: {}".format(str(e)), extra=set_client_ip(request))
        LOG.error('exception_value = %s, value = %s' % (value, type,), extra=set_client_ip(request))
        LOG.error('tb = %s' % traceback.format_exception(type, value, tb), extra=set_client_ip(request))
    return JsonResponse({'statusCode': StatusCode.BAD_REQUEST.value})
示例#4
0
def necessary_data_check():
    """
    Verifica se i dati necessari al corretto funzionamento sono già in tabella
    :return: True/False
    """
    try:
        table = AddressNation.objects.all()
        if not table:
            return False
        table = AddressCity.objects.all()
        if not table:
            return False
        table = AddressMunicipality.objects.all()
        if not table:
            return False
        table = Role.objects.all()
        if not table:
            return False
        return True
    except Exception as e:
        ype, value, tb = sys.exc_info()
        LOG.error("Exception: {}".format(str(e)), extra=set_client_ip())
        LOG.error('exception_value = %s, value = %s' % (value, type,), extra=set_client_ip())
        LOG.error('tb = %s' % traceback.format_exception(type, value, tb), extra=set_client_ip())
    return False
示例#5
0
def init_nation(request, file='nazioni.csv'):
    """
    Popola la tabella delle nazioni
    :param request:
    :param file: file nazioni in formato csv
    :return: JsonResponse con statusCode
    """
    try:
        table = AddressNation.objects.all()
        if table:
            table.delete()
        with open(os.path.join(settings.DATA_FILES_PATH, file), encoding='utf-8') as csv_file:
            reader = csv.DictReader(csv_file, delimiter=';', skipinitialspace=True)
            for row in reader:
                if row["Denominazione IT"] == '':
                    continue

                code = row["Codice AT"] if row["Codice AT"] != 'n.d.' else "Z998"

                an = AddressNation(name=row["Denominazione IT"],
                                   code=code if row["Denominazione IT"] != 'Italia' else "Z000",
                                   lettersCode=row["Codice ISO 3166 alpha3"])
                an.save()
        return JsonResponse({'statusCode': StatusCode.OK.value})
    except Exception as e:
        ype, value, tb = sys.exc_info()
        LOG.error("Exception: {}".format(str(e)), extra=set_client_ip(request))
        LOG.error('exception_value = %s, value = %s' % (value, type,), extra=set_client_ip(request))
        LOG.error('tb = %s' % traceback.format_exception(type, value, tb), extra=set_client_ip(request))

    return JsonResponse({'statusCode': StatusCode.BAD_REQUEST.value})
示例#6
0
def _download_http_crl(endpoint, key_identifier):
    """
    :param endpoint: url della crl
    :param key_identifier: chiave identificativa dell'issuer del certificato
    :return:
    """

    crl_dest = make_crl_store_path(endpoint, key_identifier) + ".crl"
    crl_meta_dest = make_crl_store_path(endpoint, key_identifier) + ".txt"

    try:
        r = requests.get(endpoint)
        if r.status_code == 200:
            try:
                crl = crypto.load_crl(crypto.FILETYPE_PEM, r.content)
            except:
                crl_x509 = x509.load_der_x509_crl(r.content, default_backend())
                crl = crypto.CRL.from_cryptography(crl_x509)
            with open(crl_dest, 'w') as f:
                f.write(crypto.dump_crl(crypto.FILETYPE_PEM, crl).decode())
            with open(crl_meta_dest, 'w') as f:
                f.write(endpoint)
        else:
            LOG.error('Errore durante il download della CRL con endpoint = {}'.
                      format(endpoint),
                      extra=set_client_ip())
    except Exception as e:
        LOG.error(
            'Eccezione durante il download della CRL con key_identifier = {}'.
            format(key_identifier),
            extra=set_client_ip())
        LOG.error("Exception: {}".format(str(e)), extra=set_client_ip())
示例#7
0
def init_prefix(request, file='prefissi.csv', encoding='utf-8'):
    """
    Popola i prefissi sulla tabella delle nazioni
    :param request: request
    :param file: file prefissi in formato csv
    :param encoding: default 'utf-8'
    :return: JsonResponse con statusCode
    """
    try:
        with open(os.path.join(settings.DATA_FILES_PATH, file), encoding='utf-8') as csv_file:
            reader = csv.DictReader(csv_file, delimiter=';', skipinitialspace=True)
            for row in reader:
                try:
                    an = AddressNation.objects.filter(name=row['Nazione']).first()
                    if an:
                        an.prefix = row['Prefisso']
                        an.save()
                except Exception as e:
                    LOG.error("Exception: {}".format(str(e)), extra=set_client_ip(request))
        return JsonResponse({'statusCode': StatusCode.OK.value})
    except Exception as e:
        ype, value, tb = sys.exc_info()
        LOG.error("Exception: {}".format(str(e)), extra=set_client_ip(request))
        LOG.error('exception_value = %s, value = %s' % (value, type,), extra=set_client_ip(request))
        LOG.error('tb = %s' % traceback.format_exception(type, value, tb), extra=set_client_ip(request))
    return JsonResponse({'statusCode': StatusCode.BAD_REQUEST.value})
示例#8
0
def init_municipality(request, file='ANPR_archivio_comuni.csv'):
    """
        Popola i comuni
        :param request: request
        :param file: file comuni in formato csv
        :return: JsonResponse con statusCode
        """
    try:
        with open(os.path.join(settings.DATA_FILES_PATH, file),
                  encoding='utf-8') as csv_file:
            reader = csv.DictReader(csv_file,
                                    delimiter=',',
                                    skipinitialspace=True)
            buffer = []
            mun_name = ''
            prov_sigla = ''

            for row in reader:
                try:
                    ac = AddressCity.objects.filter(
                        code=row['SIGLAPROVINCIA']).first()
                    if not ac:
                        ac = AddressCity(name=row['SIGLAPROVINCIA'],
                                         code=row['SIGLAPROVINCIA'])
                        ac.save()

                    if mun_name == row[
                            "DENOMINAZIONE_IT"] and prov_sigla == row[
                                'SIGLAPROVINCIA']:
                        am = buffer.pop()
                        am.dateEnd = row['DATACESSAZIONE'].strip()
                    else:
                        am = AddressMunicipality(
                            name=row["DENOMINAZIONE_IT"],
                            code=row["CODCATASTALE"],
                            dateStart=row['DATAISTITUZIONE'].strip(),
                            dateEnd=row['DATACESSAZIONE'].strip(),
                            city=ac)

                    buffer.append(am)
                    mun_name = row["DENOMINAZIONE_IT"]
                    prov_sigla = row["SIGLAPROVINCIA"]

                except Exception as e:
                    LOG.error("Exception: {}".format(str(e)),
                              extra=set_client_ip(request))
            AddressMunicipality.objects.bulk_create(buffer)
        return JsonResponse({'statusCode': StatusCode.OK.value})
    except Exception as e:
        ype, value, tb = sys.exc_info()
        LOG.error("Exception: {}".format(str(e)), extra=set_client_ip(request))
        LOG.error('exception_value = %s, value = %s' % (
            value,
            type,
        ),
                  extra=set_client_ip(request))
        LOG.error('tb = %s' % traceback.format_exception(type, value, tb),
                  extra=set_client_ip(request))
    return JsonResponse({'statusCode': StatusCode.BAD_REQUEST.value})
示例#9
0
def init_settings_rao(rao_name,
                      issuer_code,
                      rao_email,
                      rao_host,
                      rao_pwd,
                      email_crypto_type,
                      email_port,
                      smtp_mail_from=""):
    """
    Popola la tabella impostazioni del RAO
    :param rao_name: nome visualizzato sul template
    :param issuer_code: codice identificativo IPA
    :param rao_email: nome di chi invia l'email
    :param rao_host: host dell'email
    :param rao_pwd: password dell'email
    :param email_crypto_type: tipo di Crittografia (Nessuna/TLS/SSL)
    :param email_port: porta in uscita
    :param smtp_mail_from:
    :return: True/False
    """

    try:
        password = None
        if rao_pwd:
            password = agency.utils.utils.encrypt_data(rao_pwd,
                                                       settings.SECRET_KEY_ENC)
        entry_rao = SettingsRAO.objects.first()
        if not entry_rao:
            entry_rao = SettingsRAO(name=rao_name,
                                    issuerCode=issuer_code,
                                    username=rao_email,
                                    host=rao_host,
                                    password=password,
                                    port=email_port,
                                    crypto=email_crypto_type,
                                    email=smtp_mail_from)
        else:
            entry_rao.name = rao_name
            entry_rao.issuerCode = issuer_code
            entry_rao.email = smtp_mail_from
            entry_rao.username = rao_email
            entry_rao.host = rao_host
            entry_rao.password = password
            entry_rao.port = email_port
            entry_rao.crypto = email_crypto_type
        entry_rao.save()
        return True
    except Exception as e:
        ype, value, tb = sys.exc_info()
        LOG.error("Exception: {}".format(str(e)), extra=set_client_ip())
        LOG.error('exception_value = %s, value = %s' % (
            value,
            type,
        ),
                  extra=set_client_ip())
        LOG.error('tb = %s' % traceback.format_exception(type, value, tb),
                  extra=set_client_ip())
    return False
示例#10
0
def get_crl_endpoint(certificate_policies):
    """
    Recupera il primo endpoint per il download della CRL
    :param certificate_policies: Policy contente i punti di distribuzione CRL
    :return: String
    """
    for crl_point in certificate_policies:
        crl_endpoint = crl_point.full_name[0].value
        if 'ldap' not in crl_endpoint and isinstance(crl_endpoint, str):
            return crl_endpoint
    LOG.error('Nessun endpoint trovato.', extra=set_client_ip())
    return None
示例#11
0
def configuration_check():
    """
    Verifica se è stata già eseguita la configurazione
    :return: True/False
    """
    try:
        table = Operator.objects.all()
        if not table:
            return False
        table = SettingsRAO.objects.all()
        if not table:
            return False
        return True
    except Exception as e:
        LOG.error("Exception: {}".format(str(e)), extra=set_client_ip())
    return False
示例#12
0
def check_expiration_certificate(cert_string):
    """

    :param cert_string:
    :return:
    """
    try:
        certificate = x509.load_pem_x509_certificate(cert_string.encode(),
                                                     default_backend())
        if certificate.not_valid_after > datetime.datetime.now(
        ) > certificate.not_valid_before:
            return True
    except Exception as e:
        LOG.warning('Errore su check_expiration_certificate: {}'.format(
            str(e)),
                    extra=set_client_ip())
    return False
示例#13
0
def verify_policy_certificate(cert_string):
    """
    Verifica la presenza degli oid nel certificato
    :param cert_string: stringa del certificato, in formato PEM, da esaminare
    :return:
    """
    try:
        cert = x509.load_pem_x509_certificate(cert_string.encode(),
                                              default_backend())
        certificate_policies = cert.extensions.get_extension_for_oid(
            ExtensionOID.CERTIFICATE_POLICIES).value
        for p in certificate_policies:
            if p.policy_identifier.dotted_string in POLICY_OID:
                qualifiers = p.policy_qualifiers
                for qualifier in qualifiers:
                    if isinstance(qualifier, UserNotice):
                        return True
                return False
        return False
    except Exception as e:
        LOG.warning('Errore su check_certificate: {}'.format(str(e)),
                    extra=set_client_ip())
        return False
示例#14
0
 def onCall(request, *args, **kwargs):
     try:
         if check_db_not_altered():
             return function(request, *args, **kwargs)
         else:
             LOG.error("Errore in decorator only_one_admin il db è stato alterato.", extra=set_client_ip(request))
             params = {
                 'rao': get_attributes_RAO(),
             }
             return render(request, settings.TEMPLATE_URL_AGENCY + 'error.html',
                           {"statusCode": StatusCode.EXC.value, 'params': params,
                            "message": "Abbiamo rilevato un problema con l’amministratore del sistema. Contatta l’assistenza tecnica."})
     except Exception as e:
         LOG.error("Errore in decorator only_one_admin: {}".format(str(e)), extra=set_client_ip(request))
         return redirect(settings.LOGIN_URL)
示例#15
0
def verify_certificate_chain(cert_string):
    """
    Verifica la CRL del certificato
    :param cert_string: stringa del certificato, in formato PEM, da esaminare
    :return: StatusCode
    """
    try:
        certificate = crypto.load_certificate(crypto.FILETYPE_PEM,
                                              cert_string.encode())
        cert_x509 = x509.load_pem_x509_certificate(cert_string.encode(),
                                                   default_backend())
    except Exception as e:
        LOG.warning(str(e), extra=set_client_ip())
        return StatusCode.ERROR.value

    try:
        store = crypto.X509Store()
        store.set_flags(crypto.X509StoreFlags.CRL_CHECK)

        for tag in list(CertRef):
            cer = download_http_cert(tag.value)
            if cer:
                try:
                    store.add_cert(cer)
                except:
                    pass

        try:
            aki_bin = cert_x509.extensions.get_extension_for_oid(
                ExtensionOID.AUTHORITY_KEY_IDENTIFIER).value.key_identifier
            aki = format_ki(aki_bin)
            certificate_policies = cert_x509.extensions.get_extension_for_oid(
                ExtensionOID.CRL_DISTRIBUTION_POINTS).value
        except x509.extensions.ExtensionNotFound:
            LOG.warning(cert_string)
            return StatusCode.NOT_FOUND.value

        crl_uri = get_crl_endpoint(certificate_policies)

        if crl_uri is None:
            LOG.warning(
                'Impossibile stabilire endpoint per CRL con aki = {}'.format(
                    aki),
                extra=set_client_ip())
            return StatusCode.NOT_FOUND.value

        crl_latest = make_crl_store_path(crl_uri, aki) + ".crl"

        if not exists_crl(crl_uri, aki):
            download_crl(crl_uri, aki)

        with open(crl_latest) as f:
            crl_content = f.read()

        crl = x509.load_pem_x509_crl(crl_content.encode(), default_backend())
        crl_crypto = crypto.CRL.from_cryptography(crl)

        if crl.next_update < datetime.datetime.now():
            download_crl(crl_uri, aki)
            crl = x509.load_pem_x509_crl(crl_content.encode(),
                                         default_backend())
            crl_crypto = crypto.CRL.from_cryptography(crl)

        store.set_flags(crypto.X509StoreFlags.CRL_CHECK)
        store.add_crl(crl_crypto)
        store_ctx = crypto.X509StoreContext(store, certificate)

        store_ctx.verify_certificate()
        return StatusCode.OK.value
    except Exception as e:
        type, value, tb = sys.exc_info()
        LOG.error(e, extra=set_client_ip())
        LOG.error('exception_value = {0}, value = {1}'.format(
            str(value), str(type)),
                  extra=set_client_ip())
        LOG.error('tb = {}'.format(traceback.format_exception(type, value,
                                                              tb)),
                  extra=set_client_ip())
        return StatusCode.EXC.value
示例#16
0
        def onCall(request, *args, **kwargs):
            try:
                token = str(request.path)
                token = token.split("/")[-2]
                params = signing.loads(token, max_age=3600)

                if (not 'is_authenticated' in request.session) or (not request.session['is_authenticated']):
                    return redirect(settings.LOGIN_URL)

                if (not 'username' in params) or (not params['username']):
                    return HttpResponseRedirect(reverse('agency:logout_agency'))
                if (not 'username' in request.session) or (not request.session['username']):
                    return HttpResponseRedirect(reverse('agency:logout_agency'))

                if not params['username'] == request.session['username']:
                    return HttpResponseRedirect(reverse('agency:logout_agency'))
                return function(request, *args, **kwargs)
            except Exception as e:
                LOG.error("Errore in decorator login_required: {}".format(str(e)), extra=set_client_ip(request))
                return HttpResponseRedirect(reverse('agency:logout_agency'))
示例#17
0
def signed_token(user, op_username, pin):
    """
    Creazione token_sigillato
    :param user: dict contenente i dati dell'utente
    :param op_username: username dell'operatore
    :param pin: pin dell'operatore
    :return: dict con statusCode, token e passphrase
    """
    creation_time = datetime.datetime.utcnow()
    expiration_time = creation_time + datetime.timedelta(days=30)

    rao = SettingsRAO.objects.last()

    request_identity = IdentityRequest.objects.filter(
        fiscalNumberUser=user['fiscalNumber']).order_by(
            'timestamp_identification').last()
    token_to_update = TokenUser.objects.get(
        uuid_token_user=request_identity.token.uuid_token_user)

    userToken = user_token(calendar.timegm(creation_time.utctimetuple()), user,
                           rao, request_identity)

    if token_to_update:
        token_to_update.token_user = userToken['encryptedData']
        token_to_update.save()

    b64_issuer_code = base64.b64encode(rao.issuerCode.encode())

    b64_issuer_internal_reference = base64.b64encode(
        user['id_operator'].encode())

    merge_iss = b64_issuer_code.decode(
        "utf-8") + "." + b64_issuer_internal_reference.decode("utf-8")

    payload = {
        "iss": merge_iss,
        "sub": str(request_identity.uuid_identity),
        "jti": str(request_identity.token.uuid_token_user),
        "iat": calendar.timegm(creation_time.utctimetuple()),
        "exp": calendar.timegm(expiration_time.utctimetuple()),
        "fiscalNumber": user['fiscalNumber'],
        "encryptedData": userToken['encryptedData']
    }

    tokenSigillato = None

    try:
        dict_signature = sign_token_api(op_username, payload, pin)
        if dict_signature:
            if type(dict_signature) == int:
                obj = {"statusCode": dict_signature}
                return obj
            b64_signature = dict_signature.get("sign")
            x5c = dict_signature.get("cert")
            alg = dict_signature.get("alg")

            headers = {'typ': "JWT", 'alg': alg, 'x5c': [x5c]}

            b64_all = base64.urlsafe_b64encode(json.dumps(headers).encode()).decode().rstrip("=") + "." + \
                      base64.urlsafe_b64encode(json.dumps(payload).encode()).decode().rstrip("=")

            tokenSigillato = b64_all + "." + b64_signature

        else:
            obj = {"statusCode": StatusCode.ERROR.value}
            return obj

    except Exception as e:
        LOG.error("Exception: {}".format(str(e)), extra=set_client_ip())
        obj = {"statusCode": StatusCode.EXC.value}
        return obj

    obj = {
        "statusCode": StatusCode.OK.value,
        "token_sigillato": tokenSigillato,
        "passphrase": userToken['passphrase']
    }
    return obj
示例#18
0
 def onCall(request, *args, **kwargs):
     try:
         token = str(request.path)
         token = token.split("/")[-2]
         params = signing.loads(token, max_age=3600)
         if not is_admin(params['username']):
             return function(request, *args, **kwargs)
         else:
             LOG.error("Errore in decorator operator_required non sei utente Operator", extra=set_client_ip(request))
             return HttpResponseRedirect(reverse('agency:list_identity', kwargs={'t', token}))
     except Exception as e:
         LOG.error("Errore in decorator operator_required: {}".format(str(e)), extra=set_client_ip(request))
         return redirect(settings.LOGIN_URL)