Ejemplo n.º 1
0
def modify_control_flow_1_post_func(program, arg):
    if isinstance(program, Statements):
        if shouldi(arg=arg):
            vardeclist, name = genVarNotIn(arg["ident_present"])
            old = program.statements_list
            if len(old) != 0 and not is_break_inside(program):
                li = []
                we, wgt = generate_expr_for_compare(name)
                for index in range(len(old)):
                    e, gt = generate_expr_for_compare(name)
                    cb = CaseBlock(Statements([old[index]]), e)
                    li.append((cb, e, gt))
                (cb, e, gt) = li[0]
                ini = gt
                (cb1, e1, gt1) = li[0]
                for i in range(len(li) - 1):
                    (cb, e, gt) = li[i]
                    (cb1, e1, gt1) = li[i + 1]
                    cb.statement.append(gt1)
                    b = Break()
                    cb.statement.append(b)
                cb1.statement.append(wgt)
                b = Break()
                cb1.statement.append(b)
                sw = Switch(Expr([Ident(name)]), list(zip(*li)[0]))
                wh = While(Expr([we, "!=", Ident(name)]), Statements([sw]))
                program.replaceall([vardeclist, ini, wh])
    return [], arg
Ejemplo n.º 2
0
def change_str_func(program, arg):
    if isinstance(program, String):
        if len(program.value) > 1:
            list_upper_statements = get_all_upper_statements_and_pos(program)
            if list_upper_statements != [] and (not isinstance(
                    program.parent,
                    PropertyName)):  # and program != program.parent.name):
                if shouldi(arg=arg):
                    depth = jshadobf_random.randint(
                        0,
                        len(list_upper_statements) - 1)
                    s = list_upper_statements[depth][0]
                    maxi = list_upper_statements[depth][1]
                    mylist = []
                    after_escape = False
                    i = 0
                    oi = 0
                    l = program.value
                    sel = range(len(l))
                    jshadobf_random.shuffle(sel)
                    sel2 = sel[:3]
                    sel2.sort()
                    for index in sel2 + [None]:
                        i = 0
                        if index:
                            while ord(l[index - i]) >= 128:

                                print index - i
                                i += 1
                                if index - i == oi:
                                    break
                            if not (i % 2):
                                index -= 1
                        vardeclist, name = genVarNotIn(
                            arg["ident_present"],
                            Expr([String(repr(l[oi:index].encode("utf-8")))]))
                        pos = jshadobf_random.randint(0, maxi)
                        maxi = maxi + 1
                        s.insert(pos, vardeclist)
                        mylist.append(name)
                        oi = index
#
                    varlist = map(lambda x: Ident(x), mylist)
                    [
                        varlist.insert(i * 2 - 1, "+")
                        for i in range(1, len(varlist))
                    ]
                    expr = Expr([
                        Functioncall(Expr([Ident("eval")]),
                                     Listarguments([Expr(varlist)]))
                    ])
                    if program.parent.__class__ in [
                            Expr, VarDeclaration, PropertyName
                    ]:
                        program.parent.replace_item(program, expr)
    return [], arg
Ejemplo n.º 3
0
def change_list_func_post(program, arg):
    if isinstance(program, List):
        if len(program.value) > 1:
            list_upper_statements = get_all_upper_statements_and_pos(program)
            if list_upper_statements != [] and (not isinstance(
                    program.parent,
                    PropertyName)) and not is_functioncall_inside(
                        program):  # and program != program.parent.name):
                if shouldi(arg=arg):
                    ident_inside = count_object(program, [Ident])
                    if ident_inside:
                        depth = 0
                    else:
                        depth = jshadobf_random.randrange(
                            0, len(list_upper_statements))
                    s = list_upper_statements[depth][0]
                    maxi = list_upper_statements[depth][1]
                    mini = 0
                    mylist = []
                    if ident_inside:
                        mini = maxi
                    after_escape = False
                    i = 0
                    oi = 0
                    l = program.value
                    while len(l) != i:
                        i = oi + int(abs(jshadobf_random.gauss(
                            0,
                            len(l) / 3))) + 1
                        i = min(len(l), i)
                        vardeclist, name = genVarNotIn(arg["ident_present"],
                                                       Expr([List(l[oi:i])]))
                        pos = jshadobf_random.randint(mini, maxi)
                        maxi = maxi + 1
                        s.insert(pos, vardeclist)
                        mylist.append(name)
                        oi = i
                    varlist = map(lambda x: Ident(x), mylist)
                    if len(varlist) > 1:
                        callexprsuffix = CallExpressionSuffix(
                            sum([[
                                Property(Ident("concat")),
                                Listarguments([Expr([varlist[i]])])
                            ] for i in range(2, len(varlist))], []))
                        expr = Expr([
                            Functioncall(
                                MemberExpr(Expr([varlist[0]]),
                                           [Property(Ident("concat"))]),
                                Listarguments([varlist[1]]), callexprsuffix)
                        ])
                    else:
                        expr = Expr(varlist)
                    program.parent.replace_item(program, expr)
    return [], arg
Ejemplo n.º 4
0
def modify_data_flow_1_post_func(program,arg):
    if isinstance(program,Assignment):
        if shouldi(arg=arg):      
            s,pos = get_upper_statement_and_pos(program)
            s2,pos2 = get_upper_expression_statement_and_pos(program)
            if pos2 == None  and s != None:
                if not is_functioncall_inside(program):# and position_in_exprstatement(program) == 0: # TODO check position_in_exprstatement is working
                    vardeclist,name=genVarNotIn(arg["ident_present"]) 
                    s.insert(pos,Assignment(Expr([Ident(name)]),"=",program.expr))
                    s.insert(0,vardeclist)
                    program.expr = Ident(name)
                    program.expr.parent = program
    return [] , arg
Ejemplo n.º 5
0
def undeclare_var_func_post(program, variables):
    if isinstance(program, VarDeclaration):
        toaddafter = []
        indexes = range(len(program.args_dec_list))
        indexes.reverse()
        for i in indexes:
            dec = program.args_dec_list[i]
            if dec.var.name in variables:
                if dec.expr != None:
                    toaddafter.append(
                        Assignment(Ident(dec.var.name), "=", dec.expr))
                del program.args_dec_list[i]
        if isinstance(program.parent, Statements):
            pos_var_dec_list = program.parent.statements_list.index(program)
            for a in toaddafter:
                program.parent.insert(pos_var_dec_list + 1,
                                      a)  # good order due to indexes.reverse()
            if len(program.args_dec_list) == 0:
                del program.parent.statements_list[pos_var_dec_list]
        if isinstance(program.parent, Expr):
            pos_var_dec_list = program.parent.exprs.index(program)
            del program.parent.exprs[pos_var_dec_list]
            if len(toaddafter) == 1:
                program.parent.insert(pos_var_dec_list, toaddafter[0])
            else:
                program.parent.insert(pos_var_dec_list,
                                      ExpressionStatement(toaddafter))
    return [], variables
Ejemplo n.º 6
0
def duplicate_function_func_post(program, arg):
    if program.__class__ == Function:
        if shouldi(arg=arg):
            if program.ident != None:
                newfunc = deepcopy(program)
                statement, pos = get_upper_statement_and_pos(program)
                statement.insert(
                    jshadobf_random.randint(0,
                                            len(statement.statements_list) -
                                            1), newfunc)
                sl = newfunc.statements.statements_list
                if len(sl) > 0:
                    for i in range(max(1, len(sl) / 3)):
                        del sl[jshadobf_random.randint(0, len(sl) - 1)]
                i = 0
                newname = program.ident.name
                n = newname
                while newname in arg["ident_present"]:
                    i = i + 1
                    newname = program.ident.name + format(i)
                    n += " " + newname
                print red(n)
                arg["ident_present"].append(newname)
                newfunc.replace_ident(Ident(newname))
    return [], arg
Ejemplo n.º 7
0
def genVarNotIn(varnames, expr=None):
    i = jshadobf_random.randint(0, 100 * len(varnames))
    name = "dummyvar%d" % i
    while name in varnames:
        i = jshadobf_random.randint(0, 100 * len(varnames))
        name = "dummyvar%d" % i
    varnames.append(name)
    return Var([VarDeclaration(Ident(name), expr)]), name
Ejemplo n.º 8
0
def gen_dummy_expr(vartoass=None, i=0):
    operators = ['+', '-', '*', '/', "%", ">>", '<<']
    compoperators = ['==', '!=', '<', '>', '<=', '>=']
    booleanbit = ["&&", "&", "||", "|", "^"]
    possop = operators + booleanbit + compoperators
    expr = Expr([pick_type()])
    if vartoass != None:
        expr = Assignment(Expr([Ident(vartoass)]), "=", expr)
    return expr
Ejemplo n.º 9
0
def modify_data_flow_2_func(program,arg):
    if isinstance(program,Number):
        if shouldi(arg=arg):
            s,pos = get_upper_statement_and_pos(program)
            if s != None:
                whereto = jshadobf_random.randint(0,pos)
                newp = deepcopy(program)
                vardeclist,name=genVarNotIn(arg["ident_present"],newp)
                program.parent.replace_item(program, Ident(name))
                s.insert(whereto,vardeclist)
    if isinstance(program,List):
        if shouldi(arg=arg):
            s,pos = get_upper_statement_and_pos(program)
            if s != None  and not is_functioncall_inside(program):
                whereto = jshadobf_random.randint(0,pos)
                if count_object(program,[Ident] ):
                    whereto = pos
                newp = deepcopy(program)
                vardeclist,name=genVarNotIn(arg["ident_present"],newp)
                program.parent.replace_item(program, Ident(name))
                s.insert(whereto,vardeclist)
    return [] , arg
Ejemplo n.º 10
0
def aggregate_data_post_func(program, arg):
    if program.__class__ in [Program, Function]:
        l = arg["list_aggregation"].pop()
        perm = random_list_int_exclusive(0, len(l) - 1)
        #        perm = range(0,len(l))
        newl = deepcopy(l)
        newl = permute_list(newl, perm)
        vardeclist, name = genVarNotIn(arg["ident_present"], List(newl))
        i = 0
        for item in l:
            item.parent.replace_item(
                item, Expr([Ident(name),
                            Index(Number(perm.index(i)))]))
            i += 1
        program.statements.insert(0, vardeclist)
#  #      if vardeclist != None:
#  #      s.statements_list.insert(pos,Statement_plus_ending(Statements([Assignment(Var(Ident(name)),"=",program.expr)])))
#                s.insert(whereto,vardeclist)
#                if isinstance(program.parent,Expr):
#                    program.parent.replace_expr(program, Expr([Ident(name)]))

    return [], arg
Ejemplo n.º 11
0
def generate_expr_for_compare(name):
    r = jshadobf_random.randint(0, 100000)
    e = Expr([Number(r)])
    gt = Assignment(Expr([Ident(name)]), "=", Expr([Number(r)]))
    return e, gt
Ejemplo n.º 12
0
def convert_tree(tree,verbose=0):
    children = tree.getChildren()
    p = []
    if verbose > 3:
        print tree.getLine() ,":",tree.text
    if tree.text == "Program":
        p = Program(Statements([ convert_tree(c,verbose) for c in children] ))
    if tree.text == "VarDeclaration":
        if len(children) > 1:
            p = VarDeclaration(convert_tree(children[0],verbose),convert_tree(children[1],verbose))
        else:
            p = VarDeclaration(convert_tree(children[0],verbose))
    if tree.text == "Ident":
        p = Ident(children[0].text)
    if tree.text == "Suffix":
        p = Suffix(convert_tree(children[0],verbose))
    if tree.text == "MemberExpr":
        if len(children) > 1:
            p = MemberExpr(convert_tree(children[0],verbose),map(convert_tree,children[1:]))
        else:
            p = convert_tree(children[0],verbose)
    if tree.text == "Return":
        e = None
        if len(children) == 1 :
            e = convert_tree(children[0],verbose)
        p = Return(e)
    if tree.text == "ObjectLiteral" :
        o = [ convert_tree(c,verbose) for c in children]
        p = ObjectLiteral(o)
    if tree.text == "PropertyGet" :
        if children[0].text != "get":
            print "error expecting get"
            sys.exit(1)
        n = convert_tree(children[1],verbose)
        b = convert_tree(children[2],verbose)
        p = PropertyGet(n,b)
    if tree.text == "PropertySet" :
        if children[0].text != "set":
            print "error expecting set"
            sys.exit(1)
        n = convert_tree(children[1],verbose)
        i = convert_tree(children[2],verbose)
        b = convert_tree(children[3],verbose)
        p = PropertySet(n,i,b)
    if tree.text == "Function" or tree.text == "FunctionExpr":
        a = convert_tree(children[0],verbose)
        s = statement_convertor(convert_tree(children[1],verbose))
        i = None
        if len(children) == 3:
            i = convert_tree(children[2],verbose)
        funcexpr = (tree.text == "FunctionExpr")
        p = Function(i,a,s,funcexpr)
    if tree.text == "VariableStatement":
        p = convert_tree(children[0],verbose)
    if tree.text == "Var":
        p = Var(map(lambda x:convert_tree(x,verbose),children))
    if tree.text == "Listarguments":
        p = Listarguments(map(lambda x:convert_tree(x,verbose),children))
    if tree.text == "Statements":
        s = map(lambda x:convert_tree(x,verbose),children) 
        s = filter ( lambda x : x != [] , s)
        p = Statements(s)
        for i in s:
            if i.parent != p :
                print RED,"error"
                sys.exit(1)
    if tree.text == "EmptyStatement":
        p = EmptyStatement()
    if tree.text == "If":
        p = convert_tree(children[0],verbose)
        tt = convert_tree(children[1],verbose)
        t = statement_convertor(tt)
        f = None
        if (len (children) ==3 ):
            f = statement_convertor(convert_tree(children[2],verbose))
        p = If(p,t,f)
    if tree.text == "Yield":
        e = convert_tree(children[0],verbose)
        p = Yield(e)
    if tree.text == "Let":
        v = convert_tree(children[0],verbose)
        t = None
        if (len (children) ==2 ):
            tt = convert_tree(children[1],verbose)
            t = statement_convertor(tt)
        p = Let(v,t)
    if tree.text == "For":
        i = convert_tree(children[0],verbose)
        e1 = convert_tree(children[1],verbose)
        e2 = convert_tree(children[2],verbose)
        s = statement_convertor(convert_tree(children[3],verbose))
        p = For(i,e1,e2,s)
    if tree.text == "each":
        p = Each()
    if tree.text == "ForIn":
        i = convert_tree(children[0],verbose)
        e1 = convert_tree(children[1],verbose)
        each = children[2]
        s = None
        if len(children) == 4:
            s = convert_tree(children[3],verbose)
        print each
        if len(each.getChildren()) == 0:
            each = False
        elif each.getChildren()[0].text == "each":
            each = True
        else:
            print "%d:error: for cannot be followed by %s" %(each.getLine() ,each.getChildren()[0].text)
            sys.exit(0)
        if s != None:
            s = statement_convertor(s)
        p = ForIn(i,s,e1,each)
    if tree.text == "Try":
        s = convert_tree(children[0],verbose)
        rest =  map(lambda x:convert_tree(x,verbose),children[1:])
        t = statement_convertor(s)
        p = Try(t,rest)
    if tree.text == "While":
        p = convert_tree(children[0],verbose)
        t = statement_convertor(convert_tree(children[1],verbose))
        p = While(p,t)
    if tree.text == "DoWhile":
        p = convert_tree(children[1],verbose)
        t = statement_convertor(convert_tree(children[0],verbose))
        p = DoWhile(p,t)
    if tree.text == "Switch":
        e = convert_tree(children[0],verbose)
        cb = map(lambda x:convert_tree(x,verbose),children[1:])
        p = Switch(e,cb)
    if tree.text == "Throw":
        e = convert_tree(children[0],verbose)
        p = Throw(e)
    if tree.text == "CatchClause":
        i = convert_tree(children[0],verbose)
        e = statement_convertor(convert_tree(children[1],verbose))
        ex = None
        if len (children ) == 3:
            ex = convert_tree(children[2],verbose)
        p = CatchClause(i,e,ex)
    if tree.text == "FinallyClause":
        e = statement_convertor(convert_tree(children[0],verbose))
        p = FinallyClause(e)
    if tree.text == "CaseClause":
        e = convert_tree(children[0],verbose)
        cc = Statements(filter(lambda x : x != [] , map(lambda x:convert_tree(x,verbose),children[1:])))
        p = CaseBlock(cc,e)
    if tree.text == "DefaultBlock":
        cc = Statements(filter(lambda x : x != [] , map(lambda x:convert_tree(x,verbose),children[:])))
        p = CaseBlock(cc)
    if tree.text == "Break":
        i = None
        if len(children) != 0:
            i = convert_tree(children[0],verbose)
        p = Break(i)
    if tree.text == "Continue":
        i = None
        if len(children) != 0:
            i = convert_tree(children[0],verbose)
        p = Continue(i)
    if tree.text == "UnaryExpr":
        c1 = convert_tree(children[1],verbose)
        p = UnaryExpr( children[0].text,c1)
    if tree.text == "PropertyName":
        if  len(children)==2: 
            c1 = convert_tree(children[1],verbose)
            c0 = convert_tree(children[0],verbose)
            p = PropertyName( c0,c1)
        else:
            p = PropertyName( convert_tree(children[0],verbose))
    if tree.text == "Property":
        p = Property( convert_tree(children[0],verbose))
    if tree.text == "Zero":
        p = Number(0)
    if tree.text == "Ternary":
        if len(children)==3:
            p = Ternary(convert_tree(children[0],verbose),convert_tree(children[1],verbose),convert_tree(children[2],verbose))
        else:
            p = convert_tree(children[0],verbose)
    if tree.text == "Number":
        if children[0].text == "NaN":
            p = NaN()
        else:
            p = Number( children[0].text)
    if tree.text == "RegEx":
        p = RegEx( children[0].text)
    if tree.text == "List":
        p = List([ convert_tree(c,verbose) for c in children])
    if tree.text == "ListCreation":
        e = convert_tree(children[0],verbose)
        f = convert_tree(children[1],verbose)
        p = ListCreation(e,f)
    if tree.text == "String":
        p = String( children[0].text)
    if tree.text == "Assignment":
        v = convert_tree(children[0],verbose)
        t = children[1].text
        e = convert_tree(children[2],verbose)
        p = Assignment(v,t,e)
    if tree.text == "ExpressionStatement":
        p = ExpressionStatement([convert_tree(c,verbose) for c in children])
    if tree.text == "This":
        p = This()
    if tree.text == "Expr" :
        l = []
        for c in children:
            conv = convert_tree(c,verbose)
            if conv == []:
                if c.text == "And":
                    l.append("&&")
                elif c.text == "Or":
                    l.append("||")
                elif c.text == "BAnd":
                    l.append("&")
                elif c.text == "BOr":
                    l.append("|")
                elif c.text == "BXor":
                    l.append("^")
                else:
                    l.append(c.text)
            else:
                l.append(conv)
        if len(l) == 0:
            p = Expr()
        elif len(l) == 1 :
            if isinstance( l[0],Expr):
                p = l[0]
            else:
                p = Expr(l)
        else:
            if l[1] == ",":
                p = Statements([l[i] for i in range (0,len(l)+1,2)])
            else:
                p = Expr(l)
    if tree.text == "New":
        e = convert_tree(children[0],verbose)
        a = None
        if len(children) == 2:
            a = convert_tree(children[1],verbose)
        p = New(e,a)
    if tree.text == "Null":
        p = Null()
    if tree.text == "Ltrue":
        p = Ltrue()
    if tree.text == "Lfalse":
        p = Lfalse()
    if tree.text == "Index":
        p = Index(convert_tree(children[0],verbose))
    if tree.text == "Functioncall":
        if len (children) == 1 :
            p = convert_tree(children[0],verbose)
        else:
            i = convert_tree(children[0],verbose)
            a = convert_tree(children[1],verbose)
            r = None
            if len (children)> 2:
                r = CallExpressionSuffix(map( convert_tree,children[2:]))
        p = Functioncall(i,a,r)
    if p != [] :
        p.line = tree.getLine()
    return p
Ejemplo n.º 13
0
def outlining_post_func(program, arg):
    if isinstance(program, Statements):
        if shouldi(arg=arg) and len(program.statements_list) != 0:
            f = jshadobf_random.randint(0, len(program.statements_list) - 1)
            t = jshadobf_random.randint(f + 1, len(program.statements_list))
            outline = program.statements_list[f:t]
            if not is_return_inside(outline) and not is_function_inside(
                    outline):
                funcobj, funcname = genVarNotIn(arg["ident_present"])
                presence = detect_presence(outline)
                if not (presence["arguments"] or presence["this_present"] or
                        presence["break_present"] or presence["eval_present"]):
                    examine_outline = examine_function_vars(outline)
                    upfunc = get_upper_function(program)
                    examine_before = examine_function_vars(
                        upfunc, program.statements_list[f])
                    examine_func = examine_function_vars(upfunc)
                    if isinstance(upfunc, Function):
                        for v in upfunc.args_dec.args_list:
                            include_ident(examine_before["local_var"], v)
                    nameargs ,varout,vardecout , vardec,todec=  [],[],[],[],[]
                    if all_function_call_are_functionnal(outline):
                        for k in examine_outline["local_var"].keys():
                            if examine_before["local_var"].has_key(
                                    k) and examine_before["local_var"][k][0][
                                        "has_been_assigned"]:
                                nameargs.append(k)
                        for k in examine_outline["var_global_ref"].keys():
                            if examine_before["local_var"].has_key(k):
                                nameargs.append(k)
                            elif examine_func["local_var"].has_key(k):
                                todec.append(k)
                            elif examine_before["var_global_set"].has_key(k):
                                nameargs.append(k)
                        for k in examine_outline["var_global_set"].keys():
                            if examine_before["local_var"].has_key(k):
                                nameargs.append(k)
                            elif examine_func["local_var"].has_key(k):
                                todec.append(k)
                        for k in examine_outline["local_var"].keys():
                            vardecout.append(k)
                        for k in examine_outline["local_var"].keys():
                            if examine_outline["local_var"][k][0][
                                    "has_been_assigned"]:
                                varout.append(k)
                        for k in examine_outline["var_global_set"].keys():
                            varout.append(k)
                        movable = all([
                            k in nameargs + vardecout
                            for k in examine_outline["local_var"].keys() +
                            examine_outline["var_global_ref"].keys()
                        ] + [examine_outline["var_global_set"].keys() == []])
                    elif len(examine_outline["local_var"]) == 0:
                        nameargs, varout, vardecout = [], [], []
                        movable = False
                    else:
                        return [], arg

                    vardecout = list(set(vardecout))
                    varout = list(set(varout))
                    nameargs = list(set(nameargs))
                    rem = range(f, t)
                    rem.reverse()
                    for i in rem:
                        del program.statements_list[i]
                    outline = [
                        Var([VarDeclaration(Ident(n))]) for n in vardec
                    ] + outline
                    outline += [
                        Return(Expr([List([Ident(n) for n in varout])]))
                    ]
                    listarg = Listarguments([Ident(n) for n in nameargs])
                    listretobj, listretname = genVarNotIn(arg["ident_present"])

                    i = 0
                    for n in varout:
                        program.insert(
                            f,
                            Assignment(
                                Ident(n), "=",
                                MemberExpr(Expr([Ident(listretname)]),
                                           [Index(Expr([Number(str(i))]))])))
                        i = i + 1
                    for n in vardecout:
                        program.insert(f, Var([VarDeclaration(Ident(n))]))
                        i = i + 1
                    for n in todec:
                        outline.insert(0, Var([VarDeclaration(Ident(n))]))

                    program.insert(
                        f,
                        Var([
                            VarDeclaration(
                                Ident(listretname),
                                Functioncall(Ident(funcname), listarg))
                        ]))
                    uppers = []
                    if movable:
                        uppers = get_all_upper_statement_and_pos(program)
                    uppers = uppers + [(program, f)]
                    upper, pos = uppers[jshadobf_random.randint(
                        0,
                        len(uppers) - 1)]
                    outline_statement = Statements(outline)
                    l1 = deepcopy(listarg)
                    upper.insert(
                        pos, Function(Ident(funcname), l1, outline_statement))
    return [], arg