Exemple #1
0
def update_endpoint(request, endpoint_key):
    user_name = request.session.get("user_name")
    domain_name = request.session.get("domain_name")
    if request.method == "GET":
        conn = SOAControlDBConnector.getInstance()
        params = (domain_name, endpoint_key)
        endpoint = conn.select_one(SELECT_ENDPOINT, params)
        metadata = json.loads(endpoint.get("metadata"))
        policy = metadata["ietf-i2nsf-cfi-policy:policy"]
        if endpoint.get("endpoint_type") == "url":
            endpoint["content"] = policy["threat-prevention"][
                "payload-content"][0]["content"][0]
        else:
            range_ip_address = policy["endpoint-group"][
                endpoint["endpoint_type"] + "-group"][0]["range-ip-address"][0]
            endpoint["start_ip_address"] = range_ip_address.get(
                "start-ip-address")
            endpoint["end_ip_address"] = range_ip_address.get("end-ip-address")

        return render(request, 'service/intent/endpoint/create_modal.html', {
            "modal_title": _(u"Endpoint 수정"),
            "endpoint": endpoint
        })
    elif request.is_ajax() and request.method == "POST":
        conn = SOAControlDBConnector.getInstance()
        params = (request.POST.get("name"), request.POST.get("metadata"),
                  request.POST.get("endpoint_type"), user_name, domain_name,
                  endpoint_key)
        result = conn.insert(UPDATE_ENDPOINT, params)
        return JsonResponse({"result": result})
Exemple #2
0
def update_rule(request, rule_key):
    domain_name = request.session.get("domain_name")
    user_name = request.session.get("user_name")
    if request.method == "GET":
        conn = SOAControlDBConnector.getInstance()

        params = (domain_name, rule_key)
        rule = conn.select_one(SELECT_FW_RULE, params)

        params = (domain_name)
        endpoints = conn.select(SELECT_ENDPOINT_LIST, params)

        src_list = []
        dest_list = []
        for endpoint in endpoints:
            metadata = json.loads(endpoint.get("metadata"))
            policy = metadata["ietf-i2nsf-cfi-policy:policy"]
            if endpoint.get("endpoint_type") == "url":
                endpoint["metadata_str"] = policy["threat-prevention"][
                    "payload-content"][0]["content"][0]
            else:
                range_ip_address = policy["endpoint-group"][
                    endpoint["endpoint_type"] +
                    "-group"][0]["range-ip-address"][0]
                endpoint["metadata_str"] = range_ip_address.get(
                    "start-ip-address") + " ~ "
                endpoint["metadata_str"] += range_ip_address.get(
                    "end-ip-address")

            if endpoint.get("endpoint_type") == "user":
                src_list.append(endpoint)
            else:
                dest_list.append(endpoint)

        resp_data = {
            "modal_title": request.GET.get("modal_title"),
            "rule": rule,
            "source_target": src_list,
            "destination_target": dest_list
        }
        return render(request, 'service/intent/rule/create_modal.html',
                      resp_data)
    elif request.method == "POST":
        conn = SOAControlDBConnector.getInstance()
        params = (request.POST.get("policy_name"),
                  request.POST.get("source_target"),
                  request.POST.get("destination_target"),
                  request.POST.get("start_time"), request.POST.get("end_time"),
                  request.POST.get("action_data"),
                  request.POST.get("description"), user_name, domain_name,
                  rule_key)
        rule = conn.update(UPDATE_FW_RULE, params)
        return JsonResponse({"success": True})
Exemple #3
0
def delete_endpoint(request, endpoint_key):
    domain_name = request.session.get("domain_name")
    if request.method == "POST":
        conn = SOAControlDBConnector.getInstance()
        params = (domain_name, endpoint_key)
        endpoint = conn.update(DELETE_ENDPOINT, params)
        return JsonResponse({"success": True})
Exemple #4
0
def create_domain(request):
    if request.method == 'POST' and request.is_ajax():
        domain_name = request.POST.get("domain_name")
        auth_url = request.POST.get("auth_url")
        description = request.POST.get("description")
        db_ip = request.POST.get("db_ip")
        db_port = request.POST.get("db_port")
        db_user = request.POST.get("db_user")
        db_pass = request.POST.get("db_pass")
        conn = SOAControlDBConnector.getInstance()
        params = (domain_name, auth_url, description, db_ip, db_port, db_user,
                  db_pass)
        conn.insert(INSERT_DOMAINS, params)
        cnt = conn.select_one(SELECT_DOMAINS_COUNT)
        conn.update(SET_SEQ_DOMAINS, (cnt.get("cnt"), domain_name))
        result = {
            "success": {
                "message": u"도메인 추가 성공",
                "title": u"성공",
                "code": 200
            }
        }
        try:
            soa_conn = SOAManagerDBConnector.getInstance()
            params = (domain_name, auth_url, description)
            soa_conn.insert(INSERT_SOAM_DOMAIN, params)
        except Exception as e:
            logger.debug(u"soa 도메인 추가 실패(" + domain_name + ")" + e.message)
        return JsonResponse(result)
Exemple #5
0
def delete_rule(request, rule_key):
    domain_name = request.session.get("domain_name")
    if request.method == "POST":
        conn = SOAControlDBConnector.getInstance()
        params = (domain_name, rule_key)
        rule = conn.update(DELETE_FW_RULE, params)
        return JsonResponse({"success": True})
Exemple #6
0
def update_domain(request, domain_key):
    if request.method == 'POST' and request.is_ajax():
        domain_name = request.POST.get("domain_name")
        auth_url = request.POST.get("auth_url")
        description = request.POST.get("description")
        db_ip = request.POST.get("db_ip")
        db_port = request.POST.get("db_port")
        db_user = request.POST.get("db_user")
        db_pass = request.POST.get("db_pass")
        conn = SOAControlDBConnector.getInstance()
        params = (domain_name, auth_url, description, db_ip, db_port, db_user,
                  db_pass, domain_key)
        conn.insert(UPDATE_DOMAINS, params)
        result = {
            "success": {
                "message": u"도메인 수정 성공",
                "title": u"성공",
                "code": 200
            }
        }
        try:
            origin_domain_name = request.POST.get("origin_domain_name")
            params = (domain_name, auth_url, description, origin_domain_name)
            soa_conn = SOAManagerDBConnector.getInstance()
            soa_conn.update(UPDATE_SOAM_DOMAIN, params)
        except Exception as e:
            logger.debug(u"soa 도메인 수정 실패(" + domain_name + ")" + e.message)
        return JsonResponse(result)
Exemple #7
0
def setting_domain_seqdown(request, domain_key):
    if request.method == "POST":
        conn = SOAControlDBConnector.getInstance()
        order_num = int(request.POST.get("seq"))
        pre_domain_key = request.POST.get("pre_domain_key")
        if pre_domain_key:
            conn.update(UPDATE_SEQ_DOMAIN, (order_num, pre_domain_key))
        conn.update(UPDATE_SEQ_DOMAIN, (order_num - 1, domain_key))
        return JsonResponse({"success": True})
Exemple #8
0
def alarms(request):
    """
    알람 수신
    :param request:
    :return:
    """
    if request.method == 'POST':
        logger.debug("[POST] alarm\n{}".format(request.body))
        data = json.loads(request.body)
        sendto = data.get("sendto")
        subject = data.get("subject")
        recovery_info = data.get("message")
        message = json.dumps(recovery_info)
        data = (
            subject,
            message,
            sendto
        )
        conn = SOAControlDBConnector()

        domain = conn.select_one(SELECT_DOMAINS_ONE_BY_AUTH_URL, recovery_info.get("auth_url"))
        db_user = domain.get("db_user")
        db_pass = domain.get("db_password")
        db_ip = domain.get("db_ip")
        db_port = domain.get("db_port")
        auth_url = domain.get("auth_url")
        d_conn = SOAControlDomainDBConnector(db_nm="soacgui", db_user=db_user, db_pass=db_pass, db_ip=db_ip, db_port=db_port)
        d_conn.insert(INSERT_ALARM, data)
        err_msg_list = []
        domain["os_admin_id"] = "admin"
        domain["os_admin_pass"] = "******"
        result_token = KeystoneRestAPI.get_token(auth_url, domain.get("os_admin_id"), domain.get("os_admin_pass"), domain.get("domain_name"), recovery_info.get("project_name"))
        if result_token.get("success"):
            if recovery_info.get("server"):
                nova = NovaRestAPI(auth_url, result_token["success"].get("token"))
                vm_id = recovery_info["server"].get("vm_id")
                result_is_exist_vm = nova.get_server(vm_id, ["id", "name"])
                if result_is_exist_vm.get("error") and result_is_exist_vm["error"].get("code") == 404:
                    message = "not Found vm(" + vm_id + ")"
                    data = (subject, message, sendto)
                    conn.insert(INSERT_ALARM, data)
                    return JsonResponse({"result": message})
                ctrl_header = get_ctrl_header_for_recorvery(auth_url, result_token["success"])
                result = recover_vm(recovery_info["server"], ctrl_header, domain)
                if result.get("success"):
                    recovery_info["recovery"] = True
                    conn.insert(INSERT_ALARM, (
                        subject, json.dumps(recovery_info), sendto
                    ))
                elif result.get("error"):
                    err_msg_list = result["error"]
        else:
            err_msg_list.append(result_token.get("error"))
        if len(err_msg_list) > 0:
            data = (
                subject, json.dumps(err_msg_list), sendto
            )
            d_conn.insert(INSERT_ALARM, data)
    return JsonResponse({"result": True})
Exemple #9
0
def setting_domain(request):
    if request.session.get("domain_admin"):
        conn = SOAControlDBConnector.getInstance()
        try:
            select_domains = conn.select(SELECT_DOMAINS)
            return render(request, 'domain/domain_setting.html',
                          {"domains": select_domains})
        except Exception as e:
            result = {"error": {"message": e.message, "title": u"에러"}}
            return render(request, 'domain/domain_setting.html', result)
Exemple #10
0
def get_endpoint_list(request):
    token = request.session.get('passToken')
    if not token:
        response = redirect("/dashboard")
    else:
        domain_name = request.session.get("domain_name")
        conn = SOAControlDBConnector.getInstance()
        params = (domain_name)
        endpoints = conn.select(SELECT_ENDPOINT_LIST, params)
        response = render(request, "service/intent/endpoint/index.html",
                          {"endpoints": endpoints})
    return response
Exemple #11
0
def get_rule_list(request):
    token = request.session.get('passToken')
    if not token:
        response = redirect("/dashboard")
    else:
        domain_name = request.session.get("domain_name")
        conn = SOAControlDBConnector.getInstance()
        params = (domain_name)
        rules = conn.select(SELECT_FW_RULE_LIST, params)
        response = render(request, "service/intent/rule/index.html",
                          {"rules": rules})
    return response
Exemple #12
0
def create_project_for_soa(request):
    if request.method == 'POST':
        result, data = login_soa(request)
        if result.get("success"):
            token = request.session.get("passToken")
            auth_url = data.get("auth_url")
            project = data.get("project")
            data = {
                "project": {
                    "name": project.get("name"),
                    "description": project.get("description"),
                    "domain_id": request.session.get("domain_id"),
                    "enabled": True,
                    "is_domain": False,
                }
            }

            keystone = KeystoneRestAPI(auth_url, token)
            result = keystone.create_project(data)
            if result.get("success"):  # 프로젝트 생성 성공
                project_id = result["success"]["project"].get("id")
                try:
                    soac_conn = SOAControlDBConnector.getInstance()
                    params = (auth_url, project_id, project.get("name"))
                    soac_conn.insert(INSERT_SOAC_PROJECT, params)
                except Exception as e:
                    logger.debug("soac 프로젝트 생성 실패(" + project.get("name") +
                                 ")" + str(e))
                    result = {
                        "error": {
                            "title": e.message,
                            "message": "soac db insert project error",
                            "code": 500
                        }
                    }

                try:
                    soam_conn = SOAManagerDBConnector.getInstance()
                    params = (auth_url, project_id, project.get("name"),
                              project.get("description"))
                    soam_conn.insert(INSERT_SOAM_PROJECT, params)
                except Exception as e:
                    logger.debug("soam 프로젝트 생성 실패(" + project.get("name") +
                                 ")" + str(e))
                    result = {
                        "error": {
                            "title": e.message,
                            "message": "soam db insert project error",
                            "code": 500
                        }
                    }

        return JsonResponse(result)
Exemple #13
0
def root_login(request):
    if request.method == "GET":
        return render(request, 'root_login.html')
    elif request.method == "POST":
        conn = SOAControlDBConnector.getInstance()
        params = (request.POST.get("user_id"), request.POST.get("user_pass"))
        user_info = conn.select_one(SELECT_USER, params)
        if user_info:
            request.session["domain_admin"] = True
            return redirect("/dashboard/domains")
        else:
            return render(request, 'root_login.html',
                          {"error": u"아이디 또는 비밀번호가 틀렸습니다."})
Exemple #14
0
def create_user_for_soa(request):
    if request.method == 'POST':
        result, data = login_soa(request)
        if result.get("success"):
            token = request.session.get("passToken")
            auth_url = data.get("auth_url")
            user_list = data.get("user")

            response_data = {}
            for user in user_list:
                data = {
                    "user": {
                        "default_project_id": user.get("default_project_id"),
                        "name": user.get("name"),
                        "password": user.get("password"),
                        "email": user.get("email"),
                        "domain_id": request.session.get("domain_id"),
                        "enabled": True,
                        "description": u"SOA 관리포털에서 생성"
                    }
                }

                keystone = KeystoneRestAPI(auth_url, token)
                result = keystone.create_user(data)
                if result.get("success"):
                    created_user = result["success"].get("user")

                    params = (auth_url, created_user.get("default_project_id"),
                              created_user.get("id"), created_user.get("name"))

                    try:
                        soa_conn = SOAControlDBConnector.getInstance()
                        soa_conn.insert(INSERT_SOAC_USER, params)
                    except Exception as e:
                        logger.debug("soac 사용자 생성 실패(" +
                                     created_user.get("name") + ")" + str(e))
                        result = {
                            "error": {
                                "title": e.message,
                                "message": "soac db insert user error",
                                "code": 500
                            }
                        }
                        # end except
                    # end if
                response_data[user.get("name")] = result
                # end for
            result = response_data
            # end if
        return JsonResponse(result)
Exemple #15
0
def create_endpoint(request):
    user_name = request.session.get("user_name")
    domain_name = request.session.get("domain_name")
    if request.is_ajax() and request.method == "POST":
        scr_api = SecurityControllerRestAPI()
        insert_result = scr_api.insert_endpoint(request.POST.get("metadata"))
        conn = SOAControlDBConnector.getInstance()
        params = (domain_name, request.POST.get("name"),
                  request.POST.get("metadata"),
                  request.POST.get("endpoint_type"), user_name, user_name)
        result = conn.insert(INSERT_ENDPOINT, params)
        return JsonResponse({"result": insert_result})
    else:
        return render(request, 'service/intent/endpoint/create_modal.html',
                      {"modal_title": _(u"Endpoint 생성")})
Exemple #16
0
def domain_modal(request, domain_key=None):
    modal_title = request.GET.get("modal_title")
    data = {"modal_title": modal_title}
    if domain_key:
        params = (domain_key)
        conn = SOAControlDBConnector.getInstance()
        try:
            select_domain = conn.select_one(SELECT_DOMAINS_ONE, params)
            data["domain"] = select_domain
        except Exception as e:
            return JsonResponse(
                {"error": {
                    "message": e.message,
                    "title": u"에러"
                }})
    return render(request, 'domain/modal.html', data)
Exemple #17
0
def delete_project(request, project_id):
    if request.is_ajax() and request.method == 'POST':
        token = request.session.get('passToken')
        auth_url = request.session.get('auth_url')
        keystone = KeystoneRestAPI(auth_url, token)
        result = keystone.delete_project(project_id)
        try:
            soac_conn = SOAControlDBConnector.getInstance()
            params = (request.session.get("domain_name"), project_id)
            project = soac_conn.select_one(
                SELECT_SOAC_PROJECT_LIST + "AND PROJECT_ID = %s", )
            if project:
                soam_conn = SOAManagerDBConnector.getInstance()
                soam_conn.update(DELETE_SOAM_PROJECT, params)
        except Exception as e:
            pass
        return JsonResponse(result)
Exemple #18
0
def get_domains(request):
    if request.session.get("domain_admin"):
        conn = SOAControlDBConnector.getInstance()
        next_url = request.GET.get("next")
        select_domains = conn.select(SELECT_DOMAINS)
        pattern = re.compile("https?://(\d+\.\d+\.\d+\.\d+):?\d+/?v?3?", re.I)
        for domain in select_domains:
            matcher = re.match(pattern, domain.get("auth_url"))
            if matcher:
                domain["ip"] = matcher.group(1)
        request.session["available_domains"] = select_domains
        return render(request, 'domain/domain.html', {
            "domains": select_domains,
            "next_url": next_url
        })
    else:
        return redirect('/login')
Exemple #19
0
def delete_domain(request, domain_key):
    if request.method == 'POST' and request.is_ajax():
        domain_name = request.POST.get("domain_name")
        conn = SOAControlDBConnector.getInstance()
        params = (domain_key)
        conn.delete(DELETE_DOMAINS, params)
        result = {
            "success": {
                "message": u"도메인 삭제 성공",
                "title": u"성공",
                "code": 200
            }
        }
        try:
            params = (domain_name)
            soa_conn = SOAManagerDBConnector.getInstance()
            soa_conn.update(DELETE_SOAM_DOMAIN, params)
        except Exception as e:
            logger.debug(u"soa 도메인 삭제 실패(" + domain_name + ")" + e.message)

        return JsonResponse(result)
Exemple #20
0
def create_user_for_soa(request):
    if request.method == 'POST':
        # try:
            # body_str = request.body.decode('utf-8')
            # r_body = json.loads(body_str)
        # except ValueError as e:
        # result = {"error": {"title": e.message, "message": "json malformed error"}}
        # else:
        auth_url = request.GET.get("auth_url")
        user_name = request.GET.get("user_name")
        password = request.GET.get("pass")
        project_name = request.GET.get("project_name")
        soac_conn = SOAControlDBConnector.getInstance()
        domain = soac_conn.select_one(SELECT_SOAC_DOMAINS, auth_url)
        domain_name = domain.get("domain_name")
        result = common_login(request, auth_url, user_name, password, domain_name, project_name)

        if result.get("success"):
            token = request.session.get("passToken")
            project = json.loads(request.GET.get("project"))
            data = {"project": {
                "description": project.get("description"),
                "domain_id": request.session.get("domain_id"),
                "name": project.get("name"),
                "enabled": True,
                "is_domain": False,
            }}
            keystone = KeystoneRestAPI(auth_url, token)
            result = keystone.create_project(data)
            if result.get("success"):  # 프로젝트 생성 성공
                soam_conn = SOAManagerDBConnector.getInstance()
                domain = soam_conn.select_one(SELECT_SOAM_DOMAIN, auth_url)
                params = (domain.get("domain_id"), result["success"]["project"].get("id"), project.get("name"), project.get("description"))
                soam_conn.insert(INSERT_SOAM_PROJECT, params)

                params = (auth_url, result["success"]["project"].get("id"), project.get("name"))
                soac_conn.insert(INSERT_SOAC_PROJECT, params)

        return JsonResponse(result)
Exemple #21
0
def endpoints(request):
    if request.method == "GET":
        domain_name = request.session.get("domain_name")
        conn = SOAControlDBConnector.getInstance()
        params = (domain_name)
        endpoints = conn.select(SELECT_ENDPOINT_LIST, params)
        for endpoint in endpoints:
            metadata = json.loads(endpoint.get("metadata"))
            policy = metadata["ietf-i2nsf-cfi-policy:policy"]
            if endpoint.get("endpoint_type") == "url":
                endpoint["metadata_str"] = policy["threat-prevention"][
                    "payload-content"][0]["content"][0]
            else:
                range_ip_address = policy["endpoint-group"][
                    endpoint["endpoint_type"] +
                    "-group"][0]["range-ip-address"][0]
                endpoint["metadata_str"] = range_ip_address.get(
                    "start-ip-address") + " ~ "
                endpoint["metadata_str"] += range_ip_address.get(
                    "end-ip-address")
        return render(request, "service/intent/endpoint/index.html",
                      {"endpoints": endpoints})
Exemple #22
0
def delete_user_for_soa(request):
    if request.method == 'POST':
        result, data = login_soa(request)
        if result.get("success"):
            token = request.session.get("passToken")
            auth_url = data.get("auth_url")
            user_list = json.loads(data.get("user"))

            response_data = {}
            for user_id in user_list:
                keystone = KeystoneRestAPI(auth_url, token)
                result = keystone.delete_user(user_id)
                if result.get("success"):
                    deleted_user = result["success"].get("user")

                    params = (auth_url, user_id)

                    try:
                        soa_conn = SOAControlDBConnector.getInstance()
                        soa_conn.delete(INSERT_SOAC_USER, params)
                    except Exception as e:
                        logger.debug("soac 사용자 삭제 실패(" +
                                     deleted_user.get("name") + ")" + str(e))
                        result = {
                            "error": {
                                "title": e.message,
                                "message": "soac db insert user error",
                                "code": 500
                            }
                        }
                        # end except
                    # end if
                response_data[user_id.get("name")] = result
                # end for
            result = response_data
            # end if

        return JsonResponse(result)
Exemple #23
0
def admin_login_soa(request):
    if request.method == 'POST':
        user_name = request.POST.get("user_name")
        password = request.POST.get("pass")
        auth_url = request.POST.get("auth_url")
        project_name = request.POST.get("project_name")
        logger.info("{}\n{}\n{}\n{}".format(user_name, password, auth_url,
                                            project_name))

        conn = SOAControlDBConnector.getInstance()
        try:
            select_domain = conn.select_one(SELECT_SOAC_DOMAINS, auth_url)
            domain_name = select_domain.get("domain_name")

        except Exception as e:
            result = {"error": {"message": str(e), "title": "error"}}
            logger.info("ajaxLoginPOST_error_end")
            return JsonResponse(result)

        result = common_login(request, auth_url, user_name, password,
                              domain_name, project_name)
        logger.info("ajaxLoginPOST_end: {}".format(result))
        return JsonResponse(result)
Exemple #24
0
def get_rule(request, rule_key):
    domain_name = request.session.get("domain_name")
    conn = SOAControlDBConnector.getInstance()

    params = (domain_name, rule_key)
    rule = conn.select_one(SELECT_FW_RULE, params)

    params = (domain_name, rule.get("source_target"))
    src = conn.select_one(SELECT_ENDPOINT, params)
    if src:
        metadata = json.loads(src.get("metadata"))
        policy = metadata["ietf-i2nsf-cfi-policy:policy"]
        range_ip_address = policy["endpoint-group"][
            src["endpoint_type"] + "-group"][0]["range-ip-address"][0]
        src["metadata_str"] = range_ip_address.get("start-ip-address") + " ~ "
        src["metadata_str"] += range_ip_address.get("end-ip-address")

    params = (domain_name, rule.get("destination_target"))
    dest = conn.select_one(SELECT_ENDPOINT, params)
    if dest:
        metadata = json.loads(dest.get("metadata"))
        policy = metadata["ietf-i2nsf-cfi-policy:policy"]
        if dest.get("endpoint_type") == "url":
            dest["metadata_str"] = policy["threat-prevention"][
                "payload-content"][0]["content"][0]
        else:
            range_ip_address = policy["endpoint-group"][
                dest["endpoint_type"] + "-group"][0]["range-ip-address"][0]
            dest["metadata_str"] = range_ip_address.get(
                "start-ip-address") + " ~ "
            dest["metadata_str"] += range_ip_address.get("end-ip-address")

    rule["source_target"] = src
    rule["destination_target"] = dest

    return render(request, "service/intent/rule/info.html", {"rule": rule})
Exemple #25
0
def login_soa(request):
    data = None
    try:
        data = json.loads(request.POST.get("data"))
    except ValueError as e:
        result = {
            "error": {
                "title": e.message,
                "message": "json malformed error"
            }
        }
    else:
        auth_url = data.get("auth_url")
        user_name = data.get("user_name")
        password = data.get("pass")
        project_name = data.get("project_name")
        soac_conn = SOAControlDBConnector.getInstance()
        if auth_url == request.session.get("auth_url"):
            domain_name = request.session.get("domain_name")
        else:
            domain = soac_conn.select_one(SELECT_SOAC_DOMAINS, auth_url)
            domain_name = domain.get("domain_name")

        token = None
        roles = None
        roles_str = None
        project_id = None
        user_id = None
        keystone = None

        # =================================Scope Login==================================
        result = KeystoneRestAPI.get_token(auth_url, user_name, password,
                                           domain_name, project_name)
        # if type(result) == str:
        #     result = ast.literal_eval(result)  # str 타입을 dictionary 타입으로 바꿈
        if result.get('success'):
            user = result["success"].get("user")
            domain_id = user["domain"].get("id")
            if not roles:
                roles = result["success"].get("roles")
            request.session["domain_id"] = domain_id
            token = result['success']['token']
            user_id = user.get("id")
            if keystone is None:
                keystone = KeystoneRestAPI(auth_url, token)
            keystone.update_token(token)

            roles_str = ','.join(role.get("name") for role in roles)

            ctrl_engine = ControlEngine(token=token,
                                        project_id=project_id,
                                        project_name=project_name,
                                        user_id=user_id,
                                        user_name=user_name,
                                        roles=roles_str,
                                        auth_url=auth_url)
            request.session["ctrl_header"] = ctrl_engine.get_header()
        # ================================================
        request.session["passToken"] = token
        request.session["user_name"] = user_name
        request.session["domain_name"] = domain_name
        request.session["project_name"] = project_name
        request.session["auth_url"] = auth_url
        if roles_str:
            request.session["roles"] = roles_str
        else:
            request.session["roles"] = None
        if user_id:
            request.session["user_id"] = user_id
        if project_id:
            request.session["project_id"] = project_id

    return result, data
Exemple #26
0
def synchronize_soam(request, service_info, data_dic):
    # 관리포탈 동기화용
    conn = SOAControlDBConnector.getInstance()

    user_name = request.session.get("user_name")
    # 도메인명, 프로젝트 아이디, 서비스 아이디, 서비스명, 서비스 상태,
    # 동기화 상태{동기화전 I, 동기화중 S, 동기화완료 C, 동기화실패 F}, 동기화 날짜
    auth_url = request.session.get("auth_url")
    project_id = request.session.get("project_id")
    params = (auth_url, project_id, service_info.get("service_id"),
              service_info.get("name"), service_info.get("status"), user_name,
              user_name)

    logger.debug("[soac db insert service for sync]")
    # conn.insert(INSERT_SOAC_SERVICE, params)  # sync를 위해 soacDB에 넣기

    control = ControlEngine(request.session.get("ctrl_header"))
    s_result = control.get_service(service_info.get("service_id"))
    if s_result.get("success"):
        # used_security_group_list 상세정보 조회, security_group_list 생성
        select_security_groups = conn.select(
            SELECT_SECURITY_RESOURCE_GROUP_LIST)

        security_groups = data_dic.get("used_security_group_list")
        security_group_list = []
        for security_group in security_groups:
            for select_security_group in select_security_groups:
                if select_security_group.get(
                        "security_id") == security_group.get("security_id"):
                    select_security_group[
                        "security_type"] = security_group.get("security_type")
                    security_group_list.append(select_security_group)

        m_conn = SOAManagerDBConnector.getInstance()
        # security_group
        # TODO: seccurity_type => 관리포탈에서 코드조회후 코드로 넣을것
        # TODO: manufacture_icon
        # TODO: 보안장비가 이미 등록되 있을시 무시
        for security_group in security_group_list:
            params = (security_group.get("security_type"),
                      security_group.get("security_name"),
                      security_group.get("security_icon"),
                      security_group.get("manufacture_name"),
                      security_group.get("manufacture_icon"),
                      security_group.get("software_version"),
                      security_group.get("description"))

            logger.debug("[soam db insert equipment]")
            m_conn.insert(INSERT_SOAM_EQUIPMENT, params)

        params = (auth_url, project_id, service_info.get("service_id"),
                  service_info.get("name"),
                  service_info.get("service_description"))
        logger.debug("[soam db insert service]")
        m_conn.insert_service(params, data_dic)

        scheduler = Scheduler()

        def check_service_status():
            logger.debug("[check service status]")
            create_status = False
            # 서비스 상태 확인
            result = control.get_service(service_info.get("service_id"))
            if result.get("success"):
                try:
                    service_template = result["success"].get("service_detail")

                    # 생성중이면 1분뒤 다시 확인
                    if service_template.get("status") == "CREATE_IN_PROGRESS":
                        logger.debug("[wait CREATE_IN_PROGRESS]")
                        return
                    # 생성 완료면 자원 데이터 저장
                    elif service_template.get("status") == "CREATE_COMPLETE":
                        logger.debug("[soam db insert resources]")
                        params = (auth_url, project_id,
                                  service_info.get("service_id"),
                                  service_info.get("name"),
                                  service_info.get("service_description"))
                        m_conn.insert_service_resource(params,
                                                       service_template,
                                                       request)

                    # 생성 실패면
                    else:
                        pass

                    # 생성 완료 or 실패 시 soac db 수정
                    logger.debug("[soac db update service for sync complete]")
                    # params = (service_template.get("name"), service_template.get("status"), "C", user_name, auth_url,
                    #           request.session.get("project_name"), service_info.get("service_id"))
                    # conn.update(UPDATE_SOAC_SERVICE, params)
                    scheduler.kill_scheduler("check_service")
                except Exception as e:
                    error_str = """
                    Title: {}
                    Traceback: {}
                    """.format(e.message,
                               traceback.format_exc().strip())
                    logger.error(error_str)
                    scheduler.kill_scheduler("check_service")
            else:
                scheduler.kill_scheduler("check_service")

        logger.debug("[wait CREATE_IN_PROGRESS]")
        scheduler.schedule_interval(check_service_status,
                                    "check_service",
                                    seconds=30)
Exemple #27
0
def user_login(request):
    pattern = re.compile("https?://(\d+\.\d+\.\d+\.\d+):?\d+/?v?3?", re.I)
    if request.method == 'POST':
        domain_key = request.POST.get("domain_key")
        if domain_key:
            conn = SOAControlDBConnector.getInstance()
            domain = conn.select_one(SELECT_DOMAINS_ONE, (domain_key))
            auth_url = domain.get("auth_url")
            domain_name = domain.get("domain_name")

        else:
            domain_name = request.POST.get("domain_name")
            auth_url = request.POST.get("auth_url")
        user_name = request.POST.get("user_name")
        password = request.POST.get("pass")
        project_name = request.POST.get("project_name")
        matcher = pattern.match(auth_url)
        if matcher:
            ip = matcher.group(1)
            request.session["ip"] = ip

        result = common_login(request, auth_url, user_name, password,
                              domain_name, project_name)
        ip = request.session.get("ip")

        if request.is_ajax():
            # 팝업에서 로그인
            logger.info("ajaxLoginPOST")
            if result.get('success'):
                description = request.POST.get("description")
                if description:
                    request.session["description"] = description
                response = JsonResponse({'success': "login"})
                logger.info("ajaxLoginPOST_end")
                return response

            else:
                logger.info("ajaxLoginPOST_error_end")
                return JsonResponse(result)

        else:
            # 페이지에서 로그인
            logger.info("userLoginPOST")
            next_url = request.GET.get("next")
            if result.get('success'):
                if not next_url:
                    next_url = '/dashboard/service'
                response = redirect(next_url)
                request.session["referrer"] = None
                response.delete_cookie('domain_name')
                response.delete_cookie('project_name')
                response.delete_cookie('user_name')
                response.delete_cookie('pass')
                response.delete_cookie('save')
                logger.info("userLoginPOST_end")
                return response
            if result.get('error'):
                logger.info("userLoginPOST_error_end: {}".format(result))
                description = request.session.get("description")
                return render(
                    request, 'login.html', {
                        'error': result["error"],
                        "ip": ip,
                        "auth_url": auth_url,
                        "domain_name": domain_name,
                        "description": description
                    })
        return JsonResponse({"error": {"message": "원인불명", "title": "로그인실패"}})
    else:
        domain_key = request.GET.get("domain_key")
        project_name = request.GET.get("project_name")
        if not domain_key:
            return redirect("/dashboard/domains")
        conn = SOAControlDBConnector.getInstance()
        domain = conn.select_one(SELECT_DOMAINS_ONE, (domain_key))
        description = domain.get("description")
        auth_url = domain.get("auth_url")
        domain_name = domain.get("domain_name")
        db_ip = domain.get("db_ip")
        db_user = domain.get("db_user")
        db_pass = domain.get("db_password")
        db_port = domain.get("db_port")
        request.session["domain_db_ip"] = db_ip
        request.session["domain_db_user"] = db_user
        request.session["domain_db_pass"] = db_pass
        request.session["domain_db_port"] = db_port
        request.session["domain_db_nm"] = "soacgui"
        request.session["description"] = description
        request.session["auth_url"] = auth_url
        request.session["domain_name"] = domain_name
        matcher = pattern.match(auth_url)
        if matcher:
            ip = matcher.group(1)
            request.session["ip"] = ip

        data = {
            "ip": ip,
            "auth_url": auth_url,
            "domain_name": domain_name,
            "description": description
        }

        if project_name:
            data["project_name"] = project_name

        return render(request, 'login.html', data)
Exemple #28
0
def set_database(request):
    if request.method == 'POST':
        message = ""
        domain_key = request.POST.get("domain_key")
        conn = SOAControlDBConnector.getInstance()
        domain = conn.select_one(SELECT_DOMAINS_ONE, (domain_key))
        db_ip = domain.get("db_ip")
        db_user = domain.get("db_user")
        db_pass = domain.get("db_password")
        db_port = domain.get("db_port")
        try:
            message = db_ip + ":" + str(db_port) + u" 접속"
            conn = SOAControlDomainDBConnector(db_user=db_user,
                                               db_pass=db_pass,
                                               db_ip=db_ip,
                                               db_port=db_port)
            try:
                message = u"soacgui DB 생성"
                conn.execute(CREATE_DATABASE)
            except ProgrammingError:  # 이미존재
                pass
            message = db_ip + ":" + str(db_port) + u" soacgui 접속"
            conn = SOAControlDomainDBConnector(db_nm="soacgui",
                                               db_user=db_user,
                                               db_pass=db_pass,
                                               db_ip=db_ip,
                                               db_port=db_port)
            try:
                message = u"tb_security_resource_group Table 생성"
                conn.execute(CREATE_SECURITY_RESOURCE_GROUP_TABLE)
            except InternalError:  # 이미존재
                pass
            try:
                message = u"tb_security_resource_group Trigger 생성"
                conn.execute(CREATE_SECURITY_RESOURCE_GROUP_TRIGGER)
            except NotSupportedError:
                pass

            message = db_ip + ":" + str(db_port) + u" 접속"
            conn = SOAControlDomainDBConnector(db_user=db_user,
                                               db_pass=db_pass,
                                               db_ip=db_ip,
                                               db_port=db_port)
            message = u" ctrl_engine DB 생성"
            conn.execute(CREATE_ENGINE_DATABASE)
            message = db_ip + ":" + str(db_port) + u" ctrl_engine 접속"
            conn = SOAControlDomainDBConnector(db_nm="ctrl_engine",
                                               db_user=db_user,
                                               db_pass=db_pass,
                                               db_ip=db_ip,
                                               db_port=db_port)
            message = u"service_allocation Table 생성"
            conn.execute(CREATE_ENGINE_SESRVICE_ALLOCATION_TABLE)
            message = u"stack_template Table 생성"
            conn.execute(CREATE_ENGINE_STACK_TEMPLATE_TABLE)
            message = u"sfc Table 생성"
            conn.execute(CREATE_ENGINE_SFC_TABLE)
            message = u"map Table 생성"
            conn.execute(CREATE_ENGINE_MAP_TABLE)
            return JsonResponse({
                "success": {
                    "message": u"DB 생성 완료",
                    "code": 200,
                    "title": "Success"
                }
            })
        except Exception as e:
            return JsonResponse({
                "error": {
                    "message": "{!r}".format(e),
                    "code": 500,
                    "title": message + u" 실패"
                }
            })
Exemple #29
0
def new_service(request):
    if request.method == "GET":
        return render(request, "service/intent/new_service.html", {})
    elif request.is_ajax() and request.method == 'POST':
        logger.info("newIntentServicePOST")
        token = request.session.get("passToken")
        auth_url = request.session.get("auth_url")
        domain_name = request.session.get("domain_name")
        rule_key = request.POST.get("rule_key")

        neutron = NeutronRestAPI(auth_url, token)
        result = neutron.get_network_list()
        if result.get("success"):
            public_network = filter(lambda network: network["router:external"],
                                    result["success"]["networks"])

            conn = SOAControlDBConnector.getInstance()
            # rule
            params = (domain_name, rule_key)
            rule = conn.select_one(SELECT_FW_RULE, params)
            # source target
            params = (domain_name, rule.get("source_target"))
            src = conn.select_one(SELECT_ENDPOINT, params)
            # destination target
            params = (domain_name, rule.get("destination_target"))
            dest = conn.select_one(SELECT_ENDPOINT, params)

            json_param = {
                "ietf-i2nsf-cfi-policy:policy": {
                    "policy-name":
                    rule.get("policy_name"),
                    "rule": [{
                        "rule-name": "rule_name",
                        "condition": {
                            "firewall-condition": {
                                "source-target": {
                                    "src-target": src.get("name")
                                }
                            },
                            "custom-condition": {
                                "destination-target": {
                                    "dest-target": dest.get("name")
                                }
                            }
                        },
                        "action": {
                            "primary-action": rule.get("action_data")
                        }
                    }]
                }
            }

            if rule.get("start_time") and rule.get("end_time"):
                json_param["ietf-i2nsf-cfi-policy:policy"]["rule"][0][
                    "event"] = {
                        "time-information": {
                            "begin-time": rule.get("start_time"),
                            "end-time": rule.get("end_time")
                        }
                    }

            # sec_ctrl = SecurityControllerRestAPI()
            # result = sec_ctrl.get_service_template_by_rule(json_param)  # {"nsf_names": ["time_based_firewall", "url_filtering"]}
            # result = {"nsf_names": ["url_filtering"]}
            # result = {"nsf_names": ["time_based_firewall", "url_filtering"]}
            nsf_names = result.get("nsf_names")
            service_template = conn.select_service_template_by_nsf_names(
                nsf_names)
            logger.info("\n\n\n\nservice: {}\n\n\n".format(service_template))
            # params = (template_key, domain_name)
            # security_types = conn.select_one(SELECT_SECURITY_RESOURCE_GROUP_BY_TEMPLATE_KEY, params)
            link_json = json.loads(
                service_template.get("link_json").replace("\\", ""))
            links = link_json.get("links", [])
            as_links = link_json.get("asLinks", [])
            resources = link_json.get("resources", [])
            security_types = link_json.get("security_types", [])

            json_data = {
                'success': {
                    "service_detail":
                    json.loads(service_template.get("topology_json"))
                },
                "asLinks": as_links,
                "public_network": public_network,
                "service_template": service_template,
                "security_types": security_types,
                "links": links
            }

            return JsonResponse(json_data)
        else:
            return JsonResponse(result)