def test_02_import_yubikey(self):
        tokens = parseYubicoCSV(YUBIKEY_CSV)
        self.assertTrue(len(tokens) == 7, len(tokens))
        self.assertTrue("UBAM00508326_1" in tokens, tokens)

        tokens, _ = parsePSKCdata(YUBIKEY_PSKC_TOTP)
        self.assertTrue(len(tokens) == 1, len(tokens))
        self.assertTrue("UBAM10944003_2" in tokens, tokens)
        self.assertEqual(tokens["UBAM10944003_2"]["type"], "yubikey")

        tokens, _ = parsePSKCdata(YUBIKEY_PSKC_HOTP)
        self.assertTrue(len(tokens) == 1, len(tokens))
        self.assertTrue("UBOM10944003_1" in tokens, tokens)
        self.assertEqual(tokens["UBOM10944003_1"]["type"], "hotp")
예제 #2
0
def loadtokens_api(filename=None):
    """
    The call imports the given file containing token definitions.
    The file can be an OATH CSV file, an aladdin XML file or a Yubikey CSV file
    exported from the yubikey initialization tool.

    The function is called as a POST request with the file upload.

    :param filename: The name of the token file, that is imported
    :type filename: basestring
    :param type: The file type. Can be "aladdin-xml", "oathcsv" or "yubikeycsv".
    :type type: basestring
    :return: The number of the imported tokens
    :rtype: int
    """
    if not filename:
        filename = getParam(request.all_data, "filename", required)
    known_types = ['aladdin-xml', 'oathcsv', "OATH CSV", 'yubikeycsv',
                   'Yubikey CSV', 'pskc']
    file_type = getParam(request.all_data, "type", required)
    hashlib = getParam(request.all_data, "aladdin_hashlib")

    TOKENS = {}
    token_file = request.files['file']
    file_contents = ""
    # In case of form post requests, it is a "instance" of FieldStorage
    # i.e. the Filename is selected in the browser and the data is
    # transferred
    # in an iframe. see: http://jquery.malsup.com/form/#sample4
    #
    if type(token_file) == FieldStorage:  # pragma: no cover
        log.debug("Field storage file: %s", token_file)
        file_contents = token_file.value
    elif type(token_file) == FileStorage:
        log.debug("Werkzeug File storage file: %s", token_file)
        file_contents = token_file.read()
    else:  # pragma: no cover
        file_contents = token_file

    if file_contents == "":
        log.error("Error loading/importing token file. file %s empty!" %
                  filename)
        raise ParameterError("Error loading token file. File empty!")

    if file_type not in known_types:
        log.error("Unknown file type: >>%s<<. We only know the types: %s" %
                  (file_type, ', '.join(known_types)))
        raise TokenAdminError("Unknown file type: >>%s<<. We only know the "
                              "types: %s" % (file_type,
                                             ', '.join(known_types)))

    # Parse the tokens from file and get dictionary
    if file_type == "aladdin-xml":
        TOKENS = parseSafeNetXML(file_contents)
    elif file_type in ["oathcsv", "OATH CSV"]:
        TOKENS = parseOATHcsv(file_contents)
    elif file_type in ["yubikeycsv", "Yubikey CSV"]:
        TOKENS = parseYubicoCSV(file_contents)
    elif file_type in ["pskc"]:
        # At the moment we only process unencrypted data
        # TODO: We need to also parse encryption!
        TOKENS = parsePSKCdata(file_contents)

    # Now import the Tokens from the dictionary
    ret = ""
    for serial in TOKENS:
        log.debug("importing token %s" % TOKENS[serial])

        # TODO: Migration
        # this needs to return the valid realms of the admin.
        # it also checks the license token number
        # res = self.Policy.checkPolicyPre('admin', 'import', {})
        # we put the token in the FIRST realm of the admin.
        # so tokenrealm will either be ONE realm or NONE
        # log.info("setting tokenrealm %s" % res['realms'])
        tokenrealms = []
        #if res['realms']:
        #    tokenrealm = res.get('realms')[0]

        log.info("initialize token. serial: %s, realm: %s" % (serial,
                                                              tokenrealms))

        init_param = {'serial': serial,
                      'type': TOKENS[serial]['type'],
                      'description': TOKENS[serial].get("description",
                                                        "imported"),
                      'otpkey': TOKENS[serial]['otpkey'],
                      'otplen': TOKENS[serial].get('otplen'),
                      'timeStep': TOKENS[serial].get('timeStep'),
                      'hashlib': TOKENS[serial].get('hashlib')}

        if hashlib and hashlib != "auto":
            init_param['hashlib'] = hashlib

        #if tokenrealm:
        #    self.Policy.checkPolicyPre('admin', 'loadtokens',
        #                   {'tokenrealm': tokenrealm })

        init_token(init_param, tokenrealms=tokenrealms)


    g.audit_object.log({'info': "%s, %s (imported: %i)" % (file_type,
                                                              token_file,
                                                 len(TOKENS)),
                        'serial': ', '.join(TOKENS.keys())})
    # logTokenNum()

    return send_result(len(TOKENS))
예제 #3
0
 def test_02_import_yubikey(self):
     tokens = parseYubicoCSV(YUBIKEYCSV)
     self.assertTrue(len(tokens) == 7, len(tokens))
     self.assertTrue("UBAM00508326_1" in tokens, tokens)
예제 #4
0
def loadtokens_api(filename=None):
    """
    The call imports the given file containing token definitions.
    The file can be an OATH CSV file, an aladdin XML file or a Yubikey CSV file
    exported from the yubikey initialization tool.

    The function is called as a POST request with the file upload.

    :jsonparam filename: The name of the token file, that is imported
    :jsonparam type: The file type. Can be "aladdin-xml",
        "oathcsv" or "yubikeycsv".
    :jsonparam tokenrealms: comma separated list of tokens.
    :jsonparam psk: Pre Shared Key, when importing PSKC
    :return: The number of the imported tokens
    :rtype: int
    """
    if not filename:
        filename = getParam(request.all_data, "filename", required)
    known_types = [
        'aladdin-xml', 'oathcsv', "OATH CSV", 'yubikeycsv', 'Yubikey CSV',
        'pskc'
    ]
    file_type = getParam(request.all_data, "type", required)
    hashlib = getParam(request.all_data, "aladdin_hashlib")
    aes_psk = getParam(request.all_data, "psk")
    aes_password = getParam(request.all_data, "password")
    if aes_psk and len(aes_psk) != 32:
        raise TokenAdminError("The Pre Shared Key must be 128 Bit hex "
                              "encoded. It must be 32 characters long!")
    trealms = getParam(request.all_data, "tokenrealms") or ""
    tokenrealms = []
    if trealms:
        tokenrealms = trealms.split(",")

    TOKENS = {}
    token_file = request.files['file']
    file_contents = ""
    # In case of form post requests, it is a "instance" of FieldStorage
    # i.e. the Filename is selected in the browser and the data is
    # transferred
    # in an iframe. see: http://jquery.malsup.com/form/#sample4
    #
    if type(token_file) == FieldStorage:  # pragma: no cover
        log.debug("Field storage file: %s", token_file)
        file_contents = token_file.value
    elif type(token_file) == FileStorage:
        log.debug("Werkzeug File storage file: %s", token_file)
        file_contents = token_file.read()
    else:  # pragma: no cover
        file_contents = token_file

    if file_contents == "":
        log.error(
            "Error loading/importing token file. file {0!s} empty!".format(
                filename))
        raise ParameterError("Error loading token file. File empty!")

    if file_type not in known_types:
        log.error(
            "Unknown file type: >>{0!s}<<. We only know the types: {1!s}".
            format(file_type, ', '.join(known_types)))
        raise TokenAdminError("Unknown file type: >>%s<<. We only know the "
                              "types: %s" %
                              (file_type, ', '.join(known_types)))

    # Decrypt file, if necessary
    if file_contents.startswith("-----BEGIN PGP MESSAGE-----"):
        GPG = GPGImport(current_app.config)
        file_contents = GPG.decrypt(file_contents)

    # Parse the tokens from file and get dictionary
    if file_type == "aladdin-xml":
        TOKENS = parseSafeNetXML(file_contents)
    elif file_type in ["oathcsv", "OATH CSV"]:
        TOKENS = parseOATHcsv(file_contents)
    elif file_type in ["yubikeycsv", "Yubikey CSV"]:
        TOKENS = parseYubicoCSV(file_contents)
    elif file_type in ["pskc"]:
        TOKENS = parsePSKCdata(file_contents,
                               preshared_key_hex=aes_psk,
                               password=aes_password)

    # Now import the Tokens from the dictionary
    ret = ""
    for serial in TOKENS:
        log.debug("importing token {0!s}".format(TOKENS[serial]))

        log.info("initialize token. serial: {0!s}, realm: {1!s}".format(
            serial, tokenrealms))

        init_param = {
            'serial': serial,
            'type': TOKENS[serial]['type'],
            'description': TOKENS[serial].get("description", "imported"),
            'otpkey': TOKENS[serial]['otpkey'],
            'otplen': TOKENS[serial].get('otplen'),
            'timeStep': TOKENS[serial].get('timeStep'),
            'hashlib': TOKENS[serial].get('hashlib')
        }

        if hashlib and hashlib != "auto":
            init_param['hashlib'] = hashlib

        #if tokenrealm:
        #    self.Policy.checkPolicyPre('admin', 'loadtokens',
        #                   {'tokenrealm': tokenrealm })

        init_token(init_param, tokenrealms=tokenrealms)

    g.audit_object.log({
        'info':
        "{0!s}, {1!s} (imported: {2:d})".format(file_type, token_file,
                                                len(TOKENS)),
        'serial':
        ', '.join(TOKENS.keys())
    })
    # logTokenNum()

    return send_result(len(TOKENS))
 def test_02_import_yubikey(self):
     tokens = parseYubicoCSV(YUBIKEYCSV)
     self.assertTrue(len(tokens) == 7, len(tokens))
     self.assertTrue("UBAM00508326_1" in tokens, tokens)
예제 #6
0
def loadtokens_api(filename=None):
    """
    The call imports the given file containing token definitions.
    The file can be an OATH CSV file, an aladdin XML file or a Yubikey CSV file
    exported from the yubikey initialization tool.

    The function is called as a POST request with the file upload.

    :jsonparam basestring filename: The name of the token file, that is imported
    :jsonparam basestring type: The file type. Can be "aladdin-xml",
        "oathcsv" or "yubikeycsv".
    :jsonparam basestring tokenrealms: comma separated list of tokens.
    :return: The number of the imported tokens
    :rtype: int
    """
    if not filename:
        filename = getParam(request.all_data, "filename", required)
    known_types = [
        'aladdin-xml', 'oathcsv', "OATH CSV", 'yubikeycsv', 'Yubikey CSV',
        'pskc'
    ]
    file_type = getParam(request.all_data, "type", required)
    hashlib = getParam(request.all_data, "aladdin_hashlib")
    trealms = getParam(request.all_data, "tokenrealms") or ""
    tokenrealms = []
    if trealms:
        tokenrealms = trealms.split(",")

    TOKENS = {}
    token_file = request.files['file']
    file_contents = ""
    # In case of form post requests, it is a "instance" of FieldStorage
    # i.e. the Filename is selected in the browser and the data is
    # transferred
    # in an iframe. see: http://jquery.malsup.com/form/#sample4
    #
    if type(token_file) == FieldStorage:  # pragma: no cover
        log.debug("Field storage file: %s", token_file)
        file_contents = token_file.value
    elif type(token_file) == FileStorage:
        log.debug("Werkzeug File storage file: %s", token_file)
        file_contents = token_file.read()
    else:  # pragma: no cover
        file_contents = token_file

    if file_contents == "":
        log.error("Error loading/importing token file. file %s empty!" %
                  filename)
        raise ParameterError("Error loading token file. File empty!")

    if file_type not in known_types:
        log.error("Unknown file type: >>%s<<. We only know the types: %s" %
                  (file_type, ', '.join(known_types)))
        raise TokenAdminError("Unknown file type: >>%s<<. We only know the "
                              "types: %s" %
                              (file_type, ', '.join(known_types)))

    # Parse the tokens from file and get dictionary
    if file_type == "aladdin-xml":
        TOKENS = parseSafeNetXML(file_contents)
    elif file_type in ["oathcsv", "OATH CSV"]:
        TOKENS = parseOATHcsv(file_contents)
    elif file_type in ["yubikeycsv", "Yubikey CSV"]:
        TOKENS = parseYubicoCSV(file_contents)
    elif file_type in ["pskc"]:
        # At the moment we only process unencrypted data
        # TODO: We need to also parse encryption!
        TOKENS = parsePSKCdata(file_contents)

    # Now import the Tokens from the dictionary
    ret = ""
    for serial in TOKENS:
        log.debug("importing token %s" % TOKENS[serial])

        log.info("initialize token. serial: %s, realm: %s" %
                 (serial, tokenrealms))

        init_param = {
            'serial': serial,
            'type': TOKENS[serial]['type'],
            'description': TOKENS[serial].get("description", "imported"),
            'otpkey': TOKENS[serial]['otpkey'],
            'otplen': TOKENS[serial].get('otplen'),
            'timeStep': TOKENS[serial].get('timeStep'),
            'hashlib': TOKENS[serial].get('hashlib')
        }

        if hashlib and hashlib != "auto":
            init_param['hashlib'] = hashlib

        #if tokenrealm:
        #    self.Policy.checkPolicyPre('admin', 'loadtokens',
        #                   {'tokenrealm': tokenrealm })

        init_token(init_param, tokenrealms=tokenrealms)

    g.audit_object.log({
        'info':
        "%s, %s (imported: %i)" % (file_type, token_file, len(TOKENS)),
        'serial':
        ', '.join(TOKENS.keys())
    })
    # logTokenNum()

    return send_result(len(TOKENS))
예제 #7
0
def loadtokens_api(filename=None):
    """
    The call imports the given file containing token definitions.
    The file can be an OATH CSV file, an aladdin XML file or a Yubikey CSV file
    exported from the yubikey initialization tool.

    The function is called as a POST request with the file upload.

    :jsonparam filename: The name of the token file, that is imported
    :jsonparam type: The file type. Can be "aladdin-xml",
        "oathcsv" or "yubikeycsv".
    :jsonparam tokenrealms: comma separated list of tokens.
    :jsonparam psk: Pre Shared Key, when importing PSKC
    :return: The number of the imported tokens
    :rtype: int
    """
    if not filename:
        filename = getParam(request.all_data, "filename", required)
    known_types = ['aladdin-xml', 'oathcsv', "OATH CSV", 'yubikeycsv',
                   'Yubikey CSV', 'pskc']
    file_type = getParam(request.all_data, "type", required)
    hashlib = getParam(request.all_data, "aladdin_hashlib")
    aes_psk = getParam(request.all_data, "psk")
    aes_password = getParam(request.all_data, "password")
    if aes_psk and len(aes_psk) != 32:
        raise TokenAdminError("The Pre Shared Key must be 128 Bit hex "
                              "encoded. It must be 32 characters long!")
    trealms = getParam(request.all_data, "tokenrealms") or ""
    tokenrealms = []
    if trealms:
        tokenrealms = trealms.split(",")

    TOKENS = {}
    token_file = request.files['file']
    file_contents = ""
    # In case of form post requests, it is a "instance" of FieldStorage
    # i.e. the Filename is selected in the browser and the data is
    # transferred
    # in an iframe. see: http://jquery.malsup.com/form/#sample4
    #
    if type(token_file) == FieldStorage:  # pragma: no cover
        log.debug("Field storage file: %s", token_file)
        file_contents = token_file.value
    elif type(token_file) == FileStorage:
        log.debug("Werkzeug File storage file: %s", token_file)
        file_contents = token_file.read()
    else:  # pragma: no cover
        file_contents = token_file

    if file_contents == "":
        log.error("Error loading/importing token file. file {0!s} empty!".format(
                  filename))
        raise ParameterError("Error loading token file. File empty!")

    if file_type not in known_types:
        log.error("Unknown file type: >>{0!s}<<. We only know the types: {1!s}".format(file_type, ', '.join(known_types)))
        raise TokenAdminError("Unknown file type: >>%s<<. We only know the "
                              "types: %s" % (file_type,
                                             ', '.join(known_types)))

    # Parse the tokens from file and get dictionary
    if file_type == "aladdin-xml":
        TOKENS = parseSafeNetXML(file_contents)
    elif file_type in ["oathcsv", "OATH CSV"]:
        TOKENS = parseOATHcsv(file_contents)
    elif file_type in ["yubikeycsv", "Yubikey CSV"]:
        TOKENS = parseYubicoCSV(file_contents)
    elif file_type in ["pskc"]:
        TOKENS = parsePSKCdata(file_contents, preshared_key_hex=aes_psk,
                               password=aes_password)

    # Now import the Tokens from the dictionary
    ret = ""
    for serial in TOKENS:
        log.debug("importing token {0!s}".format(TOKENS[serial]))

        log.info("initialize token. serial: {0!s}, realm: {1!s}".format(serial,
                                                              tokenrealms))

        init_param = {'serial': serial,
                      'type': TOKENS[serial]['type'],
                      'description': TOKENS[serial].get("description",
                                                        "imported"),
                      'otpkey': TOKENS[serial]['otpkey'],
                      'otplen': TOKENS[serial].get('otplen'),
                      'timeStep': TOKENS[serial].get('timeStep'),
                      'hashlib': TOKENS[serial].get('hashlib')}

        if hashlib and hashlib != "auto":
            init_param['hashlib'] = hashlib

        #if tokenrealm:
        #    self.Policy.checkPolicyPre('admin', 'loadtokens',
        #                   {'tokenrealm': tokenrealm })

        init_token(init_param, tokenrealms=tokenrealms)

    g.audit_object.log({'info': "{0!s}, {1!s} (imported: {2:d})".format(file_type,
                                                           token_file,
                                                           len(TOKENS)),
                        'serial': ', '.join(TOKENS.keys())})
    # logTokenNum()

    return send_result(len(TOKENS))
예제 #8
0
파일: token.py 프로젝트: R00tAK/privacyidea
def loadtokens_api(filename=None):
    """
    The call imports the given file containing token definitions.
    The file can be an OATH CSV file, an aladdin XML file or a Yubikey CSV file
    exported from the yubikey initialization tool.

    The function is called as a POST request with the file upload.

    :jsonparam basestring filename: The name of the token file, that is imported
    :jsonparam basestring type: The file type. Can be "aladdin-xml",
        "oathcsv" or "yubikeycsv".
    :jsonparam basestring tokenrealms: comma separated list of tokens.
    :return: The number of the imported tokens
    :rtype: int
    """
    if not filename:
        filename = getParam(request.all_data, "filename", required)
    known_types = ["aladdin-xml", "oathcsv", "OATH CSV", "yubikeycsv", "Yubikey CSV", "pskc"]
    file_type = getParam(request.all_data, "type", required)
    hashlib = getParam(request.all_data, "aladdin_hashlib")
    trealms = getParam(request.all_data, "tokenrealms") or ""
    tokenrealms = []
    if trealms:
        tokenrealms = trealms.split(",")

    TOKENS = {}
    token_file = request.files["file"]
    file_contents = ""
    # In case of form post requests, it is a "instance" of FieldStorage
    # i.e. the Filename is selected in the browser and the data is
    # transferred
    # in an iframe. see: http://jquery.malsup.com/form/#sample4
    #
    if type(token_file) == FieldStorage:  # pragma: no cover
        log.debug("Field storage file: %s", token_file)
        file_contents = token_file.value
    elif type(token_file) == FileStorage:
        log.debug("Werkzeug File storage file: %s", token_file)
        file_contents = token_file.read()
    else:  # pragma: no cover
        file_contents = token_file

    if file_contents == "":
        log.error("Error loading/importing token file. file %s empty!" % filename)
        raise ParameterError("Error loading token file. File empty!")

    if file_type not in known_types:
        log.error("Unknown file type: >>%s<<. We only know the types: %s" % (file_type, ", ".join(known_types)))
        raise TokenAdminError(
            "Unknown file type: >>%s<<. We only know the " "types: %s" % (file_type, ", ".join(known_types))
        )

    # Parse the tokens from file and get dictionary
    if file_type == "aladdin-xml":
        TOKENS = parseSafeNetXML(file_contents)
    elif file_type in ["oathcsv", "OATH CSV"]:
        TOKENS = parseOATHcsv(file_contents)
    elif file_type in ["yubikeycsv", "Yubikey CSV"]:
        TOKENS = parseYubicoCSV(file_contents)
    elif file_type in ["pskc"]:
        # At the moment we only process unencrypted data
        # TODO: We need to also parse encryption!
        TOKENS = parsePSKCdata(file_contents)

    # Now import the Tokens from the dictionary
    ret = ""
    for serial in TOKENS:
        log.debug("importing token %s" % TOKENS[serial])

        log.info("initialize token. serial: %s, realm: %s" % (serial, tokenrealms))

        init_param = {
            "serial": serial,
            "type": TOKENS[serial]["type"],
            "description": TOKENS[serial].get("description", "imported"),
            "otpkey": TOKENS[serial]["otpkey"],
            "otplen": TOKENS[serial].get("otplen"),
            "timeStep": TOKENS[serial].get("timeStep"),
            "hashlib": TOKENS[serial].get("hashlib"),
        }

        if hashlib and hashlib != "auto":
            init_param["hashlib"] = hashlib

        # if tokenrealm:
        #    self.Policy.checkPolicyPre('admin', 'loadtokens',
        #                   {'tokenrealm': tokenrealm })

        init_token(init_param, tokenrealms=tokenrealms)

    g.audit_object.log(
        {"info": "%s, %s (imported: %i)" % (file_type, token_file, len(TOKENS)), "serial": ", ".join(TOKENS.keys())}
    )
    # logTokenNum()

    return send_result(len(TOKENS))