def file_export(modelFormat = 'all', outputFile = None, persona = None, task = None, envName = None, session_id = None): from cairis.mio.ModelExport import exportModel,exportRedmineScenarios,exportRedmineRequirements,exportRedmineUseCases,exportArchitecture,exportAttackPatterns,exportGRL,exportSecurityPatterns msgStr = '' if (modelFormat == 'all'): msgStr += exportModel(outputFile,session_id) elif (modelFormat == 'scenarios'): msgStr += exportRedmineScenarios(outputFile,session_id) elif (modelFormat == 'requirements'): msgStr += exportRedmineRequirements(outputFile,session_id) elif (modelFormat == 'usecases'): msgStr += exportRedmineUseCases(outputFile,session_id) elif (modelFormat == 'architecture'): msgStr += exportArchitecture(outputFile,session_id) elif (modelFormat == 'attackpatterns'): msgStr += exportAttackPatterns(outputFile,session_id) elif (modelFormat == 'securitypatterns'): msgStr += exportSecurityPatterns(outputFile,session_id) elif (modelFormat == 'GRL'): personaNames = [] personaNames.extend(persona) taskNames = [] taskNames.extend(task) if len(personaNames) == 0: raise ARMException('Persona name not specified for GRL export') elif len(taskNames) == 0: raise ARMException('Task name not specified for GRL export') elif envName == None: raise ARMException('Environment name not specified for GRL export') else: msgStr += exportGRL(outputFile,personaNames,taskNames,envName,session_id) else: raise ARMException('Export model type ' + modelFormat + ' not recognised') return msgStr
def quick_setup(dbHost, dbPort, dbRootPassword, tmpDir, rootDir, imageDir, configFile, webPort, logLevel, staticDir, assetDir, uploadDir, userName, passWd): if (len(userName) > 255): raise ARMException("Username cannot be longer than 255 characters") if (userName == "root"): raise ARMException("Username cannot be root") createUserDatabase(dbHost, dbPort, dbRootPassword, rootDir) os.environ["CAIRIS_CFG"] = configFile pathName = os.path.split( os.path.split(os.path.realpath(os.path.dirname(__file__)))[0])[0] sys.path.insert(0, pathName) fileName = os.environ.get("HOME") + "/.bashrc" f = open(fileName, 'a') f.write("export CAIRIS_CFG=" + configFile + "\n") f.write("export PYTHONPATH=${PYTHONPATH}:" + pathName + "\n") f.close() createCairisCnf(configFile, dbRootPassword, dbHost, dbPort, tmpDir, rootDir, imageDir, webPort, logLevel, staticDir, assetDir, uploadDir) from cairis.bin.add_cairis_user import user_datastore, db db.create_all() user_datastore.create_user(email=userName, password=passWd, name='Default user') db.session.commit() createDatabaseAccount(dbRootPassword, dbHost, dbPort, userName, '') createDatabaseAndPrivileges(dbRootPassword, dbHost, dbPort, userName, '', userName + '_default') createDatabaseSchema(rootDir, dbHost, dbPort, userName, '', userName + '_default')
def createUserDatabase(dbHost, dbPort, dbRootPassword, rootDir): try: rootConn = MySQLdb.connect(host=dbHost, port=int(dbPort), user='******', passwd=dbRootPassword) rootCursor = rootConn.cursor() except _mysql_exceptions.DatabaseError as e: id, msg = e exceptionText = 'Error connecting to MySQL (id:' + str( id) + ',message:' + msg + ')' raise ARMException(exceptionText) try: dropUserDbSql = "drop database if exists cairis_user" rootCursor.execute(dropUserDbSql) except _mysql_exceptions.DatabaseError as e: id, msg = e exceptionText = 'MySQL error removing existing cairis_user database (id: ' + str( id) + ', message: ' + msg raise ARMException(exceptionText) createDatabaseAccount(dbRootPassword, dbHost, dbPort, 'cairis_test', 'cairis_test') createDatabaseAndPrivileges(dbRootPassword, dbHost, dbPort, 'cairis_test', 'cairis_test', 'cairis_test_default') createDatabaseSchema(rootDir, dbHost, dbPort, 'cairis_test', 'cairis_test', 'cairis_test_default') try: createUserDbSql = "create database if not exists cairis_user" rootCursor.execute(createUserDbSql) except _mysql_exceptions.DatabaseError as e: id, msg = e exceptionText = 'MySQL error creating cairis_user database (id: ' + str( id) + ', message: ' + msg raise ARMException(exceptionText) try: recursionDepthSql = "set global max_sp_recursion_depth = 255" rootCursor.execute(recursionDepthSql) except _mysql_exceptions.DatabaseError as e: id, msg = e exceptionText = 'MySQL error setting recursion depth (id: ' + str( id) + ', message: ' + msg raise ARMException(exceptionText) try: flushPrivilegesSql = "flush privileges" rootCursor.execute(flushPrivilegesSql) except _mysql_exceptions.DatabaseError as e: id, msg = e exceptionText = 'MySQL error flushing privileges (id: ' + str( id) + ', message: ' + msg raise ARMException(exceptionText) rootCursor.close() rootConn.close()
def file_import(importFile, mFormat, overwriteFlag, session_id=None): if overwriteFlag == None: overwriteFlag = 1 from cairis.mio.ModelImport import importSecurityPatternsFile, importAttackPattern, importTVTypeFile, importDirectoryFile, importRequirementsFile, importRiskAnalysisFile, importUsabilityFile, importAssociationsFile, importProjectFile, importDomainValuesFile, importComponentViewFile, importSynopsesFile, importProcessesFile, importAssetsFile, importLocationsFile, importModelFile, importMisusabilityFile, importDataflowsFile, importStoriesFile try: ET.fromstring(open(importFile).read()) except ET.ParseError as e: raise ARMException('Error parsing ' + importFile + ': ' + str(e)) msgStr = '' if (mFormat == 'securitypattern' or mFormat == 'Security Pattern'): msgStr += importSecurityPatternsFile(importFile, session_id) elif (mFormat == 'attackpattern' or mFormat == 'Attack Pattern'): msgStr += importAttackPattern(importFile, session_id) elif (mFormat == 'tvtypes' or mFormat == 'Threat and Vulnerability Types'): msgStr += importTVTypeFile(importFile, int(overwriteFlag), session_id) elif (mFormat == 'directory' or mFormat == 'Threat and Vulnerability Directory'): msgStr += importDirectoryFile(importFile, int(overwriteFlag), session_id) elif (mFormat == 'requirements' or mFormat == 'Requirements'): msgStr += importRequirementsFile(importFile, session_id) elif (mFormat == 'riskanalysis' or mFormat == 'Risk Analysis'): msgStr += importRiskAnalysisFile(importFile, session_id) elif (mFormat == 'usability' or mFormat == 'Usability'): msgStr += importUsabilityFile(importFile, session_id) elif (mFormat == 'misusability' or mFormat == 'Misusability'): msgStr += importMisusabilityFile(importFile, session_id) elif (mFormat == 'associations' or mFormat == 'Associations'): msgStr += importAssociationsFile(importFile, session_id) elif (mFormat == 'project' or mFormat == 'Project data'): msgStr += importProjectFile(importFile, session_id) elif (mFormat == 'domainvalues' or mFormat == 'Domain Values'): msgStr += importDomainValuesFile(importFile, session_id) elif (mFormat == 'architecturalpattern' or mFormat == 'Architectural Pattern'): msgStr += importComponentViewFile(importFile, session_id) elif (mFormat == 'synopses' or mFormat == 'Synopses'): msgStr += importSynopsesFile(importFile, session_id) elif (mFormat == 'processes' or mFormat == 'Processes'): msgStr += importProcessesFile(importFile, session_id) elif (mFormat == 'assets' or mFormat == 'Assets'): msgStr += importAssetsFile(importFile, session_id) elif (mFormat == 'locations' or mFormat == 'Locations'): msgStr += importLocationsFile(importFile, session_id) elif (mFormat == 'dataflows' or mFormat == 'Dataflows'): msgStr += importDataflowsFile(importFile, session_id) elif (mFormat == 'stories' or mFormat == 'Stories'): msgStr += importStoriesFile(importFile, session_id) elif (mFormat == 'all' or mFormat == 'Model' or mFormat == 'Model file (.xml)'): msgStr += importModelFile(importFile, int(overwriteFlag), session_id) else: raise ARMException('Input model type ' + mFormat + ' not recognised') return 0
def quick_setup(dbHost, dbPort, dbRootPassword, tmpDir, rootDir, configFile, webPort, logLevel, staticDir, assetDir, userName, passWd, mailServer='', mailPort='', mailUser='', mailPasswd=''): if (len(userName) > 255): raise ARMException("Username cannot be longer than 255 characters") if (userName == "root"): raise ARMException("Username cannot be root") createDbOwnerDatabase(dbRootPassword, dbHost, dbPort) createUserDatabase(dbHost, dbPort, dbRootPassword, rootDir) os.environ["CAIRIS_CFG"] = configFile pathName = os.path.split( os.path.split(os.path.realpath(os.path.dirname(__file__)))[0])[0] sys.path.insert(0, pathName) fileName = os.environ.get("HOME") + "/.bashrc" f = open(fileName, 'a') f.write("export CAIRIS_SRC=" + rootDir + "\n") f.write("export CAIRIS_CFG_DIR=${CAIRIS_SRC}/config\n") f.write("export CAIRIS_CFG=" + configFile + "\n") f.write("export PYTHONPATH=${PYTHONPATH}:" + pathName + "\n") f.close() createCairisCnf(configFile, dbRootPassword, dbHost, dbPort, tmpDir, rootDir, webPort, logLevel, staticDir, assetDir, mailServer, mailPort, mailUser, mailPasswd) from cairis.bin.add_cairis_user import user_datastore, db db.create_all() if (userName != ''): rp = ''.join(choice(ascii_letters + digits) for i in range(255)) dbAccount = canonicalDbUser(userName) user_datastore.create_user(email=userName, account=dbAccount, password=passWd, dbtoken=rp, name='Default user') db.session.commit() createDatabaseAccount(dbRootPassword, dbHost, dbPort, userName, rp) createDatabaseAndPrivileges(dbRootPassword, dbHost, dbPort, userName, rp, dbAccount + '_default') createDatabaseSchema(rootDir, dbHost, dbPort, userName, rp, dbAccount + '_default') createDefaults(rootDir, dbHost, dbPort, userName, rp, dbAccount + '_default')
def file_import(importFile, mFormat, overwriteFlag, session_id=None): if overwriteFlag == None: overwriteFlag = 1 if (os.access(importFile, os.R_OK)) == False: raise ARMException("Cannot access " + importFile) from cairis.mio.ModelImport import importSecurityPatternsFile, importAttackPattern, importTVTypeFile, importDirectoryFile, importRequirementsFile, importRiskAnalysisFile, importUsabilityFile, importAssociationsFile, importProjectFile, importDomainValuesFile, importComponentViewFile, importSynopsesFile, importProcessesFile, importAssetsFile, importLocationsFile, importModelFile, importMisusabilityFile, importDataflowsFile msgStr = '' if (mFormat == 'securitypattern' or mFormat == 'Security Pattern'): msgStr += importSecurityPatternsFile(importFile, session_id=session_id) elif (mFormat == 'attackpattern' or mFormat == 'Attack Pattern'): msgStr += importAttackPattern(importFile, session_id) elif (mFormat == 'tvtypes' or mFormat == 'Threat and Vulnerability Types'): msgStr += importTVTypeFile(importFile, int(overwriteFlag), session_id) elif (mFormat == 'directory' or mFormat == 'Threat and Vulnerability Directory'): msgStr += importDirectoryFile(importFile, int(overwriteFlag), session_id) elif (mFormat == 'requirements' or mFormat == 'Requirements'): msgStr += importRequirementsFile(importFile, session_id) elif (mFormat == 'riskanalysis' or mFormat == 'Risk Analysis'): msgStr += importRiskAnalysisFile(importFile, session_id) elif (mFormat == 'usability' or mFormat == 'Usability'): msgStr += importUsabilityFile(importFile, session_id) elif (mFormat == 'misusability' or mFormat == 'Misusability'): msgStr += importMisusabilityFile(importFile, session_id) elif (mFormat == 'associations' or mFormat == 'Associations'): msgStr += importAssociationsFile(importFile, session_id) elif (mFormat == 'project' or mFormat == 'Project data'): msgStr += importProjectFile(importFile, session_id) elif (mFormat == 'domainvalues' or mFormat == 'Domain Values'): msgStr += importDomainValuesFile(importFile, session_id) elif (mFormat == 'architecturalpattern' or mFormat == 'Architectural Pattern'): msgStr += importComponentViewFile(importFile, session_id) elif (mFormat == 'synopses' or mFormat == 'Synopses'): msgStr += importSynopsesFile(importFile, session_id) elif (mFormat == 'processes' or mFormat == 'Processes'): msgStr += importProcessesFile(importFile, session_id) elif (mFormat == 'assets' or mFormat == 'Assets'): msgStr += importAssetsFile(importFile, session_id) elif (mFormat == 'locations' or mFormat == 'Locations'): msgStr += importLocationsFile(importFile, session_id) elif (mFormat == 'dataflows' or mFormat == 'Dataflows'): msgStr += importDataflowsFile(importFile, session_id) elif (mFormat == 'all' or mFormat == 'Model'): msgStr += importModelFile(importFile, int(overwriteFlag), session_id) else: raise ARMException('Input model type ' + mFormat + ' not recognised') return 0
def package_import(pkgStr,session_id = None): from cairis.core.Borg import Borg b = Borg() buf = io.BytesIO(pkgStr) zf = ZipFile(buf) fileList = zf.namelist() modelImages = [] models = {'cairis_model' : '', 'locations' : [], 'architectural_pattern' : [], 'security_patterns' : []} for fileName in fileList: fName,fType = fileName.split('.') if (fType == 'xml'): zf.extract(fileName,b.tmpDir) modelType = ET.fromstring(open(b.tmpDir + '/' + fileName).read()).tag os.remove(b.tmpDir + '/' + fileName) if (modelType == 'cairis_model'): if (models[modelType] != ''): raise ARMException('Cannot have more than one CAIRIS model file in the package file') models[modelType] = fileName else: models[modelType].append(fileName) else: modelImages.append(fileName) cairisModel = models['cairis_model'] if (cairisModel == ''): raise ARMException('No CAIRIS model file in the package file') else: zf.extract(cairisModel,b.tmpDir) file_import(b.tmpDir + '/' + cairisModel,'all',1,session_id) os.remove(b.tmpDir + '/' + cairisModel) for typeKey in ['locations','architectural_pattern','security_patterns']: for modelFile in models[typeKey]: zf.extract(modelFile,b.tmpDir) if (typeKey == 'architectural_pattern'): typeKey = 'architecturalpattern' elif (typeKey == 'security_patterns'): typeKey = 'securitypattern' file_import(b.tmpDir + '/' + modelFile,typeKey,0,session_id) os.remove(b.tmpDir + '/' + modelFile) for imageFile in modelImages: buf = zf.read(imageFile) mimeType = magic.from_buffer(buf,mime=True) dbProxy = b.dbProxy if (session_id != None): dbProxy = b.settings[session_id]['dbProxy'] dbProxy.setImage(imageFile,buf,mimeType)
def createUserDatabase(dbHost,dbPort,dbRootPassword,rootDir): try: rootConn = MySQLdb.connect(host=dbHost,port=int(dbPort),user='******',passwd=dbRootPassword) rootCursor = rootConn.cursor() except _mysql_exceptions.DatabaseError as e: id,msg = e exceptionText = 'Error connecting to MySQL (id:' + str(id) + ',message:' + msg + ')' raise ARMException(exceptionText) try: dropUserDbSql = "drop database if exists cairis_user" rootCursor.execute(dropUserDbSql) except _mysql_exceptions.DatabaseError, e: id,msg = e exceptionText = 'MySQL error removing existing cairis_user database (id: ' + str(id) + ', message: ' + msg raise ARMException(exceptionText)
def main(args=None): parser = argparse.ArgumentParser(description='Computer Aided Integration of Requirements and Information Security - Model Import') parser.add_argument('modelFile',help='model file to import') parser.add_argument('--user',dest='userName',help='user name', default='cairis_test') parser.add_argument('--database',dest='dbName',help='database name',default='cairis_test') parser.add_argument('--type',dest='modelFormat',help='model type to import. One of securitypattern, attackpattern, tvtypes, directory, requirements, riskanalysis, usability, misusability, project, domainvalues, architecturalpattern, associations, synopses, processes, assets, locations, dataflows, package, or all',default='all') parser.add_argument('--overwrite',dest='isOverwrite',help='Where appropriate, overwrite an existing CAIRIS model with this model',default=1) parser.add_argument('--image_dir',dest='imageDir',help='Where appropriate, directory for model images (overwrites default_image_dir value in cairis.cnf)') args = parser.parse_args() mFormat = args.modelFormat importFile = args.modelFile overwriteFlag = args.isOverwrite if (os.access(importFile, os.R_OK)) == False: raise ARMException("Cannot access " + importFile) import cairis.core.BorgFactory from cairis.core.Borg import Borg cairis.core.BorgFactory.initialise(user=args.userName,db=args.dbName) b = Borg() if (mFormat == 'package'): pkgStr = open(importFile,'rb').read() package_import(pkgStr) else: if args.imageDir != None: b.imageDir = os.path.abspath(args.imageDir) file_import(importFile,mFormat,overwriteFlag)
def updateTrustBoundaries(self): for tbKey in self.theTrustBoundaries: tbMinX = self.theTrustBoundaries[tbKey]['minX'] tbMaxX = self.theTrustBoundaries[tbKey]['maxX'] tbMinY = self.theTrustBoundaries[tbKey]['minY'] tbMaxY = self.theTrustBoundaries[tbKey]['maxY'] tbName = self.theTrustBoundaries[tbKey]['name'] for objtKey in self.theObjects: objtName = self.theObjects[objtKey]['name'] minX = self.theObjects[objtKey]['minX'] maxX = self.theObjects[objtKey]['maxX'] minY = self.theObjects[objtKey]['minY'] maxY = self.theObjects[objtKey]['maxY'] if (tbMinX <= minX and tbMaxX >= maxX and tbMinY <= minY and tbMaxY >= maxY): if (tbKey not in self.theUpdatedTrustBoundaries): self.theUpdatedTrustBoundaries[tbKey] = { 'name': tbName, 'components': [] } compType = self.theObjects[objtKey]['type'] if (compType == 'entity'): raise ARMException( "Cannot add entity " + objtName + " to trust boundary " + tbName + ". Entities are invalid trust boundary components." ) else: self.theUpdatedTrustBoundaries[tbKey][ 'components'].append({ 'name': objtName, 'type': compType })
def updateFlows(self): validFlowTypes = set([('entity', 'process'), ('process', 'entity'), ('datastore', 'process'), ('process', 'datastore'), ('process', 'process')]) for objtKey in self.theFlows: f = self.theFlows[objtKey] dfName = f['name'] fromName = self.theObjects[f['from_name']]['name'] fromType = self.theObjects[f['from_name']]['type'] toName = self.theObjects[f['to_name']]['name'] toType = self.theObjects[f['to_name']]['type'] if ((fromType, toType) not in validFlowTypes): raise ARMException('Data flow ' + dfName + ' is invalid because ' + fromType + ' to ' + toType + ' flows are not permissible.') else: self.theUpdatedFlows.append({ 'name': dfName, 'from_name': fromName, 'from_type': fromType, 'to_name': toName, 'to_type': toType, 'assets': f['assets'] })
def extractModel(session_id = None,ignoreValidityCheck = 0): b = Borg() if (ignoreValidityCheck == 0): valStr = b.get_dbproxy(session_id).validateForExport() if (len(valStr) > 0): raise ARMException(valStr) xmlBuf = '<?xml version="1.0"?>\n<!DOCTYPE cairis_model PUBLIC "-//CAIRIS//DTD MODEL 1.0//EN" "http://cairis.org/dtd/cairis_model.dtd">\n<cairis_model>\n\n\n' xmlBuf+= b.get_dbproxy(session_id).tvTypesToXml(0)[0] + '\n\n' xmlBuf+= b.get_dbproxy(session_id).domainValuesToXml(0)[0] + '\n\n' xmlBuf+= b.get_dbproxy(session_id).projectToXml(0) + '\n\n' xmlBuf+= b.get_dbproxy(session_id).riskAnalysisToXml(0)[0] + '\n\n' xmlBuf+= b.get_dbproxy(session_id).usabilityToXml(0)[0] + '\n\n' xmlBuf+= b.get_dbproxy(session_id).goalsToXml(0)[0] + '\n\n' xmlBuf+= b.get_dbproxy(session_id).associationsToXml(0)[0] + '\n\n' xmlBuf+= b.get_dbproxy(session_id).synopsesToXml(0)[0] + '\n\n' xmlBuf+= b.get_dbproxy(session_id).misusabilityToXml(0)[0] + '\n\n' xmlBuf+= b.get_dbproxy(session_id).dataflowsToXml(0)[0] + '\n\n' xmlBuf+= b.get_dbproxy(session_id).locationsToXml()[0] + '\n\n</cairis_model>' return xmlBuf
def on_ok(self): try: if (len(self.theUsername.value) > 255): raise ARMException( "Username cannot be longer than 255 characters") self.createUserDatabase() self.createCairisCnf() os.environ["CAIRIS_CFG"] = str(self.theFileName.value) sys.path.insert(0, self.pathName) fileName = os.environ.get("HOME") + "/.bashrc" f = open(fileName, 'a') f.write("export CAIRIS_CFG=" + str(self.theFileName.value) + "\n") f.write("export PYTHONPATH=${PYTHONPATH}:" + self.pathName + "\n") f.close() from cairis.bin.add_cairis_user import user_datastore, db db.create_all() user_datastore.create_user(email=self.theUsername.value, password=self.thePassword.value) db.session.commit() createDatabaseAccount(self.theRootPassword.value, self.theHost.value, self.thePort.value, self.theUsername.value, '') createDatabaseAndPrivileges(self.theRootPassword.value, self.theHost.value, self.thePort.value, self.theUsername.value, '', self.theUsername.value + '_default') createDatabaseSchema(self.theRootDir.value, self.theHost.value, self.thePort.value, self.theUsername.value, '', self.theUsername.value + '_default') self.parentApp.setNextForm(None) except ARMException as e: np.notify_confirm(str(e), title='Error') except SQLAlchemyError as e: np.notify_confirm('Error adding CAIRIS user: '******'Error')
except _mysql_exceptions.DatabaseError, e: id,msg = e exceptionText = 'MySQL error removing existing cairis_user database (id: ' + str(id) + ', message: ' + msg raise ARMException(exceptionText) createDatabaseAccount(dbRootPassword,dbHost,dbPort,'cairis_test','cairis_test') createDatabaseAndPrivileges(dbRootPassword,dbHost,dbPort,'cairis_test','cairis_test','cairis_test_default') createDatabaseSchema(rootDir,dbHost,dbPort,'cairis_test','cairis_test','cairis_test_default') try: createUserDbSql = "create database if not exists cairis_user" rootCursor.execute(createUserDbSql) except _mysql_exceptions.DatabaseError, e: id,msg = e exceptionText = 'MySQL error creating cairis_user database (id: ' + str(id) + ', message: ' + msg raise ARMException(exceptionText) try: recursionDepthSql = "set global max_sp_recursion_depth = 255" rootCursor.execute(recursionDepthSql) except _mysql_exceptions.DatabaseError, e: id,msg = e exceptionText = 'MySQL error setting recursion depth (id: ' + str(id) + ', message: ' + msg raise ARMException(exceptionText) try: flushPrivilegesSql = "flush privileges" rootCursor.execute(flushPrivilegesSql) except _mysql_exceptions.DatabaseError, e: id,msg = e exceptionText = 'MySQL error flushing privileges (id: ' + str(id) + ', message: ' + msg
def startElement(self, name, attrs): if (name == 'object'): self.theObjectId = attrs['id'] if self.theModelType == 'dataflow': if 'type' not in attrs: if 'assets' not in attrs and self.theObjectId != '0': self.theFlows[self.theObjectId] = { 'assets': ['Unknown information'] } elif 'assets' in attrs and self.theObjectId != '0': self.theFlows[self.theObjectId] = { 'name': 'Undefined flow', 'assets': list( map(lambda v: v.strip(), attrs['assets'].split(','))) } self.inFlow = 1 else: objtType = attrs['type'].lower().strip() if objtType in [ 'trust_boundary', 'trust boundary', 'trustboundary' ]: if 'name' not in attrs: raise ARMException( 'Trust boundary defined without a name') self.theTrustBoundaries[self.theObjectId] = { 'name': sanitise(attrs['name']) } self.inTrustBoundary = 1 else: if 'label' not in attrs: raise ARMException( 'DFD object defined without a name') objtName = sanitise(attrs['label']) if objtType not in ['process', 'entity', 'datastore']: raise ARMException( objtType + ' is not a valid type for DFD object ' + objtName) self.theObjects[self.theObjectId] = { 'name': objtName, 'type': objtType } self.inObject = 1 elif self.theModelType == 'asset': if 'label' not in attrs: raise ARMException('Object ' + self.theObjectId + " has no label.") assetName = attrs['label'].strip() assetType = 'information' if 'type' in attrs: assetType = attrs['type'].lower().strip() if (assetType not in [ 'hardware', 'information', 'people', 'software', 'systems' ]): raise ARMException( attrs['type'] + " is an invalid type for asset " + assetName + ". Valid types are Hardware, Information, People, Software, and Systems." ) assetSC = 'TBD' if 'short_code' in attrs: assetSC = attrs['short_code'] assetDesc = 'To be defined' if 'description' in attrs: assetDesc = attrs['description'] assetSig = 'To be defined' if 'significance' in attrs: assetSig = attrs['significance'] secProperties = [0, 0, 0, 0, 0, 0, 0, 0] propRationale = [ 'None', 'None', 'None', 'None', 'None', 'None', 'None', 'None' ] secAttrs = [ 'confidentiality', 'integrity', 'availability', 'accountability', 'anonymity', 'pseudonymity', 'unlinkability', 'unobservability' ] valueLookup = {'none': 0, 'low': 1, 'medium': 2, 'high': 3} for idx, secAttr in enumerate(secAttrs): saKey = '' if secAttr in attrs: saKey = secAttr elif secAttr not in attrs and secAttr.capitalize( ) in attrs: saKey = secAttr.capitalize() if saKey != '': secProp = attrs[saKey].lower().strip() if secProp not in valueLookup: raise ARMException(secProp + ' is an invalid ' + secAttr + ' value for asset ' + assetName) else: propValue = valueLookup[secProp] secProperties[idx] = propValue prKey = secAttr + '_rationale' if prKey in attrs: propRationale[idx] = attrs[prKey] else: if propValue == 0: propRationale[idx] = 'None' else: propRationale[idx] = 'To be defined' else: secProperties[idx] = 0 propRationale[idx] = 'None' if (secProperties == [0, 0, 0, 0, 0, 0, 0, 0]): secAttrs = [0, 0, 1, 0, 0, 0, 0, 0] propRationale = [] for secProp in secProperties: if (secProp == 0): propRationale.append('None') else: propRationale.append('To be defined') self.theObjects[self.theObjectId] = { 'name': assetName, 'short_code': assetSC, 'type': assetType.capitalize(), 'description': assetDesc, 'significance': assetSig, 'properties': secProperties, 'rationale': propRationale } elif (name == 'mxCell' and self.theModelType == 'dataflow' and self.inFlow): objectId = self.theObjectId if ('source' in attrs and 'target' in attrs and self.inFlow): if objectId in self.theFlows: self.theFlows[objectId]['from_name'] = attrs['source'] self.theFlows[objectId]['from_type'] = '' self.theFlows[objectId]['to_name'] = attrs['target'] self.theFlows[objectId]['to_type'] = '' elif ('parent' in attrs and objectId in self.theFlows and attrs['parent'] != '0'): self.theFlows[objectId]['name'] = attrs['value'] self.inFlow = 0 elif (name == 'mxCell' and self.theModelType == 'asset' and 'source' in attrs and 'target' in attrs): if ('style' not in attrs): raise ARMException('Missing style attribute in mxCell id ' + attrs['id']) d = attrsToDict(attrs['style']) headNav = 0 tailNav = 0 headType = 'Association' tailType = 'Association' if (('startArrow' not in d) and ('endArrow' not in d) and ('edgeStyle' in d) and (d['edgeStyle'] == 'orthogonalEdgeStyle')): tailNav = 1 else: if (('startArrow' not in d) or (d['startArrow'] == 'None')): headType = 'Association' elif d['startArrow'] in ['classic', 'open', 'openThin']: headType = 'Association' headNav = 1 elif d['startArrow'] in ['diamond', 'diamondThin']: headType = 'Aggregation' if d['startFill'] == 1: headType = 'Composition' elif d['startArrow'] == 'block': headType = 'Inheritance' if (('endArrow' not in d) or (d['endArrow'] == 'None')): tailType = 'Association' elif d['endArrow'] in ['classic', 'open', 'openThin']: tailType = 'Association' tailNav = 1 elif d['endArrow'] in ['diamond', 'diamondThin']: tailType = 'Aggregation' if d['endFill'] == 1: tailType = 'Composition' elif d['endArrow'] == 'block': tailType = 'Inheritance' self.theAssociations.append({ 'head': attrs['source'], 'tail': attrs['target'], 'headType': headType, 'headNav': headNav, 'tailType': tailType, 'tailNav': tailNav }) elif (name == 'mxGeometry' and self.theModelType == 'dataflow'): if (self.inObject): self.theObjects[self.theObjectId]['minX'] = float(attrs['x']) self.theObjects[self.theObjectId]['maxX'] = float( attrs['x']) + float(attrs['width']) self.theObjects[self.theObjectId]['minY'] = float(attrs['y']) self.theObjects[self.theObjectId]['maxY'] = float( attrs['y']) + float(attrs['height']) elif (self.inTrustBoundary): self.theTrustBoundaries[self.theObjectId]['minX'] = float( attrs['x']) self.theTrustBoundaries[self.theObjectId]['maxX'] = float( attrs['x']) + float(attrs['width']) self.theTrustBoundaries[self.theObjectId]['minY'] = float( attrs['y']) self.theTrustBoundaries[self.theObjectId]['maxY'] = float( attrs['y']) + float(attrs['height'])
class CAIRISDatabaseConfigurationForm(np.ActionForm): def create(self): self.findRootDir() self.pathName = os.path.realpath(__file__) self.pathName = self.pathName.replace("quick_setup.py", "") self.name = "Configure CAIRIS database and initial account" self.theHost = self.add(np.TitleText, name="Database host:", value="localhost") self.thePort = self.add(np.TitleText, name="Database port:", value="3306") self.theRootPassword = self.add(np.TitlePassword, name="Database root password:"******"") self.theTmpDir = self.add(np.TitleText, name="Temp directory:", value="/tmp") self.theRootDir = self.add(np.TitleText, name="Root directory:", value=self.pathName + "cairis") self.theImageDir = self.add(np.TitleText, name="Default image directory:", value=".") self.theFileName = self.add(np.TitleText, name="CAIRIS configuration file name:", value=os.environ.get("HOME") + "/cairis.cnf") self.theWebPort = self.add(np.TitleText, name="Web port:", value="7071") self.theLogLevel = self.add(np.TitleText, name="Log level:", value="warning") self.theStaticDir = self.add(np.TitleText, name="Static directory:", value=self.pathName + "cairis/web") self.theUploadDir = self.add(np.TitleText, name="Upload directory:", value="/tmp") self.theUsername = self.add(np.TitleText, name="Initial Username:"******"") self.thePassword = self.add(np.TitlePassword, name="Initial Password:"******"") self.theSecretKey = os.urandom(16).encode('hex') self.theSalt = os.urandom(16).encode('hex') def findRootDir(self): self.defaultRootDir = "/usr/local/lib/python2.7/dist-packages/cairis" for cpath in sys.path: if "/dist-packages/cairis-" in cpath and cpath.endswith(".egg"): self.defaultRootDir = os.path.join(cpath, "cairis") break def on_ok(self): try: if (len(self.theUsername.value) > 255): raise ARMException( "Username cannot be longer than 255 characters") self.createUserDatabase() self.createCairisCnf() os.environ["CAIRIS_CFG"] = str(self.theFileName.value) sys.path.insert(0, self.pathName) fileName = os.environ.get("HOME") + "/.bashrc" f = open(fileName, 'a') f.write("export CAIRIS_CFG=" + str(self.theFileName.value) + "\n") f.write("export PYTHONPATH=${PYTHONPATH}:" + self.pathName + "\n") f.close() from cairis.bin.add_cairis_user import user_datastore, db db.create_all() user_datastore.create_user(email=self.theUsername.value, password=self.thePassword.value) db.session.commit() createDatabaseAccount(self.theRootPassword.value, self.theHost.value, self.thePort.value, self.theUsername.value, '') createDatabaseAndPrivileges(self.theRootPassword.value, self.theHost.value, self.thePort.value, self.theUsername.value, '', self.theUsername.value + '_default') createDatabaseSchema(self.theRootDir.value, self.theHost.value, self.thePort.value, self.theUsername.value, '', self.theUsername.value + '_default') self.parentApp.setNextForm(None) except ARMException as e: np.notify_confirm(str(e), title='Error') except SQLAlchemyError as e: np.notify_confirm('Error adding CAIRIS user: '******'Error') def on_cancel(self): self.parentApp.setNextForm(None) def createUserDatabase(self): try: rootConn = MySQLdb.connect(host=self.theHost.value, port=int(self.thePort.value), user='******', passwd=self.theRootPassword.value) rootCursor = rootConn.cursor() except _mysql_exceptions.DatabaseError as e: id, msg = e exceptionText = 'Error connecting to MySQL (id:' + str( id) + ',message:' + msg + ')' raise ARMException(exceptionText) try: dropUserDbSql = "drop database if exists cairis_user" rootCursor.execute(dropUserDbSql) except _mysql_exceptions.DatabaseError, e: id, msg = e exceptionText = 'MySQL error removing existing cairis_user database (id: ' + str( id) + ', message: ' + msg raise ARMException(exceptionText) createDatabaseAccount(self.theRootPassword.value, self.theHost.value, self.thePort.value, 'cairis_test', 'cairis_test') createDatabaseAndPrivileges(self.theRootPassword.value, self.theHost.value, self.thePort.value, 'cairis_test', 'cairis_test', 'cairis_test_default') createDatabaseSchema(self.theRootDir.value, self.theHost.value, self.thePort.value, 'cairis_test', 'cairis_test', 'cairis_test_default') try: createUserDbSql = "create database if not exists cairis_user" rootCursor.execute(createUserDbSql) except _mysql_exceptions.DatabaseError, e: id, msg = e exceptionText = 'MySQL error creating cairis_user database (id: ' + str( id) + ', message: ' + msg raise ARMException(exceptionText)