def get_auth(): return { 'username': persist_db.dict_get( 'auth', 'username') or DEFAULT_USERNAME, 'token': persist_db.dict_get('auth', 'token_enc'), 'secret': persist_db.dict_get('auth', 'secret'), }
def check_auth(username, password, remote_addr=None): if remote_addr: cache_key = 'ip_' + remote_addr count = cache_db.list_length(cache_key) if count and count > 10: raise flask.abort(403) key_exists = cache_db.exists(cache_key) cache_db.list_rpush(cache_key, '') if not key_exists: cache_db.expire(cache_key, 20) db_username = persist_db.dict_get('auth', 'username') or DEFAULT_USERNAME if username != db_username: return False db_password = persist_db.dict_get('auth', 'password') if not db_password: if password == DEFAULT_PASSWORD: return True return False pass_ver, pass_salt, db_pass_hash = db_password.split('$') if pass_ver == '0': pass_hash = _hash_password_v0(pass_salt, password) elif pass_ver == '1': pass_hash = _hash_password_v1(pass_salt, password) else: return False return pass_hash == db_pass_hash
def send_key_email(self, key_link_domain): email_from = persist_db.dict_get('auth', 'email_from') email_api_key = persist_db.dict_get('auth', 'email_api_key') if not email_from or not email_api_key: raise EmailNotConfiguredError('Email not configured', { 'org_id': self.org.id, 'user_id': self.id, }) key_link = self.org.create_user_key_link(self.id) response = utils.request.post(POSTMARK_SERVER, headers={ 'Accept': 'application/json', 'Content-Type': 'application/json', 'X-Postmark-Server-Token': email_api_key, }, json_data={ 'From': email_from, 'To': self.email, 'Subject': 'Pritunl VPN Key', 'TextBody': 'Your vpn key and configuration can be ' + 'downloaded from the temporary link below:\n\n' + key_link_domain + key_link['view_url'], }, ) response = response.json() error_code = response.get('ErrorCode') error_msg = response.get('Message') if error_code == 0: pass elif error_code == 10: raise EmailApiKeyInvalid('Email api key invalid', { 'org_id': self.org.id, 'user_id': self.id, 'error_code': error_code, 'error_msg': error_msg, }) elif error_code == 400: raise EmailFromInvalid('Email from invalid', { 'org_id': self.org.id, 'user_id': self.id, 'error_code': error_code, 'error_msg': error_msg, }) else: logger.error('Unknown send user email error. %r' % { 'org_id': self.org.id, 'user_id': self.id, 'error_code': error_code, 'error_msg': error_msg, }) raise EmailError('Unknown send user email error.', { 'org_id': self.org.id, 'user_id': self.id, 'error_code': error_code, 'error_msg': error_msg, })
def check_session(): from pritunl import app_server auth_token = flask.request.headers.get("Auth-Token", None) if auth_token: auth_timestamp = flask.request.headers.get("Auth-Timestamp", None) auth_nonce = flask.request.headers.get("Auth-Nonce", None) auth_signature = flask.request.headers.get("Auth-Signature", None) if not auth_token or not auth_timestamp or not auth_nonce or not auth_signature: return False try: if abs(int(auth_timestamp) - int(time.time())) > AUTH_TIME_WINDOW: return False except ValueError: return False cache_key = "auth_nonce-%s" % auth_nonce if cache_db.exists(cache_key): return False cache_db.expire(cache_key, int(AUTH_TIME_WINDOW * 2.1)) cache_db.set(cache_key, auth_timestamp) auth_token_hash = persist_db.dict_get("auth", "token") auth_secret = persist_db.dict_get("auth", "secret") if not auth_token_hash or not auth_secret: return False if not _test_password_hash(auth_token_hash, auth_token): return False auth_string = "&".join( [auth_token, auth_timestamp, auth_nonce, flask.request.method, flask.request.path] + ([flask.request.data] if flask.request.data else []) ) if len(auth_string) > AUTH_SIG_STRING_MAX_LEN: return False auth_test_signature = base64.b64encode(hmac.new(auth_secret.encode(), auth_string, hashlib.sha256).digest()) if auth_signature != auth_test_signature: return False else: if not flask.session: return False if not flask.session.get("auth"): flask.session.clear() return False if not app_server.ssl and flask.session.get("source") != get_remote_addr(): flask.session.clear() return False if app_server.session_timeout and int(time.time()) - flask.session["timestamp"] > app_server.session_timeout: flask.session.clear() return False return True
def check_auth(username, password, remote_addr=None): if remote_addr: cache_key = "ip_" + remote_addr count = cache_db.list_length(cache_key) if count and count > 10: raise flask.abort(403) key_exists = cache_db.exists(cache_key) cache_db.list_rpush(cache_key, "") if not key_exists: cache_db.expire(cache_key, 20) db_username = persist_db.dict_get("auth", "username") or DEFAULT_USERNAME if username != db_username: return False db_password = persist_db.dict_get("auth", "password") if not db_password: if password == DEFAULT_PASSWORD: return True return False return _test_password_hash(db_password, password)
def get_bandwidth(self, period=None): data = {} date = datetime.datetime.utcnow() date -= datetime.timedelta(microseconds=date.microsecond, seconds=date.second) periods = (period,) if period else ('1m', '5m', '30m', '2h', '1d') for period in periods: if period == '1m': date_end = date date_cur = date_end - datetime.timedelta(hours=6) date_step = datetime.timedelta(minutes=1) elif period == '5m': date_end = date - datetime.timedelta(minutes=date.minute % 5) date_cur = date_end - datetime.timedelta(days=1) date_step = datetime.timedelta(minutes=5) elif period == '30m': date_end = date - datetime.timedelta(minutes=date.minute % 30) date_cur = date_end - datetime.timedelta(days=7) date_step = datetime.timedelta(minutes=30) elif period == '2h': date_end = date - datetime.timedelta(minutes=date.minute, hours=date.hour % 2) date_cur = date_end - datetime.timedelta(days=30) date_step = datetime.timedelta(hours=2) elif period == '1d': date_end = date - datetime.timedelta(minutes=date.minute, hours=date.hour) date_cur = date_end - datetime.timedelta(days=365) date_step = datetime.timedelta(days=1) data_p = { 'received': [], 'received_total': 0, 'sent': [], 'sent_total': 0, } data[period] = data_p cache_key = self.get_cache_key('bandwidth-%s' % period) while date_cur < date_end: date_cur += date_step timestamp = int(date_cur.strftime('%s')) bandwidth = persist_db.dict_get(cache_key, str(timestamp)) if bandwidth: bandwidth = bandwidth.split(',') bytes_recv = int(bandwidth[0]) bytes_sent = int(bandwidth[1]) else: bytes_recv = 0 bytes_sent = 0 data_p['received'].append((timestamp, bytes_recv)) data_p['received_total'] += bytes_recv data_p['sent'].append((timestamp, bytes_sent)) data_p['sent_total'] += bytes_sent if len(periods) == 1: return data[periods[0]] else: return data
def _update_clients_bandwidth(self, clients): # Remove client no longer connected for client_id in cache_db.dict_keys(self.get_cache_key('clients')): if client_id not in clients: cache_db.dict_remove(self.get_cache_key('clients'), client_id) # Get total bytes send and recv for all clients bytes_recv_t = 0 bytes_sent_t = 0 for client_id in clients: bytes_recv = clients[client_id]['bytes_received'] bytes_sent = clients[client_id]['bytes_sent'] prev_bytes_recv = 0 prev_bytes_sent = 0 client_prev = cache_db.dict_get(self.get_cache_key('clients'), client_id) cache_db.dict_set(self.get_cache_key('clients'), client_id, '%s,%s' % (bytes_recv, bytes_sent)) if client_prev: client_prev = client_prev.split(',') prev_bytes_recv = int(client_prev[0]) prev_bytes_sent = int(client_prev[1]) if prev_bytes_recv > bytes_recv or prev_bytes_sent > bytes_sent: prev_bytes_recv = 0 prev_bytes_sent = 0 bytes_recv_t += bytes_recv - prev_bytes_recv bytes_sent_t += bytes_sent - prev_bytes_sent # Store bytes send recv into time periods if bytes_recv_t != 0 or bytes_sent_t != 0: date = datetime.datetime.utcnow() date -= datetime.timedelta(microseconds=date.microsecond, seconds=date.second) timestamp_1m = date.strftime('%s') timestamp_1m_min = int((date - datetime.timedelta( hours=6)).strftime('%s')) date_5m = date - datetime.timedelta(minutes=date.minute % 5) timestamp_5m = date_5m.strftime('%s') timestamp_5m_min = int((date_5m - datetime.timedelta( days=1)).strftime('%s')) date_30m = date - datetime.timedelta(minutes=date.minute % 30) timestamp_30m = date_30m.strftime('%s') timestamp_30m_min = int((date_30m - datetime.timedelta( days=7)).strftime('%s')) date_2h = date - datetime.timedelta( hours=date.hour % 2, minutes=date.minute) timestamp_2h = date_2h.strftime('%s') timestamp_2h_min = int((date_2h - datetime.timedelta( days=30)).strftime('%s')) date_1d = date - datetime.timedelta( hours=date.hour, minutes=date.minute) timestamp_1d = date_1d.strftime('%s') timestamp_1d_min = int((date_1d - datetime.timedelta( days=365)).strftime('%s')) for period, timestamp, timestamp_min in ( ('1m', timestamp_1m, timestamp_1m_min), ('5m', timestamp_5m, timestamp_5m_min), ('30m', timestamp_30m, timestamp_30m_min), ('2h', timestamp_2h, timestamp_2h_min), ('1d', timestamp_1d, timestamp_1d_min), ): bytes_recv = bytes_recv_t bytes_sent = bytes_sent_t prev_bandwidth = persist_db.dict_get( self.get_cache_key('bandwidth-%s' % period), timestamp) if prev_bandwidth: prev_bandwidth = prev_bandwidth.split(',') bytes_recv += int(prev_bandwidth[0]) bytes_sent += int(prev_bandwidth[1]) persist_db.dict_set(self.get_cache_key( 'bandwidth-%s' % period), timestamp, '%s,%s' % (bytes_recv, bytes_sent)) for timestamp_p in persist_db.dict_keys(self.get_cache_key( 'bandwidth-%s' % period)): if int(timestamp_p) <= timestamp_min: persist_db.dict_remove(self.get_cache_key( 'bandwidth-%s' % period), timestamp_p)
def get_auth(): return { "username": persist_db.dict_get("auth", "username") or DEFAULT_USERNAME, "token": persist_db.dict_get("auth", "token_enc"), "secret": persist_db.dict_get("auth", "secret"), }
def _get_password_data(): password = persist_db.dict_get("auth", "password") if not password: return None, None, None pass_split = password.split("$") return (int(pass_split[0]), pass_split[1], pass_split[2])
def check_session(): from pritunl import app_server auth_valid = True auth_token = flask.request.headers.get('Auth-Token', None) if auth_token: auth_timestamp = flask.request.headers.get('Auth-Timestamp', None) auth_nonce = flask.request.headers.get('Auth-Nonce', None) auth_signature = flask.request.headers.get('Auth-Signature', None) if not auth_token or not auth_timestamp or not auth_nonce or \ not auth_signature: return False auth_nonce = auth_nonce[:32] try: if abs(int(auth_timestamp) - int(time.time())) > AUTH_TIME_WINDOW: return False except ValueError: return False cache_key = 'auth_nonce-%s' % auth_nonce if cache_db.exists(cache_key): return False auth_token_hash = persist_db.dict_get('auth', 'token') auth_secret = persist_db.dict_get('auth', 'secret') if not auth_token_hash or not auth_secret: return False if not _test_password_hash(auth_token_hash, auth_token): auth_valid = False auth_string = '&'.join([ auth_token, auth_timestamp, auth_nonce, flask.request.method, flask.request.path] + ([flask.request.data] if flask.request.data else [])) if len(auth_string) > AUTH_SIG_STRING_MAX_LEN: return False auth_test_signature = base64.b64encode(hmac.new( auth_secret.encode(), auth_string, hashlib.sha256).digest()) if auth_signature != auth_test_signature: auth_valid = False if auth_valid: cache_db.expire(cache_key, int(AUTH_TIME_WINDOW * 2.1)) cache_db.set(cache_key, auth_timestamp) else: if not flask.session: return False if not flask.session.get('auth'): flask.session.clear() return False if not app_server.ssl and flask.session.get( 'source') != get_remote_addr(): flask.session.clear() return False if app_server.session_timeout and int(time.time()) - \ flask.session['timestamp'] > app_server.session_timeout: flask.session.clear() return False return auth_valid
def _get_password_data(): password = persist_db.dict_get('auth', 'password') if not password: return None, None, None pass_split = password.split('$') return (int(pass_split[0]), pass_split[1], pass_split[2])
def get_auth(): return persist_db.dict_get('auth', 'username')