def add_inator(data): """Add a new inator.""" if request.method == 'GET': return {} if request.method == 'POST': try: inators = data['inators'] except KeyError: data['inators'] = {} inators = data['inators'] try: Condition(int(request.form['condition'])) except ValueError: abort(400) new_inator = { 'ident': str(uuid.uuid4()), 'name': request.form['name'], 'added': datetime.now(), 'location': request.form['location'], 'condition': Condition(int(request.form['condition'])), 'description': request.form['description'] } inators[new_inator['ident']] = new_inator data['inators'] = inators flash("Successfully added " + new_inator['name'] + ".", 'success') return redirect(url_for('list_inators'))
def build(self): self.create_initial_state("s1", "fire_locator", sim.find_fire, Condition(3, 0)).create_state( "s2", "fire_fighters", sim.go_to_fire_location, Condition(3, 0)).create_state( "s3", "fire_locator", sim.tend_away_from_fire, Condition(3, 0))
def test_to_srt(): global a1, a2, a3 assert "{} = {}".format(a1, a2) == str( Condition(Side(a1), Side(a2), ConditionState.IS_EQUAL)) assert "{} != 0".format(a1) == str( Condition(Side(a1), Side(), ConditionState.IS_NOT_ZERO)) assert "{} != {}".format(a1, a2) == str( Condition(Side(a1), Side(a2), ConditionState.IS_NOT_ZERO)) assert "{} = 0".format(a1) == str( Condition(Side(a1), Side(), ConditionState.IS_ZERO))
def CG1(): t1 = table.Table("data/posts.xml") t2 = select(t1, Condition("PostTypeId","==", 1), ["Id","OwnerUserId"]) t3 = select(t1, Condition("PostTypeId","==", 2), ["ParentId","OwnerUserId"]) t4 = join(t2,t3,[("Id","ParentId")]) t5 = group(t4, ["OwnerUserId1", "OwnerUserId2"], "Count", "cnt") g = graph.Graph("directed") g.addNodes(t1,"OwnerUserId") g.addEdges(t5,"OwnerUserId1","OwnerUserId2",["Count"]) return g
def CG9(): t1 = table.Table("data/badges.xml") #[UserId","Name"...] t2 = table.Table("data/posts.xml") #["Id","PostTypeId","OwnerUserId",...] t3 = join(t1,t2,["UserId"],["OwnerUserId"],["Name"],["PostTypeId","ParentId","Id"]) t4 = select(t3, Condition("PostTypeId", "==", 1)) #Questions t5 = select(t3, Condition("PostTypeId", "==", 2)) #Answers t6 = join(t5,t4,["ParentId"],["Id"],["Name"],["Name"],["Id","Badge1","Badge2"]) t7 = group(t6,["Badge1","Badge2"],"Count","cnt") g = graph.Graph("directed") g.addNodes(t1,"Name") g.addEdges(t7,"Badge1","Badge2",["Count"]) return g
def get_captcha(): condition_connections = ConditionConnection.choice() if condition_connections[0] == ConditionConnection.Single: # 单个条件 cond = Condition(Condition.Any).generate_condition() return condition_connections[2] % cond[0], condition_connections[1](cond[1]) elif condition_connections[0] == ConditionConnection.Conbine: # 组合条件 cond1 = Condition(Condition.Any).generate_condition() cond2 = Condition(Condition.Any).generate_condition() return condition_connections[2] % (cond1[0], cond2[0]), condition_connections[1](cond1[1], cond2[1]) elif condition_connections[0] == ConditionConnection.ConbineSum: # 组合求合 cond1 = Condition(Condition.UseData).generate_condition() cond2 = Condition(Condition.UseData).generate_condition() return condition_connections[2] % (cond1[0], cond2[0]), condition_connections[1](cond1[1], cond2[1])
def __init__(self, ast_node, func): self.func = func self.ast_node = ast_node self.asm = "" # Assignment if ast_node.token.text == "ASSIGN": # Get the variable and expression var, expr = ast_node.children var = func.getVar(var.text) # Calculate the answer expr = Expression(expr, func) factor = expr.evaluate() # Add the calculations to the function body self.asm += str(expr) self.asm += self.header() self.asm += var.assign(factor, func.prog.next_loop.next()) if ast_node.token.text == "IF": cond, true_body, false_body = ast_node.children idnum = self.func.prog.next_loop.next() self.true = ".truebranch%s" % idnum self.false = ".falsebranch%s" % idnum self.asm += IF_ASM.format( cond=Condition(cond, self), id=idnum, true_body=''.join( map(str, [Statement(s, self.func) for s in true_body.children])), false_body=''.join( map(str, [Statement(s, self.func) for s in false_body.children]))) if ast_node.token.text == "WHILE": cond, body = ast_node.children idnum = self.func.prog.next_loop.next() self.true = ".loopbegin%s" % idnum self.false = ".loopexit%s" % idnum self.asm += WHILE_ASM.format( id=idnum, cond=Condition(cond, self), body=''.join( map(str, [Statement(s, self.func) for s in body.children])))
def splitString(message): ac = Action() con = Condition() message = message.lower() m = message.split(". ") if len(m) > 1: for i in m: splitString(i) #print(message) if len(message) > 1 and (message.index("if") == 0 or message.index("if") == 1): strings = message.split(",") conditions = strings[0].split(" ") cond = "" for word in conditions: if word == "and": analyzeString(cond, "condition", "and") cond = "" elif word == "or": analyzeString(cond, "condition", "or") cond = "" else: cond += word + " " analyzeString(cond, "condition", "na", con, ac) analyzeString(strings[1], "action", "na", con, ac) #print(json.dumps({**con.toJSON(), **ac.toJSON()})) return [{**con.toJSON(), **ac.toJSON()}]
def main(): parser = argparse.ArgumentParser(description="Attack agent") parser.add_argument('-f', '--filename', help='database filename', dest='db_file') parser.add_argument('-p', '--port', help='Listener port number (default port is 10000)', type=int, default=10000) parser.add_argument('-ip', help='Listener ip address', type=str) args = parser.parse_args() if args.db_file is not None: database_records = read_records_from_json(args.db_file) manager = AttackManager(database_records) manager.update() print(manager) # assumed_target_state = {"protocol": "ip", "address": "127.0.0.1"} goal = Condition() goal.add(("shell", "EQ PERMANENT")) goal.add(("privilege", "EQ 0")) print(goal) else: print('invalid DB file')
def test_spider(): from session import Session from condition import Condition from spider import Spider from parameter import Parameter from datetime import datetime s = Session() c = Condition() # parameter = Parameter(param=str(c), sess=s) spider = Spider(sess=s) # page: 每页几条; order: 排序标准; direction: 顺序 (asc - 正序 desc - 倒序) print( spider.tree_content(param=Parameter(param=str( c.district('西藏自治区').date(datetime(1991, 1, 1), datetime( 2018, 9, 15))), sess=s))) for i in spider.content_list(param=Parameter(param=str( c.district('西藏自治区').date(datetime(1991, 1, 1), datetime(2018, 9, 15))), sess=s), page=20, order='法院层级', direction='asc'): print(i)
def detect_change(data): mydb = connect_to_db() mycursor = mydb.cursor(prepared=True) for i in range(len(data)): item = data[i] print(item.condition_text) print("last_value: {}".format(item.last_value)) condition = Condition(item.condition_text) query_string = 'http://{}/marketdata/{}'.format(marketdata_host, item.symbol) dat = requests.get(url = query_string).json() is_condition_true = condition.evaluate(dat) last_value = item.last_value item.last_value = is_condition_true data[i] = item print(dat) print(condition.evaluate(dat)) # Only notify if true and it previously was not true, to avoid constant notifications if condition.evaluate(dat) and last_value != is_condition_true: user = fetch_user(item.user_id, mycursor) print('Notifying user: {}'.format(user.username)) text = "{}%20your%20notification%20for%20{}:%20{}".format(user.username, item.symbol, item.condition_text) if item.notification_method == NOTIFICATION_METHOD.SMS: query_string = 'http://{}:{}/notify/text?message={}&number=test_num'.format(notification_service_host, notification_service_port, text) requests.post(url = query_string) elif item.notification_method == NOTIFICATION_METHOD.EMAIL: query_string = 'http://{}:{}/notify/email?message={}&email=test_address'.format(notification_service_host, notification_service_port, text) requests.post(url = query_string) elif item.notification_method == NOTIFICATION_METHOD.BOTH: query_string = 'http://{}:{}/notify/text?message={}&number=test_num'.format(notification_service_host, notification_service_port, text) requests.post(url = query_string) query_string = 'http://{}:{}/notify/email?message={}&email=test_address'.format(notification_service_host, notification_service_port, text) requests.post(url = query_string) mydb.disconnect() return data
def main(): """ The entry point of red agent """ listener_port = constant.DEFAULT_LISTENER_PORT #TODO: Command line arguments should be handled elegantly. if len(sys.argv) > 1: listener_port = sys.argv[1] AttackDB().update() Listener().work(constant.DEFAULT_LISTENER_IP, int(listener_port)) assumed_state = { constant.STATE_KEY_PROTOCOL: constant.STATE_VALUE_PROTOCOL_IP, constant.STATE_KEY_ADDRESS: constant.DEFAULT_TARGET_IP } goal = Condition() goal.add((constant.STATE_KEY_SHELL, constant.CONDITION_OPERATOR_EQUAL, constant.STATE_VALUE_SHELL_PERMANENT)) goal.add((constant.STATE_KEY_PRIVILEGE, constant.CONDITION_OPERATOR_EQUAL, constant.STATE_VALUE_PRIVILEGE_ROOT)) planner = Planner(assumed_state, goal) try: planner.make_plan() print(planner) planner.run() except Exception as e: traceback.print_exc() Listener().stop() raise e Listener().stop() sys.exit(0)
def add_inator(data): """Add a new inator.""" if request.method == 'GET': return {} if request.method == 'POST': try: # Getting random UUID data ident = str(uuid.uuid4()) # Creating new dictionary to append to data newInator = { 'name': request.form['name'], 'location': request.form['location'], 'description': request.form['description'], 'added': datetime.now(), 'ident': ident, 'condition': Condition(int(request.form['condition'])) } except ValueError: # Bad gatway abort(400) try: # Make sure the identifier exists and add it to the data data['inators'][ident] = newInator flash('Successfully added {}.'.format(newInator['name'], 'success')) return redirect(url_for('list_inators')) except KeyError: return redirect(url_for('list_inators'))
def inator_record(name, added): """Return an inator record. Return a dictionary that represents data for an inator. Each record contains a randomly generated identifier, a random location, a random condition, and a random description. The name of the inator and the date/time it was added are requried as parameters. :param str name: The name of the inator :param datetime.datetime added: The date/time the inator record was added to the searchinator. :return: A dictionary representing an inator :rtype: dict """ return { 'ident': str(uuid.uuid4()), 'name': name, 'added': added, 'location': random.choice(PLACES), 'condition': Condition(random.randint(1, 5)), 'description': ' '.join(random.sample(LOREM_IPSUM, random.randint(1, 5))) }
def __init__(self, id1, id2, effect): if isinstance(id1, int) and isinstance(id2, int) and isinstance( effect, Condition): self.id1 = id1 # int self.id2 = id2 # int self.effect = Condition(effect.getState(), effect.getPredicate()) else: raise Exception("[Link]: invalid parameters types")
def p_condition(p): '''condition : value EQU value | value INEQU value | value LOWERTHAN value | value GREATERTHAN value | value LOWEREQU value | value GREATEREQU value''' p[0] = Condition(left=p[1], operator=p[2], right=p[3])
def p_condition(p): ''' condition : expression EQUAL expression | expression LTHAN expression | expression GTHAN expression | expression NOT_EQUAL expression ''' p[0] = Condition(p[1], p[2], p[3])
def fetchConditions(): cur.execute("SELECT id FROM conditions;") res = [] i = 0 results = cur.fetchall() for row in results: res.append(Condition(row[0], cur)) i = i + 1 return res
def CG2(): t1 = table.Table("data/posts.xml") #["Id","PostTypeId","OwnerUserId",...] t2 = table.Table("data/votes.xml") #["PostId","VoteTypeId","UserId",...] t3 = select(t1, attributes=["Id","OwnerUserId"]) t4 = select(t2, Condition("VoteTypeId", "==", 2),["PostId","UserId"]) t5 = join(t4,t3,[("PostId","Id")]) t6 = group(t5,["UserId","OwnerUserId"], "Count","cnt") g = graph.Graph("directed") g.addNodes(t1,"OwnerUserId") g.addNodes(t2,"UserId") g.addEdges(t6,"UserId","OwnerUserId",["Count"]) return g
def whereParser(tables, abb2table, table_num, command): ret = [] if command == '': return ret conds = re.split(r'\s*AND\s*', command) for c in conds: if c[0] == '(' and c[-1] == ')': condapps = CompCondition(c[1:-1]) ret.append(condapps) for condapp in condapps.conditions: if table_num == 1: table = abb2table.values()[0] kname = table + '_' + condapp.left if kname not in tables: tables[kname] = getIndex(table, condapp.left) else: if '__' in condapp.left: table = abb2table[condapp.left.split('__')[0]] kname = table + '_' + condapp.left.split('__')[1] if kname not in tables: tables[kname] = getIndex( table, condapp.left.split('__')[1]) if '__' in condapp.right: table = abb2table[condapp.right.split('__')[0]] kname = table + '_' + condapp.right.split('__')[1] if kname not in tables: tables[kname] = getIndex( table, condapp.right.split('__')[1]) else: condapp = Condition(c) ret.append(condapp) if table_num == 1: table = abb2table.values()[0] kname = table + '_' + condapp.left if kname not in tables: tables[kname] = getIndex(table, condapp.left) else: if '__' in condapp.left: table = abb2table[condapp.left.split('__')[0]] kname = table + '_' + condapp.left.split('__')[1] if kname not in tables: tables[kname] = getIndex(table, condapp.left.split('__')[1]) if '__' in condapp.right: table = abb2table[condapp.right.split('__')[0]] kname = table + '_' + condapp.right.split('__')[1] if kname not in tables: tables[kname] = getIndex(table, condapp.left.split('__')[1]) return ret
def as_inator(dct): """Attempt to construct values of an inator with appropriate types.""" keyset = {'ident', 'name', 'location', 'description', 'condition', 'added'} if set(dct.keys()) == keyset: try: new_dct = dct.copy() new_dct['added'] = load_time(new_dct['added']) new_dct['condition'] = Condition(int(new_dct['condition'])) return new_dct except ValueError: return dct else: return dct
def test_court(): from session import Session from condition import Condition from spider import Spider from parameter import Parameter from datetime import datetime s = Session() c = Condition().district('北京市') spider = Spider(sess=s) # print(spider.tree_content(param=Parameter(param=str(c), sess=s))) # print(spider.court_tree_content(condition=c, parval='北京市')) for i in spider.court(condition=c.date(start_date=datetime(2017, 5, 15), end_date=datetime(2017, 5, 16)), district='广东省'): print(c.court(*i[0:3]), i[3])
def gen_all_common_conditions( self, variables: List[Variable] ) -> List[Tuple[List[Condition], List[Condition]]]: assert all([ isinstance(x, Variable) and not x.is_unknown() for x in variables ]) cconditions = [] # type: List[Tuple[List[Condition], List[Condition]]] assert len(variables) > 0 for zero_pos in self.__generate_zero_positions(variables): zero_conds = [] # type: List[Condition] none_zero_conds = [] # type: List[Condition] for index in range(len(variables)): if index in zero_pos: zero_conds.append( Condition(Side(variables[index]), Side(), ConditionState.IS_ZERO)) else: none_zero_conds.append( Condition(Side(variables[index]), Side(), ConditionState.IS_NOT_ZERO)) cconditions.append((zero_conds, none_zero_conds)) return cconditions
def wait_for(self, condition_input, timeout=5, sleep_after=0): """ Wait for a condition to be true on the driver in timeout seconds Args: condition_input (Condition / function): condition to evaluate, either an instance of the Condition class or a function that evaluates to truthy or falsey timeout (int): seconds to wait before raising a selenium TimeoutException sleep_after (int): seconds to sleep after the condition is met """ if not isinstance(condition_input, Condition): condition = Condition(lambda d: condition_input(), self.driver) else: condition = condition_input wait_for(condition, timeout=timeout) sleep(sleep_after)
def update(self): """ Storing each attack records into __records in an instance of this class. An attack record is stored in there as an instance of RT class. """ global DB_RECORDS for e in DB_RECORDS: keys = list(e.keys()) if not "Name" in keys or not "Preconditions" in keys \ or not "Postconditions" in keys or not "Command" in keys: print("INVALID RECORD :\n" + str(e) + "\n") continue name = e["Name"] cond = Condition() for pre in e["Preconditions"]: cond.add(pre) post = e["Postconditions"] cmd = e["Command"] self.__records.append(RT(name, cond, post, cmd))
def update(self): """ Storing each attack record into __records as an instance of this class. An attack record is stored in there as an instance of AttackRecord class. """ for record in self.records_from_db: keys = list(record.keys()) if not ("Name" in keys) or \ not ("Preconditions" in keys) or \ not ("Postconditions" in keys) or \ not ("Command" in keys): print("INVALID RECORD :\n" + str(record) + "\n") continue name = record["Name"] pre_conditions = Condition() for pre_condition in record["Preconditions"]: pre_conditions.add(pre_condition) post_conditions = record["Postconditions"] command = record["Command"] self.__records.append( AttackRecord(name, pre_conditions, post_conditions, command))
def test_equality_false(self): cond = Condition('x == y') self.assertEqual(False, cond.evaluate(self.data), 'Should be equal')
from step import Step from condition import Condition from link import Link steps = [] steps.append( Step(0, "Start", [], [ Condition(True, "on b a"), Condition(True, "on c b"), Condition(True, "on a table0"), Condition(True, "clear c"), Condition(True, "clear table1") ])) steps.append( Step(1, "Finish", [ Condition(True, "clear a"), Condition(True, "clear b"), Condition(True, "on b c") ], [])) steps.append( Step(2, "mov c b table1", [ Condition(True, "on c b"), Condition(True, "clear c"), Condition(True, "clear table1") ], [ Condition(True, "on a table0"), Condition(True, "on b a"), Condition(True, "clear b"), Condition(True, "clear c"), Condition(True, "on c table1") ])) steps.append(
from step import Step from condition import Condition from link import Link steps = [] steps.append( Step(0, "start", [], [ Condition(True, "clear table4"), Condition(True, "clear table3"), Condition(True, "on c a"), Condition(True, "on b table0"), Condition(True, "on a table1"), Condition(True, "clear c"), Condition(True, "clear b") ])) steps.append( Step(1, "finish", [Condition(True, "on a b"), Condition(True, "on b c")], [])) steps.append( Step(2, "move a table1 b", [ Condition(True, "on a table1"), Condition(True, "clear b"), Condition(True, "clear a") ], [ Condition(True, "on a b"), Condition(False, "on a table1"), Condition(True, "clear table1"), Condition(False, "clear b") ])) steps.append( Step(3, "move b a c", [ Condition(True, "on b a"),
def test_multiple_conditions_beginning_and_end_brackets(self): cond = Condition('( x == y or z < 1 ) and ( x == y and z == x)') # Will evaluate to ( False or True ) and ( False and True ) self.assertEqual(False, cond.evaluate(self.data), 'Should be equal')