Beispiel #1
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
Beispiel #2
0
    def post(self):
        session_id = get_session_id(session, request)

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

        try:
            wb = request.files['file']
            fd, abs_path = mkstemp(suffix='.xlsx')
            fs_temp = open(abs_path, 'wb')
            fs_temp.write(wb.stream.read())
            fs_temp.close()
            os.close(fd)
            dao = self.DAOModule(session_id)
            postMsg = getattr(dao, self.thePostMethod)(abs_path)
            dao.close()
            os.remove(abs_path)
            resp_dict = {'message': postMsg}
            resp = make_response(
                json_serialize(resp_dict, session_id=session_id), OK)
            resp.contenttype = 'application/json'
            return resp
        except DatabaseProxyException as ex:
            raise ARMHTTPError(ex)
        except ARMException as ex:
            raise ARMHTTPError(ex)
        except LookupError as ex:
            raise MissingParameterHTTPError(param_names=['file'])
        except Exception as ex:
            raise CairisHTTPError(status_code=CONFLICT,
                                  message=str(ex),
                                  status='Unknown error')
Beispiel #3
0
    def update_requirement(self, requirement, name=None):
        old_requirement = None
        old_reference = None
        if name is not None:
            old_requirement = self.db_proxy.getRequirement(name)
            old_reference = old_requirement.asset()
        else:
            self.close()
            raise MissingParameterHTTPError(param_names=['theId'])

        if old_requirement is not None:
            try:
                requirement.theVersion = old_requirement.theVersion
                requirement.theId = old_requirement.theId
                requirement.incrementVersion()
                self.db_proxy.updateRequirement(requirement)
                reqReference = requirement.asset()
                if (reqReference != old_reference):
                    self.db_proxy.reassociateRequirement(
                        requirement.name(), reqReference)
                    self.db_proxy.relabelRequirements(reqReference)
                    self.db_proxy.relabelRequirements(old_reference)
            except DatabaseProxyException as ex:
                self.close()
                raise ARMHTTPError(ex)
        else:
            self.close()
            raise MissingParameterHTTPError(param_names=['id'])
Beispiel #4
0
  def add_requirement(self, requirement, asset_name=None, environment_name=None):
    try:
      self.db_proxy.nameCheck(requirement.theName, 'requirement')
    except ARMException as ex:
      self.close()
      raise ARMHTTPError(ex)

    new_id = self.db_proxy.newId()
    requirement.theId = new_id

    if asset_name is not None:
      try:
        self.db_proxy.addRequirement(requirement, assetName=asset_name, isAsset=True)
      except Exception as ex:
        self.close()
        handle_exception(ex)
    elif environment_name is not None:
      try:
        self.db_proxy.addRequirement(requirement, assetName=environment_name, isAsset=False)
      except Exception as ex:
        self.close()
        handle_exception(ex)
    else:
      self.close()
      raise MissingParameterHTTPError(param_names=['requirement', 'environment'])

    return new_id
Beispiel #5
0
 def convert_loc_list(self,real_loc_list = None, fake_loc_list = None):
   new_loc_list = []
   if real_loc_list is not None:
     if len(real_loc_list) > 0:
       for real_loc in real_loc_list:
         assert isinstance(real_loc,Location)
         loc_dict = {}
         loc_dict['theName'] = real_loc.name()
         loc_dict['theAssetInstances'] = []  
         for ai in real_loc.assetInstances():
           loc_dict['theAssetInstances'].append({'theName':ai[0],'theAsset':ai[1]})  
         loc_dict['thePersonaInstances'] = []  
         for pi in real_loc.personaInstances():
           loc_dict['thePersonaInstances'].append({'theName':pi[0],'thePersona':pi[1]})  
         loc_dict['theLinks'] = real_loc.links()
         new_loc_list.append(loc_dict)
   elif fake_loc_list is not None:
     if len(fake_loc_list) > 0:
       for fake_loc in fake_loc_list:
         check_required_keys(fake_loc,LocationModel.required) 
         assetInstances = []
         for ai in fake_loc['theAssetInstances']:
           assetInstances.append((ai['theName'],ai['theAsset']))
         personaInstances = []
         for pi in fake_loc['thePersonaInstances']:
           personaInstances.append((pi['theName'],pi['thePersona']))
         new_loc_list.append(Location(-1,fake_loc['theName'],assetInstances,personaInstances,fake_loc['theLinks']))
   else:
     self.close()
     raise MissingParameterHTTPError(param_names=['real_loc_list', 'fake_loc_list'])
   return new_loc_list
Beispiel #6
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
Beispiel #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 DatabaseProxyException as ex:
            self.close()
            raise ARMHTTPError(ex)
        except ARMException as ex:
            self.close()
            raise ARMHTTPError(ex)
Beispiel #8
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'])
Beispiel #9
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 DatabaseProxyException as ex:
            self.close()
            raise ARMHTTPError(ex)
        except ARMException as ex:
            self.close()
            raise ARMHTTPError(ex)
Beispiel #10
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
Beispiel #11
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()
            try:
                db_proxy = b.get_dbproxy(session_id)
            except SessionNotFound as ex:
                raise NoSessionError(ex)

            if isinstance(db_proxy, MySQLDatabaseProxy):
                if db_proxy.conn is None:
                    db_proxy.reconnect(session_id=session_id)
                return db_proxy
            else:
                raise CairisHTTPError(
                    status_code=CONFLICT,
                    message=
                    'The database connection was not properly set up. Please try to reset the connection.'
                )
        else:
            raise MissingParameterHTTPError(param_names=['session_id'])
Beispiel #12
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 DatabaseProxyException as ex:
                self.close()
                raise ARMHTTPError(ex)
        else:
            self.close()
            raise MissingParameterHTTPError(param_names=['id'])
Beispiel #13
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)
Beispiel #14
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, PersonaEnvironmentProperties)
                 del real_prop.theCodes
                 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, PersonaEnvironmentPropertiesModel.required)
                 new_prop = PersonaEnvironmentProperties(
                     environmentName=fake_prop['theEnvironmentName'],
                     direct=fake_prop['theDirectFlag'],
                     description=fake_prop['theNarrative'],
                     roles=fake_prop['theRoles'],
                     pCodes=[])
                 new_props.append(new_prop)
     else:
         self.close()
         raise MissingParameterHTTPError(
             param_names=['real_props', 'fake_props'])
     return new_props
Beispiel #15
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
Beispiel #16
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, TaskEnvironmentProperties)
                    del real_prop.theCodes
                    ptList = []
                    for ptc in real_prop.personas():
                        ptList.append(
                            PersonaTaskCharacteristics(ptc[0], ptc[1], ptc[2],
                                                       ptc[3], ptc[4]))
                    real_prop.thePersonas = ptList
                    gcaList = []
                    for gca in real_prop.concernAssociations():
                        gcaList.append(
                            ConcernAssociationModel(gca[0], gca[1], gca[2],
                                                    gca[3], gca[4]))
                    real_prop.theConcernAssociations = gcaList
                    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, TaskEnvironmentPropertiesModel.required)
                    ptList = []
                    for ptc in fake_prop['thePersonas']:
                        ptList.append([
                            ptc['thePersona'], ptc['theDuration'],
                            ptc['theFrequency'], ptc['theDemands'],
                            ptc['theGoalConflict']
                        ])
                    fake_prop['thePersonas'] = ptList
                    gcaList = []
                    for gca in fake_prop['theConcernAssociations']:
                        gcaList.append([
                            gca['theSource'], gca['theSourceNry'],
                            gca['theLinkVerb'], gca['theTarget'],
                            gca['theTargetNry']
                        ])
                    fake_prop['theConcernAssociations'] = gcaList

                    new_prop = TaskEnvironmentProperties(
                        environmentName=fake_prop['theEnvironmentName'],
                        deps=fake_prop['theDependencies'],
                        personas=fake_prop['thePersonas'],
                        assets=fake_prop['theAssets'],
                        concs=fake_prop['theConcernAssociations'],
                        narrative=fake_prop['theNarrative'],
                        consequences=fake_prop['theConsequences'],
                        benefits=fake_prop['theBenefits'],
                        tCodes=[])
                    new_props.append(new_prop)
        else:
            self.close()
            raise MissingParameterHTTPError(
                param_names=['real_props', 'fake_props'])
        return new_props
Beispiel #17
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
                    del real_prop.theRationale
                    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'])
Beispiel #18
0
 def delete_requirement(self, name=None):
     if name is not None:
         req = self.db_proxy.getRequirement(name)
         reqReference = req.asset()
         self.db_proxy.deleteRequirement(req.id())
         self.db_proxy.relabelRequirements(reqReference)
     else:
         self.close()
         raise MissingParameterHTTPError(param_names=['name'])
Beispiel #19
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, ObstacleEnvironmentProperties)
                del real_prop.theLabel

                new_goal_refinements = []
                for gr in real_prop.theGoalRefinements:
                    new_goal_refinements.append(
                        RefinementModel(gr[0], gr[1], gr[2], gr[3], gr[4]))

                new_subgoal_refinements = []
                for sgr in real_prop.theSubGoalRefinements:
                    new_subgoal_refinements.append(
                        RefinementModel(sgr[0], sgr[1], sgr[2], sgr[3],
                                        sgr[4]))

                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, ObstacleEnvironmentPropertiesModel.required)

                new_goal_refinements = []
                for gr in fake_prop['theGoalRefinements']:
                    new_goal_refinements.append(
                        (gr['theEndName'], gr['theEndType'], gr['theRefType'],
                         gr['isAlternate'], gr['theRationale']))

                new_subgoal_refinements = []
                for sgr in fake_prop['theSubGoalRefinements']:
                    new_subgoal_refinements.append(
                        (sgr['theEndName'], sgr['theEndType'],
                         sgr['theRefType'], sgr['isAlternate'],
                         sgr['theRationale']))

                new_prop = ObstacleEnvironmentProperties(
                    environmentName=fake_prop['theEnvironmentName'],
                    lbl='',
                    definition=fake_prop['theDefinition'],
                    category=fake_prop['theCategory'],
                    gRefs=new_goal_refinements,
                    sgRefs=new_subgoal_refinements,
                    concs=fake_prop['theConcerns'])
                new_prop.theProbability = fake_prop['theProbability']
                new_prop.theProbabilityRationale = fake_prop[
                    'theProbabilityRationale']
                new_props.append(new_prop)
        else:
            self.close()
            raise MissingParameterHTTPError(
                param_names=['real_props', 'fake_props'])

        return new_props
Beispiel #20
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)
        del real_prop.theLabel
        new_concern_assocs = []
        for concern_assoc in real_prop.theConcernAssociations:
          new_concern_assocs.append(ConcernAssociationModel(concern_assoc[0],concern_assoc[1],concern_assoc[2],concern_assoc[3],concern_assoc[4]))

        new_goal_refinements = []
        for gr in real_prop.theGoalRefinements:
          new_goal_refinements.append(RefinementModel(gr[0],gr[1],gr[2],gr[3],gr[4]))

        new_subgoal_refinements = []
        for sgr in real_prop.theSubGoalRefinements:
          new_subgoal_refinements.append(RefinementModel(sgr[0],sgr[1],sgr[2],sgr[3],sgr[4]))

        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([concern_assoc['theSource'],concern_assoc['theSourceNry'],concern_assoc['theLinkVerb'],concern_assoc['theTarget'],concern_assoc['theTargetNry']])

        new_goal_refinements = []
        for gr in fake_prop['theGoalRefinements']:
          new_goal_refinements.append((gr['theEndName'],gr['theEndType'],gr['theRefType'],gr['isAlternate'],gr['theRationale']))

        new_subgoal_refinements = []
        for sgr in fake_prop['theSubGoalRefinements']:
          new_subgoal_refinements.append((sgr['theEndName'],sgr['theEndType'],sgr['theRefType'],sgr['isAlternate'],sgr['theRationale']))

        new_prop = GoalEnvironmentProperties(
          environmentName=fake_prop['theEnvironmentName'],
          lbl='',
          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
Beispiel #21
0
    def update_requirement(self, requirement, name=None):
        old_requirement = None
        if name is not None:
            old_requirement = self.db_proxy.getRequirement(name)
        else:
            self.close()
            raise MissingParameterHTTPError(param_names=['theId'])

        if old_requirement is not None:
            try:
                requirement.theVersion = old_requirement.theVersion
                requirement.theId = old_requirement.theId
                requirement.incrementVersion()
                self.db_proxy.updateRequirement(requirement)
            except DatabaseProxyException as ex:
                self.close()
                raise ARMHTTPError(ex)
        else:
            self.close()
            raise MissingParameterHTTPError(param_names=['id'])
Beispiel #22
0
    def post(self):
        session_id = get_session_id(session, request)

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

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

        try:
            dao = ImportDAO(session_id)
            dao.package_import(package.stream.read())
            dao.close()
        except DatabaseProxyException as ex:
            raise ARMHTTPError(ex)
        except ARMException as ex:
            raise ARMHTTPError(ex)
        except Exception as ex:
            import pytest
            pytest.set_trace()
            raise CairisHTTPError(status_code=500,
                                  message=str(ex),
                                  status='Unknown error')

        resp_dict = {'message': 'Package successfully imported'}
        resp = make_response(json_serialize(resp_dict, session_id=session_id),
                             OK)
        resp.contenttype = 'application/json'
        return resp
Beispiel #23
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, UseCaseEnvironmentProperties)
                    s = []
                    for step in real_prop.steps().theSteps:
                        excs = []
                        for excKey in step.exceptions():
                            exc = step.exception(excKey)
                            excs.append(
                                ExceptionAttributes(exc[0], exc[1], exc[2],
                                                    exc[3], exc[4]))
                        s.append(
                            StepAttributes(step.text(), step.synopsis(),
                                           step.actor(), step.actorType(),
                                           step.tags(), excs))
                    real_prop.theSteps = s
                    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, UseCaseEnvironmentPropertiesModel.required)
                    steps = Steps()
                    for fs in fake_prop['theSteps']:
                        aStep = Step(fs['theStepText'], fs['theSynopsis'],
                                     fs['theActor'], fs['theActorType'],
                                     fs['theTags'])
                        for exc in fs['theExceptions']:
                            aStep.addException(
                                (exc['theName'], exc['theDimensionType'],
                                 exc['theDimensionValue'],
                                 exc['theCategoryName'],
                                 exc['theDescription']))
                        steps.append(aStep)
                    fake_prop['theSteps'] = steps

                    new_prop = UseCaseEnvironmentProperties(
                        environmentName=fake_prop['theEnvironmentName'],
                        preCond=fake_prop['thePreCond'],
                        steps=fake_prop['theSteps'],
                        postCond=fake_prop['thePostCond'])
                    new_props.append(new_prop)
        else:
            self.close()
            raise MissingParameterHTTPError(
                param_names=['real_props', 'fake_props'])
        return new_props
Beispiel #24
0
  def delete_requirement(self, name=None, req_id=None):
    if name is not None:
      req = self.get_requirement_by_name(name)
    elif req_id is not None:
      req = self.get_requirement_by_id(req_id)
    else:
      self.close()
      raise MissingParameterHTTPError(param_names=['id'])

    if req is None:
      self.close()
      raise ObjectNotFoundHTTPError('The provided requirement')

    self.db_proxy.deleteRequirement(req.theId)
Beispiel #25
0
    def post(self, type):
        session_id = get_session_id(session, request)
        try:
            if not request.files:
                raise LookupError()
            file = request.files['file']
        except LookupError:
            raise MissingParameterHTTPError(param_names=['file'])

        try:
            fd, abs_path = mkstemp(suffix='.xml')
            fs_temp = open(abs_path, 'wb')
            xml_text = file.stream.read()
            fs_temp.write(xml_text)
            fs_temp.close()
            fd_close(fd)
        except IOError:
            raise CairisHTTPError(
                status_code=CONFLICT,
                status='Unable to load XML file',
                message='The XML file could not be loaded on the server.' +
                'Please check if the application has permission to write temporary files.'
            )

        try:
            dao = ImportDAO(session_id)
            result = dao.file_import(abs_path, type, 1)
            dao.close()
        except DatabaseProxyException as ex:
            raise ARMHTTPError(ex)
        except ARMException as ex:
            raise ARMHTTPError(ex)
        except Exception as ex:
            raise CairisHTTPError(status_code=500,
                                  message=str(ex),
                                  status='Unknown error')

        remove_file(abs_path)

        message = str(result)
        if (result == 0):
            message = file.filename + ' imported'
        resp_dict = {'message': message}
        resp = make_response(json_serialize(resp_dict, session_id=session_id),
                             OK)
        resp.headers['Content-Type'] = 'application/json'
        return resp
Beispiel #26
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 DatabaseProxyException as ex:
        self.close()
        raise ARMHTTPError(ex)
      except ARMException as ex:
        self.close()
        raise ARMHTTPError(ex)
    else:
      self.close()
      raise MissingParameterHTTPError(param_names=['id'])
Beispiel #27
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 DatabaseProxyException as ex:
            self.close()
            raise ARMHTTPError(ex)
        except ARMException as ex:
            self.close()
            raise ARMHTTPError(ex)
Beispiel #28
0
 def convert_props(self, real_props=None, fake_props=None, rationales=None):
     prop_dict = {}
     prop_dict['None'] = 0
     prop_dict['Low'] = 1
     prop_dict['Medium'] = 2
     prop_dict['High'] = 3
     rev_prop_dict = {}
     rev_prop_dict[0] = 'None'
     rev_prop_dict[1] = 'Low'
     rev_prop_dict[2] = 'Medium'
     rev_prop_dict[3] = 'High'
     new_props = []
     if real_props is not None:
         if len(real_props) > 0:
             new_sec_attrs = []
             for idx in range(0, len(real_props)):
                 try:
                     attr_name = self.rev_attr_dict[idx]
                     attr_value = rev_prop_dict[real_props[idx]]
                     new_sec_attr = SecurityAttribute(
                         attr_name, attr_value, rationales[idx])
                     new_props.append(new_sec_attr)
                 except LookupError:
                     self.logger.warning(
                         'Unable to find key in dictionary. Attribute is being skipped.'
                     )
         return new_props
     elif fake_props is not None:
         if len(fake_props) > 0:
             new_props = array(8 * [0]).astype(numpy.int32)
             new_rationale = ['None'] * 8
             for sec_attr in fake_props:
                 attr_id = self.attr_dict[sec_attr['name']]
                 attr_value = prop_dict[sec_attr['value']]
                 attr_rationale = sec_attr['rationale']
                 new_props[attr_id] = attr_value
                 new_rationale[attr_id] = attr_rationale
         return (new_props, new_rationale)
     else:
         self.close()
         raise MissingParameterHTTPError(
             param_names=['real_props', 'fake_props'])
Beispiel #29
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 DatabaseProxyException as ex:
            self.close()
            raise ARMHTTPError(ex)
        except ARMException as ex:
            self.close()
            raise ARMHTTPError(ex)
Beispiel #30
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 DatabaseProxyException as ex:
            self.close()
            raise ARMHTTPError(ex)
        except ARMException as ex:
            self.close()
            raise ARMHTTPError(ex)