Example #1
0
def user_otp_secret_put(org_id, user_id):
    org = Organization.get_org(id=org_id)
    user = org.get_user(user_id)
    user.generate_otp_secret()
    user.commit()
    Event(type=USERS_UPDATED, resource_id=org.id)
    return utils.jsonify(user.dict())
Example #2
0
def user_key_link_get(org_id, user_id):
    org = Organization.get_org(id=org_id)
    key_id = uuid.uuid4().hex

    view_id = None
    uri_id = None
    for i in xrange(2):
        for i in xrange(2048):
            temp_id = ''.join(random.sample(SHORT_URL_CHARS, SHORT_URL_LEN))
            if not view_id:
                if not cache_db.exists(_get_view_key(temp_id)):
                    view_id = temp_id
                    break
            else:
                if not cache_db.exists(_get_uri_key(temp_id)):
                    uri_id = temp_id
                    break
        if not view_id and not uri_id:
            raise KeyLinkError('Failed to generate random id')

    cache_db.expire(_get_key_key(key_id), KEY_LINK_TIMEOUT)
    cache_db.dict_set(_get_key_key(key_id), 'org_id', org_id)
    cache_db.dict_set(_get_key_key(key_id), 'user_id', user_id)
    cache_db.dict_set(_get_key_key(key_id), 'view_id', view_id)
    cache_db.dict_set(_get_key_key(key_id), 'uri_id', uri_id)

    conf_urls = []
    if app_server.inline_certs:
        for server in org.iter_servers():
            conf_id = uuid.uuid4().hex

            cache_db.expire(_get_conf_key(conf_id), KEY_LINK_TIMEOUT)
            cache_db.dict_set(_get_conf_key(conf_id), 'org_id', org_id)
            cache_db.dict_set(_get_conf_key(conf_id), 'user_id', user_id)
            cache_db.dict_set(_get_conf_key(conf_id), 'server_id', server.id)

            conf_urls.append({
                'id': conf_id,
                'server_name': server.name,
                'url': '/key/%s.ovpn' % conf_id,
            })

    cache_db.expire(_get_view_key(view_id), KEY_LINK_TIMEOUT)
    cache_db.dict_set(_get_view_key(view_id), 'org_id', org_id)
    cache_db.dict_set(_get_view_key(view_id), 'user_id', user_id)
    cache_db.dict_set(_get_view_key(view_id), 'key_id', key_id)
    cache_db.dict_set(_get_view_key(view_id), 'uri_id', uri_id)
    cache_db.dict_set(_get_view_key(view_id),
        'conf_urls', json.dumps(conf_urls))

    cache_db.expire(_get_uri_key(uri_id), KEY_LINK_TIMEOUT)
    cache_db.dict_set(_get_uri_key(uri_id), 'org_id', org_id)
    cache_db.dict_set(_get_uri_key(uri_id), 'user_id', user_id)

    return utils.jsonify({
        'id': key_id,
        'key_url': '/key/%s.tar' % key_id,
        'view_url': '/k/%s' % view_id,
        'uri_url': '/ku/%s' % uri_id,
    })
Example #3
0
def user_put(org_id, user_id):
    org = Organization.get_org(id=org_id)
    user = org.get_user(user_id)
    name = utils.filter_str(flask.request.json['name'])
    user.rename(name)

    return utils.jsonify(user.dict())
Example #4
0
def user_post(org_id):
    org = Organization.get_org(id=org_id)
    users = []

    if isinstance(flask.request.json, list):
        users_data = flask.request.json
    else:
        users_data = [flask.request.json]

    for user_data in users_data:
        name = utils.filter_str(user_data['name'])
        email = utils.filter_str(user_data.get('email'))
        user = org.new_user(type=CERT_CLIENT, name=name, email=email)

        disabled = user_data.get('disabled')
        if disabled is not None:
            user.disabled = disabled

        user.commit()
        users.append(user.dict())

    Event(type=ORGS_UPDATED)
    Event(type=USERS_UPDATED, resource_id=org.id)
    Event(type=SERVERS_UPDATED)

    if isinstance(flask.request.json, list):
        LogEntry(message='Created %s new users.' % len(flask.request.json))
        return utils.jsonify(users)
    else:
        LogEntry(message='Created new user "%s".' % users[0]['name'])
        return utils.jsonify(users[0])
Example #5
0
def org_get(org_id=None):
    if org_id:
        return utils.jsonify(Organization.get_org(id=org_id).dict())
    else:
        orgs = []
        for org in Organization.iter_orgs():
            orgs.append(org.dict())
        return utils.jsonify(orgs)
Example #6
0
def user_get(org_id, user_id=None, page=None):
    org = Organization.get_org(id=org_id)
    if user_id:
        return utils.jsonify(org.get_user(user_id).dict())
    else:
        page = flask.request.args.get('page', None)
        page = int(page) if page else page
        search = flask.request.args.get('search', None)
        limit = int(flask.request.args.get('limit', USER_PAGE_COUNT))
        otp_auth = False
        search_more = True
        server_count = 0
        clients = {}

        for server in org.iter_servers():
            server_count += 1
            if server.otp_auth:
                otp_auth = True
            server_clients = server.clients
            for client_id in server_clients:
                client = server_clients[client_id]
                if client_id not in clients:
                    clients[client_id] = {}
                clients[client_id][server.id] = client

        users = []
        for user in org.iter_users(page=page, prefix=search,
                prefix_limit=limit):
            if user is None:
                search_more = False
                break
            is_client = user.id in clients
            user_dict = user.dict()
            user_dict['status'] = True if is_client else False
            user_dict['otp_auth'] = otp_auth
            user_dict['servers'] = clients[user.id] if is_client else {}
            users.append(user_dict)

        if page is not None:
            return utils.jsonify({
                'page': page,
                'page_total': org.page_total,
                'server_count': server_count,
                'users': users,
            })
        elif search is not None:
            return utils.jsonify({
                'search': search,
                'search_more': search_more,
                'search_limit': limit,
                'search_count': org.get_last_prefix_count(),
                'search_time':  round((time.time() - flask.g.start), 4),
                'server_count': server_count,
                'users': users,
            })
        else:
            return utils.jsonify(users)
Example #7
0
def _get_key_archive(org_id, user_id):
    org = Organization.get_org(id=org_id)
    user = org.get_user(user_id)
    key_archive = user.build_key_archive()
    response = flask.Response(response=key_archive,
        mimetype='application/octet-stream')
    response.headers.add('Content-Disposition',
        'attachment; filename="%s.tar"' % user.name)
    return response
Example #8
0
def user_put(org_id, user_id):
    org = Organization.get_org(id=org_id)
    user = org.get_user(user_id)

    name = flask.request.json.get('name')
    if name:
        name = utils.filter_str(name)

    if 'email' in flask.request.json:
        email = flask.request.json['email']
        if email:
            user.email = utils.filter_str(email)
        else:
            user.email = None

    disabled = flask.request.json.get('disabled')
    if disabled is not None:
        user.disabled = disabled

    if name:
        user.rename(name)
    else:
        user.commit()
        Event(type=USERS_UPDATED, resource_id=user.org.id)

    if disabled:
        if user.type == CERT_CLIENT:
            LogEntry(message='Disabled user "%s".' % user.name)

        for server in org.iter_servers():
            server_clients = server.clients
            if user_id in server_clients:
                server.restart()
    elif disabled == False and user.type == CERT_CLIENT:
        LogEntry(message='Enabled user "%s".' % user.name)

    send_key_email = flask.request.json.get('send_key_email')
    if send_key_email and user.email:
        try:
            user.send_key_email(send_key_email)
        except EmailNotConfiguredError:
            return utils.jsonify({
                'error': EMAIL_NOT_CONFIGURED,
                'error_msg': EMAIL_NOT_CONFIGURED_MSG,
            }, 400)
        except EmailFromInvalid:
            return utils.jsonify({
                'error': EMAIL_FROM_INVALID,
                'error_msg': EMAIL_FROM_INVALID_MSG,
            }, 400)
        except EmailApiKeyInvalid:
            return utils.jsonify({
                'error': EMAIL_API_KEY_INVALID,
                'error_msg': EMAIL_API_KEY_INVALID_MSG,
            }, 400)

    return utils.jsonify(user.dict())
Example #9
0
def user_delete(org_id, user_id):
    org = Organization.get_org(id=org_id)
    user = org.get_user(user_id)
    user_id = user.id
    user.remove()

    for server in org.iter_servers():
        server_clients = server.clients
        if user_id in server_clients:
            server.restart()

    return utils.jsonify({})
Example #10
0
def _get_key_archive(org_id, user_id):
    org = Organization.get_org(id=org_id)
    user = org.get_user(user_id)
    archive_temp_path = user.build_key_archive()
    try:
        with open(archive_temp_path, 'r') as archive_file:
            response = flask.Response(response=archive_file.read(),
                mimetype='application/octet-stream')
            response.headers.add('Content-Disposition',
                'attachment; filename="%s.tar"' % user.name)
    finally:
        user.clean_key_archive()
    return response
Example #11
0
def user_post(org_id):
    org = Organization.get_org(id=org_id)
    name = utils.filter_str(flask.request.json["name"])
    email = None
    if "email" in flask.request.json:
        email = utils.filter_str(flask.request.json["email"])
    user = org.new_user(type=CERT_CLIENT, name=name, email=email)

    disabled = flask.request.json.get("disabled")
    if disabled is not None:
        user.disabled = disabled
        user.commit()

    return utils.jsonify(user.dict())
Example #12
0
def server_org_delete(server_id, org_id):
    server = Server.get_server(id=server_id)
    org = Organization.get_org(id=org_id)
    if server.status:
        return utils.jsonify({
            'error': SERVER_NOT_OFFLINE,
            'error_msg': SERVER_NOT_OFFLINE_DETACH_ORG_MSG,
        }, 400)
    server.remove_org(org)
    server.commit()
    Event(type=SERVERS_UPDATED)
    Event(type=SERVER_ORGS_UPDATED, resource_id=server.id)
    Event(type=USERS_UPDATED, resource_id=org.id)
    return utils.jsonify({})
Example #13
0
def user_delete(org_id, user_id):
    org = Organization.get_org(id=org_id)
    user = org.get_user(user_id)
    name = user.name
    user.remove()

    Event(type=ORGS_UPDATED)
    Event(type=USERS_UPDATED, resource_id=org.id)

    for server in org.iter_servers():
        server_clients = server.clients
        if user_id in server_clients:
            server.restart()

    LogEntry(message='Deleted user "%s".' % name)

    return utils.jsonify({})
Example #14
0
def server_org_put(server_id, org_id):
    server = Server.get_server(id=server_id)
    org = Organization.get_org(id=org_id)
    if server.status:
        return utils.jsonify({
            'error': SERVER_NOT_OFFLINE,
            'error_msg': SERVER_NOT_OFFLINE_ATTACH_ORG_MSG,
        }, 400)
    server.add_org(org)
    server.commit()
    Event(type=SERVERS_UPDATED)
    Event(type=SERVER_ORGS_UPDATED, resource_id=server.id)
    Event(type=USERS_UPDATED, resource_id=org.id)
    return utils.jsonify({
        'id': org.id,
        'server': server.id,
        'name': org.name,
    })
Example #15
0
def user_uri_key_page_get(uri_id):
    org_id = cache_db.dict_get(_get_uri_key(uri_id), 'org_id')
    user_id = cache_db.dict_get(_get_uri_key(uri_id), 'user_id')

    # Check for expire
    if not cache_db.exists(_get_uri_key(uri_id)):
        time.sleep(RATE_LIMIT_SLEEP)
        return flask.abort(404)

    org = Organization.get_org(id=org_id)
    user = org.get_user(user_id)

    keys = {}
    for server in org.iter_servers():
        key = user.build_key_conf(server.id)
        keys[key['name']] = key['conf']

    return utils.jsonify(keys)
Example #16
0
def user_linked_key_page_get(view_id):
    view_id_key = 'view_token-%s' % view_id
    org_id = cache_db.dict_get(view_id_key, 'org_id')
    user_id = cache_db.dict_get(view_id_key, 'user_id')
    key_id = cache_db.dict_get(view_id_key, 'key_id')
    conf_urls = cache_db.dict_get(view_id_key, 'conf_urls')
    if conf_urls:
        conf_urls = json.loads(conf_urls)

    # Check for expire
    if not cache_db.exists(view_id_key):
        time.sleep(RATE_LIMIT_SLEEP)
        return flask.abort(404)

    org = Organization.get_org(id=org_id)
    user = org.get_user(user_id)

    key_page = StaticFile(app_server.www_path, KEY_INDEX_NAME,
        cache=False).data
    key_page = key_page.replace('<%= user_name %>', '%s - %s' % (
        org.name, user.name))
    key_page = key_page.replace('<%= user_key_url %>', '/key/%s.tar' % (
        key_id))

    if org.otp_auth:
        key_page = key_page.replace('<%= user_otp_key %>', user.otp_secret)
        key_page = key_page.replace('<%= user_otp_url %>',
            'otpauth://totp/%s@%s?secret=%s' % (
                user.name, org.name, user.otp_secret))
    else:
        key_page = key_page.replace('<%= user_otp_key %>', '')
        key_page = key_page.replace('<%= user_otp_url %>', '')

    key_page = key_page.replace('<%= view_id %>', view_id)

    conf_links = ''
    for conf_url in conf_urls:
        conf_links += '<a class="sm" title="Download Mobile Key" ' + \
            'href="%s">Download Mobile Key (%s)</a><br>\n' % (
                conf_url['url'], conf_url['server_name'])
    key_page = key_page.replace('<%= conf_links %>', conf_links)

    return key_page
Example #17
0
def user_linked_key_conf_get(conf_id):
    org_id = cache_db.dict_get(_get_conf_key(conf_id), 'org_id')
    user_id = cache_db.dict_get(_get_conf_key(conf_id), 'user_id')
    server_id = cache_db.dict_get(_get_conf_key(conf_id), 'server_id')

    # Check for expire
    if not cache_db.exists(_get_conf_key(conf_id)):
        time.sleep(RATE_LIMIT_SLEEP)
        return flask.abort(404)

    org = Organization.get_org(id=org_id)
    user = org.get_user(user_id)
    key_conf = user.build_key_conf(server_id)

    response = flask.Response(response=key_conf['conf'],
        mimetype='application/octet-stream')
    response.headers.add('Content-Disposition',
        'attachment; filename="%s"' % key_conf['name'])

    return response
Example #18
0
def user_put(org_id, user_id):
    org = Organization.get_org(id=org_id)
    user = org.get_user(user_id)

    name = flask.request.json.get("name")
    if name:
        name = utils.filter_str(name)

    if "email" in flask.request.json:
        email = flask.request.json["email"]
        if email:
            user.email = utils.filter_str(email)
        else:
            user.email = None

    disabled = flask.request.json.get("disabled")
    if disabled is not None:
        user.disabled = disabled

    if name:
        user.rename(name)
    else:
        user.commit()
        Event(type=USERS_UPDATED, resource_id=user.org.id)

    if disabled:
        if user.type == CERT_CLIENT:
            LogEntry(message='Disabled user "%s".' % user.name)

        for server in org.iter_servers():
            server_clients = server.clients
            if user_id in server_clients:
                server.restart()
    elif disabled == False and user.type == CERT_CLIENT:
        LogEntry(message='Enabled user "%s".' % user.name)

    return utils.jsonify(user.dict())
Example #19
0
def user_key_link_get(org_id, user_id):
    org = Organization.get_org(id=org_id)
    return utils.jsonify(org.create_user_key_link(user_id))
Example #20
0
def user_otp_secret_put(org_id, user_id):
    org = Organization.get_org(id=org_id)
    user = org.get_user(user_id)
    user.generate_otp_secret()
    return utils.jsonify(user.dict())
Example #21
0
def user_post(org_id):
    org = Organization.get_org(id=org_id)
    name = utils.filter_str(flask.request.json['name'])
    user = org.new_user(CERT_CLIENT, name)
    return utils.jsonify(user.dict())
Example #22
0
def user_get(org_id, user_id=None, page=None):
    org = Organization.get_org(id=org_id)
    if user_id:
        return utils.jsonify(org.get_user(user_id).dict())
    else:
        page = flask.request.args.get("page", None)
        page = int(page) if page else page
        search = flask.request.args.get("search", None)
        limit = int(flask.request.args.get("limit", USER_PAGE_COUNT))
        otp_auth = False
        search_more = True
        server_count = 0
        clients = {}
        servers = []

        for server in org.iter_servers():
            servers.append(server)
            server_count += 1
            if server.otp_auth:
                otp_auth = True
            server_clients = server.clients
            for client_id in server_clients:
                client = server_clients[client_id]
                if client_id not in clients:
                    clients[client_id] = {}
                clients[client_id][server.id] = client

        users = []
        for user in org.iter_users(page=page, prefix=search, prefix_limit=limit):
            if user is None:
                search_more = False
                break
            is_client = user.id in clients
            user_dict = user.dict()
            user_dict["status"] = is_client
            user_dict["otp_auth"] = otp_auth
            server_data = []
            for server in servers:
                local_ip_addr, remote_ip_addr = server.get_ip_set(org_id, user.id)
                data = {
                    "id": server.id,
                    "name": server.name,
                    "status": is_client and server.id in clients[user.id],
                    "local_address": local_ip_addr,
                    "remote_address": remote_ip_addr,
                    "real_address": None,
                    "virt_address": None,
                    "bytes_received": None,
                    "bytes_sent": None,
                    "connected_since": None,
                }
                if is_client:
                    client_data = clients[user.id].get(server.id)
                    if client_data:
                        data.update(client_data)
                server_data.append(data)
            user_dict["servers"] = server_data
            users.append(user_dict)

        if page is not None:
            return utils.jsonify(
                {"page": page, "page_total": org.page_total, "server_count": server_count, "users": users}
            )
        elif search is not None:
            return utils.jsonify(
                {
                    "search": search,
                    "search_more": search_more,
                    "search_limit": limit,
                    "search_count": org.get_last_prefix_count(),
                    "search_time": round((time.time() - flask.g.start), 4),
                    "server_count": server_count,
                    "users": users,
                }
            )
        else:
            return utils.jsonify(users)
Example #23
0
def user_get(org_id, user_id=None, page=None):
    org = Organization.get_org(id=org_id)
    if user_id:
        return utils.jsonify(org.get_user(user_id).dict())
    else:
        page = flask.request.args.get('page', None)
        page = int(page) if page else page
        search = flask.request.args.get('search', None)
        limit = int(flask.request.args.get('limit', USER_PAGE_COUNT))
        otp_auth = False
        search_more = True
        server_count = 0
        clients = {}
        servers = []

        for server in org.iter_servers():
            servers.append(server)
            server_count += 1
            if server.otp_auth:
                otp_auth = True
            server_clients = server.clients
            for client_id in server_clients:
                client = server_clients[client_id]
                if client_id not in clients:
                    clients[client_id] = {}
                clients[client_id][server.id] = client

        users = []
        for user in org.iter_users(page=page, prefix=search,
                prefix_limit=limit):
            if user is None:
                search_more = False
                break
            is_client = user.id in clients
            user_dict = user.dict()
            user_dict['status'] = is_client
            user_dict['otp_auth'] = otp_auth
            server_data = []
            for server in servers:
                local_ip_addr, remote_ip_addr = server.get_ip_set(
                    org_id, user.id)
                data = {
                    'id': server.id,
                    'name': server.name,
                    'status': is_client and server.id in clients[user.id],
                    'local_address': local_ip_addr,
                    'remote_address': remote_ip_addr,
                    'real_address': None,
                    'virt_address': None,
                    'bytes_received': None,
                    'bytes_sent': None,
                    'connected_since': None,
                }
                if is_client:
                    client_data = clients[user.id].get(server.id)
                    if client_data:
                        data.update(client_data)
                server_data.append(data)
            user_dict['servers'] = server_data
            users.append(user_dict)

        if page is not None:
            return utils.jsonify({
                'page': page,
                'page_total': org.page_total,
                'server_count': server_count,
                'users': users,
            })
        elif search is not None:
            return utils.jsonify({
                'search': search,
                'search_more': search_more,
                'search_limit': limit,
                'search_count': org.get_last_prefix_count(),
                'search_time':  round((time.time() - flask.g.start), 4),
                'server_count': server_count,
                'users': users,
            })
        else:
            return utils.jsonify(users)
Example #24
0
def org_put(org_id):
    org = Organization.get_org(id=org_id)
    name = utils.filter_str(flask.request.json['name'])
    org.rename(name)
    return utils.jsonify(org.dict())
Example #25
0
def org_delete(org_id):
    org = Organization.get_org(id=org_id)
    org.remove()
    return utils.jsonify({})