Beispiel #1
0
    def from_json(self, request):
        json = request.get_json(silent=True)
        if json is False or json is None:
            self.close()
            raise MalformedJSONHTTPError(data=request.get_data())

        json_dict = json['object']
        check_required_keys(json_dict, RiskModel.required)
        json_dict['__python_obj__'] = Risk.__module__ + '.' + Risk.__name__

        if json_dict['theMisuseCase']:
            mc_dict = json_dict['theMisuseCase']
            check_required_keys(mc_dict, MisuseCaseModel.required)
            mc_dict[
                '__python_obj__'] = MisuseCase.__module__ + '.' + MisuseCase.__name__
            for idx in range(0, len(mc_dict['theEnvironmentProperties'])):
                mcep_dict = mc_dict['theEnvironmentProperties'][idx]
                check_required_keys(
                    mcep_dict, MisuseCaseEnvironmentPropertiesModel.required)
                mcep_dict[
                    '__python_obj__'] = MisuseCaseEnvironmentProperties.__module__ + '.' + MisuseCaseEnvironmentProperties.__name__
                mc_dict['theEnvironmentProperties'][idx] = mcep_dict
            json_dict['theMisuseCase'] = mc_dict

        risk = json_deserialize(json_dict)

        if isinstance(risk, Risk):
            return risk
        else:
            raise MalformedJSONHTTPError()
Beispiel #2
0
    def from_json(self, request, to_props=False):
        json = request.get_json(silent=True)
        if json is False or json is None:
            self.close()
            raise MalformedJSONHTTPError(data=request.get_data())

        json_dict = json['object']
        if to_props and isinstance(json_dict, list):
            props = self.convert_props(fake_props=json_dict)
            return props
        else:
            assert isinstance(json_dict, dict)
            check_required_keys(json_dict, AssetModel.required)
            json_dict[
                '__python_obj__'] = Asset.__module__ + '.' + Asset.__name__
            env_props = json_dict.pop('theEnvironmentProperties', [])
            env_props = self.convert_props(fake_props=env_props)
            json_dict.pop('theEnvironmentDictionary', None)
            json_dict.pop('theAssetPropertyDictionary', None)
            asset = json_serialize(json_dict)
            asset = json_deserialize(asset)

            if isinstance(asset, Asset):
                asset.theEnvironmentProperties = env_props
                return asset
            else:
                self.close()
                raise MalformedJSONHTTPError()
    def from_json(self, request):
        json = request.get_json(silent=True)
        if json is False or json is None:
            self.close()
            raise MalformedJSONHTTPError(data=request.get_data())

        json_dict = json['object']
        check_required_keys(json_dict, VulnerabilityModel.required)
        json_dict[
            '__python_obj__'] = Vulnerability.__module__ + '.' + Vulnerability.__name__

        for idx in range(0, len(json_dict['theEnvironmentProperties'])):
            property = json_dict['theEnvironmentProperties'][idx]
            check_required_keys(
                property, VulnerabilityEnvironmentPropertiesModel.required)
            property[
                '__python_obj__'] = VulnerabilityEnvironmentProperties.__module__ + '.' + VulnerabilityEnvironmentProperties.__name__
            json_dict['theEnvironmentProperties'][idx] = property

        vulnerability = json_serialize(json_dict)
        vulnerability = json_deserialize(vulnerability)
        if not isinstance(vulnerability, Vulnerability):
            self.close()
            raise MalformedJSONHTTPError(data=request.get_data())
        else:
            return vulnerability
Beispiel #4
0
    def from_json(self, request):
        json = request.get_json(silent=True)
        if json is False or json is None:
            self.close()
            raise MalformedJSONHTTPError(data=request.get_data())

        json_dict = json['object']
        assert isinstance(json_dict, dict)
        check_required_keys(json_dict, EnvironmentModel.required)
        json_dict['__python_obj__'] = Environment.__module__+'.'+Environment.__name__

        if json_dict.has_key('theTensions'):
            assert isinstance(json_dict['theTensions'], list)
            tensions = json_dict['theTensions']
            json_dict['theTensions'] = {}
            for tension in tensions:
                check_required_keys(tension, EnvironmentTensionModel.required)
                key = tuple([tension['base_attr_id'], tension['attr_id']])
                value = tuple([tension['value'], tension['rationale']])
                json_dict['theTensions'][key] = value

        new_json_environment = json_serialize(json_dict)
        environment = json_deserialize(new_json_environment)
        if not isinstance(environment, Environment):
            self.close()
            raise MalformedJSONHTTPError(data=request.get_data())
        else:
            return environment
Beispiel #5
0
    def from_json(self, request):
        """
        :rtype : Attacker
        :raise MalformedJSONHTTPError:
        """
        json = request.get_json(silent=True)
        if json is False or json is None:
            self.close()
            raise MalformedJSONHTTPError(data=request.get_data())

        json_dict = json['object']
        check_required_keys(json_dict, AttackerModel.required)
        json_dict[
            '__python_obj__'] = Attacker.__module__ + '.' + Attacker.__name__

        attacker_props = self.convert_props(
            fake_props=json_dict['theEnvironmentProperties'])
        json_dict['theEnvironmentProperties'] = []

        attacker = json_serialize(json_dict)
        attacker = json_deserialize(attacker)
        attacker.theEnvironmentProperties = attacker_props
        if not isinstance(attacker, Attacker):
            self.close()
            raise MalformedJSONHTTPError(data=request.get_data())
        else:
            return attacker
Beispiel #6
0
    def from_json(self, request):
        json = request.get_json(silent=True)
        if json is False or json is None:
            self.close()
            raise MalformedJSONHTTPError(data=request.get_data())

        return json['object']
Beispiel #7
0
    def type_from_json(self, request):
        json = request.get_json(silent=True)
        if json is False or json is None:
            self.close()
            raise MalformedJSONHTTPError(data=request.get_data())

        json_dict = json['object']
        check_required_keys(json_dict, ValueTypeModel.required)
        json_dict[
            '__python_obj__'] = ValueType.__module__ + '.' + ValueType.__name__

        value_type = json_serialize(json_dict)
        value_type = json_deserialize(value_type)
        if not isinstance(value_type, ValueType):
            self.close()
            raise MalformedJSONHTTPError(data=request.get_data())
        else:
            return value_type
Beispiel #8
0
    def from_json(self, request):
        """
        :rtype Role
        """
        json = request.get_json(silent=True)
        if json is False or json is None:
            self.close()
            raise MalformedJSONHTTPError(data=request.get_data())

        json_dict = json['object']
        check_required_keys(json_dict, RoleModel.required)
        json_dict['__python_obj__'] = Role.__module__+'.'+Role.__name__
        role = json_serialize(json_dict)
        role = json_deserialize(role)
        if not isinstance(role, Role):
            self.close()
            raise MalformedJSONHTTPError(data=request.get_data())
        else:
            return role
Beispiel #9
0
 def from_json(self, request):
     json_dict = super(DependencyDAO, self).from_json(request)
     check_required_keys(json_dict, DependencyModel.required)
     json_dict[
         '__python_obj__'] = Dependency.__module__ + '.' + Dependency.__name__
     dependency = json_deserialize(json_dict)
     if isinstance(dependency, Dependency):
         return dependency
     else:
         self.close()
         raise MalformedJSONHTTPError(json_serialize(json_dict))
Beispiel #10
0
    def from_json(self, request):
        json = request.get_json(silent=True)
        if json is False or json is None:
            self.close()
            raise MalformedJSONHTTPError(data=request.get_data())

        json_dict = json['object']
        check_required_keys(json_dict, ThreatModel.required)
        json_dict['__python_obj__'] = Threat.__module__ + '.' + Threat.__name__

        threat_props = self.convert_props(
            fake_props=json_dict['theEnvironmentProperties'])
        json_dict['theEnvironmentProperties'] = []

        threat = json_serialize(json_dict)
        threat = json_deserialize(threat)
        threat.theEnvironmentProperties = threat_props
        if not isinstance(threat, Threat):
            self.close()
            raise MalformedJSONHTTPError(data=request.get_data())
        else:
            return threat
Beispiel #11
0
    def from_json(self, request):
        self.logger.debug('Request data: %s', request.data)
        json = request.get_json(silent=True)
        if json is False or json is None:
            self.close()
            raise MalformedJSONHTTPError(data=request.get_data())

        json_dict = json['object']
        check_required_keys(json_dict, GoalModel.required)
        json_dict['__python_obj__'] = Goal.__module__ + '.' + Goal.__name__
        props_list = json_dict.pop('theEnvironmentProperties', [])
        json_dict.pop('theEnvironmentDictionary', None)
        real_props = self.convert_properties(fake_props=props_list)

        new_json_goal = json_serialize(json_dict)
        new_json_goal = json_deserialize(new_json_goal)
        new_json_goal.theEnvironmentProperties = real_props

        if not isinstance(new_json_goal, Goal):
            self.close()
            raise MalformedJSONHTTPError(data=request.get_data())
        else:
            return new_json_goal
Beispiel #12
0
    def from_json(self, request):
        json = request.get_json(silent=True)
        if json is False or json is None:
            self.close()
            raise MalformedJSONHTTPError(data=request.get_data())

        json_dict = json['object']
        check_required_keys(json_dict, ProjectSettings.required)
        json_dict[
            '__python_obj__'] = ProjectSettings.__module__ + '.' + ProjectSettings.__name__

        contrs = json_dict['contributions'] or []
        if not isinstance(contrs, list):
            contrs = []

        for idx in range(0, len(contrs)):
            try:
                check_required_keys(contrs[idx], Contributor.required)
                json_dict['contributions'][idx] = (contrs[idx]['firstName'],
                                                   contrs[idx]['surname'],
                                                   contrs[idx]['affliation'],
                                                   contrs[idx]['role'])
            except MissingParameterHTTPError:
                SilentHTTPError(
                    'A contribution did not contain all required fields. Skipping this one.'
                )

        revisions = json_dict['revisions'] or []
        if not isinstance(revisions, list):
            revisions = []

        for idx in range(0, len(revisions)):
            try:
                check_required_keys(revisions[idx], Revision.required)
                json_dict['revisions'][idx] = (revisions[idx]['id'],
                                               revisions[idx]['date'],
                                               revisions[idx]['description'])
            except MissingParameterHTTPError:
                SilentHTTPError(
                    'A revision did not contain all required fields. Skipping this one.'
                )

        json_dict['definitions'] = json_dict.get('definitions', None) or {}
        json_dict['definitions'] = json_dict['definitions'].items()

        settings = json_deserialize(json_dict)
        return settings
Beispiel #13
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()
Beispiel #14
0
def json_deserialize(string, class_name=None):
    """
    Deserializes the JSON object to the appropriate class instance.
    :param string: The JSON string
    :type string: str
    :param class_name: The name of the target class
    :type class_name: str
    :return: Returns a dictionary or a class instance depending on the target class chosen
    :rtype: list|dict|Asset|Goal|Requirement|Risk
    """
    if isinstance(string, dict) or isinstance(string, list):
        string = json_serialize(string)

    if isinstance(string, list):
        list_result = []
        for item_string in string:
            item_string = json_serialize(item_string)
            for key in conv_terms:
                item_string = item_string.replace(conv_terms[key], key)
            list_result.append(json_deserialize(item_string))

    if isinstance(string, str):
        for key in conv_terms:
            string = string.replace(conv_terms[key], key)

    try:
        obj = deserialize(string)
        if isinstance(obj, Environment):
            tensions = {}
            for key, value in obj.theTensions.items():
                key = str(key)
                attrs = key.strip('(').strip(')').split(',')
                if len(attrs) == 2:
                    idx1 = int(attrs[0].strip(' '))
                    idx2 = int(attrs[1].strip(' '))
                    tuple_key = (idx1, idx2)
                    tensions[tuple_key] = value

            obj = Environment(
                id=obj.theId,
                name=obj.theName,
                sc=obj.theShortCode,
                description=obj.theDescription,
                environments=obj.theEnvironments,
                duplProperty=obj.theDuplicateProperty,
                overridingEnvironment=obj.theOverridingEnvironment,
                envTensions=tensions)

        if isinstance(obj, dict):
            if class_name == 'asset':
                from CairisHTTPError import MalformedJSONHTTPError
                raise MalformedJSONHTTPError()
            elif class_name == 'goal':
                obj = deserialize_goal(dict)
            elif class_name == 'requirement':
                obj = deserialize_requirement(dict)

        return obj
    except Exception as ex:
        from CairisHTTPError import handle_exception
        handle_exception(ex)