Пример #1
0
def initialize_db():
    os.umask(0)
    if not os.path.exists(VFENSE_TMP_PATH):
        os.mkdir(VFENSE_TMP_PATH, 0755)
    if not os.path.exists(RETHINK_CONF):
        subprocess.Popen(['ln', '-s', RETHINK_SOURCE_CONF, RETHINK_CONF], )
    if not os.path.exists('/var/lib/rethinkdb/vFense'):
        os.makedirs('/var/lib/rethinkdb/vFense')
        subprocess.Popen([
            'chown', '-R', 'rethinkdb.rethinkdb', '/var/lib/rethinkdb/vFense'
        ], )

    if not os.path.exists(VFENSE_LOG_PATH):
        os.mkdir(VFENSE_LOG_PATH, 0755)
    if not os.path.exists(VFENSE_SCHEDULER_PATH):
        os.mkdir(VFENSE_SCHEDULER_PATH, 0755)
    if not os.path.exists(VFENSE_APP_PATH):
        os.mkdir(VFENSE_APP_PATH, 0755)
    if not os.path.exists(VFENSE_APP_TMP_PATH):
        os.mkdir(VFENSE_APP_TMP_PATH, 0775)
    if not os.path.exists(os.path.join(VFENSE_VULN_PATH, 'windows/data/xls')):
        os.makedirs(os.path.join(VFENSE_VULN_PATH, 'windows/data/xls'), 0755)
    if not os.path.exists(os.path.join(VFENSE_VULN_PATH, 'cve/data/xml')):
        os.makedirs(os.path.join(VFENSE_VULN_PATH, 'cve/data/xml'), 0755)
    if not os.path.exists(os.path.join(VFENSE_VULN_PATH, 'ubuntu/data/html')):
        os.makedirs(os.path.join(VFENSE_VULN_PATH, 'ubuntu/data/html'), 0755)
    if get_distro() in DEBIAN_DISTROS:
        subprocess.Popen(['update-rc.d', 'vFense', 'defaults'], )

        if not os.path.exists('/etc/init.d/vFense'):
            subprocess.Popen([
                'ln', '-s',
                os.path.join(VFENSE_BASE_SRC_PATH, 'daemon/vFense'),
                VFENSE_INIT_D
            ], )

    if get_distro() in REDHAT_DISTROS:
        if os.path.exists('/usr/bin/rqworker'):
            subprocess.Popen(
                ['ln', '-s', '/usr/bin/rqworker', '/usr/local/bin/rqworker'], )

    if os.path.exists(get_sheduler_location()):
        subprocess.Popen([
            'patch', '-N',
            get_sheduler_location(),
            os.path.join(VFENSE_CONF_PATH, 'patches/scheduler.patch')
        ], )
    try:
        tp_exists = pwd.getpwnam('vfense')

    except Exception as e:
        if get_distro() in DEBIAN_DISTROS:
            subprocess.Popen([
                'adduser',
                '--disabled-password',
                '--gecos',
                '',
                'vfense',
            ], )
        elif get_distro() in REDHAT_DISTROS:
            subprocess.Popen([
                'useradd',
                'vfense',
            ], )

    rethink_start = subprocess.Popen(['service', 'rethinkdb', 'start'])
    while not db_connect():
        print 'Sleeping until rethink starts'
        sleep(2)
    completed = True
    if completed:
        conn = db_connect()
        r.db_create('vFense').run(conn)
        db = r.db('vFense')
        conn.close()
        ci.initialize_indexes_and_create_tables()
        conn = db_connect()

        default_customer = Customer(DefaultCustomers.DEFAULT,
                                    server_queue_ttl=args.queue_ttl,
                                    package_download_url=url)

        customers.create_customer(default_customer, init=True)

        group_data = group.create_group(DefaultGroups.ADMIN,
                                        DefaultCustomers.DEFAULT,
                                        [Permissions.ADMINISTRATOR])
        admin_group_id = group_data['generated_ids']
        user.create_user(
            DefaultUsers.ADMIN,
            'vFense Admin Account',
            args.admin_password,
            admin_group_id,
            DefaultCustomers.DEFAULT,
            '',
        )
        print 'Admin username = admin'
        print 'Admin password = %s' % (args.admin_password)
        agent_pass = generate_pass()
        while not check_password(agent_pass)[0]:
            agent_pass = generate_pass()

        user.create_user(
            DefaultUsers.AGENT,
            'vFense Agent Communication Account',
            agent_pass,
            admin_group_id,
            DefaultCustomers.DEFAULT,
            '',
        )
        print 'Agent api user = agent_api'
        print 'Agent password = %s' % (agent_pass)

        monit.monit_initialization()

        if args.cve_data:
            print "Updating CVE's..."
            load_up_all_xml_into_db()
            print "Done Updating CVE's..."
            print "Updating Microsoft Security Bulletin Ids..."
            parse_bulletin_and_updatedb()
            print "Done Updating Microsoft Security Bulletin Ids..."
            print "Updating Ubuntu Security Bulletin Ids...( This can take a couple of minutes )"
            begin_usn_home_page_processing(full_parse=True)
            print "Done Updating Ubuntu Security Bulletin Ids..."

        conn.close()
        completed = True

        msg = 'Rethink Initialization and Table creation is now complete'
        #rethink_stop = subprocess.Popen(['service', 'rethinkdb','stop'])
        rql_msg = 'Rethink stopped successfully\n'

        return completed, msg
    else:
        completed = False
        msg = 'Failed during Rethink startup process'
        return completed, msg
Пример #2
0
    help='ssl certificate to use, default is to use server.key')
parser.add_argument('--cve-data',
                    dest='cve_data',
                    action='store_true',
                    help='Initialize CVE data. This is the default.')
parser.add_argument(
    '--no-cve-data',
    dest='cve_data',
    action='store_false',
    help='Not to initialize CVE data. This is for testing purposes.')
parser.set_defaults(cve_data=True)

args = parser.parse_args()

if args.admin_password:
    password_validated = check_password(args.admin_password)
    if not password_validated[0]:
        print(
            'Password failed to meet the minimum requirements.\n' +
            'Uppercase, Lowercase, Numeric, Special ' +
            'and a minimum of 8 characters.\nYour password: %s is %s' %
            (args.admin_password, password_validated[1]))
        sys.exit(1)

if args.queue_ttl:
    args.queue_ttl = int(args.queue_ttl)
    if args.queue_ttl < 2:
        args.queue_ttl = 10

if args.dns_name:
    url = 'https://%s/packages/' % (args.dns_name)
Пример #3
0
def initialize_db():
    os.umask(0)
    if not os.path.exists(VFENSE_TMP_PATH):
        os.mkdir(VFENSE_TMP_PATH, 0755)
    if not os.path.exists(RETHINK_CONF):
        subprocess.Popen(["ln", "-s", RETHINK_SOURCE_CONF, RETHINK_CONF])
    if not os.path.exists("/var/lib/rethinkdb/vFense"):
        os.makedirs("/var/lib/rethinkdb/vFense")
        subprocess.Popen(["chown", "-R", "rethinkdb.rethinkdb", "/var/lib/rethinkdb/vFense"])

    if not os.path.exists(VFENSE_LOG_PATH):
        os.mkdir(VFENSE_LOG_PATH, 0755)
    if not os.path.exists(VFENSE_SCHEDULER_PATH):
        os.mkdir(VFENSE_SCHEDULER_PATH, 0755)
    if not os.path.exists(VFENSE_APP_PATH):
        os.mkdir(VFENSE_APP_PATH, 0755)
    if not os.path.exists(VFENSE_APP_TMP_PATH):
        os.mkdir(VFENSE_APP_TMP_PATH, 0775)
    if not os.path.exists(os.path.join(VFENSE_VULN_PATH, "windows/data/xls")):
        os.makedirs(os.path.join(VFENSE_VULN_PATH, "windows/data/xls"), 0755)
    if not os.path.exists(os.path.join(VFENSE_VULN_PATH, "cve/data/xml")):
        os.makedirs(os.path.join(VFENSE_VULN_PATH, "cve/data/xml"), 0755)
    if not os.path.exists(os.path.join(VFENSE_VULN_PATH, "ubuntu/data/html")):
        os.makedirs(os.path.join(VFENSE_VULN_PATH, "ubuntu/data/html"), 0755)
    if get_distro() in DEBIAN_DISTROS:
        subprocess.Popen(["update-rc.d", "vFense", "defaults"])

        if not os.path.exists("/etc/init.d/vFense"):
            subprocess.Popen(["ln", "-s", os.path.join(VFENSE_BASE_SRC_PATH, "daemon/vFense"), VFENSE_INIT_D])

    if get_distro() in REDHAT_DISTROS:
        if os.path.exists("/usr/bin/rqworker"):
            subprocess.Popen(["ln", "-s", "/usr/bin/rqworker", "/usr/local/bin/rqworker"])

    if os.path.exists(get_sheduler_location()):
        subprocess.Popen(
            ["patch", "-N", get_sheduler_location(), os.path.join(VFENSE_CONF_PATH, "patches/scheduler.patch")]
        )
    try:
        tp_exists = pwd.getpwnam("vfense")

    except Exception as e:
        if get_distro() in DEBIAN_DISTROS:
            subprocess.Popen(["adduser", "--disabled-password", "--gecos", "", "vfense"])
        elif get_distro() in REDHAT_DISTROS:
            subprocess.Popen(["useradd", "vfense"])

    rethink_start = subprocess.Popen(["service", "rethinkdb", "start"])
    while not db_connect():
        print "Sleeping until rethink starts"
        sleep(2)
    completed = True
    if completed:
        conn = db_connect()
        r.db_create("vFense").run(conn)
        db = r.db("vFense")
        conn.close()
        ci.initialize_indexes_and_create_tables()
        conn = db_connect()

        default_customer = Customer(DefaultCustomers.DEFAULT, server_queue_ttl=args.queue_ttl, package_download_url=url)

        customers.create_customer(default_customer, init=True)

        group_data = group.create_group(DefaultGroups.ADMIN, DefaultCustomers.DEFAULT, [Permissions.ADMINISTRATOR])
        admin_group_id = group_data["generated_ids"]
        user.create_user(
            DefaultUsers.ADMIN,
            "vFense Admin Account",
            args.admin_password,
            admin_group_id,
            DefaultCustomers.DEFAULT,
            "",
        )
        print "Admin username = admin"
        print "Admin password = %s" % (args.admin_password)
        agent_pass = generate_pass()
        while not check_password(agent_pass)[0]:
            agent_pass = generate_pass()

        user.create_user(
            DefaultUsers.AGENT,
            "vFense Agent Communication Account",
            agent_pass,
            admin_group_id,
            DefaultCustomers.DEFAULT,
            "",
        )
        print "Agent api user = agent_api"
        print "Agent password = %s" % (agent_pass)

        monit.monit_initialization()

        if args.cve_data:
            print "Updating CVE's..."
            load_up_all_xml_into_db()
            print "Done Updating CVE's..."
            print "Updating Microsoft Security Bulletin Ids..."
            parse_bulletin_and_updatedb()
            print "Done Updating Microsoft Security Bulletin Ids..."
            print "Updating Ubuntu Security Bulletin Ids...( This can take a couple of minutes )"
            begin_usn_home_page_processing(full_parse=True)
            print "Done Updating Ubuntu Security Bulletin Ids..."

        conn.close()
        completed = True

        msg = "Rethink Initialization and Table creation is now complete"
        # rethink_stop = subprocess.Popen(['service', 'rethinkdb','stop'])
        rql_msg = "Rethink stopped successfully\n"

        return completed, msg
    else:
        completed = False
        msg = "Failed during Rethink startup process"
        return completed, msg
Пример #4
0
)
parser.add_argument(
    "--cve-data", dest="cve_data", action="store_true", help="Initialize CVE data. This is the default."
)
parser.add_argument(
    "--no-cve-data",
    dest="cve_data",
    action="store_false",
    help="Not to initialize CVE data. This is for testing purposes.",
)
parser.set_defaults(cve_data=True)

args = parser.parse_args()

if args.admin_password:
    password_validated = check_password(args.admin_password)
    if not password_validated[0]:
        print (
            "Password failed to meet the minimum requirements.\n"
            + "Uppercase, Lowercase, Numeric, Special "
            + "and a minimum of 8 characters.\nYour password: %s is %s" % (args.admin_password, password_validated[1])
        )
        sys.exit(1)

if args.queue_ttl:
    args.queue_ttl = int(args.queue_ttl)
    if args.queue_ttl < 2:
        args.queue_ttl = 10

if args.dns_name:
    url = "https://%s/packages/" % (args.dns_name)
Пример #5
0
def create_user(
    username, fullname, password, group_ids,
    customer_name, email, enabled=CommonKeys.YES, user_name=None,
    uri=None, method=None
    ):
    """Add a new user into vFense
    Args:
        username (str): The name of the user you are creating.
        fullname (str): The full name of the user you are creating.
        password (str): The unencrypted password of the user.
        group_ids (list): List of vFense group ids to add the user too.
        customer_name (str): The customer, this user will be part of.
        email (str): Email address of the user.
        enabled (str): yes or no
            Default=no

    Kwargs:
        user_name (str): The name of the user who called this function.
        uri (str): The uri that was used to call this function.
        method (str): The HTTP methos that was used to call this function.

    Basic Usage:
        >>> from vFense.user.users import create_user
        >>> username = '******'
        >>> fullname = 'testing 4 life'
        >>> password = '******'
        >>> group_ids = ['8757b79c-7321-4446-8882-65457f28c78b']
        >>> customer_name = 'default'
        >>> email = '*****@*****.**'
        >>> enabled = 'yes'
        >>> create_user(
                username, fullname, password,
                group_ids, customer_name, email, enabled
            )

    Return:
        Dictionary of the status of the operation.
        {
            'uri': None,
            'rv_status_code': 1010,
            'http_method': None,
            'http_status': 200,
            'message': 'None - create user testing123 was created',
            'data': {
                'current_customer': 'default',
                'full_name': 'tester4life',
                'default_customer': 'default',
                'password': '******',
                'user_name': 'testing123',
                'enabled': 'yes',
                'email': '*****@*****.**'
            }
        }
    """

    user_exist = get_user(username)
    pass_strength = check_password(password)
    status = create_user.func_name + ' - '
    generated_ids = []
    generic_status_code = 0
    vfense_status_code = 0
    user_data = (
        {
            UserKeys.CurrentCustomer: customer_name,
            UserKeys.DefaultCustomer: customer_name,
            UserKeys.FullName: fullname,
            UserKeys.UserName: username,
            UserKeys.Enabled: enabled,
            UserKeys.Email: email
        }
    )
    if enabled != CommonKeys.YES or enabled != CommonKeys.NO:
        enabled = CommonKeys.NO


    valid_user_name = (
        re.search('([A-Za-z0-9_-]{1,24})', username)
    )
    valid_user_length = (
        len(username) <= DefaultStringLength.USER_NAME
    )

    try:
        if (not user_exist and pass_strength[0] and
                valid_user_length and valid_user_name):
            encrypted_password = Crypto().hash_bcrypt(password)
            user_data[UserKeys.Password] = encrypted_password
            customer_is_valid = get_customer(customer_name)
            validated_groups, _, invalid_groups = validate_group_ids(
                group_ids, customer_name
            )

            if customer_is_valid and validated_groups:
                object_status, _, _, generated_ids = (
                    insert_user(user_data)
                )
                generated_ids.append(username)

                add_user_to_customers(
                    username, [customer_name],
                    user_name, uri, method
                )

                add_user_to_groups(
                    username, customer_name, group_ids,
                    user_name, uri, method
                )
                if object_status == DbCodes.Inserted:
                    msg = 'user name %s created' % (username)
                    generic_status_code = GenericCodes.ObjectCreated
                    vfense_status_code = UserCodes.UserCreated
                    user_data.pop(UserKeys.Password)

            elif not customer_is_valid and validated_groups:
                msg = 'customer name %s does not exist' % (customer_name)
                object_status = DbCodes.Skipped
                generic_status_code = GenericCodes.InvalidId
                vfense_status_code = CustomerFailureCodes.CustomerDoesNotExist

            elif not validated_groups and customer_is_valid:
                msg = 'group ids %s does not exist' % (invalid_groups)
                object_status = DbCodes.Skipped
                generic_status_code = GenericCodes.InvalidId
                vfense_status_code = GroupFailureCodes.InvalidGroupId

            else:
                group_error = (
                    'group ids %s does not exist' % (invalid_groups)
                )
                customer_error = (
                    'customer name %s does not exist' % (customer_name)
                )
                msg = group_error + ' and ' + customer_error
                object_status = DbCodes.Errors
                generic_status_code = GenericFailureCodes.FailedToCreateObject
                vfense_status_code = UserFailureCodes.FailedToCreateUser

        elif user_exist:
            msg = 'username %s already exists' % (username)
            object_status = GenericCodes.ObjectExists
            generic_status_code = GenericCodes.ObjectExists
            vfense_status_code = UserFailureCodes.UserNameExists

        elif not pass_strength[0]:
            msg = (
                    'password does not meet the min requirements: strength=%s'
                    % (pass_strength[1])
            )
            object_status = GenericFailureCodes.FailedToCreateObject
            generic_status_code = GenericFailureCodes.FailedToCreateObject
            vfense_status_code = UserFailureCodes.WeakPassword

        elif not valid_user_name or not valid_user_length:
            status_code = DbCodes.Errors
            msg = (
                'user name is not within the 24 character range '+
                'or contains unsupported characters :%s' %
                (username)
            )
            generic_status_code = GenericCodes.InvalidId
            vfense_status_code = UserFailureCodes.InvalidUserName

        results = {
            ApiResultKeys.DB_STATUS_CODE: object_status,
            ApiResultKeys.GENERIC_STATUS_CODE: generic_status_code,
            ApiResultKeys.VFENSE_STATUS_CODE: vfense_status_code,
            ApiResultKeys.MESSAGE: status + msg,
            ApiResultKeys.GENERATED_IDS: generated_ids,
            ApiResultKeys.DATA: [user_data],
            ApiResultKeys.USERNAME: user_name,
            ApiResultKeys.URI: uri,
            ApiResultKeys.HTTP_METHOD: method
        }

    except Exception as e:
        logger.exception(e)
        msg = 'Failed to create user %s: %s' % (username, str(e))
        status_code = DbCodes.Errors
        generic_status_code = GenericFailureCodes.FailedToCreateObject
        vfense_status_code = UserFailureCodes.FailedToCreateUser

        results = {
            ApiResultKeys.DB_STATUS_CODE: status_code,
            ApiResultKeys.GENERIC_STATUS_CODE: generic_status_code,
            ApiResultKeys.VFENSE_STATUS_CODE: vfense_status_code,
            ApiResultKeys.MESSAGE: status + msg,
            ApiResultKeys.GENERATED_IDS: [],
            ApiResultKeys.DATA: [user_data],
            ApiResultKeys.USERNAME: user_name,
            ApiResultKeys.URI: uri,
            ApiResultKeys.HTTP_METHOD: method
        }

    return(results)
Пример #6
0
def change_password(
    username, password, new_password,
    user_name=None, uri=None, method=None
    ):
    """Change password for a user.
    Args:
        username (str): The name of the user you are deleteing.
        password (str): Original password.
        new_password (str): New password.

    Kwargs:
        user_name (str): The name of the user who called this function.
        uri (str): The uri that was used to call this function.
        method (str): The HTTP methos that was used to call this function.

    Return:
        Dictionary of the status of the operation.
        {
            'uri': None,
            'rv_status_code': 1008,
            'http_method': None,
            'http_status': 200,
            'message': 'None - change_password - Password changed for user admin - admin was updated',
            'data': []
        }
    """
    user_exist = get_user(username, without_fields=None)
    status = change_password.func_name + ' - '
    try:
        generic_status_code = 0
        vfense_status_code = 0
        if user_exist:
            pass_strength = check_password(new_password)
            original_encrypted_password = user_exist[UserKeys.Password].encode('utf-8')
            original_password_verified = (
                Crypto().verify_bcrypt_hash(password, original_encrypted_password)
            )
            encrypted_new_password = Crypto().hash_bcrypt(new_password)
            new_password_verified_against_orignal_password = (
                Crypto().verify_bcrypt_hash(new_password, original_encrypted_password)
            )
            if (original_password_verified and pass_strength[0] and
                    not new_password_verified_against_orignal_password):

                user_data = {UserKeys.Password: encrypted_new_password}

                object_status, _, _, _ = (
                    update_user(username, user_data)
                )

                if object_status == DbCodes.Replaced:
                    msg = 'Password changed for user %s - ' % (username)
                    generic_status_code = GenericCodes.ObjectUpdated
                    vfense_status_code = UserCodes.PasswordChanged

            elif new_password_verified_against_orignal_password:
                msg = 'New password is the same as the original - user %s - ' % (username)
                object_status = DbCodes.Unchanged
                generic_status_code = GenericFailureCodes.FailedToUpdateObject
                vfense_status_code = UserFailureCodes.NewPasswordSameAsOld

            elif original_password_verified and not pass_strength[0]:
                msg = 'New password is to weak for user %s - ' % (username)
                object_status = DbCodes.Unchanged
                generic_status_code = GenericFailureCodes.FailedToUpdateObject
                vfense_status_code = UserFailureCodes.WeakPassword

            elif not original_password_verified:
                msg = 'Password not verified for user %s - ' % (username)
                object_status = DbCodes.Unchanged
                generic_status_code = GenericFailureCodes.FailedToUpdateObject
                vfense_status_code = UserFailureCodes.InvalidPassword

            results = {
                ApiResultKeys.DB_STATUS_CODE: object_status,
                ApiResultKeys.GENERIC_STATUS_CODE: generic_status_code,
                ApiResultKeys.VFENSE_STATUS_CODE: vfense_status_code,
                ApiResultKeys.UPDATED_IDS: [username],
                ApiResultKeys.MESSAGE: status + msg,
                ApiResultKeys.DATA: [],
                ApiResultKeys.USERNAME: user_name,
                ApiResultKeys.URI: uri,
                ApiResultKeys.HTTP_METHOD: method
            }


        else:
            msg = 'User %s does not exist - ' % (username)
            object_status = DbCodes.Skipped
            generic_status_code = GenericCodes.InvalidId
            vfense_status_code = UserFailureCodes.UserNameDoesNotExist

            results = {
                ApiResultKeys.DB_STATUS_CODE: object_status,
                ApiResultKeys.GENERIC_STATUS_CODE: generic_status_code,
                ApiResultKeys.VFENSE_STATUS_CODE: vfense_status_code,
                ApiResultKeys.MESSAGE: status + msg,
                ApiResultKeys.DATA: [],
                ApiResultKeys.USERNAME: user_name,
                ApiResultKeys.URI: uri,
                ApiResultKeys.HTTP_METHOD: method
            }


    except Exception as e:
        logger.exception(e)
        status_code = DbCodes.Errors
        generic_status_code = GenericFailureCodes.FailedToUpdateObject
        vfense_status_code = UserFailureCodes.FailedToUpdateUser
        msg = 'Failed to update password for user %s: %s' % (username, str(e))

        results = {
            ApiResultKeys.DB_STATUS_CODE: status_code,
            ApiResultKeys.GENERIC_STATUS_CODE: generic_status_code,
            ApiResultKeys.VFENSE_STATUS_CODE: vfense_status_code,
            ApiResultKeys.MESSAGE: status + msg,
            ApiResultKeys.DATA: [],
            ApiResultKeys.USERNAME: user_name,
            ApiResultKeys.URI: uri,
            ApiResultKeys.HTTP_METHOD: method
        }

    return(results)