Example #1
0
def update_context_defaults(section):
    # Circular imports FTW!
    from pwnlib.util import safeeval
    from pwnlib.log import getLogger
    log = getLogger(__name__)
    for key, value in section.items():
        if key not in ContextType.defaults:
            log.warn("Unknown configuration option %r in section %r" %
                     (key, 'context'))
            continue

        default = ContextType.defaults[key]

        if isinstance(
                default,
                six.string_types + six.integer_types + (tuple, list, dict)):
            value = safeeval.expr(value)
        else:
            log.warn("Unsupported configuration option %r in section %r" %
                     (key, 'context'))

        # Attempt to set the value, to see if it is value:
        try:
            with context.local(**{key: value}):
                value = getattr(context, key)
        except (ValueError, AttributeError) as e:
            log.warn("Could not set context.%s=%s via pwn.conf (%s)", key,
                     section[key], e)
            continue

        ContextType.defaults[key] = value
Example #2
0
def update_context_defaults(section):
    # Circular imports FTW!
    from pwnlib.util import safeeval
    from pwnlib.log import getLogger
    log = getLogger(__name__)
    for key, value in section.items():
        if key not in ContextType.defaults:
            log.warn("Unknown configuration option %r in section %r" % (key, 'context'))
            continue
        if isinstance(ContextType.defaults[key], (str, unicode, tuple)):
            value = safeeval.expr(value)

        ContextType.defaults[key] = value
Example #3
0
def update_context_defaults(section):
    # Circular imports FTW!
    from pwnlib.util import safeeval
    from pwnlib.log import getLogger
    log = getLogger(__name__)
    for key, value in section.items():
        if key not in ContextType.defaults:
            log.warn("Unknown configuration option %r in section %r" %
                     (key, 'context'))
            continue
        if isinstance(ContextType.defaults[key], (str, unicode, tuple)):
            value = safeeval.expr(value)

        ContextType.defaults[key] = value
Example #4
0
def update_context_defaults(section):
    # Circular imports FTW!
    from pwnlib.util import safeeval
    from pwnlib.log import getLogger
    log = getLogger(__name__)
    for key, value in section.items():
        if key not in ContextType.defaults:
            log.warn("Unknown configuration option %r in section %r" % (key, 'context'))
            continue

        default = ContextType.defaults[key]

        if isinstance(default, (str, unicode, tuple, int, long, list, dict)):
            value = safeeval.expr(value)
        else:
            log.warn("Unsupported configuration option %r in section %r" % (key, 'context'))

        ContextType.defaults[key] = type(default)(value)
Example #5
0
python = open(sys.argv[1], "w")
header = open(sys.argv[2], "w")

data = sys.stdin.read().strip().split('\n')

res = ""
regex = re.compile('^%constant ([^=]+) = ([^";]+);')
for l in data:
    m = regex.match(l)
    if not m:
        continue
    if '"' in l or '=' not in l or ';' not in l or not l.startswith(
            '%constant '):
        continue

    key = m.group(1)
    val = m.group(2)

    # Handle weird special cases from C syntax
    if val.endswith('UL'):
        val = val[:-2]
    elif val.endswith('L'):
        val = val[:-1]

    print >> python, "%s = %s" % (key, val)
    if re.match(r'^0[0-9]', val) or re.match(r'[^0-9a-fA-Fx]0[0-9]', val):
        print >> header, "#define %s %s" % (key, hex(safeeval.expr(val)))
    else:
        print >> header, "#define %s %s" % (key, val)
Example #6
0
def main():
    args = p.parse_args()

    if args.exact:
        # This is the simple case
        print cpp(args.exact).strip()
    else:
        # New we search in the right module.
        # But first: We find the right module
        if context.os == 'freebsd':
            mod = constants.freebsd
        else:
            mod = getattr(getattr(constants, context.os), context.arch)

        # Compile the given regex, for optimized lookup
        if args.case_insensitive:
            matcher = re.compile(args.regex, re.IGNORECASE)
        else:
            matcher = re.compile(args.regex)

        # Evaluate the given constant
        if args.constant:
            constant = safeeval.expr(args.constant)
        else:
            constant = None

        # The found matching constants and the length of the longest string
        out = []
        maxlen = 0

        for k in dir(mod):
            # No python stuff
            if k.endswith('__') and k.startswith('__'):
                continue

            # Run the regex
            if not matcher.search(k):
                continue

            # Check the constant
            if constant != None:
                val = getattr(mod, k)
                if args.mask_mode:
                    if constant & val != val:
                        continue
                else:
                    if constant != val:
                        continue

            # Append it
            out.append((getattr(mod, k), k))
            maxlen = max(len(k), maxlen)

        # Output all matching constants
        for _, k in sorted(out):
            print '#define %s %s' % (k.ljust(maxlen), cpp(k).strip())

        # If we are in match_mode, then try to find a combination of
        # constants that yield the exact given value
        # We do not want to find combinations using the value 0.
        if not (constant == None or constant == 0) and args.mask_mode:
            mask = constant
            good = []
            out = [(v, k) for v, k in out if v != 0]

            while mask and out:
                cur = out.pop()
                mask &= ~cur[0]
                good.append(cur)

                out = [(v, k) for v, k in out if mask & v == v]

            if reduce(lambda x, cur: x | cur[0], good, 0) == constant:
                print
                print '(%s) == %s' % (' | '.join(
                    k for v, k in good), args.constant)
Example #7
0
def main():
    args = p.parse_args()

    if args.exact:
        # This is the simple case
        print cpp(args.exact).strip()
    else:
        # New we search in the right module.
        # But first: We find the right module
        if context.os == 'freebsd':
            mod = constants.freebsd
        else:
            mod = getattr(getattr(constants, context.os), context.arch)

        # Compile the given regex, for optimized lookup
        if args.case_insensitive:
            matcher = re.compile(args.regex, re.IGNORECASE)
        else:
            matcher = re.compile(args.regex)

        # Evaluate the given constant
        if args.constant:
            constant = safeeval.expr(args.constant)
        else:
            constant = None

        # The found matching constants and the length of the longest string
        out    = []
        maxlen = 0

        for k in dir(mod):
            # No python stuff
            if k.endswith('__') and k.startswith('__'):
                continue

            # Run the regex
            if not matcher.search(k):
                continue

            # Check the constant
            if constant != None:
                val = getattr(mod, k)
                if args.mask_mode:
                    if constant & val != val:
                        continue
                else:
                    if constant != val:
                        continue

            # Append it
            out.append((getattr(mod, k), k))
            maxlen = max(len(k), maxlen)

        # Output all matching constants
        for _, k in sorted(out):
            print '#define %s %s' % (k.ljust(maxlen), cpp(k).strip())

        # If we are in match_mode, then try to find a combination of
        # constants that yield the exact given value
        # We do not want to find combinations using the value 0.
        if not (constant == None or constant == 0) and args.mask_mode:
            mask = constant
            good = []
            out = [(v, k) for v, k in out if v != 0]

            while mask and out:
                cur = out.pop()
                mask &= ~cur[0]
                good.append(cur)

                out = [(v, k) for v, k in out if mask & v == v]

            if reduce(lambda x, cur: x | cur[0], good, 0) == constant:
                print
                print '(%s) == %s' % (' | '.join(k for v, k in good), args.constant)
Example #8
0
for l in data:
    m = regex.match(l)
    if not m:
        continue
    if '"' in l or '=' not in l or ';' not in l or not l.startswith(
            '%constant '):
        continue

    key = m.group(1)
    val = m.group(2)

    # Handle weird special cases from C syntax
    paren = False
    if val[:1] == '(' and val[-1:] == ')' and ')' not in val[1:-1]:
        val = val[1:-1]
        paren = True
    val = val.rstrip('UuLl')
    val = val.replace('7ll', '7')

    if re.match(r'^0[0-9]', val):
        val = '0o' + val[1:]
    val = re.sub(r'([|^&( ]0)([0-7])', r'\1o\2', val)

    if paren:
        val = '(%s)' % val
    print("{key} = Constant({key!r},{val})".format(**locals()), file=python)
    if re.search(r'0o[0-7]', val) or re.match(r'[^0-9a-fA-Fx]0[0-9]', val):
        print("#define %s %s" % (key, hex(safeeval.expr(val))), file=header)
    else:
        print("#define %s %s" % (key, val), file=header)
Example #9
0
from pwnlib.util import safeeval

python = open(sys.argv[1], "w")
header = open(sys.argv[2], "w")

data = sys.stdin.read().strip().split('\n')

res = ""
regex = re.compile('^%constant ([^=]+) = ([^";]+);')
for l in data:
    m = regex.match(l)
    if not m:
        continue
    if '"' in l or '=' not in l or ';' not in l or not l.startswith('%constant '):
        continue

    key = m.group(1)
    val = m.group(2)

    # Handle weird special cases from C syntax
    if val.endswith('UL'):
        val = val[:-2]
    elif val.endswith('L'):
        val = val[:-1]

    print >> python, "%s = %s" % (key, val)
    if re.match(r'^0[0-9]', val) or re.match(r'[^0-9a-fA-Fx]0[0-9]', val):
        print >> header, "#define %s %s" % (key, hex(safeeval.expr(val)))
    else:
        print >> header, "#define %s %s" % (key, val)
Example #10
0
def render_body(context, filepath, flags='O_RDONLY', mode=420, **pageargs):
    __M_caller = context.caller_stack._push_frame()
    try:
        __M_locals = __M_dict_builtin(pageargs=pageargs,
                                      flags=flags,
                                      mode=mode,
                                      filepath=filepath)
        int = context.get('int', UNDEFINED)
        hex = context.get('hex', UNDEFINED)
        repr = context.get('repr', UNDEFINED)
        long = context.get('long', UNDEFINED)
        len = context.get('len', UNDEFINED)
        str = context.get('str', UNDEFINED)
        ord = context.get('ord', UNDEFINED)
        isinstance = context.get('isinstance', UNDEFINED)
        __M_writer = context.writer()
        __M_writer(u'\n')
        __M_writer(u'\n')

        from pwnlib.shellcraft.common import label
        from pwnlib.asm import cpp
        from pwnlib.util.safeeval import expr
        from pwnlib.constants.linux import arm as consts
        filepath_lab, after = label("filepath"), label("after")
        filepath_out = [hex(ord(c)) for c in filepath]
        while True:
            filepath_out.append("0")
            if len(filepath_out) % 4 == 0:
                break
        filepath_out = ', '.join(filepath_out)

        if isinstance(mode, (int, long)):
            mode = hex(mode)

        __M_locals_builtin_stored = __M_locals_builtin()
        __M_locals.update(
            __M_dict_builtin([
                (__M_key, __M_locals_builtin_stored[__M_key]) for __M_key in [
                    'c', 'filepath_lab', 'expr', 'after', 'filepath_out',
                    'label', 'mode', 'consts', 'cpp'
                ] if __M_key in __M_locals_builtin_stored
            ]))
        __M_writer(u'\n')
        if expr(cpp("%s & O_CREAT" % flags, arch='arm', os='linux')):
            __M_writer(u'    mov r2, #(')
            __M_writer(unicode(mode))
            __M_writer(u')\n')
        __M_writer(u'    mov r1, #(')
        __M_writer(unicode(flags))
        __M_writer(u')\n    adr r0, ')
        __M_writer(unicode(filepath_lab))
        __M_writer(u'\n    svc SYS_open\n    b ')
        __M_writer(unicode(after))
        __M_writer(u'\n\n    /* The string ')
        __M_writer(unicode(repr(str(filepath))))
        __M_writer(u' */\n')
        __M_writer(unicode(filepath_lab))
        __M_writer(u': .byte ')
        __M_writer(unicode(filepath_out))
        __M_writer(u'\n\n')
        __M_writer(unicode(after))
        __M_writer(u':\n')
        return ''
    finally:
        context.caller_stack._pop_frame()
python = open(sys.argv[1], "w")
header = open(sys.argv[2], "w")

print('from pwnlib.constants.constant import Constant', file=python)

data = sys.stdin.read().strip().split('\n')

res = ""
regex = re.compile('^%constant ([^=]+) = ([^";]+);')
for l in data:
    m = regex.match(l)
    if not m:
        continue
    if '"' in l or '=' not in l or ';' not in l or not l.startswith('%constant '):
        continue

    key = m.group(1)
    val = m.group(2)

    # Handle weird special cases from C syntax
    if val.endswith('UL'):
        val = val[:-2]
    elif val.endswith('L'):
        val = val[:-1]

    print("{key} = Constant({key!r}, {val})".format(**locals()), file=python)
    if re.match(r'^0[0-9]', val) or re.match(r'[^0-9a-fA-Fx]0[0-9]', val):
        print("#define %s %s" % (key, hex(safeeval.expr(val))), file=header)
    else:
        print("#define %s %s" % (key, val), file=header)