Ejemplo n.º 1
0
def get_session_id(session, request):
    """
    Looks up the session ID in the HTTP session, request URL and body
    :type session: flask.session
    :type request: flask.request
    """
    session_id = None

    # Look if HTTP session is being used
    if session is not None:
        session_id = session.get('session_id', session_id)

    # Look if form data is being used
    if request.form:
        session_id = request.form.get('session_id', session_id)

    # Look if body contains session ID
    json = request.get_json(silent=True)
    if json is not False and json is not None:
        session_id = json.get('session_id', session_id)

    # Check if the session ID is provided by query parameters
    session_id = request.args.get('session_id', session_id)

    if session_id is None:
        raise MissingParameterHTTPError(param_names=['session_id'])

    return session_id
Ejemplo n.º 2
0
    def update_role(self, role, name=None, role_id=-1):
        if name is not None:
            old_role = self.get_role_by_name(name, simplify=False)
            if role is None:
                self.close()
                raise ObjectNotFoundHTTPError('The asset')
            role_id = old_role.theId

        if role_id > -1:
            params = RoleParameters(
                name=role.theName,
                rType=role.theType,
                sCode=role.theShortCode,
                desc=role.theDescription,
                cProperties=[]
            )
            params.setId(role_id)

            try:
                self.db_proxy.updateRole(params)
            except ARM.DatabaseProxyException as ex:
                self.close()
                raise ARMHTTPError(ex)
        else:
            self.close()
            raise MissingParameterHTTPError(param_names=['id'])
Ejemplo n.º 3
0
def check_required_keys(json_dict, required):
    """
    :return:
    :raise MissingParameterHTTPError:
    """
    if not all(reqKey in json_dict for reqKey in required):
        raise MissingParameterHTTPError(param_names=required)
Ejemplo n.º 4
0
    def update_threat(self, threat, name=None, threat_id=None):
        if name is not None:
            found_threat = self.get_threat_by_name(name, simplify=False)
        elif threat_id is not None:
            found_threat = self.get_threat_by_id(threat_id, simplify=False)
        else:
            self.close()
            raise MissingParameterHTTPError(param_names=['name'])

        threat_params = ThreatParameters(
            threatName=threat.theThreatName,
            thrType=threat.theType,
            thrMethod=threat.theMethod,
            tags=threat.theTags,
            cProperties=threat.theEnvironmentProperties)
        threat_params.setId(found_threat.theId)

        try:
            if self.check_existing_threat(name):
                self.db_proxy.updateThreat(threat_params)
        except ARM.DatabaseProxyException as ex:
            self.close()
            raise ARMHTTPError(ex)
        except ARM.ARMException as ex:
            self.close()
            raise ARMHTTPError(ex)
Ejemplo n.º 5
0
    def get_dbproxy(self, session_id):
        """
        Searches the MySQLDatabaseProxy instance associated with the session ID.
        :param
            session_id: The session ID
        :type
            session_id: str
        :rtype
            MySQLDatabaseProxy
        :return
            The MySQLDatabaseProxy instance associated with the session ID
        :raise
            CairisHTTPError
        """
        if session_id:
            b = Borg()
            db_proxy = b.get_dbproxy(session_id)

            if db_proxy is None:
                raise CairisHTTPError(
                    status_code=httplib.CONFLICT,
                    message='The database connection could not be created.')
            elif isinstance(db_proxy, MySQLDatabaseProxy):
                db_proxy.reconnect(session_id=session_id)
                return db_proxy
            else:
                raise CairisHTTPError(
                    status_code=httplib.CONFLICT,
                    message=
                    'The database connection was not properly set up. Please try to reset the connection.'
                )
        else:
            raise MissingParameterHTTPError(param_names=['session_id'])
Ejemplo n.º 6
0
    def convert_scores(self, real_scores=None, fake_scores=None):
        new_scores = []
        if real_scores:
            if len(real_scores) > 0:
                for idx in range(0, len(real_scores)):
                    real_score = real_scores[idx]
                    if len(real_score) == 4:
                        new_score = RiskScore(response_name=real_score[0],
                                              unmit_score=real_score[1],
                                              mit_score=real_score[2],
                                              details=real_score[3])
                        new_scores.append(new_score)
        elif fake_scores:
            if len(fake_scores) > 0:
                for idx in range(0, len(fake_scores)):
                    fake_score = fake_scores[idx]
                    assert isinstance(fake_score, RiskScore)
                    check_required_keys(fake_score, RiskScore.required)
                    if fake_score['unmitScore'] == -1:
                        fake_score['unmitScore'] = None
                    if fake_score['mitScore'] == -1:
                        fake_score['mitScore'] = None
                    new_score = (fake_score['responseName'],
                                 fake_score['unmitScore'],
                                 fake_score['mitScore'], fake_score['details'])
                    new_scores.append(new_score)
        else:
            self.close()
            raise MissingParameterHTTPError(param_names=['scores'])

        return new_scores
Ejemplo n.º 7
0
    def update_vulnerability(self, vulnerability, name=None, vuln_id=None):
        if name is not None:
            found_vulnerability = self.get_vulnerability_by_name(
                name, simplify=False)
        elif vuln_id is not None:
            found_vulnerability = self.get_vulnerability_by_id(vuln_id,
                                                               simplify=False)
        else:
            self.close()
            raise MissingParameterHTTPError(param_names=['name'])

        vuln_params = VulnerabilityParameters(
            vulName=vulnerability.theVulnerabilityName,
            vulDesc=vulnerability.theVulnerabilityDescription,
            vulType=vulnerability.theVulnerabilityType,
            tags=vulnerability.theTags,
            cProperties=vulnerability.theEnvironmentProperties)
        vuln_params.setId(found_vulnerability.theVulnerabilityId)

        try:
            if self.check_existing_vulnerability(name):
                self.db_proxy.updateVulnerability(vuln_params)
        except ARM.DatabaseProxyException as ex:
            self.close()
            raise ARMHTTPError(ex)
        except ARM.ARMException as ex:
            self.close()
            raise ARMHTTPError(ex)
Ejemplo n.º 8
0
    def convert_properties(self, real_props=None, fake_props=None):
        new_props = []
        if real_props is not None:
            for real_prop in real_props:
                assert isinstance(real_prop, GoalEnvironmentProperties)

                new_concern_assocs = []
                for concern_assoc in real_prop.theConcernAssociations:
                    new_concern_assocs.append(list(concern_assoc))

                new_goal_refinements = []
                for goal_refinement in real_prop.theGoalRefinements:
                    new_goal_refinements.append(list(goal_refinement))

                new_subgoal_refinements = []
                for subgoal_refinement in real_prop.theSubGoalRefinements:
                    new_subgoal_refinements.append(list(subgoal_refinement))

                real_prop.theConcernAssociations = new_concern_assocs
                real_prop.theGoalRefinements = new_goal_refinements
                real_prop.theSubGoalRefinements = new_subgoal_refinements
                new_props.append(real_prop)
        elif fake_props is not None:
            for fake_prop in fake_props:
                check_required_keys(fake_prop,
                                    GoalEnvironmentPropertiesModel.required)

                new_concern_assocs = []
                for concern_assoc in fake_prop['theConcernAssociations']:
                    new_concern_assocs.append(tuple(concern_assoc))

                new_goal_refinements = []
                for goal_refinement in fake_prop['theGoalRefinements']:
                    new_goal_refinements.append(tuple(goal_refinement))

                new_subgoal_refinements = []
                for subgoal_refinement in fake_prop['theSubGoalRefinements']:
                    new_subgoal_refinements.append(tuple(subgoal_refinement))

                new_prop = GoalEnvironmentProperties(
                    environmentName=fake_prop['theEnvironmentName'],
                    lbl=fake_prop['theLabel'],
                    definition=fake_prop['theDefinition'],
                    category=fake_prop['theCategory'],
                    priority=fake_prop['thePriority'],
                    fitCriterion=fake_prop['theFitCriterion'],
                    issue=fake_prop['theIssue'],
                    goalRefinements=new_goal_refinements,
                    subGoalRefinements=new_subgoal_refinements,
                    concs=fake_prop['theConcerns'],
                    cas=new_concern_assocs,
                )
                new_props.append(new_prop)
        else:
            self.close()
            raise MissingParameterHTTPError(
                param_names=['real_props', 'fake_props'])

        return new_props
Ejemplo n.º 9
0
    def convert_props(self, real_props=None, fake_props=None):
        new_props = []
        if real_props is not None:
            if len(real_props) > 0:
                assert isinstance(real_props[0], ThreatEnvironmentProperties)
                for real_prop in real_props:
                    assert isinstance(real_prop, ThreatEnvironmentProperties)
                    assert len(real_prop.theProperties) == len(
                        real_prop.theRationale)
                    new_attrs = []
                    for idx in range(0, len(real_prop.theProperties)):
                        attr_name = self.rev_attr_dict.get(idx)
                        attr_value = self.prop_dict[
                            real_prop.theProperties[idx]]
                        attr_rationale = real_prop.theRationale[idx]
                        new_attr = SecurityAttribute(attr_name, attr_value,
                                                     attr_rationale)
                        new_attrs.append(new_attr)
                    real_prop.theProperties = new_attrs
                    new_props.append(real_prop)

            return new_props
        elif fake_props is not None:
            if len(fake_props) > 0:
                check_required_keys(fake_props[0],
                                    ThreatEnvironmentPropertiesModel.required)
                for fake_prop in fake_props:
                    check_required_keys(
                        fake_prop, ThreatEnvironmentPropertiesModel.required)
                    new_ndprops = array([0] * 8).astype(numpy.core.int32)
                    new_ratios = ['None'] * 8
                    for idx in range(0, len(fake_prop['theProperties'])):
                        new_attr = fake_prop['theProperties'][idx]
                        check_required_keys(new_attr,
                                            SecurityAttribute.required)
                        attr_id = self.attr_dict.get(new_attr['name'], -1)
                        if -1 < attr_id < len(self.attr_dict):
                            attr_value = self.rev_prop_dict[new_attr['value']]
                            attr_rationale = new_attr['rationale']
                            new_ndprops[attr_id] = attr_value
                            new_ratios[attr_id] = attr_rationale
                    fake_prop['theProperties'] = new_ndprops
                    fake_prop['theRationale'] = new_ratios
                    new_prop = ThreatEnvironmentProperties(
                        environmentName=fake_prop['theEnvironmentName'],
                        lhood=fake_prop['theLikelihood'],
                        assets=fake_prop['theAssets'],
                        attackers=fake_prop['theAttackers'],
                        pRationale=fake_prop['theRationale'],
                        syProperties=fake_prop['theProperties'])
                    new_props.append(new_prop)

            return new_props
        else:
            self.close()
            raise MissingParameterHTTPError(
                param_names=['real_props', 'fake_props'])
Ejemplo n.º 10
0
    def post(self):
        session_id = get_session_id(session, request)

        if session_id is None:
            raise CairisHTTPError(
                status_code=httplib.BAD_REQUEST,
                message=
                'The session is neither started or no session ID is provided with the request.'
            )

        content_length = request.content_length
        max_length = 10 * 1024 * 1024
        if content_length > max_length:
            raise MissingParameterHTTPError(
                exception=RuntimeError('File exceeded maximum size (10MB)'))

        try:
            file = request.files['file']
        except LookupError as ex:
            raise MissingParameterHTTPError(param_names=['file'])
        except Exception as ex:
            raise CairisHTTPError(status_code=httplib.CONFLICT,
                                  message=str(ex.message),
                                  status='Unknown error')

        dao = UploadDAO(session_id)
        filename = dao.upload_image(file)

        resp_dict = {
            'message': 'File successfully uploaded',
            'filename': filename
        }
        resp = make_response(json_serialize(resp_dict, session_id=session_id),
                             httplib.OK)
        resp.contenttype = 'application/json'
        return resp
Ejemplo n.º 11
0
    def post(self):
        try:
            b = Borg()
            dict_form = request.get_json(silent=True)

            if dict_form is False or dict_form is None:
                raise MalformedJSONHTTPError(data=request.get_data())

            b.logger.info(dict_form)
            s = set_dbproxy(dict_form)

            resp_dict = {'session_id': s['session_id'], 'message': 'Configuration successfully applied'}
            resp = make_response(encode(resp_dict), httplib.OK)
            resp.headers['Content-type'] = 'application/json'
            return resp

        except KeyError:
            return MissingParameterHTTPError()
Ejemplo n.º 12
0
    def delete_threat(self, name=None, threat_id=None):
        if name is not None:
            found_threat = self.get_threat_by_name(name, simplify=False)
        elif threat_id is not None:
            found_threat = self.get_threat_by_id(threat_id, simplify=False)
        else:
            self.close()
            raise MissingParameterHTTPError(param_names=['name'])

        threat_id = found_threat.theId

        try:
            self.db_proxy.deleteThreat(threat_id)
        except ARM.DatabaseProxyException as ex:
            self.close()
            raise ARMHTTPError(ex)
        except ARM.ARMException as ex:
            self.close()
            raise ARMHTTPError(ex)
Ejemplo n.º 13
0
    def delete_environment(self, name=None, env_id=None):
        if name is not None:
            found_environment = self.get_environment_by_name(name, simplify=False)
            if found_environment is None:
                raise ObjectNotFoundHTTPError('The provided environment name')
            env_id = found_environment.theId

        if env_id is not None and env_id > -1:
            try:
                self.db_proxy.deleteEnvironment(env_id)
            except ARM.DatabaseProxyException as ex:
                self.close()
                raise ARMHTTPError(ex)
            except ARM.ARMException as ex:
                self.close()
                raise ARMHTTPError(ex)
        else:
            self.close()
            raise MissingParameterHTTPError(param_names=['id'])
Ejemplo n.º 14
0
    def delete_asset(self, name=None, asset_id=-1):
        if name is not None:
            found_asset = self.get_asset_by_name(name)
        elif asset_id > -1:
            found_asset = self.get_asset_by_id(asset_id)
        else:
            self.close()
            raise MissingParameterHTTPError(param_names=['name'])

        if found_asset is None or not isinstance(found_asset, Asset):
            self.close()
            raise ObjectNotFoundHTTPError('The provided asset name')

        try:
            self.db_proxy.deleteAsset(found_asset.theId)
        except ARM.DatabaseProxyException as ex:
            self.close()
            raise ARMHTTPError(ex)
        except ARM.ARMException as ex:
            self.close()
            raise ARMHTTPError(ex)
Ejemplo n.º 15
0
    def delete_role(self, name=None, role_id=-1):
        if name is not None:
            found_role = self.get_role_by_name(name)
        elif role_id > -1:
            found_role = self.get_role_by_id(role_id)
        else:
            self.close()
            raise MissingParameterHTTPError(param_names=['name'])

        if found_role is None or not isinstance(found_role, Role):
            self.close()
            raise ObjectNotFoundHTTPError('The provided role name')

        try:
            self.db_proxy.deleteRole(found_role.theId)
        except ARM.DatabaseProxyException as ex:
            self.close()
            raise ARMHTTPError(ex)
        except ARM.ARMException as ex:
            self.close()
            raise ARMHTTPError(ex)
Ejemplo n.º 16
0
    def delete_vulnerability(self, name=None, vuln_id=None):
        if name is not None:
            found_vulnerability = self.get_vulnerability_by_name(
                name, simplify=False)
        elif vuln_id is not None:
            found_vulnerability = self.get_vulnerability_by_id(vuln_id,
                                                               simplify=False)
        else:
            self.close()
            raise MissingParameterHTTPError(param_names=['name'])

        vuln_id = found_vulnerability.theVulnerabilityId

        try:
            self.db_proxy.deleteVulnerability(vuln_id)
        except ARM.DatabaseProxyException as ex:
            self.close()
            raise ARMHTTPError(ex)
        except ARM.ARMException as ex:
            self.close()
            raise ARMHTTPError(ex)
Ejemplo n.º 17
0
def handle_user_config_form():
    try:
        dict_form = request.form

        conf = {
            'host': dict_form['host'],
            'port': int(dict_form['port']),
            'user': dict_form['user'],
            'passwd': dict_form['passwd'],
            'db': dict_form['db'],
            'jsonPrettyPrint': dict_form.get('jsonPrettyPrint', False) == 'on'
        }
        s = set_dbproxy(conf)
        debug = ''
        '''debug += '{0}\nSession vars:\n{1}\nQuery string:\n'.format(
            'Configuration successfully updated',
            json_serialize(s, session_id=s['session_id']))'''

        resp = make_response(debug + 'session_id={0}'.format(s['session_id']), httplib.OK)
        resp.headers['Content-type'] = 'text/plain'
        resp.headers['Access-Control-Allow-Origin'] = "*"
        return resp
    except KeyError as ex:
        return MissingParameterHTTPError(exception=ex)
Ejemplo n.º 18
0
    def convert_props(self, real_props=None, fake_props=None):
        new_props = []
        if real_props is not None:
            if len(real_props) > 0:
                for real_prop in real_props:
                    assert isinstance(real_prop, AttackerEnvironmentProperties)
                    capabilities = []
                    for capability in real_prop.theCapabilities:
                        if len(capability) == 2:
                            capabilities.append({
                                'name': capability[0],
                                'value': capability[1]
                            })
                    real_prop.theCapabilities = capabilities
                    new_props.append(real_prop)
        elif fake_props is not None:
            if len(fake_props) > 0:
                for fake_prop in fake_props:
                    check_required_keys(
                        fake_prop, AttackerEnvironmentPropertiesModel.required)
                    cap_list = []
                    assert isinstance(cap_list, list)
                    for cap in fake_prop['theCapabilities']:
                        cap_list.append((cap['name'], cap['value']))
                    new_prop = AttackerEnvironmentProperties(
                        environmentName=fake_prop['theEnvironmentName'],
                        roles=fake_prop['theRoles'],
                        motives=fake_prop['theMotives'],
                        capabilities=cap_list)
                    new_props.append(new_prop)
        else:
            self.close()
            raise MissingParameterHTTPError(
                param_names=['real_props', 'fake_props'])

        return new_props
Ejemplo n.º 19
0
    def convert_props(self, real_props=None, fake_props=None):
        new_props = []
        if real_props is not None:
            if len(real_props) > 0:
                for real_prop in real_props:
                    assert isinstance(real_prop, AssetEnvironmentProperties)
                    asset_values = self.get_asset_values(
                        real_prop.theEnvironmentName)
                    prop_dict = {}
                    for asset_value in asset_values:
                        prop_dict[asset_value.theId] = asset_value.theName

                    for idx in range(0, len(real_prop.theAssociations)):
                        real_prop.theAssociations[idx] = list(
                            real_prop.theAssociations[idx])
                    sec_props = real_prop.theProperties
                    rationales = real_prop.theRationale

                    if len(sec_props) == len(rationales):
                        new_sec_attrs = []
                        for idx in range(0, len(sec_props)):
                            try:
                                attr_name = self.rev_attr_dict[idx]
                                attr_value = prop_dict[sec_props[idx]]
                                new_sec_attr = SecurityAttribute(
                                    attr_name, attr_value, rationales[idx])
                                new_sec_attrs.append(new_sec_attr)
                            except LookupError:
                                self.logger.warning(
                                    'Unable to find key in dictionary. Attribute is being skipped.'
                                )
                        real_prop.theProperties = new_sec_attrs
                        delattr(real_prop, 'theRationale')

                    new_props.append(real_prop)
        elif fake_props is not None:
            if len(fake_props) > 0:
                for fake_prop in fake_props:
                    check_required_keys(
                        fake_prop, AssetEnvironmentPropertiesModel.required)
                    asset_values = self.get_asset_values(
                        fake_prop['theEnvironmentName'])
                    rev_prop_dict = {}
                    for asset_value in asset_values:
                        rev_prop_dict[asset_value.theName] = asset_value.theId

                    assert isinstance(fake_prop['theAssociations'], list)
                    for idx in range(0, len(fake_prop['theAssociations'])):
                        fake_prop['theAssociations'][idx] = tuple(
                            fake_prop['theAssociations'][idx])
                    sec_attrs = fake_prop['theProperties']
                    new_syProps = array(8 * [0]).astype(numpy.int32)
                    new_rationale = ['None'] * 8

                    for sec_attr in sec_attrs:
                        attr_id = self.attr_dict[sec_attr['name']]
                        attr_value = rev_prop_dict[sec_attr['value']]
                        attr_rationale = sec_attr['rationale']
                        new_syProps[attr_id] = attr_value
                        new_rationale[attr_id] = attr_rationale

                    new_prop = AssetEnvironmentProperties(
                        environmentName=fake_prop['theEnvironmentName'],
                        syProperties=new_syProps,
                        pRationale=new_rationale,
                        associations=fake_prop['theAssociations'])
                    new_props.append(new_prop)
        else:
            self.close()
            raise MissingParameterHTTPError(
                param_names=['real_props', 'fake_props'])

        return new_props