• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

Gallopsled / pwntools / 1

29 May 2020 09:05AM UTC coverage: 0.0% (-72.4%) from 72.414%
1

push

github

layderv
__str__ to __bytes__ in python2

0 of 8 new or added lines in 2 files covered. (0.0%)

11301 existing lines in 133 files now uncovered.

0 of 15497 relevant lines covered (0.0%)

0.0 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

0.0
/pwnlib/commandline/shellcraft.py
1
#!/usr/bin/env python2
UNCOV
2
from __future__ import absolute_import
×
UNCOV
3
from __future__ import division
×
4

UNCOV
5
import argparse
×
UNCOV
6
import os
×
UNCOV
7
import six
×
UNCOV
8
import sys
×
UNCOV
9
import types
×
10

UNCOV
11
import pwnlib
×
UNCOV
12
pwnlib.args.free_form = False
×
13

UNCOV
14
from pwn import *
×
UNCOV
15
from pwnlib.commandline import common
×
16

17

18
#  ____  _          _ _                 __ _
19
# / ___|| |__   ___| | | ___ _ __ __ _ / _| |_
20
# \___ \| '_ \ / _ \ | |/ __| '__/ _` | |_| __|
21
#  ___) | | | |  __/ | | (__| | | (_| |  _| |_
22
# |____/|_| |_|\___|_|_|\___|_|  \__,_|_|  \__|
23

UNCOV
24
def _string(s):
×
25
    out = []
×
26
    for co in bytearray(s):
×
27
        c = chr(co)
×
28
        if co >= 0x20 and co <= 0x7e and c not in '/$\'"`':
×
29
            out.append(c)
×
30
        else:
31
            out.append('\\x%02x' % co)
×
32
    return '"' + ''.join(out) + '"\n'
×
33

34

UNCOV
35
p = common.parser_commands.add_parser(
×
36
    'shellcraft',
37
    help = 'Microwave shellcode -- Easy, fast and delicious',
38
)
39

40

UNCOV
41
p.add_argument(
×
42
    '-?', '--show',
43
    action = 'store_true',
44
    help = 'Show shellcode documentation',
45
)
46

UNCOV
47
p.add_argument(
×
48
    '-o', '--out',
49
    metavar = 'file',
50
    type = argparse.FileType('wb'),
51
    default = getattr(sys.stdout, 'buffer', sys.stdout),
52
    help = 'Output file (default: stdout)',
53
)
54

UNCOV
55
p.add_argument(
×
56
    '-f', '--format',
57
    metavar = 'format',
58
    choices = ['r', 'raw',
59
               's', 'str', 'string',
60
               'c',
61
               'h', 'hex',
62
               'a', 'asm', 'assembly',
63
               'p',
64
               'i', 'hexii',
65
               'e', 'elf',
66
               'd', 'escaped',
67
               'default'],
68
    default = 'default',
69
    help = 'Output format (default: hex), choose from {e}lf, {r}aw, {s}tring, {c}-style array, {h}ex string, hex{i}i, {a}ssembly code, {p}reprocssed code, escape{d} hex string',
70
)
71

UNCOV
72
p.add_argument(
×
73
    'shellcode',
74
    nargs = '?',
75
    help = 'The shellcode you want',
76
    type = str
77
)
78

UNCOV
79
p.add_argument(
×
80
    'args',
81
    nargs = '*',
82
    metavar = 'arg',
83
    default = (),
84
    help = 'Argument to the chosen shellcode',
85
)
86

UNCOV
87
p.add_argument(
×
88
    '-d',
89
    '--debug',
90
    help='Debug the shellcode with GDB',
91
    action='store_true'
92
)
93

UNCOV
94
p.add_argument(
×
95
    '-b',
96
    '--before',
97
    help='Insert a debug trap before the code',
98
    action='store_true'
99
)
100

UNCOV
101
p.add_argument(
×
102
    '-a',
103
    '--after',
104
    help='Insert a debug trap after the code',
105
    action='store_true'
106
)
107

UNCOV
108
p.add_argument(
×
109
    '-v', '--avoid',
110
    action='append',
111
    help = 'Encode the shellcode to avoid the listed bytes'
112
)
113

UNCOV
114
p.add_argument(
×
115
    '-n', '--newline',
116
    dest='avoid',
117
    action='append_const',
118
    const='\n',
119
    help = 'Encode the shellcode to avoid newlines'
120
)
121

UNCOV
122
p.add_argument(
×
123
    '-z', '--zero',
124
    dest='avoid',
125
    action='append_const',
126
    const='\x00',
127
    help = 'Encode the shellcode to avoid NULL bytes'
128
)
129

UNCOV
130
p.add_argument(
×
131
    '-r',
132
    '--run',
133
    help="Run output",
134
    action='store_true'
135
)
136

UNCOV
137
p.add_argument(
×
138
    '--color',
139
    help="Color output",
140
    action='store_true',
141
    default=sys.stdout.isatty()
142
)
143

UNCOV
144
p.add_argument(
×
145
    '--no-color',
146
    help="Disable color output",
147
    action='store_false',
148
    dest='color'
149
)
150

UNCOV
151
p.add_argument(
×
152
    '--syscalls',
153
    help="List syscalls",
154
    action='store_true'
155
)
156

UNCOV
157
p.add_argument(
×
158
    '--address',
159
    help="Load address",
160
    default=None
161
)
162

UNCOV
163
p.add_argument(
×
164
    '-l', '--list',
165
    action='store_true',
166
    help='List available shellcodes, optionally provide a filter'
167
)
168

UNCOV
169
p.add_argument(
×
170
    '-s', '--shared',
171
    action='store_true',
172
    help='Generated ELF is a shared library'
173
)
174

UNCOV
175
def get_template(name):
×
176
    func = shellcraft
×
177
    for attr in name.split('.'):
×
178
        func = getattr(func, attr)
×
179
    return func
×
180

UNCOV
181
def is_not_a_syscall_template(name):
×
182
    template_src = shellcraft._get_source(name)
×
183
    return '/syscalls' not in template_src
×
184

UNCOV
185
def main(args):
×
186
    if args.list:
×
187
        templates = shellcraft.templates
×
188

189
        if args.shellcode:
×
190
            templates = filter(lambda a: args.shellcode in a, templates)
×
191
        elif not args.syscalls:
×
192
            templates = filter(is_not_a_syscall_template, templates)
×
193

194
        print('\n'.join(templates))
×
195
        exit()
×
196

197
    if not args.shellcode:
×
198
        common.parser.print_usage()
×
199
        exit()
×
200

201
    if args.shellcode not in shellcraft.templates:
×
202
        log.error("Unknown shellcraft template %r. Use --list to see available shellcodes." % args.shellcode)
×
203

204
    func = get_template(args.shellcode)
×
205

206
    if args.show:
×
207
        # remove doctests
208
        doc = []
×
209
        in_doctest = False
×
210
        block_indent = None
×
211
        caption = None
×
212
        lines = func.__doc__.splitlines()
×
213
        i = 0
×
214
        while i < len(lines):
×
215
            line = lines[i]
×
216
            if line.lstrip().startswith('>>>'):
×
217
                # this line starts a doctest
218
                in_doctest = True
×
219
                block_indent = None
×
220
                if caption:
×
221
                    # delete back up to the caption
222
                    doc = doc[:caption - i]
×
223
                    caption = None
×
224
            elif line == '':
×
225
                # skip blank lines
226
                pass
×
227
            elif in_doctest:
×
228
                # indentation marks the end of a doctest
229
                indent = len(line) - len(line.lstrip())
×
230
                if block_indent is None:
×
231
                    if not line.lstrip().startswith('...'):
×
232
                        block_indent = indent
×
233
                elif indent < block_indent:
×
234
                    in_doctest = False
×
235
                    block_indent = None
×
236
                    # re-evalutate this line
237
                    continue
×
238
            elif line.endswith(':'):
×
239
                # save index of caption
240
                caption = i
×
241
            else:
242
                # this is not blank space and we're not in a doctest, so the
243
                # previous caption (if any) was not for a doctest
244
                caption = None
×
245

246
            if not in_doctest:
×
247
                doc.append(line)
×
248
            i += 1
×
249
        print('\n'.join(doc).rstrip())
×
250
        exit()
×
251

252
    defargs = len(six.get_function_defaults(func) or ())
×
253
    reqargs = six.get_function_code(func).co_argcount - defargs
×
254
    if len(args.args) < reqargs:
×
255
        if defargs > 0:
×
256
            log.critical('%s takes at least %d arguments' % (args.shellcode, reqargs))
×
257
            sys.exit(1)
×
258
        else:
259
            log.critical('%s takes exactly %d arguments' % (args.shellcode, reqargs))
×
260
            sys.exit(1)
×
261

262
    # Captain uglyness saves the day!
263
    for i, val in enumerate(args.args):
×
264
        try:
×
265
            args.args[i] = util.safeeval.expr(val)
×
266
        except ValueError:
×
267
            pass
×
268

269
    # And he strikes again!
270
    list(map(common.context_arg, args.shellcode.split('.')))
×
271
    code = func(*args.args)
×
272

273

274
    if args.before:
×
275
        code = shellcraft.trap() + code
×
276
    if args.after:
×
277
        code = code + shellcraft.trap()
×
278

279

280
    if args.format in ['a', 'asm', 'assembly']:
×
281
        if args.color:
×
282
            from pygments import highlight
×
283
            from pygments.formatters import TerminalFormatter
×
284
            from pwnlib.lexer import PwntoolsLexer
×
285

286
            code = highlight(code, PwntoolsLexer(), TerminalFormatter())
×
287

288
        print(code)
×
289
        exit()
×
290
    if args.format == 'p':
×
291
        print(cpp(code))
×
292
        exit()
×
293

294
    assembly = code
×
295

296
    vma = args.address
×
297
    if vma:
×
298
        vma = eval(vma)
×
299

300
    if args.format in ['e','elf']:
×
301
        args.format = 'default'
×
302
        try: os.fchmod(args.out.fileno(), 0o700)
×
303
        except OSError: pass
×
304

305

306
        if not args.avoid:
×
307
            code = read(make_elf_from_assembly(assembly, vma=vma, shared=args.shared))
×
308
        else:
309
            code = asm(assembly)
×
310
            code = encode(code, args.avoid)
×
311
            code = make_elf(code, vma=vma, shared=args.shared)
×
312
            # code = read(make_elf(encode(asm(code), args.avoid)))
313
    else:
314
        code = encode(asm(assembly), args.avoid)
×
315

316
    if args.format == 'default':
×
317
        if args.out.isatty():
×
318
            args.format = 'hex'
×
319
        else:
320
            args.format = 'raw'
×
321

322
    arch = args.shellcode.split('.')[0]
×
323

324
    if args.debug:
×
325
        if not args.avoid:
×
326
            proc = gdb.debug_assembly(assembly, arch=arch, vma=vma)
×
327
        else:
328
            proc = gdb.debug_shellcode(code, arch=arch, vma=vma)
×
329
        proc.interactive()
×
330
        sys.exit(0)
×
331

332
    if args.run:
×
333
        proc = run_shellcode(code, arch=arch)
×
334
        proc.interactive()
×
335
        sys.exit(0)
×
336

337
    if args.format in ['s', 'str', 'string']:
×
338
        code = _string(code)
×
339
    elif args.format == 'c':
×
340
        code = '{' + ', '.join(map(hex, bytearray(code))) + '}' + '\n'
×
341
    elif args.format in ['h', 'hex']:
×
342
        code = pwnlib.util.fiddling.enhex(code) + '\n'
×
343
    elif args.format in ['i', 'hexii']:
×
344
        code = hexii(code) + '\n'
×
345
    elif args.format in ['d', 'escaped']:
×
346
        code = ''.join('\\x%02x' % c for c in bytearray(code)) + '\n'
×
347
    if not sys.stdin.isatty():
×
348
        args.out.write(getattr(sys.stdin, 'buffer', sys.stdin).read())
×
349

350
    if not hasattr(code, 'decode'):
×
351
        code = code.encode()
×
352
    args.out.write(code)
×
353

UNCOV
354
if __name__ == '__main__':
×
355
    pwnlib.commandline.common.main(__file__)
×
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc