def login_user(request): form = LoginForm() if request.method == 'POST': form = LoginForm(request.POST) if form.is_valid(): password = form.cleaned_data['password'].encode('utf-8') username = form.cleaned_data['username'].strip() user = authenticate(username=username, password=password) if user and user.is_active: login(request, user) log_admin_action(request, 'logged in') config = read_config_file() if not config['api_password']: initial_setup(username, password) config = read_config_file() api = get_api(config) set_api_version(api) if api.backup(): log_admin_action(request, 'restoring from backup') subprocess.call([ '/opt/openmanage/bin/run_restore_omva.sh', ]) elif not config['groups']: create_initial_group() config_mgr_ = config_mgr.ConfigManager( config_mgr.default_config()) api = get_api(config_mgr_.config) subprocess.call([ '/opt/openmanage/bin/first_setup.sh', api.info()['brand_identifier'] ]) request.session['username'] = username return redirect(urllib.unquote(request.GET.get('next', '/'))) else: errors = form._errors.setdefault(NON_FIELD_ERRORS, ErrorList()) errors.append('Invalid username or password') return render_to_response('login.html', dict( form=form, request_login=True, ), RequestContext(request))
def authenticate_netkes(self, username, password): log = logging.getLogger('admin_actions.authenticate_netkes') log.info('Attempting to log in "%s" through netkes' % username) config = read_config_file() api = get_api(config) if account_mgr.authenticator(config, username, password, False): api_user = api.get_user(username) group_id = api_user['group_id'] config_group = get_config_group(config, group_id) if not config_group['admin_group']: log.info('Username "%s" is not in an admin group' % username) return None try: admin_group = models.AdminGroup.objects.get(user_group_id=group_id) except models.AdminGroup.DoesNotExist: log.info('Unable to find admin group for group %s' % group_id) return None group = Group.objects.get(pk=admin_group.group_id) try: user = User.objects.get(username=username) except User.DoesNotExist: user = User(username=username, password='******') user.save() user.groups.add(group) return user else: msg = '''Failed to authenticate "%s". Username or password incorrect. ''' % username log.info(msg)
def new_fun(request, *args, **kwargs): if not request.session.get('username', False): return redirect(reverse('blue_mgnt:login') + '?next=%s' % urllib.quote(request.path)) config = read_config_file() api = get_api(config) account_info = dict() quota = api.quota() account_info['device_count'] = quota['device_count'] account_info['share_count'] = quota['share_count'] account_info['space_used'] = quota['bytes_used'] account_info['space_allocated'] = quota['bytes_allocated'] account_info['space_available'] = (quota['bytes_available'] or 0) / (10.0 ** 9) account_info['show_available'] = True if not account_info['space_available']: account_info['show_available'] = False account_info['space_available'] = account_info['space_allocated'] user_count = api.get_user_count() account_info['total_users'] = user_count account_info['total_groups'] = len(config['groups']) account_info['total_auth_codes'] = models.AdminSetupTokensUse.objects.count() account_info['api_user'] = config['api_user'] account_info['info'] = api.info() with open('/opt/openmanage/etc/OpenManage_version.txt') as f: account_info['version'] = f.readlines()[0] return fun(request, api, account_info, config, request.session['username'], *args, **kwargs)
def authenticate_netkes(self, username, password): log = logging.getLogger('admin_actions.authenticate_netkes') log.info('Attempting to log in "%s" through netkes' % username) config = read_config_file() api = get_api(config) if account_mgr.authenticator(config, username, password, False): api_user = api.get_user(username) group_id = api_user['group_id'] config_group = get_config_group(config, group_id) if not config_group['admin_group']: log.info('Username "%s" is not in an admin group' % username) return None try: admin_group = models.AdminGroup.objects.get( user_group_id=group_id) except models.AdminGroup.DoesNotExist: log.info('Unable to find admin group for group %s' % group_id) return None group = Group.objects.get(pk=admin_group.group_id) try: user = User.objects.get(username=username) except User.DoesNotExist: user = User(username=username, password='******') user.save() user.groups.add(group) return user else: msg = '''Failed to authenticate "%s". Username or password incorrect. ''' % username log.info(msg)
def new_fun(request, *args, **kwargs): if not request.session.get('username', False): return redirect( reverse('blue_mgnt:login') + '?next=%s' % urllib.quote(request.path)) config = read_config_file() api = get_api(config) account_info = dict() quota = api.quota() account_info['device_count'] = quota['device_count'] account_info['share_count'] = quota['share_count'] account_info['space_used'] = quota['bytes_used'] account_info['space_allocated'] = quota['bytes_allocated'] account_info['space_available'] = (quota['bytes_available'] or 0) / (10.0**9) account_info['show_available'] = True if not account_info['space_available']: account_info['show_available'] = False account_info['space_available'] = account_info['space_allocated'] user_count = api.get_user_count() account_info['total_users'] = user_count account_info['total_groups'] = len(config['groups']) account_info[ 'total_auth_codes'] = models.AdminSetupTokensUse.objects.count() account_info['api_user'] = config['api_user'] account_info['info'] = api.info() with open('/opt/openmanage/etc/OpenManage_version.txt') as f: account_info['version'] = f.readlines()[0] return fun(request, api, account_info, config, request.session['username'], *args, **kwargs)
def authenticate(self, username=None, password=None): user = self.authenticate_superuser(username, password) if user: return user config = read_config_file() if config['api_user']: return self.authenticate_netkes(username, password) return None
def authenticate(self, username=None, password=None): user = self.authenticate_superuser(username, password) if user: return user config = read_config_file() if config['api_user']: return self.authenticate_netkes(username, password) return None
def login_user(request): form = LoginForm() if request.method == 'POST': form = LoginForm(request.POST) if form.is_valid(): password = form.cleaned_data['password'].encode('utf-8') username = form.cleaned_data['username'].strip() user = authenticate(username=username, password=password) if user and user.is_active: login(request, user) remote_addr = request.META['REMOTE_ADDR'] log_admin_action(request, 'logged in')# from ip: %s' % remote_addr) config = read_config_file() if not config['api_password']: initial_setup(username, password) config = read_config_file() api = get_api(config) if api.backup(): log_admin_action(request, 'restoring from backup') subprocess.call(['/opt/openmanage/bin/run_restore_omva.sh',]) elif not config['groups']: create_initial_group() config_mgr_ = config_mgr.ConfigManager(config_mgr.default_config()) api = get_api(config_mgr_.config) subprocess.call(['/opt/openmanage/bin/first_setup.sh', api.info()['brand_identifier']]) request.session['username'] = username return redirect(urllib.unquote(request.GET.get('next', '/'))) else: errors = form._errors.setdefault(NON_FIELD_ERRORS , ErrorList()) errors.append('Invalid username or password') return render_to_response('login.html', dict( form=form, request_login=True, ), RequestContext(request))
def apply_sql(): common.set_config(common.read_config_file()) sql_files = glob.glob('/opt/openmanage/net_kes/sql/*.sql') sql_files = [(x.split('/')[-1], open(x).readlines()) for x in sql_files] sql_files = sorted(sql_files, key=lambda x: x[0]) for sql_file in sql_files: with get_cursor(common.get_config()) as cur: cur.execute('select * from sql_updates where name=%s', (sql_file[0], )) if cur.rowcount == 0: cur.execute(''.join(sql_file[1])) cur.execute('insert into sql_updates (name) values (%s)', (sql_file[0], ))
def apply_scripts(): common.set_config(common.read_config_file()) files = glob.glob('/opt/openmanage/upgrade/scripts/*.sh') files = sorted(files) for file_ in files: with get_cursor(common.get_config()) as cur: cur.execute('select * from updates where name=%s', (file_, )) if cur.rowcount == 0: print "Applying", file_ retcode = call([file_], shell=True) if retcode == 0: cur.execute('insert into updates (name) values (%s)', (file_, ))
def apply_sql(): config = common.read_config_file() config['db_user'] = '******' sql_files = glob.glob('/opt/openmanage/sql/*.sql') sql_files = [(x.split('/')[-1], open(x).readlines()) for x in sql_files] sql_files = sorted(sql_files, key=lambda x: x[0]) for sql_file in sql_files: with get_cursor(config, False) as cur: cur.execute('select * from sql_updates where name=%s', (sql_file[0], )) if cur.rowcount == 0: print "Applying", sql_file[0] cur.execute(''.join(sql_file[1])) cur.execute('insert into sql_updates (name) values (%s)', (sql_file[0], ))
def test_encrypt_and_decrypt_with_layers(self): config = common.read_config_file() brand_identifier = config['api_user'] escrow_data = "test data" sign_key = RSA.generate(2048, random_string) escrowed_data = encrypt_with_layers(escrow_data, sign_key, brand_identifier) layer_count = 2 plaintext_data = server.read_escrow_data(brand_identifier, escrowed_data, layer_count=layer_count, sign_key=sign_key) self.assertEqual(escrow_data, plaintext_data)
def apply_scripts(): common.set_config(common.read_config_file()) files = glob.glob('/opt/openmanage/upgrade/scripts/*.sh') files = sorted(files) for file_ in files: with get_cursor(common.get_config()) as cur: cur.execute('select * from updates where name=%s', (file_, )) if cur.rowcount == 0: print "Applying", file_ retcode = call([file_], shell=True) if retcode == 0: cur.execute('insert into updates (name) values (%s)', (file_, ))
def test_encrypt_and_decrypt_with_layers(self): config = common.read_config_file() brand_identifier = config['api_user'] escrow_data = "test data" sign_key = RSA.generate(2048, random_string) escrowed_data = encrypt_with_layers(escrow_data, sign_key, brand_identifier) layer_count = 2 plaintext_data = server.read_escrow_data(brand_identifier, escrowed_data, layer_count=layer_count, sign_key=sign_key) self.assertEqual(escrow_data, plaintext_data)
def apply_sql(): common.set_config(common.read_config_file()) config = common.get_config() config['db_user'] = '******' sql_files = glob.glob('/opt/openmanage/sql/*.sql') sql_files = [(x.split('/')[-1], open(x).readlines()) for x in sql_files] sql_files = sorted(sql_files, key=lambda x: x[0]) for sql_file in sql_files: with get_cursor(config, False) as cur: cur.execute('select * from sql_updates where name=%s', (sql_file[0], )) if cur.rowcount == 0: print "Applying", sql_file[0] cur.execute(''.join(sql_file[1])) cur.execute('insert into sql_updates (name) values (%s)', (sql_file[0], ))
def handle(self, *args, **options): config = read_config_file() api = get_api(config) backed_up_within_seconds = options.get('backed_up_within') * SECONDS_IN_A_DAY not_backed_up_within_seconds = options.get('not_backed_up_within') * SECONDS_IN_A_DAY sort_order = options.get('sort_order') search_by = 'recently_stopped_uploading={}|{}'.format( backed_up_within_seconds, not_backed_up_within_seconds ) filename = timezone.now().strftime('backup_status_%Y-%m-%d_%H:%M:%S.csv') writer = csv.writer(open(os.path.join(options.get('outdir'), filename), 'w')) headers = [ 'name', 'device_name', 'bytes_stored', 'last_login', 'last_backup_complete', ] writer.writerow(headers) rows = [] for user in api.list_users(search_by=search_by): for device in api.list_devices(user['email']): last_backup_complete = device['last_backup_complete'] if ( last_backup_complete and self._backed_up_within(last_backup_complete, backed_up_within_seconds) and not self._backed_up_within(last_backup_complete, not_backed_up_within_seconds) ): rows.append([ user['name'], device['name'], user['bytes_stored'], datetime.datetime.fromtimestamp( device['last_login'], ).strftime('%Y-%m-%d_%H:%M:%S'), datetime.datetime.fromtimestamp( device['last_backup_complete'], ).strftime('%Y-%m-%d_%H:%M:%S'), ]) rows = sorted( rows, key=lambda x: x[SORT_COLUMNS[sort_order]], reverse=options.get('reverse') ) for row in rows: writer.writerow(row) self.stdout.write(self.style.SUCCESS('Successfully created backup status report'))
def authenticate_superuser(self, username, password): log = logging.getLogger('admin_actions.authenticate_superuser') log.info('Attempting to log "%s" in as a superuser' % username) config = read_config_file() if config['api_user'] and (username != config['api_user']): log.info('Username "%s" does not match superuser username' % username) return None initial_auth = False if not config['api_user']: new_pass, api_pass = hash_password(password) api = Api.create( django_settings.ACCOUNT_API_URL, username, api_pass, ) try: api.ping() initial_auth = True except urllib2.HTTPError: log.info('''Failed initial log in for "%s" as a superuser. Password incorrect or unable to contact accounts api''' % username) return None local_pass = config.get('local_password', '') if initial_auth or bcrypt.hashpw(password, local_pass) == local_pass: try: user = User.objects.get(username=username) except ObjectDoesNotExist: user = User(username=username, password='******') user.is_staff = True user.is_superuser = True user.save() user.user_permissions = Permission.objects.filter( content_type__app_label='blue_mgnt', content_type__model='AccountsApi') return user else: msg = '''Failed to log in "%s" as a superuser. Password incorrect. ''' % username log.info(msg) return None
def authenticate_superuser(self, username, password): log = logging.getLogger('admin_actions.authenticate_superuser') log.info('Attempting to log "%s" in as a superuser' % username) config = read_config_file() if config['api_user'] and (username != config['api_user']): log.info('Username "%s" does not match superuser username' % username) return None initial_auth = False if not config['api_user']: new_pass, api_pass = hash_password(password) api = Api.create( django_settings.ACCOUNT_API_URL, username, api_pass, ) try: api.ping() initial_auth = True except urllib2.HTTPError: log.info('''Failed initial log in for "%s" as a superuser. Password incorrect or unable to contact accounts api''' % username) return None local_pass = config.get('local_password', '') if initial_auth or bcrypt.hashpw(password, local_pass) == local_pass: try: user = User.objects.get(username=username) except ObjectDoesNotExist: user = User(username=username, password='******') user.is_staff = True user.is_superuser = True user.save() user.user_permissions = Permission.objects.filter( content_type__app_label='blue_mgnt', content_type__model='AccountsApi' ) return user else: msg = '''Failed to log in "%s" as a superuser. Password incorrect. ''' % username log.info(msg) return None
def setUp(self): self.client = Client() self.sign_key = RSA.generate(2048, random_string) self.config = common.read_config_file() self.brand_identifier = self.config['api_user'] self.auth = { 'password': '******', 'challenge': 'challenge', } auth = encrypt_with_layers(json.dumps(self.auth), self.sign_key, self.brand_identifier) username = urllib.quote('test_username') self.post_data = { 'brand_id': self.brand_identifier, 'username': username, 'auth': b2a_base64(auth), 'escrow_data': sentinel.escrow_data, 'sign_key': dumps(self.sign_key), 'layer_count': 2, } self.session_post_data = { 'brand_id': self.brand_identifier, }
def setUp(self): self.client = Client() self.sign_key = RSA.generate(2048, random_string) self.config = common.read_config_file() self.brand_identifier = self.config['api_user'] self.auth = { 'password': '******', 'challenge': 'challenge', } auth = encrypt_with_layers(json.dumps(self.auth), self.sign_key, self.brand_identifier) username = urllib.quote('test_username') self.post_data = { 'brand_id': self.brand_identifier, 'username': username, 'auth': b2a_base64(auth), 'escrow_data': sentinel.escrow_data, 'sign_key': dumps(self.sign_key), 'layer_count': 2, } self.session_post_data = { 'brand_id': self.brand_identifier, }
def setUp(self): self.config = common.read_config_file() self.brand_identifier = self.config['api_user'] self.client = Client()
import datetime from hashlib import sha256 import subprocess from binascii import a2b_base64 import bcrypt import nacl.secret from nacl.exceptions import CryptoError from netkes import common from netkes.account_mgr.accounts_api import Api os.environ['DJANGO_SETTINGS_MODULE'] = 'omva.settings' from openmanage.views import create_secret_box config = common.read_config_file() api = Api.create( config["api_root"], config["api_user"], config["api_password"], ) date = datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S') filename = 'openmanage-backup-%s.tar.bz2' % date path = '/opt/openmanage/tmp_backup/%s' % filename backup = api.backup() data = a2b_base64(backup['data'])
def setUp(self): self.config = common.read_config_file() self.brand_identifier = self.config['api_user'] self.client = Client()
def get_base_url(url=None): if not url: url = read_config_file()['api_root'] split = urlparse.urlparse(url) return urlparse.urlunsplit((split.scheme, split.netloc, '', '', ''))
from netkes import common import logging PROJECT_DIR = os.path.abspath(os.path.dirname(__file__)) sys.path += [os.path.join(PROJECT_DIR, '../apps')] sys.path += ['/opt/openmanage/django/apps'] DEBUG = False TEMPLATE_DEBUG = DEBUG ADMINS = () MANAGERS = ADMINS common.set_config(common.read_config_file()) config = common.get_config() DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'openmanage', 'USER': '******', 'PASSWORD': '******', 'HOST': 'localhost', } } DATABASE_ENGINE = 'postgresql_psycopg2' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. DATABASE_NAME = 'openmanage' # Or path to database file if using sqlite3. DATABASE_USER = '******' # Not used with sqlite3.
import argparse from netkes import common from netkes.account_mgr.accounts_api import Api config = common.read_config_file() parser = argparse.ArgumentParser(description='Update OMVA URL.') parser.add_argument('url') args = parser.parse_args() api = Api.create(config["api_root"], config["api_user"], config["api_password"]) api.update_enterprise_settings(dict(omva_url=args.url))
def get_base_url(url=None): if not url: url = read_config_file()['api_root'] split = urlparse.urlparse(url) return urlparse.urlunsplit((split.scheme, split.netloc, '', '', ''))
from netkes import common import logging PROJECT_DIR = os.path.abspath(os.path.dirname(__file__)) sys.path += [os.path.join(PROJECT_DIR, '../apps')] sys.path += ['/opt/openmanage/django/apps'] DEBUG = False TEMPLATE_DEBUG = DEBUG ADMINS = () MANAGERS = ADMINS common.set_config(common.read_config_file()) config = common.get_config() DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'openmanage', 'USER': '******', 'PASSWORD': '******', 'HOST': 'localhost', } } DATABASE_ENGINE = 'postgresql_psycopg2' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. DATABASE_NAME = 'openmanage' # Or path to database file if using sqlite3. DATABASE_USER = '******' # Not used with sqlite3.