├── .gitignore ├── README.md ├── ctf1 ├── append │ ├── etc │ │ └── inittab │ ├── home │ │ ├── level00 │ │ │ ├── syntax.txt │ │ │ └── tools.txt │ │ ├── level02 │ │ │ ├── flask │ │ │ │ ├── __init__.py │ │ │ │ ├── app.py │ │ │ │ ├── blueprints.py │ │ │ │ ├── config.py │ │ │ │ ├── ctx.py │ │ │ │ ├── debughelpers.py │ │ │ │ ├── exceptions.py │ │ │ │ ├── ext │ │ │ │ │ └── __init__.py │ │ │ │ ├── exthook.py │ │ │ │ ├── globals.py │ │ │ │ ├── helpers.py │ │ │ │ ├── logging.py │ │ │ │ ├── module.py │ │ │ │ ├── session.py │ │ │ │ ├── sessions.py │ │ │ │ ├── signals.py │ │ │ │ ├── templating.py │ │ │ │ ├── testing.py │ │ │ │ ├── testsuite │ │ │ │ │ ├── __init__.py │ │ │ │ │ ├── appctx.py │ │ │ │ │ ├── basic.py │ │ │ │ │ ├── blueprints.py │ │ │ │ │ ├── config.py │ │ │ │ │ ├── deprecations.py │ │ │ │ │ ├── examples.py │ │ │ │ │ ├── ext.py │ │ │ │ │ ├── helpers.py │ │ │ │ │ ├── regression.py │ │ │ │ │ ├── signals.py │ │ │ │ │ ├── static │ │ │ │ │ │ └── index.html │ │ │ │ │ ├── subclassing.py │ │ │ │ │ ├── templates │ │ │ │ │ │ ├── _macro.html │ │ │ │ │ │ ├── context_template.html │ │ │ │ │ │ ├── escaping_template.html │ │ │ │ │ │ ├── mail.txt │ │ │ │ │ │ ├── nested │ │ │ │ │ │ │ └── nested.txt │ │ │ │ │ │ ├── simple_template.html │ │ │ │ │ │ └── template_filter.html │ │ │ │ │ ├── templating.py │ │ │ │ │ ├── test_apps │ │ │ │ │ │ ├── blueprintapp │ │ │ │ │ │ │ ├── __init__.py │ │ │ │ │ │ │ └── apps │ │ │ │ │ │ │ │ ├── __init__.py │ │ │ │ │ │ │ │ ├── admin │ │ │ │ │ │ │ │ ├── __init__.py │ │ │ │ │ │ │ │ ├── static │ │ │ │ │ │ │ │ │ ├── css │ │ │ │ │ │ │ │ │ │ └── test.css │ │ │ │ │ │ │ │ │ └── test.txt │ │ │ │ │ │ │ │ └── templates │ │ │ │ │ │ │ │ │ └── admin │ │ │ │ │ │ │ │ │ └── index.html │ │ │ │ │ │ │ │ └── frontend │ │ │ │ │ │ │ │ ├── __init__.py │ │ │ │ │ │ │ │ └── templates │ │ │ │ │ │ │ │ └── frontend │ │ │ │ │ │ │ │ └── index.html │ │ │ │ │ │ ├── config_module_app.py │ │ │ │ │ │ ├── config_package_app │ │ │ │ │ │ │ └── __init__.py │ │ │ │ │ │ ├── flask_broken │ │ │ │ │ │ │ ├── __init__.py │ │ │ │ │ │ │ └── b.py │ │ │ │ │ │ ├── flask_newext_package │ │ │ │ │ │ │ ├── __init__.py │ │ │ │ │ │ │ └── submodule.py │ │ │ │ │ │ ├── flask_newext_simple.py │ │ │ │ │ │ ├── flaskext │ │ │ │ │ │ │ ├── __init__.py │ │ │ │ │ │ │ ├── oldext_package │ │ │ │ │ │ │ │ ├── __init__.py │ │ │ │ │ │ │ │ └── submodule.py │ │ │ │ │ │ │ └── oldext_simple.py │ │ │ │ │ │ ├── importerror.py │ │ │ │ │ │ ├── lib │ │ │ │ │ │ │ └── python2.5 │ │ │ │ │ │ │ │ └── site-packages │ │ │ │ │ │ │ │ ├── SiteEgg.egg │ │ │ │ │ │ │ │ ├── site_app.py │ │ │ │ │ │ │ │ └── site_package │ │ │ │ │ │ │ │ └── __init__.py │ │ │ │ │ │ ├── main_app.py │ │ │ │ │ │ ├── moduleapp │ │ │ │ │ │ │ ├── __init__.py │ │ │ │ │ │ │ └── apps │ │ │ │ │ │ │ │ ├── __init__.py │ │ │ │ │ │ │ │ ├── admin │ │ │ │ │ │ │ │ ├── __init__.py │ │ │ │ │ │ │ │ ├── static │ │ │ │ │ │ │ │ │ ├── css │ │ │ │ │ │ │ │ │ │ └── test.css │ │ │ │ │ │ │ │ │ └── test.txt │ │ │ │ │ │ │ │ └── templates │ │ │ │ │ │ │ │ │ └── index.html │ │ │ │ │ │ │ │ └── frontend │ │ │ │ │ │ │ │ ├── __init__.py │ │ │ │ │ │ │ │ └── templates │ │ │ │ │ │ │ │ └── index.html │ │ │ │ │ │ ├── path │ │ │ │ │ │ │ └── installed_package │ │ │ │ │ │ │ │ └── __init__.py │ │ │ │ │ │ └── subdomaintestmodule │ │ │ │ │ │ │ ├── __init__.py │ │ │ │ │ │ │ └── static │ │ │ │ │ │ │ └── hello.txt │ │ │ │ │ ├── testing.py │ │ │ │ │ └── views.py │ │ │ │ ├── views.py │ │ │ │ └── wrappers.py │ │ │ ├── jinja2 │ │ │ │ ├── __init__.py │ │ │ │ ├── _debugsupport.c │ │ │ │ ├── _markupsafe │ │ │ │ │ ├── __init__.py │ │ │ │ │ ├── _bundle.py │ │ │ │ │ ├── _constants.py │ │ │ │ │ ├── _native.py │ │ │ │ │ └── tests.py │ │ │ │ ├── _stringdefs.py │ │ │ │ ├── bccache.py │ │ │ │ ├── compiler.py │ │ │ │ ├── constants.py │ │ │ │ ├── debug.py │ │ │ │ ├── defaults.py │ │ │ │ ├── environment.py │ │ │ │ ├── exceptions.py │ │ │ │ ├── ext.py │ │ │ │ ├── filters.py │ │ │ │ ├── lexer.py │ │ │ │ ├── loaders.py │ │ │ │ ├── meta.py │ │ │ │ ├── nodes.py │ │ │ │ ├── optimizer.py │ │ │ │ ├── parser.py │ │ │ │ ├── runtime.py │ │ │ │ ├── sandbox.py │ │ │ │ ├── tests.py │ │ │ │ ├── testsuite │ │ │ │ │ ├── __init__.py │ │ │ │ │ ├── api.py │ │ │ │ │ ├── core_tags.py │ │ │ │ │ ├── debug.py │ │ │ │ │ ├── doctests.py │ │ │ │ │ ├── ext.py │ │ │ │ │ ├── filters.py │ │ │ │ │ ├── imports.py │ │ │ │ │ ├── inheritance.py │ │ │ │ │ ├── lexnparse.py │ │ │ │ │ ├── loader.py │ │ │ │ │ ├── regression.py │ │ │ │ │ ├── res │ │ │ │ │ │ ├── __init__.py │ │ │ │ │ │ └── templates │ │ │ │ │ │ │ ├── broken.html │ │ │ │ │ │ │ ├── foo │ │ │ │ │ │ │ └── test.html │ │ │ │ │ │ │ ├── syntaxerror.html │ │ │ │ │ │ │ └── test.html │ │ │ │ │ ├── security.py │ │ │ │ │ ├── tests.py │ │ │ │ │ └── utils.py │ │ │ │ ├── utils.py │ │ │ │ └── visitor.py │ │ │ ├── start.sh │ │ │ └── werkzeug │ │ │ │ ├── __init__.py │ │ │ │ ├── _internal.py │ │ │ │ ├── contrib │ │ │ │ ├── __init__.py │ │ │ │ ├── atom.py │ │ │ │ ├── cache.py │ │ │ │ ├── fixers.py │ │ │ │ ├── iterio.py │ │ │ │ ├── jsrouting.py │ │ │ │ ├── kickstart.py │ │ │ │ ├── limiter.py │ │ │ │ ├── lint.py │ │ │ │ ├── profiler.py │ │ │ │ ├── securecookie.py │ │ │ │ ├── sessions.py │ │ │ │ ├── testtools.py │ │ │ │ └── wrappers.py │ │ │ │ ├── datastructures.py │ │ │ │ ├── debug │ │ │ │ ├── __init__.py │ │ │ │ ├── console.py │ │ │ │ ├── repr.py │ │ │ │ ├── shared │ │ │ │ │ ├── FONT_LICENSE │ │ │ │ │ ├── console.png │ │ │ │ │ ├── debugger.js │ │ │ │ │ ├── jquery.js │ │ │ │ │ ├── less.png │ │ │ │ │ ├── more.png │ │ │ │ │ ├── source.png │ │ │ │ │ ├── style.css │ │ │ │ │ └── ubuntu.ttf │ │ │ │ └── tbtools.py │ │ │ │ ├── exceptions.py │ │ │ │ ├── formparser.py │ │ │ │ ├── http.py │ │ │ │ ├── local.py │ │ │ │ ├── posixemulation.py │ │ │ │ ├── routing.py │ │ │ │ ├── script.py │ │ │ │ ├── security.py │ │ │ │ ├── serving.py │ │ │ │ ├── templates.py │ │ │ │ ├── test.py │ │ │ │ ├── testapp.py │ │ │ │ ├── testsuite │ │ │ │ ├── __init__.py │ │ │ │ ├── compat.py │ │ │ │ ├── contrib │ │ │ │ │ ├── __init__.py │ │ │ │ │ ├── cache.py │ │ │ │ │ ├── fixers.py │ │ │ │ │ ├── iterio.py │ │ │ │ │ ├── securecookie.py │ │ │ │ │ ├── sessions.py │ │ │ │ │ └── wrappers.py │ │ │ │ ├── datastructures.py │ │ │ │ ├── debug.py │ │ │ │ ├── exceptions.py │ │ │ │ ├── formparser.py │ │ │ │ ├── http.py │ │ │ │ ├── internal.py │ │ │ │ ├── local.py │ │ │ │ ├── multipart │ │ │ │ │ ├── collect.py │ │ │ │ │ ├── firefox3-2png1txt │ │ │ │ │ │ ├── file1.png │ │ │ │ │ │ ├── file2.png │ │ │ │ │ │ ├── request.txt │ │ │ │ │ │ └── text.txt │ │ │ │ │ ├── firefox3-2pnglongtext │ │ │ │ │ │ ├── file1.png │ │ │ │ │ │ ├── file2.png │ │ │ │ │ │ ├── request.txt │ │ │ │ │ │ └── text.txt │ │ │ │ │ ├── ie6-2png1txt │ │ │ │ │ │ ├── file1.png │ │ │ │ │ │ ├── file2.png │ │ │ │ │ │ ├── request.txt │ │ │ │ │ │ └── text.txt │ │ │ │ │ ├── ie7_full_path_request.txt │ │ │ │ │ ├── opera8-2png1txt │ │ │ │ │ │ ├── file1.png │ │ │ │ │ │ ├── file2.png │ │ │ │ │ │ ├── request.txt │ │ │ │ │ │ └── text.txt │ │ │ │ │ └── webkit3-2png1txt │ │ │ │ │ │ ├── file1.png │ │ │ │ │ │ ├── file2.png │ │ │ │ │ │ ├── request.txt │ │ │ │ │ │ └── text.txt │ │ │ │ ├── res │ │ │ │ │ └── test.txt │ │ │ │ ├── routing.py │ │ │ │ ├── security.py │ │ │ │ ├── serving.py │ │ │ │ ├── test.py │ │ │ │ ├── urls.py │ │ │ │ ├── utils.py │ │ │ │ ├── wrappers.py │ │ │ │ └── wsgi.py │ │ │ │ ├── urls.py │ │ │ │ ├── useragents.py │ │ │ │ ├── utils.py │ │ │ │ ├── wrappers.py │ │ │ │ └── wsgi.py │ │ └── level05 │ │ │ └── start.sh │ ├── opt │ │ └── bootlocal.sh │ └── root │ │ └── .profile ├── boot │ └── isolinux │ │ ├── boot.msg │ │ └── isolinux.cfg ├── code │ ├── README │ └── levels │ │ ├── level01 │ │ ├── Makefile │ │ └── level01.c │ │ ├── level02 │ │ ├── level02.py │ │ └── templates │ │ │ └── index.html │ │ ├── level03 │ │ ├── Makefile │ │ └── level03.c │ │ ├── level04 │ │ ├── Makefile │ │ └── level04.c │ │ ├── level05 │ │ └── level05.py │ │ └── level06 │ │ ├── Makefile │ │ └── level06.c ├── motd │ ├── banner.txt │ ├── level00.txt │ ├── level01.txt │ ├── level02.txt │ ├── level03.txt │ ├── level04.txt │ ├── level05.txt │ └── level06.txt └── special │ ├── README.md │ └── levels │ ├── level01 │ ├── Makefile │ └── level01.c │ ├── level03 │ ├── Makefile │ └── level03.c │ └── level04 │ ├── Makefile │ └── level04.c ├── images ├── end.png └── start.png └── scripts ├── build.sh ├── clean.sh ├── common.sh ├── get-livecd.sh ├── install-openssh.sh ├── install-python.sh ├── install-tcz.sh ├── pack-iso.sh ├── rebuild.sh ├── setup-ctf1.sh ├── unpack-iso.sh └── unpack-squashfs.sh /.gitignore: -------------------------------------------------------------------------------- 1 | work 2 | tmp 3 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Capture The Flag! 2 | ================= 3 | 4 | Remaster Linux Live CD images for the purpose of creating ready to 5 | use security wargames with pre-installed vulnerabilities to exploit. 6 | 7 | 8 | Requirements 9 | ------------ 10 | 11 | You will need the following in order to build the Live CD using 12 | the scripts in this project: 13 | 14 | * Linux, with root access using `sudo` 15 | * `git` 16 | * `make`, `gcc` -- for building vulnerable programs 17 | * `pwgen` -- for generating random passwords 18 | * `rsync` 19 | * `genisoimage` -- for `mkisofs` 20 | * `advancecomp` -- for `advdef` 21 | * `squashfs-tools` -- for `unsquashfs` 22 | * `curl` -- for downloading packages and other files 23 | 24 | 25 | Requirements when building in 64-bit systems 26 | -------------------------------------------- 27 | 28 | The base Live CD is 32-bit, and therefore the C programs 29 | must be built 32-bit too. In order to do that you need 30 | to install 32-bit development libraries. In Debian for 31 | example the package is called `libc6-dev-i386`. 32 | 33 | 34 | Building the Live CD 35 | -------------------- 36 | 37 | You have different options to build the CD: 38 | 39 | * Basic build: using a single script to build everything 40 | * 3-step build: 3 steps to give you a chance to customize 41 | * Expert build: if you want to understand everything 42 | 43 | Choose whichever method is most suitable for you. 44 | 45 | 46 | Basic build (for the impatient) 47 | ------------------------------- 48 | 49 | To fetch all the necessary files including the 8MB TinyCore base 50 | base image, the hacking contest data and all the required TinyCore 51 | packages and remaster the CD: 52 | 53 | ./scripts/rebuild.sh 54 | 55 | Note: some of the steps need to run `sudo`, so you will be prompted 56 | for your password one or more times. 57 | 58 | 59 | 3-step build 60 | ------------ 61 | 62 | The idea of this build method is to create the basic CD data but stop 63 | before rebuilding the image so that you can customize it first. 64 | 65 | 1. Build the basic CD data: 66 | 67 | ./scripts/build.sh 68 | 69 | Note: some of the steps need to run `sudo`, so you will be 70 | prompted for your password one or more times. 71 | 72 | 2. Customize the contents in the `extract` directory. This step is 73 | completely up to you, depending on what you want to customize. 74 | You might want to install some custom packages, for example 75 | keymaps for non US keyboards: 76 | 77 | sudo ./scripts/install-tcz.sh kmaps 78 | 79 | 3. Create the final ISO: 80 | 81 | sudo ./scripts/pack-iso.sh 82 | 83 | 84 | Disclaimer 85 | ---------- 86 | 87 | The challenges are based on the original online contest 88 | organized by Stripe: 89 | https://stripe.com/blog/capture-the-flag 90 | 91 | 92 | Using the Live CD 93 | ----------------- 94 | 95 | See http://janosgyerik.github.com/capture-the-flag/ 96 | 97 | 98 | Screenshots 99 | ----------- 100 | 101 | ![Start](https://github.com/janosgyerik/capture-the-flag/raw/master/images/start.png) 102 | ![End](https://github.com/janosgyerik/capture-the-flag/raw/master/images/end.png) 103 | 104 | 105 | Solutions 106 | --------- 107 | 108 | The solutions are intentionally omitted from this project. 109 | You can find the solutions to the original Stripe challenges on the internet, 110 | but don't be surprised if they won't work on this Live CD out of the box. 111 | That's intentional too ;-) 112 | 113 | Please keep your own solutions private. 114 | 115 | 116 | Abusing the CD 117 | -------------- 118 | 119 | If you want to get root access in the live system, 120 | you can either do `su - tc` to become the admin user, 121 | or boot the system with the `mc superuser` boot option. 122 | This is no secret, and you won't learn anything this way. 123 | 124 | 125 | Links 126 | ----- 127 | 128 | * [Latest ISO image](https://github.com/janosgyerik/capture-the-flag/releases/download/v1.0/ctf1-r14.iso) 129 | * [Blog announcement of Capture The Flag, by Stripe](https://stripe.com/blog/capture-the-flag) 130 | * [Blog announcement of Capture The Flag 2.0, by Stripe](https://stripe.com/blog/capture-the-flag-20) 131 | * https://insecure.org/stf/smashstack.html 132 | * [Tiny Core Linux](http://distro.ibiblio.org/tinycorelinux/) 133 | * [The CTF ASCII art generator](http://patorjk.com/software/taag/#p=testall&f=Graffiti&t=CTF) 134 | -------------------------------------------------------------------------------- /ctf1/append/etc/inittab: -------------------------------------------------------------------------------- 1 | # /etc/inittab: init configuration for busybox init. 2 | # Boot-time system configuration/initialization script. 3 | # 4 | ::sysinit:/etc/init.d/rcS 5 | 6 | # /sbin/getty respawn shell invocations for selected ttys. 7 | tty1::respawn:/sbin/getty -nl /sbin/autologin 38400 tty1 8 | tty2::respawn:/sbin/getty 38400 tty2 9 | tty3::respawn:/sbin/getty 38400 tty3 10 | #tty4::askfirst:/sbin/getty 38400 tty4 11 | #tty5::askfirst:/sbin/getty 38400 tty5 12 | #tty6::askfirst:/sbin/getty 38400 tty6 13 | 14 | # Stuff to do when restarting the init 15 | # process, or before rebooting. 16 | ::restart:/etc/init.d/rc.shutdown 17 | ::restart:/sbin/init 18 | ::ctrlaltdel:/sbin/reboot 19 | ::shutdown:/etc/init.d/rc.shutdown 20 | 21 | -------------------------------------------------------------------------------- /ctf1/append/home/level00/syntax.txt: -------------------------------------------------------------------------------- 1 | Hi there! 2 | 3 | If you know what to do but have a bit of struggle with the 4 | syntax, you may find these examples helpful. 5 | 6 | Example 1: send an HTTP GET to a local web server and output the result 7 | 8 | curl localhost:1234 9 | 10 | Example 2: passing binary data as command line arguments 11 | 12 | /path/to/program arg1 $(printf "\x41\x00\x20\x41") arg2 13 | 14 | Example 3: view binary data in hexadecimal format 15 | 16 | printf "\x41\x00\x20\x41" | hexdump 17 | 18 | Example 4: send an HTTP POST with the POST data in a file, and at 19 | the same time set a cookie 20 | 21 | curl localhost:1234 --data-urlencode @postdata.txt --cookie name=value 22 | 23 | Example 5: repeat something a 100 times 24 | 25 | for i in $(seq 1 100); do echo hello $i; done 26 | 27 | Good luck, and have fun! 28 | The ctf-o-matic team 29 | -------------------------------------------------------------------------------- /ctf1/append/home/level00/tools.txt: -------------------------------------------------------------------------------- 1 | Hi there! 2 | 3 | For your convenience, we included some tools that you migth 4 | find helpful: 5 | 6 | * objdump # display information from object files 7 | * gdb # the GNU debugger 8 | * curl # transfer a URL (run http GET/POST requests, etc) 9 | * ruby # interpreted object oriented scripting language 10 | * python # interpreted object oriented scripting language 11 | * vi # a programmer's text editor 12 | * nano # text editor, an enhanced free Pico clone 13 | 14 | However, epecially at higher levels it is probably easier to 15 | copy the source code files of the levels to your host system, 16 | compile them as 32-bit Linux binaries, and develop the exploit 17 | code in your comfortable environment using your favorite 18 | tools. When an exploit code is ready, copy it to the Live CD 19 | using scp or sftp, and login to the Live CD as execute against 20 | the vulnerable programs. (At least that's how *we* do it...) 21 | 22 | If you need superuser access while running the Live CD, 23 | you can switch to the `tc` user with `su - tc` and perform 24 | administrative tasks using `sudo`. To install additional 25 | software use the `tce` command (with the `tc` user), this 26 | is the package manager of Tiny Core Linux, the base system 27 | of this Live CD. 28 | 29 | Good luck, and have fun! 30 | The ctf-o-matic team 31 | -------------------------------------------------------------------------------- /ctf1/append/home/level02/flask/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | flask 4 | ~~~~~ 5 | 6 | A microframework based on Werkzeug. It's extensively documented 7 | and follows best practice patterns. 8 | 9 | :copyright: (c) 2011 by Armin Ronacher. 10 | :license: BSD, see LICENSE for more details. 11 | """ 12 | 13 | __version__ = '0.9' 14 | 15 | # utilities we import from Werkzeug and Jinja2 that are unused 16 | # in the module but are exported as public interface. 17 | from werkzeug.exceptions import abort 18 | from werkzeug.utils import redirect 19 | from jinja2 import Markup, escape 20 | 21 | from .app import Flask, Request, Response 22 | from .config import Config 23 | from .helpers import url_for, jsonify, json_available, flash, \ 24 | send_file, send_from_directory, get_flashed_messages, \ 25 | get_template_attribute, make_response, safe_join, \ 26 | stream_with_context 27 | from .globals import current_app, g, request, session, _request_ctx_stack, \ 28 | _app_ctx_stack 29 | from .ctx import has_request_context, has_app_context, \ 30 | after_this_request 31 | from .module import Module 32 | from .blueprints import Blueprint 33 | from .templating import render_template, render_template_string 34 | 35 | # the signals 36 | from .signals import signals_available, template_rendered, request_started, \ 37 | request_finished, got_request_exception, request_tearing_down 38 | 39 | # only import json if it's available 40 | if json_available: 41 | from .helpers import json 42 | 43 | # backwards compat, goes away in 1.0 44 | from .sessions import SecureCookieSession as Session 45 | -------------------------------------------------------------------------------- /ctf1/append/home/level02/flask/debughelpers.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | flask.debughelpers 4 | ~~~~~~~~~~~~~~~~~~ 5 | 6 | Various helpers to make the development experience better. 7 | 8 | :copyright: (c) 2011 by Armin Ronacher. 9 | :license: BSD, see LICENSE for more details. 10 | """ 11 | 12 | 13 | class DebugFilesKeyError(KeyError, AssertionError): 14 | """Raised from request.files during debugging. The idea is that it can 15 | provide a better error message than just a generic KeyError/BadRequest. 16 | """ 17 | 18 | def __init__(self, request, key): 19 | form_matches = request.form.getlist(key) 20 | buf = ['You tried to access the file "%s" in the request.files ' 21 | 'dictionary but it does not exist. The mimetype for the request ' 22 | 'is "%s" instead of "multipart/form-data" which means that no ' 23 | 'file contents were transmitted. To fix this error you should ' 24 | 'provide enctype="multipart/form-data" in your form.' % 25 | (key, request.mimetype)] 26 | if form_matches: 27 | buf.append('\n\nThe browser instead transmitted some file names. ' 28 | 'This was submitted: %s' % ', '.join('"%s"' % x 29 | for x in form_matches)) 30 | self.msg = ''.join(buf).encode('utf-8') 31 | 32 | def __str__(self): 33 | return self.msg 34 | 35 | 36 | class FormDataRoutingRedirect(AssertionError): 37 | """This exception is raised by Flask in debug mode if it detects a 38 | redirect caused by the routing system when the request method is not 39 | GET, HEAD or OPTIONS. Reasoning: form data will be dropped. 40 | """ 41 | 42 | def __init__(self, request): 43 | exc = request.routing_exception 44 | buf = ['A request was sent to this URL (%s) but a redirect was ' 45 | 'issued automatically by the routing system to "%s".' 46 | % (request.url, exc.new_url)] 47 | 48 | # In case just a slash was appended we can be extra helpful 49 | if request.base_url + '/' == exc.new_url.split('?')[0]: 50 | buf.append(' The URL was defined with a trailing slash so ' 51 | 'Flask will automatically redirect to the URL ' 52 | 'with the trailing slash if it was accessed ' 53 | 'without one.') 54 | 55 | buf.append(' Make sure to directly send your %s-request to this URL ' 56 | 'since we can\'t make browsers or HTTP clients redirect ' 57 | 'with form data reliably or without user interaction.' % 58 | request.method) 59 | buf.append('\n\nNote: this exception is only raised in debug mode') 60 | AssertionError.__init__(self, ''.join(buf).encode('utf-8')) 61 | 62 | 63 | def attach_enctype_error_multidict(request): 64 | """Since Flask 0.8 we're monkeypatching the files object in case a 65 | request is detected that does not use multipart form data but the files 66 | object is accessed. 67 | """ 68 | oldcls = request.files.__class__ 69 | class newcls(oldcls): 70 | def __getitem__(self, key): 71 | try: 72 | return oldcls.__getitem__(self, key) 73 | except KeyError, e: 74 | if key not in request.form: 75 | raise 76 | raise DebugFilesKeyError(request, key) 77 | newcls.__name__ = oldcls.__name__ 78 | newcls.__module__ = oldcls.__module__ 79 | request.files.__class__ = newcls 80 | -------------------------------------------------------------------------------- /ctf1/append/home/level02/flask/exceptions.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | flask.exceptions 4 | ~~~~~~~~~~~~ 5 | 6 | Flask specific additions to :class:`~werkzeug.exceptions.HTTPException` 7 | 8 | :copyright: (c) 2011 by Armin Ronacher. 9 | :license: BSD, see LICENSE for more details. 10 | """ 11 | from werkzeug.exceptions import HTTPException, BadRequest 12 | from .helpers import json 13 | 14 | 15 | class JSONHTTPException(HTTPException): 16 | """A base class for HTTP exceptions with ``Content-Type: 17 | application/json``. 18 | 19 | The ``description`` attribute of this class must set to a string (*not* an 20 | HTML string) which describes the error. 21 | 22 | """ 23 | 24 | def get_body(self, environ): 25 | """Overrides :meth:`werkzeug.exceptions.HTTPException.get_body` to 26 | return the description of this error in JSON format instead of HTML. 27 | 28 | """ 29 | return json.dumps(dict(description=self.get_description(environ))) 30 | 31 | def get_headers(self, environ): 32 | """Returns a list of headers including ``Content-Type: 33 | application/json``. 34 | 35 | """ 36 | return [('Content-Type', 'application/json')] 37 | 38 | 39 | class JSONBadRequest(JSONHTTPException, BadRequest): 40 | """Represents an HTTP ``400 Bad Request`` error whose body contains an 41 | error message in JSON format instead of HTML format (as in the superclass). 42 | 43 | """ 44 | 45 | #: The description of the error which occurred as a string. 46 | description = ( 47 | 'The browser (or proxy) sent a request that this server could not ' 48 | 'understand.' 49 | ) 50 | -------------------------------------------------------------------------------- /ctf1/append/home/level02/flask/ext/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | flask.ext 4 | ~~~~~~~~~ 5 | 6 | Redirect imports for extensions. This module basically makes it possible 7 | for us to transition from flaskext.foo to flask_foo without having to 8 | force all extensions to upgrade at the same time. 9 | 10 | When a user does ``from flask.ext.foo import bar`` it will attempt to 11 | import ``from flask_foo import bar`` first and when that fails it will 12 | try to import ``from flaskext.foo import bar``. 13 | 14 | We're switching from namespace packages because it was just too painful for 15 | everybody involved. 16 | 17 | :copyright: (c) 2011 by Armin Ronacher. 18 | :license: BSD, see LICENSE for more details. 19 | """ 20 | 21 | 22 | def setup(): 23 | from ..exthook import ExtensionImporter 24 | importer = ExtensionImporter(['flask_%s', 'flaskext.%s'], __name__) 25 | importer.install() 26 | 27 | 28 | setup() 29 | del setup 30 | -------------------------------------------------------------------------------- /ctf1/append/home/level02/flask/globals.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | flask.globals 4 | ~~~~~~~~~~~~~ 5 | 6 | Defines all the global objects that are proxies to the current 7 | active context. 8 | 9 | :copyright: (c) 2011 by Armin Ronacher. 10 | :license: BSD, see LICENSE for more details. 11 | """ 12 | 13 | from functools import partial 14 | from werkzeug.local import LocalStack, LocalProxy 15 | 16 | def _lookup_object(name): 17 | top = _request_ctx_stack.top 18 | if top is None: 19 | raise RuntimeError('working outside of request context') 20 | return getattr(top, name) 21 | 22 | 23 | def _find_app(): 24 | top = _app_ctx_stack.top 25 | if top is None: 26 | raise RuntimeError('working outside of application context') 27 | return top.app 28 | 29 | 30 | # context locals 31 | _request_ctx_stack = LocalStack() 32 | _app_ctx_stack = LocalStack() 33 | current_app = LocalProxy(_find_app) 34 | request = LocalProxy(partial(_lookup_object, 'request')) 35 | session = LocalProxy(partial(_lookup_object, 'session')) 36 | g = LocalProxy(partial(_lookup_object, 'g')) 37 | -------------------------------------------------------------------------------- /ctf1/append/home/level02/flask/logging.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | flask.logging 4 | ~~~~~~~~~~~~~ 5 | 6 | Implements the logging support for Flask. 7 | 8 | :copyright: (c) 2011 by Armin Ronacher. 9 | :license: BSD, see LICENSE for more details. 10 | """ 11 | 12 | from __future__ import absolute_import 13 | 14 | from logging import getLogger, StreamHandler, Formatter, getLoggerClass, DEBUG 15 | 16 | 17 | def create_logger(app): 18 | """Creates a logger for the given application. This logger works 19 | similar to a regular Python logger but changes the effective logging 20 | level based on the application's debug flag. Furthermore this 21 | function also removes all attached handlers in case there was a 22 | logger with the log name before. 23 | """ 24 | Logger = getLoggerClass() 25 | 26 | class DebugLogger(Logger): 27 | def getEffectiveLevel(x): 28 | if x.level == 0 and app.debug: 29 | return DEBUG 30 | return Logger.getEffectiveLevel(x) 31 | 32 | class DebugHandler(StreamHandler): 33 | def emit(x, record): 34 | StreamHandler.emit(x, record) if app.debug else None 35 | 36 | handler = DebugHandler() 37 | handler.setLevel(DEBUG) 38 | handler.setFormatter(Formatter(app.debug_log_format)) 39 | logger = getLogger(app.logger_name) 40 | # just in case that was not a new logger, get rid of all the handlers 41 | # already attached to it. 42 | del logger.handlers[:] 43 | logger.__class__ = DebugLogger 44 | logger.addHandler(handler) 45 | return logger 46 | -------------------------------------------------------------------------------- /ctf1/append/home/level02/flask/module.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | flask.module 4 | ~~~~~~~~~~~~ 5 | 6 | Implements a class that represents module blueprints. 7 | 8 | :copyright: (c) 2011 by Armin Ronacher. 9 | :license: BSD, see LICENSE for more details. 10 | """ 11 | 12 | import os 13 | 14 | from .blueprints import Blueprint 15 | 16 | 17 | def blueprint_is_module(bp): 18 | """Used to figure out if something is actually a module""" 19 | return isinstance(bp, Module) 20 | 21 | 22 | class Module(Blueprint): 23 | """Deprecated module support. Until Flask 0.6 modules were a different 24 | name of the concept now available as blueprints in Flask. They are 25 | essentially doing the same but have some bad semantics for templates and 26 | static files that were fixed with blueprints. 27 | 28 | .. versionchanged:: 0.7 29 | Modules were deprecated in favor for blueprints. 30 | """ 31 | 32 | def __init__(self, import_name, name=None, url_prefix=None, 33 | static_path=None, subdomain=None): 34 | if name is None: 35 | assert '.' in import_name, 'name required if package name ' \ 36 | 'does not point to a submodule' 37 | name = import_name.rsplit('.', 1)[1] 38 | Blueprint.__init__(self, name, import_name, url_prefix=url_prefix, 39 | subdomain=subdomain, template_folder='templates') 40 | 41 | if os.path.isdir(os.path.join(self.root_path, 'static')): 42 | self._static_folder = 'static' 43 | -------------------------------------------------------------------------------- /ctf1/append/home/level02/flask/session.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | flask.session 4 | ~~~~~~~~~~~~~ 5 | 6 | This module used to flask with the session global so we moved it 7 | over to flask.sessions 8 | 9 | :copyright: (c) 2011 by Armin Ronacher. 10 | :license: BSD, see LICENSE for more details. 11 | """ 12 | 13 | from warnings import warn 14 | warn(DeprecationWarning('please use flask.sessions instead')) 15 | 16 | from .sessions import SecureCookieSession, NullSession 17 | 18 | Session = SecureCookieSession 19 | _NullSession = NullSession 20 | -------------------------------------------------------------------------------- /ctf1/append/home/level02/flask/signals.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | flask.signals 4 | ~~~~~~~~~~~~~ 5 | 6 | Implements signals based on blinker if available, otherwise 7 | falls silently back to a noop 8 | 9 | :copyright: (c) 2011 by Armin Ronacher. 10 | :license: BSD, see LICENSE for more details. 11 | """ 12 | signals_available = False 13 | try: 14 | from blinker import Namespace 15 | signals_available = True 16 | except ImportError: 17 | class Namespace(object): 18 | def signal(self, name, doc=None): 19 | return _FakeSignal(name, doc) 20 | 21 | class _FakeSignal(object): 22 | """If blinker is unavailable, create a fake class with the same 23 | interface that allows sending of signals but will fail with an 24 | error on anything else. Instead of doing anything on send, it 25 | will just ignore the arguments and do nothing instead. 26 | """ 27 | 28 | def __init__(self, name, doc=None): 29 | self.name = name 30 | self.__doc__ = doc 31 | def _fail(self, *args, **kwargs): 32 | raise RuntimeError('signalling support is unavailable ' 33 | 'because the blinker library is ' 34 | 'not installed.') 35 | send = lambda *a, **kw: None 36 | connect = disconnect = has_receivers_for = receivers_for = \ 37 | temporarily_connected_to = connected_to = _fail 38 | del _fail 39 | 40 | # the namespace for code signals. If you are not flask code, do 41 | # not put signals in here. Create your own namespace instead. 42 | _signals = Namespace() 43 | 44 | 45 | # core signals. For usage examples grep the sourcecode or consult 46 | # the API documentation in docs/api.rst as well as docs/signals.rst 47 | template_rendered = _signals.signal('template-rendered') 48 | request_started = _signals.signal('request-started') 49 | request_finished = _signals.signal('request-finished') 50 | request_tearing_down = _signals.signal('request-tearing-down') 51 | got_request_exception = _signals.signal('got-request-exception') 52 | appcontext_tearing_down = _signals.signal('appcontext-tearing-down') 53 | -------------------------------------------------------------------------------- /ctf1/append/home/level02/flask/templating.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | flask.templating 4 | ~~~~~~~~~~~~~~~~ 5 | 6 | Implements the bridge to Jinja2. 7 | 8 | :copyright: (c) 2011 by Armin Ronacher. 9 | :license: BSD, see LICENSE for more details. 10 | """ 11 | import posixpath 12 | from jinja2 import BaseLoader, Environment as BaseEnvironment, \ 13 | TemplateNotFound 14 | 15 | from .globals import _request_ctx_stack 16 | from .signals import template_rendered 17 | from .module import blueprint_is_module 18 | 19 | 20 | def _default_template_ctx_processor(): 21 | """Default template context processor. Injects `request`, 22 | `session` and `g`. 23 | """ 24 | reqctx = _request_ctx_stack.top 25 | return dict( 26 | config=reqctx.app.config, 27 | request=reqctx.request, 28 | session=reqctx.session, 29 | g=reqctx.g 30 | ) 31 | 32 | 33 | class Environment(BaseEnvironment): 34 | """Works like a regular Jinja2 environment but has some additional 35 | knowledge of how Flask's blueprint works so that it can prepend the 36 | name of the blueprint to referenced templates if necessary. 37 | """ 38 | 39 | def __init__(self, app, **options): 40 | if 'loader' not in options: 41 | options['loader'] = app.create_global_jinja_loader() 42 | BaseEnvironment.__init__(self, **options) 43 | self.app = app 44 | 45 | 46 | class DispatchingJinjaLoader(BaseLoader): 47 | """A loader that looks for templates in the application and all 48 | the blueprint folders. 49 | """ 50 | 51 | def __init__(self, app): 52 | self.app = app 53 | 54 | def get_source(self, environment, template): 55 | for loader, local_name in self._iter_loaders(template): 56 | try: 57 | return loader.get_source(environment, local_name) 58 | except TemplateNotFound: 59 | pass 60 | 61 | raise TemplateNotFound(template) 62 | 63 | def _iter_loaders(self, template): 64 | loader = self.app.jinja_loader 65 | if loader is not None: 66 | yield loader, template 67 | 68 | # old style module based loaders in case we are dealing with a 69 | # blueprint that is an old style module 70 | try: 71 | module, local_name = posixpath.normpath(template).split('/', 1) 72 | blueprint = self.app.blueprints[module] 73 | if blueprint_is_module(blueprint): 74 | loader = blueprint.jinja_loader 75 | if loader is not None: 76 | yield loader, local_name 77 | except (ValueError, KeyError): 78 | pass 79 | 80 | for blueprint in self.app.blueprints.itervalues(): 81 | if blueprint_is_module(blueprint): 82 | continue 83 | loader = blueprint.jinja_loader 84 | if loader is not None: 85 | yield loader, template 86 | 87 | def list_templates(self): 88 | result = set() 89 | loader = self.app.jinja_loader 90 | if loader is not None: 91 | result.update(loader.list_templates()) 92 | 93 | for name, blueprint in self.app.blueprints.iteritems(): 94 | loader = blueprint.jinja_loader 95 | if loader is not None: 96 | for template in loader.list_templates(): 97 | prefix = '' 98 | if blueprint_is_module(blueprint): 99 | prefix = name + '/' 100 | result.add(prefix + template) 101 | 102 | return list(result) 103 | 104 | 105 | def _render(template, context, app): 106 | """Renders the template and fires the signal""" 107 | rv = template.render(context) 108 | template_rendered.send(app, template=template, context=context) 109 | return rv 110 | 111 | 112 | def render_template(template_name_or_list, **context): 113 | """Renders a template from the template folder with the given 114 | context. 115 | 116 | :param template_name_or_list: the name of the template to be 117 | rendered, or an iterable with template names 118 | the first one existing will be rendered 119 | :param context: the variables that should be available in the 120 | context of the template. 121 | """ 122 | ctx = _request_ctx_stack.top 123 | ctx.app.update_template_context(context) 124 | return _render(ctx.app.jinja_env.get_or_select_template(template_name_or_list), 125 | context, ctx.app) 126 | 127 | 128 | def render_template_string(source, **context): 129 | """Renders a template from the given template source string 130 | with the given context. 131 | 132 | :param template_name: the sourcecode of the template to be 133 | rendered 134 | :param context: the variables that should be available in the 135 | context of the template. 136 | """ 137 | ctx = _request_ctx_stack.top 138 | ctx.app.update_template_context(context) 139 | return _render(ctx.app.jinja_env.from_string(source), 140 | context, ctx.app) 141 | -------------------------------------------------------------------------------- /ctf1/append/home/level02/flask/testing.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | flask.testing 4 | ~~~~~~~~~~~~~ 5 | 6 | Implements test support helpers. This module is lazily imported 7 | and usually not used in production environments. 8 | 9 | :copyright: (c) 2011 by Armin Ronacher. 10 | :license: BSD, see LICENSE for more details. 11 | """ 12 | 13 | from __future__ import with_statement 14 | 15 | from contextlib import contextmanager 16 | from werkzeug.test import Client, EnvironBuilder 17 | from flask import _request_ctx_stack 18 | 19 | 20 | def make_test_environ_builder(app, path='/', base_url=None, *args, **kwargs): 21 | """Creates a new test builder with some application defaults thrown in.""" 22 | http_host = app.config.get('SERVER_NAME') 23 | app_root = app.config.get('APPLICATION_ROOT') 24 | if base_url is None: 25 | base_url = 'http://%s/' % (http_host or 'localhost') 26 | if app_root: 27 | base_url += app_root.lstrip('/') 28 | return EnvironBuilder(path, base_url, *args, **kwargs) 29 | 30 | 31 | class FlaskClient(Client): 32 | """Works like a regular Werkzeug test client but has some knowledge about 33 | how Flask works to defer the cleanup of the request context stack to the 34 | end of a with body when used in a with statement. For general information 35 | about how to use this class refer to :class:`werkzeug.test.Client`. 36 | 37 | Basic usage is outlined in the :ref:`testing` chapter. 38 | """ 39 | 40 | preserve_context = False 41 | 42 | @contextmanager 43 | def session_transaction(self, *args, **kwargs): 44 | """When used in combination with a with statement this opens a 45 | session transaction. This can be used to modify the session that 46 | the test client uses. Once the with block is left the session is 47 | stored back. 48 | 49 | with client.session_transaction() as session: 50 | session['value'] = 42 51 | 52 | Internally this is implemented by going through a temporary test 53 | request context and since session handling could depend on 54 | request variables this function accepts the same arguments as 55 | :meth:`~flask.Flask.test_request_context` which are directly 56 | passed through. 57 | """ 58 | if self.cookie_jar is None: 59 | raise RuntimeError('Session transactions only make sense ' 60 | 'with cookies enabled.') 61 | app = self.application 62 | environ_overrides = kwargs.setdefault('environ_overrides', {}) 63 | self.cookie_jar.inject_wsgi(environ_overrides) 64 | outer_reqctx = _request_ctx_stack.top 65 | with app.test_request_context(*args, **kwargs) as c: 66 | sess = app.open_session(c.request) 67 | if sess is None: 68 | raise RuntimeError('Session backend did not open a session. ' 69 | 'Check the configuration') 70 | 71 | # Since we have to open a new request context for the session 72 | # handling we want to make sure that we hide out own context 73 | # from the caller. By pushing the original request context 74 | # (or None) on top of this and popping it we get exactly that 75 | # behavior. It's important to not use the push and pop 76 | # methods of the actual request context object since that would 77 | # mean that cleanup handlers are called 78 | _request_ctx_stack.push(outer_reqctx) 79 | try: 80 | yield sess 81 | finally: 82 | _request_ctx_stack.pop() 83 | 84 | resp = app.response_class() 85 | if not app.session_interface.is_null_session(sess): 86 | app.save_session(sess, resp) 87 | headers = resp.get_wsgi_headers(c.request.environ) 88 | self.cookie_jar.extract_wsgi(c.request.environ, headers) 89 | 90 | def open(self, *args, **kwargs): 91 | kwargs.setdefault('environ_overrides', {}) \ 92 | ['flask._preserve_context'] = self.preserve_context 93 | 94 | as_tuple = kwargs.pop('as_tuple', False) 95 | buffered = kwargs.pop('buffered', False) 96 | follow_redirects = kwargs.pop('follow_redirects', False) 97 | builder = make_test_environ_builder(self.application, *args, **kwargs) 98 | 99 | return Client.open(self, builder, 100 | as_tuple=as_tuple, 101 | buffered=buffered, 102 | follow_redirects=follow_redirects) 103 | 104 | def __enter__(self): 105 | if self.preserve_context: 106 | raise RuntimeError('Cannot nest client invocations') 107 | self.preserve_context = True 108 | return self 109 | 110 | def __exit__(self, exc_type, exc_value, tb): 111 | self.preserve_context = False 112 | 113 | # on exit we want to clean up earlier. Normally the request context 114 | # stays preserved until the next request in the same thread comes 115 | # in. See RequestGlobals.push() for the general behavior. 116 | top = _request_ctx_stack.top 117 | if top is not None and top.preserved: 118 | top.pop() 119 | -------------------------------------------------------------------------------- /ctf1/append/home/level02/flask/testsuite/appctx.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | flask.testsuite.appctx 4 | ~~~~~~~~~~~~~~~~~~~~~~ 5 | 6 | Tests the application context. 7 | 8 | :copyright: (c) 2012 by Armin Ronacher. 9 | :license: BSD, see LICENSE for more details. 10 | """ 11 | 12 | from __future__ import with_statement 13 | 14 | import flask 15 | import unittest 16 | from flask.testsuite import FlaskTestCase 17 | 18 | 19 | class AppContextTestCase(FlaskTestCase): 20 | 21 | def test_basic_url_generation(self): 22 | app = flask.Flask(__name__) 23 | app.config['SERVER_NAME'] = 'localhost' 24 | app.config['PREFERRED_URL_SCHEME'] = 'https' 25 | 26 | @app.route('/') 27 | def index(): 28 | pass 29 | 30 | with app.app_context(): 31 | rv = flask.url_for('index') 32 | self.assert_equal(rv, 'https://localhost/') 33 | 34 | def test_url_generation_requires_server_name(self): 35 | app = flask.Flask(__name__) 36 | with app.app_context(): 37 | with self.assert_raises(RuntimeError): 38 | flask.url_for('index') 39 | 40 | def test_url_generation_without_context_fails(self): 41 | with self.assert_raises(RuntimeError): 42 | flask.url_for('index') 43 | 44 | def test_request_context_means_app_context(self): 45 | app = flask.Flask(__name__) 46 | with app.test_request_context(): 47 | self.assert_equal(flask.current_app._get_current_object(), app) 48 | self.assert_equal(flask._app_ctx_stack.top, None) 49 | 50 | def test_app_context_provides_current_app(self): 51 | app = flask.Flask(__name__) 52 | with app.app_context(): 53 | self.assert_equal(flask.current_app._get_current_object(), app) 54 | self.assert_equal(flask._app_ctx_stack.top, None) 55 | 56 | def test_app_tearing_down(self): 57 | cleanup_stuff = [] 58 | app = flask.Flask(__name__) 59 | @app.teardown_appcontext 60 | def cleanup(exception): 61 | cleanup_stuff.append(exception) 62 | 63 | with app.app_context(): 64 | pass 65 | 66 | self.assert_equal(cleanup_stuff, [None]) 67 | 68 | def test_custom_request_globals_class(self): 69 | class CustomRequestGlobals(object): 70 | def __init__(self): 71 | self.spam = 'eggs' 72 | app = flask.Flask(__name__) 73 | app.request_globals_class = CustomRequestGlobals 74 | with app.test_request_context(): 75 | self.assert_equal( 76 | flask.render_template_string('{{ g.spam }}'), 'eggs') 77 | 78 | def test_context_refcounts(self): 79 | called = [] 80 | app = flask.Flask(__name__) 81 | @app.teardown_request 82 | def teardown_req(error=None): 83 | called.append('request') 84 | @app.teardown_appcontext 85 | def teardown_app(error=None): 86 | called.append('app') 87 | @app.route('/') 88 | def index(): 89 | with flask._app_ctx_stack.top: 90 | with flask._request_ctx_stack.top: 91 | pass 92 | self.assert_(flask._request_ctx_stack.request.environ 93 | ['werkzeug.request'] is not None) 94 | c = app.test_client() 95 | c.get('/') 96 | self.assertEqual(called, ['request', 'app']) 97 | 98 | 99 | def suite(): 100 | suite = unittest.TestSuite() 101 | suite.addTest(unittest.makeSuite(AppContextTestCase)) 102 | return suite 103 | -------------------------------------------------------------------------------- /ctf1/append/home/level02/flask/testsuite/deprecations.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | flask.testsuite.deprecations 4 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 5 | 6 | Tests deprecation support. 7 | 8 | :copyright: (c) 2011 by Armin Ronacher. 9 | :license: BSD, see LICENSE for more details. 10 | """ 11 | 12 | from __future__ import with_statement 13 | 14 | import flask 15 | import unittest 16 | from flask.testsuite import FlaskTestCase, catch_warnings 17 | 18 | 19 | class DeprecationsTestCase(FlaskTestCase): 20 | 21 | def test_init_jinja_globals(self): 22 | class MyFlask(flask.Flask): 23 | def init_jinja_globals(self): 24 | self.jinja_env.globals['foo'] = '42' 25 | 26 | with catch_warnings() as log: 27 | app = MyFlask(__name__) 28 | @app.route('/') 29 | def foo(): 30 | return app.jinja_env.globals['foo'] 31 | 32 | c = app.test_client() 33 | self.assert_equal(c.get('/').data, '42') 34 | self.assert_equal(len(log), 1) 35 | self.assert_('init_jinja_globals' in str(log[0]['message'])) 36 | 37 | 38 | def suite(): 39 | suite = unittest.TestSuite() 40 | suite.addTest(unittest.makeSuite(DeprecationsTestCase)) 41 | return suite 42 | -------------------------------------------------------------------------------- /ctf1/append/home/level02/flask/testsuite/examples.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | flask.testsuite.examples 4 | ~~~~~~~~~~~~~~~~~~~~~~~~ 5 | 6 | Tests the examples. 7 | 8 | :copyright: (c) 2011 by Armin Ronacher. 9 | :license: BSD, see LICENSE for more details. 10 | """ 11 | import os 12 | import unittest 13 | from flask.testsuite import add_to_path 14 | 15 | 16 | def setup_path(): 17 | example_path = os.path.join(os.path.dirname(__file__), 18 | os.pardir, os.pardir, 'examples') 19 | add_to_path(os.path.join(example_path, 'flaskr')) 20 | add_to_path(os.path.join(example_path, 'minitwit')) 21 | 22 | 23 | def suite(): 24 | setup_path() 25 | suite = unittest.TestSuite() 26 | try: 27 | from minitwit_tests import MiniTwitTestCase 28 | except ImportError: 29 | pass 30 | else: 31 | suite.addTest(unittest.makeSuite(MiniTwitTestCase)) 32 | try: 33 | from flaskr_tests import FlaskrTestCase 34 | except ImportError: 35 | pass 36 | else: 37 | suite.addTest(unittest.makeSuite(FlaskrTestCase)) 38 | return suite 39 | -------------------------------------------------------------------------------- /ctf1/append/home/level02/flask/testsuite/ext.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | flask.testsuite.ext 4 | ~~~~~~~~~~~~~~~~~~~ 5 | 6 | Tests the extension import thing. 7 | 8 | :copyright: (c) 2011 by Armin Ronacher. 9 | :license: BSD, see LICENSE for more details. 10 | """ 11 | from __future__ import with_statement 12 | 13 | import sys 14 | import unittest 15 | from flask.testsuite import FlaskTestCase 16 | 17 | 18 | class ExtImportHookTestCase(FlaskTestCase): 19 | 20 | def setup(self): 21 | # we clear this out for various reasons. The most important one is 22 | # that a real flaskext could be in there which would disable our 23 | # fake package. Secondly we want to make sure that the flaskext 24 | # import hook does not break on reloading. 25 | for entry, value in sys.modules.items(): 26 | if (entry.startswith('flask.ext.') or 27 | entry.startswith('flask_') or 28 | entry.startswith('flaskext.') or 29 | entry == 'flaskext') and value is not None: 30 | sys.modules.pop(entry, None) 31 | from flask import ext 32 | reload(ext) 33 | 34 | # reloading must not add more hooks 35 | import_hooks = 0 36 | for item in sys.meta_path: 37 | cls = type(item) 38 | if cls.__module__ == 'flask.exthook' and \ 39 | cls.__name__ == 'ExtensionImporter': 40 | import_hooks += 1 41 | self.assert_equal(import_hooks, 1) 42 | 43 | def teardown(self): 44 | from flask import ext 45 | for key in ext.__dict__: 46 | self.assert_('.' not in key) 47 | 48 | def test_flaskext_new_simple_import_normal(self): 49 | from flask.ext.newext_simple import ext_id 50 | self.assert_equal(ext_id, 'newext_simple') 51 | 52 | def test_flaskext_new_simple_import_module(self): 53 | from flask.ext import newext_simple 54 | self.assert_equal(newext_simple.ext_id, 'newext_simple') 55 | self.assert_equal(newext_simple.__name__, 'flask_newext_simple') 56 | 57 | def test_flaskext_new_package_import_normal(self): 58 | from flask.ext.newext_package import ext_id 59 | self.assert_equal(ext_id, 'newext_package') 60 | 61 | def test_flaskext_new_package_import_module(self): 62 | from flask.ext import newext_package 63 | self.assert_equal(newext_package.ext_id, 'newext_package') 64 | self.assert_equal(newext_package.__name__, 'flask_newext_package') 65 | 66 | def test_flaskext_new_package_import_submodule_function(self): 67 | from flask.ext.newext_package.submodule import test_function 68 | self.assert_equal(test_function(), 42) 69 | 70 | def test_flaskext_new_package_import_submodule(self): 71 | from flask.ext.newext_package import submodule 72 | self.assert_equal(submodule.__name__, 'flask_newext_package.submodule') 73 | self.assert_equal(submodule.test_function(), 42) 74 | 75 | def test_flaskext_old_simple_import_normal(self): 76 | from flask.ext.oldext_simple import ext_id 77 | self.assert_equal(ext_id, 'oldext_simple') 78 | 79 | def test_flaskext_old_simple_import_module(self): 80 | from flask.ext import oldext_simple 81 | self.assert_equal(oldext_simple.ext_id, 'oldext_simple') 82 | self.assert_equal(oldext_simple.__name__, 'flaskext.oldext_simple') 83 | 84 | def test_flaskext_old_package_import_normal(self): 85 | from flask.ext.oldext_package import ext_id 86 | self.assert_equal(ext_id, 'oldext_package') 87 | 88 | def test_flaskext_old_package_import_module(self): 89 | from flask.ext import oldext_package 90 | self.assert_equal(oldext_package.ext_id, 'oldext_package') 91 | self.assert_equal(oldext_package.__name__, 'flaskext.oldext_package') 92 | 93 | def test_flaskext_old_package_import_submodule(self): 94 | from flask.ext.oldext_package import submodule 95 | self.assert_equal(submodule.__name__, 'flaskext.oldext_package.submodule') 96 | self.assert_equal(submodule.test_function(), 42) 97 | 98 | def test_flaskext_old_package_import_submodule_function(self): 99 | from flask.ext.oldext_package.submodule import test_function 100 | self.assert_equal(test_function(), 42) 101 | 102 | def test_flaskext_broken_package_no_module_caching(self): 103 | for x in xrange(2): 104 | with self.assert_raises(ImportError): 105 | import flask.ext.broken 106 | 107 | def test_no_error_swallowing(self): 108 | try: 109 | import flask.ext.broken 110 | except ImportError: 111 | exc_type, exc_value, tb = sys.exc_info() 112 | self.assert_(exc_type is ImportError) 113 | self.assert_equal(str(exc_value), 'No module named missing_module') 114 | self.assert_(tb.tb_frame.f_globals is globals()) 115 | 116 | next = tb.tb_next 117 | self.assert_('flask_broken/__init__.py' in next.tb_frame.f_code.co_filename) 118 | 119 | 120 | def suite(): 121 | suite = unittest.TestSuite() 122 | suite.addTest(unittest.makeSuite(ExtImportHookTestCase)) 123 | return suite 124 | -------------------------------------------------------------------------------- /ctf1/append/home/level02/flask/testsuite/regression.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | flask.testsuite.regression 4 | ~~~~~~~~~~~~~~~~~~~~~~~~~~ 5 | 6 | Tests regressions. 7 | 8 | :copyright: (c) 2011 by Armin Ronacher. 9 | :license: BSD, see LICENSE for more details. 10 | """ 11 | 12 | from __future__ import with_statement 13 | 14 | import gc 15 | import sys 16 | import flask 17 | import threading 18 | import unittest 19 | from werkzeug.test import run_wsgi_app, create_environ 20 | from flask.testsuite import FlaskTestCase 21 | 22 | 23 | _gc_lock = threading.Lock() 24 | 25 | 26 | class _NoLeakAsserter(object): 27 | 28 | def __init__(self, testcase): 29 | self.testcase = testcase 30 | 31 | def __enter__(self): 32 | gc.disable() 33 | _gc_lock.acquire() 34 | loc = flask._request_ctx_stack._local 35 | 36 | # Force Python to track this dictionary at all times. 37 | # This is necessary since Python only starts tracking 38 | # dicts if they contain mutable objects. It's a horrible, 39 | # horrible hack but makes this kinda testable. 40 | loc.__storage__['FOOO'] = [1, 2, 3] 41 | 42 | gc.collect() 43 | self.old_objects = len(gc.get_objects()) 44 | 45 | def __exit__(self, exc_type, exc_value, tb): 46 | if not hasattr(sys, 'getrefcount'): 47 | gc.collect() 48 | new_objects = len(gc.get_objects()) 49 | if new_objects > self.old_objects: 50 | self.testcase.fail('Example code leaked') 51 | _gc_lock.release() 52 | gc.enable() 53 | 54 | 55 | class MemoryTestCase(FlaskTestCase): 56 | 57 | def assert_no_leak(self): 58 | return _NoLeakAsserter(self) 59 | 60 | def test_memory_consumption(self): 61 | app = flask.Flask(__name__) 62 | @app.route('/') 63 | def index(): 64 | return flask.render_template('simple_template.html', whiskey=42) 65 | 66 | def fire(): 67 | with app.test_client() as c: 68 | rv = c.get('/') 69 | self.assert_equal(rv.status_code, 200) 70 | self.assert_equal(rv.data, '

42

') 71 | 72 | # Trigger caches 73 | fire() 74 | 75 | # This test only works on CPython 2.7. 76 | if sys.version_info >= (2, 7) and \ 77 | not hasattr(sys, 'pypy_translation_info'): 78 | with self.assert_no_leak(): 79 | for x in xrange(10): 80 | fire() 81 | 82 | 83 | def suite(): 84 | suite = unittest.TestSuite() 85 | suite.addTest(unittest.makeSuite(MemoryTestCase)) 86 | return suite 87 | -------------------------------------------------------------------------------- /ctf1/append/home/level02/flask/testsuite/signals.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | flask.testsuite.signals 4 | ~~~~~~~~~~~~~~~~~~~~~~~ 5 | 6 | Signalling. 7 | 8 | :copyright: (c) 2011 by Armin Ronacher. 9 | :license: BSD, see LICENSE for more details. 10 | """ 11 | import flask 12 | import unittest 13 | from flask.testsuite import FlaskTestCase 14 | 15 | 16 | class SignalsTestCase(FlaskTestCase): 17 | 18 | def test_template_rendered(self): 19 | app = flask.Flask(__name__) 20 | 21 | @app.route('/') 22 | def index(): 23 | return flask.render_template('simple_template.html', whiskey=42) 24 | 25 | recorded = [] 26 | def record(sender, template, context): 27 | recorded.append((template, context)) 28 | 29 | flask.template_rendered.connect(record, app) 30 | try: 31 | app.test_client().get('/') 32 | self.assert_equal(len(recorded), 1) 33 | template, context = recorded[0] 34 | self.assert_equal(template.name, 'simple_template.html') 35 | self.assert_equal(context['whiskey'], 42) 36 | finally: 37 | flask.template_rendered.disconnect(record, app) 38 | 39 | def test_request_signals(self): 40 | app = flask.Flask(__name__) 41 | calls = [] 42 | 43 | def before_request_signal(sender): 44 | calls.append('before-signal') 45 | 46 | def after_request_signal(sender, response): 47 | self.assert_equal(response.data, 'stuff') 48 | calls.append('after-signal') 49 | 50 | @app.before_request 51 | def before_request_handler(): 52 | calls.append('before-handler') 53 | 54 | @app.after_request 55 | def after_request_handler(response): 56 | calls.append('after-handler') 57 | response.data = 'stuff' 58 | return response 59 | 60 | @app.route('/') 61 | def index(): 62 | calls.append('handler') 63 | return 'ignored anyway' 64 | 65 | flask.request_started.connect(before_request_signal, app) 66 | flask.request_finished.connect(after_request_signal, app) 67 | 68 | try: 69 | rv = app.test_client().get('/') 70 | self.assert_equal(rv.data, 'stuff') 71 | 72 | self.assert_equal(calls, ['before-signal', 'before-handler', 73 | 'handler', 'after-handler', 74 | 'after-signal']) 75 | finally: 76 | flask.request_started.disconnect(before_request_signal, app) 77 | flask.request_finished.disconnect(after_request_signal, app) 78 | 79 | def test_request_exception_signal(self): 80 | app = flask.Flask(__name__) 81 | recorded = [] 82 | 83 | @app.route('/') 84 | def index(): 85 | 1/0 86 | 87 | def record(sender, exception): 88 | recorded.append(exception) 89 | 90 | flask.got_request_exception.connect(record, app) 91 | try: 92 | self.assert_equal(app.test_client().get('/').status_code, 500) 93 | self.assert_equal(len(recorded), 1) 94 | self.assert_(isinstance(recorded[0], ZeroDivisionError)) 95 | finally: 96 | flask.got_request_exception.disconnect(record, app) 97 | 98 | 99 | def suite(): 100 | suite = unittest.TestSuite() 101 | if flask.signals_available: 102 | suite.addTest(unittest.makeSuite(SignalsTestCase)) 103 | return suite 104 | -------------------------------------------------------------------------------- /ctf1/append/home/level02/flask/testsuite/static/index.html: -------------------------------------------------------------------------------- 1 |

Hello World!

2 | -------------------------------------------------------------------------------- /ctf1/append/home/level02/flask/testsuite/subclassing.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | flask.testsuite.subclassing 4 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~ 5 | 6 | Test that certain behavior of flask can be customized by 7 | subclasses. 8 | 9 | :copyright: (c) 2011 by Armin Ronacher. 10 | :license: BSD, see LICENSE for more details. 11 | """ 12 | import flask 13 | import unittest 14 | from StringIO import StringIO 15 | from logging import StreamHandler 16 | from flask.testsuite import FlaskTestCase 17 | 18 | 19 | class FlaskSubclassingTestCase(FlaskTestCase): 20 | 21 | def test_supressed_exception_logging(self): 22 | class SupressedFlask(flask.Flask): 23 | def log_exception(self, exc_info): 24 | pass 25 | 26 | out = StringIO() 27 | app = SupressedFlask(__name__) 28 | app.logger_name = 'flask_tests/test_supressed_exception_logging' 29 | app.logger.addHandler(StreamHandler(out)) 30 | 31 | @app.route('/') 32 | def index(): 33 | 1/0 34 | 35 | rv = app.test_client().get('/') 36 | self.assert_equal(rv.status_code, 500) 37 | self.assert_('Internal Server Error' in rv.data) 38 | 39 | err = out.getvalue() 40 | self.assert_equal(err, '') 41 | 42 | 43 | def suite(): 44 | suite = unittest.TestSuite() 45 | suite.addTest(unittest.makeSuite(FlaskSubclassingTestCase)) 46 | return suite 47 | -------------------------------------------------------------------------------- /ctf1/append/home/level02/flask/testsuite/templates/_macro.html: -------------------------------------------------------------------------------- 1 | {% macro hello(name) %}Hello {{ name }}!{% endmacro %} 2 | -------------------------------------------------------------------------------- /ctf1/append/home/level02/flask/testsuite/templates/context_template.html: -------------------------------------------------------------------------------- 1 |

{{ value }}|{{ injected_value }} 2 | -------------------------------------------------------------------------------- /ctf1/append/home/level02/flask/testsuite/templates/escaping_template.html: -------------------------------------------------------------------------------- 1 | {{ text }} 2 | {{ html }} 3 | {% autoescape false %}{{ text }} 4 | {{ html }}{% endautoescape %} 5 | {% autoescape true %}{{ text }} 6 | {{ html }}{% endautoescape %} 7 | -------------------------------------------------------------------------------- /ctf1/append/home/level02/flask/testsuite/templates/mail.txt: -------------------------------------------------------------------------------- 1 | {{ foo}} Mail 2 | -------------------------------------------------------------------------------- /ctf1/append/home/level02/flask/testsuite/templates/nested/nested.txt: -------------------------------------------------------------------------------- 1 | I'm nested 2 | -------------------------------------------------------------------------------- /ctf1/append/home/level02/flask/testsuite/templates/simple_template.html: -------------------------------------------------------------------------------- 1 |

{{ whiskey }}

2 | -------------------------------------------------------------------------------- /ctf1/append/home/level02/flask/testsuite/templates/template_filter.html: -------------------------------------------------------------------------------- 1 | {{ value|super_reverse }} -------------------------------------------------------------------------------- /ctf1/append/home/level02/flask/testsuite/test_apps/blueprintapp/__init__.py: -------------------------------------------------------------------------------- 1 | from flask import Flask 2 | 3 | app = Flask(__name__) 4 | from blueprintapp.apps.admin import admin 5 | from blueprintapp.apps.frontend import frontend 6 | app.register_blueprint(admin) 7 | app.register_blueprint(frontend) 8 | -------------------------------------------------------------------------------- /ctf1/append/home/level02/flask/testsuite/test_apps/blueprintapp/apps/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ctf-o-matic/capture-the-flag/cbed26b321871b78c6656ee020c2687482d6b540/ctf1/append/home/level02/flask/testsuite/test_apps/blueprintapp/apps/__init__.py -------------------------------------------------------------------------------- /ctf1/append/home/level02/flask/testsuite/test_apps/blueprintapp/apps/admin/__init__.py: -------------------------------------------------------------------------------- 1 | from flask import Blueprint, render_template 2 | 3 | admin = Blueprint('admin', __name__, url_prefix='/admin', 4 | template_folder='templates', 5 | static_folder='static') 6 | 7 | 8 | @admin.route('/') 9 | def index(): 10 | return render_template('admin/index.html') 11 | 12 | 13 | @admin.route('/index2') 14 | def index2(): 15 | return render_template('./admin/index.html') 16 | -------------------------------------------------------------------------------- /ctf1/append/home/level02/flask/testsuite/test_apps/blueprintapp/apps/admin/static/css/test.css: -------------------------------------------------------------------------------- 1 | /* nested file */ 2 | -------------------------------------------------------------------------------- /ctf1/append/home/level02/flask/testsuite/test_apps/blueprintapp/apps/admin/static/test.txt: -------------------------------------------------------------------------------- 1 | Admin File 2 | -------------------------------------------------------------------------------- /ctf1/append/home/level02/flask/testsuite/test_apps/blueprintapp/apps/admin/templates/admin/index.html: -------------------------------------------------------------------------------- 1 | Hello from the Admin 2 | -------------------------------------------------------------------------------- /ctf1/append/home/level02/flask/testsuite/test_apps/blueprintapp/apps/frontend/__init__.py: -------------------------------------------------------------------------------- 1 | from flask import Blueprint, render_template 2 | 3 | frontend = Blueprint('frontend', __name__, template_folder='templates') 4 | 5 | 6 | @frontend.route('/') 7 | def index(): 8 | return render_template('frontend/index.html') 9 | -------------------------------------------------------------------------------- /ctf1/append/home/level02/flask/testsuite/test_apps/blueprintapp/apps/frontend/templates/frontend/index.html: -------------------------------------------------------------------------------- 1 | Hello from the Frontend 2 | -------------------------------------------------------------------------------- /ctf1/append/home/level02/flask/testsuite/test_apps/config_module_app.py: -------------------------------------------------------------------------------- 1 | import os 2 | import flask 3 | here = os.path.abspath(os.path.dirname(__file__)) 4 | app = flask.Flask(__name__) 5 | -------------------------------------------------------------------------------- /ctf1/append/home/level02/flask/testsuite/test_apps/config_package_app/__init__.py: -------------------------------------------------------------------------------- 1 | import os 2 | import flask 3 | here = os.path.abspath(os.path.dirname(__file__)) 4 | app = flask.Flask(__name__) 5 | -------------------------------------------------------------------------------- /ctf1/append/home/level02/flask/testsuite/test_apps/flask_broken/__init__.py: -------------------------------------------------------------------------------- 1 | import flask.ext.broken.b 2 | import missing_module 3 | -------------------------------------------------------------------------------- /ctf1/append/home/level02/flask/testsuite/test_apps/flask_broken/b.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ctf-o-matic/capture-the-flag/cbed26b321871b78c6656ee020c2687482d6b540/ctf1/append/home/level02/flask/testsuite/test_apps/flask_broken/b.py -------------------------------------------------------------------------------- /ctf1/append/home/level02/flask/testsuite/test_apps/flask_newext_package/__init__.py: -------------------------------------------------------------------------------- 1 | ext_id = 'newext_package' 2 | -------------------------------------------------------------------------------- /ctf1/append/home/level02/flask/testsuite/test_apps/flask_newext_package/submodule.py: -------------------------------------------------------------------------------- 1 | def test_function(): 2 | return 42 3 | -------------------------------------------------------------------------------- /ctf1/append/home/level02/flask/testsuite/test_apps/flask_newext_simple.py: -------------------------------------------------------------------------------- 1 | ext_id = 'newext_simple' 2 | -------------------------------------------------------------------------------- /ctf1/append/home/level02/flask/testsuite/test_apps/flaskext/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ctf-o-matic/capture-the-flag/cbed26b321871b78c6656ee020c2687482d6b540/ctf1/append/home/level02/flask/testsuite/test_apps/flaskext/__init__.py -------------------------------------------------------------------------------- /ctf1/append/home/level02/flask/testsuite/test_apps/flaskext/oldext_package/__init__.py: -------------------------------------------------------------------------------- 1 | ext_id = 'oldext_package' 2 | -------------------------------------------------------------------------------- /ctf1/append/home/level02/flask/testsuite/test_apps/flaskext/oldext_package/submodule.py: -------------------------------------------------------------------------------- 1 | def test_function(): 2 | return 42 3 | -------------------------------------------------------------------------------- /ctf1/append/home/level02/flask/testsuite/test_apps/flaskext/oldext_simple.py: -------------------------------------------------------------------------------- 1 | ext_id = 'oldext_simple' 2 | -------------------------------------------------------------------------------- /ctf1/append/home/level02/flask/testsuite/test_apps/importerror.py: -------------------------------------------------------------------------------- 1 | # NoImportsTestCase 2 | raise NotImplementedError 3 | -------------------------------------------------------------------------------- /ctf1/append/home/level02/flask/testsuite/test_apps/lib/python2.5/site-packages/SiteEgg.egg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ctf-o-matic/capture-the-flag/cbed26b321871b78c6656ee020c2687482d6b540/ctf1/append/home/level02/flask/testsuite/test_apps/lib/python2.5/site-packages/SiteEgg.egg -------------------------------------------------------------------------------- /ctf1/append/home/level02/flask/testsuite/test_apps/lib/python2.5/site-packages/site_app.py: -------------------------------------------------------------------------------- 1 | import flask 2 | 3 | app = flask.Flask(__name__) 4 | -------------------------------------------------------------------------------- /ctf1/append/home/level02/flask/testsuite/test_apps/lib/python2.5/site-packages/site_package/__init__.py: -------------------------------------------------------------------------------- 1 | import flask 2 | 3 | app = flask.Flask(__name__) 4 | -------------------------------------------------------------------------------- /ctf1/append/home/level02/flask/testsuite/test_apps/main_app.py: -------------------------------------------------------------------------------- 1 | import flask 2 | 3 | # Test Flask initialization with main module. 4 | app = flask.Flask('__main__') 5 | -------------------------------------------------------------------------------- /ctf1/append/home/level02/flask/testsuite/test_apps/moduleapp/__init__.py: -------------------------------------------------------------------------------- 1 | from flask import Flask 2 | 3 | app = Flask(__name__) 4 | from moduleapp.apps.admin import admin 5 | from moduleapp.apps.frontend import frontend 6 | app.register_module(admin) 7 | app.register_module(frontend) 8 | -------------------------------------------------------------------------------- /ctf1/append/home/level02/flask/testsuite/test_apps/moduleapp/apps/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ctf-o-matic/capture-the-flag/cbed26b321871b78c6656ee020c2687482d6b540/ctf1/append/home/level02/flask/testsuite/test_apps/moduleapp/apps/__init__.py -------------------------------------------------------------------------------- /ctf1/append/home/level02/flask/testsuite/test_apps/moduleapp/apps/admin/__init__.py: -------------------------------------------------------------------------------- 1 | from flask import Module, render_template 2 | 3 | 4 | admin = Module(__name__, url_prefix='/admin') 5 | 6 | 7 | @admin.route('/') 8 | def index(): 9 | return render_template('admin/index.html') 10 | 11 | 12 | @admin.route('/index2') 13 | def index2(): 14 | return render_template('./admin/index.html') 15 | -------------------------------------------------------------------------------- /ctf1/append/home/level02/flask/testsuite/test_apps/moduleapp/apps/admin/static/css/test.css: -------------------------------------------------------------------------------- 1 | /* nested file */ 2 | -------------------------------------------------------------------------------- /ctf1/append/home/level02/flask/testsuite/test_apps/moduleapp/apps/admin/static/test.txt: -------------------------------------------------------------------------------- 1 | Admin File 2 | -------------------------------------------------------------------------------- /ctf1/append/home/level02/flask/testsuite/test_apps/moduleapp/apps/admin/templates/index.html: -------------------------------------------------------------------------------- 1 | Hello from the Admin 2 | -------------------------------------------------------------------------------- /ctf1/append/home/level02/flask/testsuite/test_apps/moduleapp/apps/frontend/__init__.py: -------------------------------------------------------------------------------- 1 | from flask import Module, render_template 2 | 3 | 4 | frontend = Module(__name__) 5 | 6 | 7 | @frontend.route('/') 8 | def index(): 9 | return render_template('frontend/index.html') 10 | -------------------------------------------------------------------------------- /ctf1/append/home/level02/flask/testsuite/test_apps/moduleapp/apps/frontend/templates/index.html: -------------------------------------------------------------------------------- 1 | Hello from the Frontend 2 | -------------------------------------------------------------------------------- /ctf1/append/home/level02/flask/testsuite/test_apps/path/installed_package/__init__.py: -------------------------------------------------------------------------------- 1 | import flask 2 | 3 | app = flask.Flask(__name__) 4 | -------------------------------------------------------------------------------- /ctf1/append/home/level02/flask/testsuite/test_apps/subdomaintestmodule/__init__.py: -------------------------------------------------------------------------------- 1 | from flask import Module 2 | 3 | 4 | mod = Module(__name__, 'foo', subdomain='foo') 5 | -------------------------------------------------------------------------------- /ctf1/append/home/level02/flask/testsuite/test_apps/subdomaintestmodule/static/hello.txt: -------------------------------------------------------------------------------- 1 | Hello Subdomain 2 | -------------------------------------------------------------------------------- /ctf1/append/home/level02/flask/testsuite/views.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | flask.testsuite.views 4 | ~~~~~~~~~~~~~~~~~~~~~ 5 | 6 | Pluggable views. 7 | 8 | :copyright: (c) 2011 by Armin Ronacher. 9 | :license: BSD, see LICENSE for more details. 10 | """ 11 | import flask 12 | import flask.views 13 | import unittest 14 | from flask.testsuite import FlaskTestCase 15 | from werkzeug.http import parse_set_header 16 | 17 | 18 | class ViewTestCase(FlaskTestCase): 19 | 20 | def common_test(self, app): 21 | c = app.test_client() 22 | 23 | self.assert_equal(c.get('/').data, 'GET') 24 | self.assert_equal(c.post('/').data, 'POST') 25 | self.assert_equal(c.put('/').status_code, 405) 26 | meths = parse_set_header(c.open('/', method='OPTIONS').headers['Allow']) 27 | self.assert_equal(sorted(meths), ['GET', 'HEAD', 'OPTIONS', 'POST']) 28 | 29 | def test_basic_view(self): 30 | app = flask.Flask(__name__) 31 | 32 | class Index(flask.views.View): 33 | methods = ['GET', 'POST'] 34 | def dispatch_request(self): 35 | return flask.request.method 36 | 37 | app.add_url_rule('/', view_func=Index.as_view('index')) 38 | self.common_test(app) 39 | 40 | def test_method_based_view(self): 41 | app = flask.Flask(__name__) 42 | 43 | class Index(flask.views.MethodView): 44 | def get(self): 45 | return 'GET' 46 | def post(self): 47 | return 'POST' 48 | 49 | app.add_url_rule('/', view_func=Index.as_view('index')) 50 | 51 | self.common_test(app) 52 | 53 | def test_view_patching(self): 54 | app = flask.Flask(__name__) 55 | 56 | class Index(flask.views.MethodView): 57 | def get(self): 58 | 1/0 59 | def post(self): 60 | 1/0 61 | 62 | class Other(Index): 63 | def get(self): 64 | return 'GET' 65 | def post(self): 66 | return 'POST' 67 | 68 | view = Index.as_view('index') 69 | view.view_class = Other 70 | app.add_url_rule('/', view_func=view) 71 | self.common_test(app) 72 | 73 | def test_view_inheritance(self): 74 | app = flask.Flask(__name__) 75 | 76 | class Index(flask.views.MethodView): 77 | def get(self): 78 | return 'GET' 79 | def post(self): 80 | return 'POST' 81 | 82 | class BetterIndex(Index): 83 | def delete(self): 84 | return 'DELETE' 85 | 86 | app.add_url_rule('/', view_func=BetterIndex.as_view('index')) 87 | c = app.test_client() 88 | 89 | meths = parse_set_header(c.open('/', method='OPTIONS').headers['Allow']) 90 | self.assert_equal(sorted(meths), ['DELETE', 'GET', 'HEAD', 'OPTIONS', 'POST']) 91 | 92 | def test_view_decorators(self): 93 | app = flask.Flask(__name__) 94 | 95 | def add_x_parachute(f): 96 | def new_function(*args, **kwargs): 97 | resp = flask.make_response(f(*args, **kwargs)) 98 | resp.headers['X-Parachute'] = 'awesome' 99 | return resp 100 | return new_function 101 | 102 | class Index(flask.views.View): 103 | decorators = [add_x_parachute] 104 | def dispatch_request(self): 105 | return 'Awesome' 106 | 107 | app.add_url_rule('/', view_func=Index.as_view('index')) 108 | c = app.test_client() 109 | rv = c.get('/') 110 | self.assert_equal(rv.headers['X-Parachute'], 'awesome') 111 | self.assert_equal(rv.data, 'Awesome') 112 | 113 | def test_implicit_head(self): 114 | app = flask.Flask(__name__) 115 | 116 | class Index(flask.views.MethodView): 117 | def get(self): 118 | return flask.Response('Blub', headers={ 119 | 'X-Method': flask.request.method 120 | }) 121 | 122 | app.add_url_rule('/', view_func=Index.as_view('index')) 123 | c = app.test_client() 124 | rv = c.get('/') 125 | self.assert_equal(rv.data, 'Blub') 126 | self.assert_equal(rv.headers['X-Method'], 'GET') 127 | rv = c.head('/') 128 | self.assert_equal(rv.data, '') 129 | self.assert_equal(rv.headers['X-Method'], 'HEAD') 130 | 131 | def test_explicit_head(self): 132 | app = flask.Flask(__name__) 133 | 134 | class Index(flask.views.MethodView): 135 | def get(self): 136 | return 'GET' 137 | def head(self): 138 | return flask.Response('', headers={'X-Method': 'HEAD'}) 139 | 140 | app.add_url_rule('/', view_func=Index.as_view('index')) 141 | c = app.test_client() 142 | rv = c.get('/') 143 | self.assert_equal(rv.data, 'GET') 144 | rv = c.head('/') 145 | self.assert_equal(rv.data, '') 146 | self.assert_equal(rv.headers['X-Method'], 'HEAD') 147 | 148 | 149 | def suite(): 150 | suite = unittest.TestSuite() 151 | suite.addTest(unittest.makeSuite(ViewTestCase)) 152 | return suite 153 | -------------------------------------------------------------------------------- /ctf1/append/home/level02/jinja2/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | jinja2 4 | ~~~~~~ 5 | 6 | Jinja2 is a template engine written in pure Python. It provides a 7 | Django inspired non-XML syntax but supports inline expressions and 8 | an optional sandboxed environment. 9 | 10 | Nutshell 11 | -------- 12 | 13 | Here a small example of a Jinja2 template:: 14 | 15 | {% extends 'base.html' %} 16 | {% block title %}Memberlist{% endblock %} 17 | {% block content %} 18 | 23 | {% endblock %} 24 | 25 | 26 | :copyright: (c) 2010 by the Jinja Team. 27 | :license: BSD, see LICENSE for more details. 28 | """ 29 | __docformat__ = 'restructuredtext en' 30 | __version__ = '2.7-dev' 31 | 32 | # high level interface 33 | from jinja2.environment import Environment, Template 34 | 35 | # loaders 36 | from jinja2.loaders import BaseLoader, FileSystemLoader, PackageLoader, \ 37 | DictLoader, FunctionLoader, PrefixLoader, ChoiceLoader, \ 38 | ModuleLoader 39 | 40 | # bytecode caches 41 | from jinja2.bccache import BytecodeCache, FileSystemBytecodeCache, \ 42 | MemcachedBytecodeCache 43 | 44 | # undefined types 45 | from jinja2.runtime import Undefined, DebugUndefined, StrictUndefined 46 | 47 | # exceptions 48 | from jinja2.exceptions import TemplateError, UndefinedError, \ 49 | TemplateNotFound, TemplatesNotFound, TemplateSyntaxError, \ 50 | TemplateAssertionError 51 | 52 | # decorators and public utilities 53 | from jinja2.filters import environmentfilter, contextfilter, \ 54 | evalcontextfilter 55 | from jinja2.utils import Markup, escape, clear_caches, \ 56 | environmentfunction, evalcontextfunction, contextfunction, \ 57 | is_undefined 58 | 59 | __all__ = [ 60 | 'Environment', 'Template', 'BaseLoader', 'FileSystemLoader', 61 | 'PackageLoader', 'DictLoader', 'FunctionLoader', 'PrefixLoader', 62 | 'ChoiceLoader', 'BytecodeCache', 'FileSystemBytecodeCache', 63 | 'MemcachedBytecodeCache', 'Undefined', 'DebugUndefined', 64 | 'StrictUndefined', 'TemplateError', 'UndefinedError', 'TemplateNotFound', 65 | 'TemplatesNotFound', 'TemplateSyntaxError', 'TemplateAssertionError', 66 | 'ModuleLoader', 'environmentfilter', 'contextfilter', 'Markup', 'escape', 67 | 'environmentfunction', 'contextfunction', 'clear_caches', 'is_undefined', 68 | 'evalcontextfilter', 'evalcontextfunction' 69 | ] 70 | -------------------------------------------------------------------------------- /ctf1/append/home/level02/jinja2/_debugsupport.c: -------------------------------------------------------------------------------- 1 | /** 2 | * jinja2._debugsupport 3 | * ~~~~~~~~~~~~~~~~~~~~ 4 | * 5 | * C implementation of `tb_set_next`. 6 | * 7 | * :copyright: (c) 2010 by the Jinja Team. 8 | * :license: BSD. 9 | */ 10 | 11 | #include 12 | 13 | 14 | static PyObject* 15 | tb_set_next(PyObject *self, PyObject *args) 16 | { 17 | PyTracebackObject *tb, *old; 18 | PyObject *next; 19 | 20 | if (!PyArg_ParseTuple(args, "O!O:tb_set_next", &PyTraceBack_Type, &tb, &next)) 21 | return NULL; 22 | if (next == Py_None) 23 | next = NULL; 24 | else if (!PyTraceBack_Check(next)) { 25 | PyErr_SetString(PyExc_TypeError, 26 | "tb_set_next arg 2 must be traceback or None"); 27 | return NULL; 28 | } 29 | else 30 | Py_INCREF(next); 31 | 32 | old = tb->tb_next; 33 | tb->tb_next = (PyTracebackObject*)next; 34 | Py_XDECREF(old); 35 | 36 | Py_INCREF(Py_None); 37 | return Py_None; 38 | } 39 | 40 | static PyMethodDef module_methods[] = { 41 | {"tb_set_next", (PyCFunction)tb_set_next, METH_VARARGS, 42 | "Set the tb_next member of a traceback object."}, 43 | {NULL, NULL, 0, NULL} /* Sentinel */ 44 | }; 45 | 46 | 47 | #if PY_MAJOR_VERSION < 3 48 | 49 | #ifndef PyMODINIT_FUNC /* declarations for DLL import/export */ 50 | #define PyMODINIT_FUNC void 51 | #endif 52 | PyMODINIT_FUNC 53 | init_debugsupport(void) 54 | { 55 | Py_InitModule3("jinja2._debugsupport", module_methods, ""); 56 | } 57 | 58 | #else /* Python 3.x module initialization */ 59 | 60 | static struct PyModuleDef module_definition = { 61 | PyModuleDef_HEAD_INIT, 62 | "jinja2._debugsupport", 63 | NULL, 64 | -1, 65 | module_methods, 66 | NULL, 67 | NULL, 68 | NULL, 69 | NULL 70 | }; 71 | 72 | PyMODINIT_FUNC 73 | PyInit__debugsupport(void) 74 | { 75 | return PyModule_Create(&module_definition); 76 | } 77 | 78 | #endif 79 | -------------------------------------------------------------------------------- /ctf1/append/home/level02/jinja2/_markupsafe/_bundle.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | jinja2._markupsafe._bundle 4 | ~~~~~~~~~~~~~~~~~~~~~~~~~~ 5 | 6 | This script pulls in markupsafe from a source folder and 7 | bundles it with Jinja2. It does not pull in the speedups 8 | module though. 9 | 10 | :copyright: Copyright 2010 by the Jinja team, see AUTHORS. 11 | :license: BSD, see LICENSE for details. 12 | """ 13 | import sys 14 | import os 15 | import re 16 | 17 | 18 | def rewrite_imports(lines): 19 | for idx, line in enumerate(lines): 20 | new_line = re.sub(r'(import|from)\s+markupsafe\b', 21 | r'\1 jinja2._markupsafe', line) 22 | if new_line != line: 23 | lines[idx] = new_line 24 | 25 | 26 | def main(): 27 | if len(sys.argv) != 2: 28 | print 'error: only argument is path to markupsafe' 29 | sys.exit(1) 30 | basedir = os.path.dirname(__file__) 31 | markupdir = sys.argv[1] 32 | for filename in os.listdir(markupdir): 33 | if filename.endswith('.py'): 34 | f = open(os.path.join(markupdir, filename)) 35 | try: 36 | lines = list(f) 37 | finally: 38 | f.close() 39 | rewrite_imports(lines) 40 | f = open(os.path.join(basedir, filename), 'w') 41 | try: 42 | for line in lines: 43 | f.write(line) 44 | finally: 45 | f.close() 46 | 47 | 48 | if __name__ == '__main__': 49 | main() 50 | -------------------------------------------------------------------------------- /ctf1/append/home/level02/jinja2/_markupsafe/_native.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | markupsafe._native 4 | ~~~~~~~~~~~~~~~~~~ 5 | 6 | Native Python implementation the C module is not compiled. 7 | 8 | :copyright: (c) 2010 by Armin Ronacher. 9 | :license: BSD, see LICENSE for more details. 10 | """ 11 | from jinja2._markupsafe import Markup 12 | 13 | 14 | def escape(s): 15 | """Convert the characters &, <, >, ' and " in string s to HTML-safe 16 | sequences. Use this if you need to display text that might contain 17 | such characters in HTML. Marks return value as markup string. 18 | """ 19 | if hasattr(s, '__html__'): 20 | return s.__html__() 21 | return Markup(unicode(s) 22 | .replace('&', '&') 23 | .replace('>', '>') 24 | .replace('<', '<') 25 | .replace("'", ''') 26 | .replace('"', '"') 27 | ) 28 | 29 | 30 | def escape_silent(s): 31 | """Like :func:`escape` but converts `None` into an empty 32 | markup string. 33 | """ 34 | if s is None: 35 | return Markup() 36 | return escape(s) 37 | 38 | 39 | def soft_unicode(s): 40 | """Make a string unicode if it isn't already. That way a markup 41 | string is not converted back to unicode. 42 | """ 43 | if not isinstance(s, unicode): 44 | s = unicode(s) 45 | return s 46 | -------------------------------------------------------------------------------- /ctf1/append/home/level02/jinja2/_markupsafe/tests.py: -------------------------------------------------------------------------------- 1 | import gc 2 | import unittest 3 | from jinja2._markupsafe import Markup, escape, escape_silent 4 | 5 | 6 | class MarkupTestCase(unittest.TestCase): 7 | 8 | def test_markup_operations(self): 9 | # adding two strings should escape the unsafe one 10 | unsafe = '' 11 | safe = Markup('username') 12 | assert unsafe + safe == unicode(escape(unsafe)) + unicode(safe) 13 | 14 | # string interpolations are safe to use too 15 | assert Markup('%s') % '' == \ 16 | '<bad user>' 17 | assert Markup('%(username)s') % { 18 | 'username': '' 19 | } == '<bad user>' 20 | 21 | # an escaped object is markup too 22 | assert type(Markup('foo') + 'bar') is Markup 23 | 24 | # and it implements __html__ by returning itself 25 | x = Markup("foo") 26 | assert x.__html__() is x 27 | 28 | # it also knows how to treat __html__ objects 29 | class Foo(object): 30 | def __html__(self): 31 | return 'awesome' 32 | def __unicode__(self): 33 | return 'awesome' 34 | assert Markup(Foo()) == 'awesome' 35 | assert Markup('%s') % Foo() == \ 36 | 'awesome' 37 | 38 | # escaping and unescaping 39 | assert escape('"<>&\'') == '"<>&'' 40 | assert Markup("Foo & Bar").striptags() == "Foo & Bar" 41 | assert Markup("<test>").unescape() == "" 42 | 43 | def test_all_set(self): 44 | import jinja2._markupsafe as markup 45 | for item in markup.__all__: 46 | getattr(markup, item) 47 | 48 | def test_escape_silent(self): 49 | assert escape_silent(None) == Markup() 50 | assert escape(None) == Markup(None) 51 | assert escape_silent('') == Markup(u'<foo>') 52 | 53 | 54 | class MarkupLeakTestCase(unittest.TestCase): 55 | 56 | def test_markup_leaks(self): 57 | counts = set() 58 | for count in xrange(20): 59 | for item in xrange(1000): 60 | escape("foo") 61 | escape("") 62 | escape(u"foo") 63 | escape(u"") 64 | counts.add(len(gc.get_objects())) 65 | assert len(counts) == 1, 'ouch, c extension seems to leak objects' 66 | 67 | 68 | def suite(): 69 | suite = unittest.TestSuite() 70 | suite.addTest(unittest.makeSuite(MarkupTestCase)) 71 | 72 | # this test only tests the c extension 73 | if not hasattr(escape, 'func_code'): 74 | suite.addTest(unittest.makeSuite(MarkupLeakTestCase)) 75 | 76 | return suite 77 | 78 | 79 | if __name__ == '__main__': 80 | unittest.main(defaultTest='suite') 81 | -------------------------------------------------------------------------------- /ctf1/append/home/level02/jinja2/constants.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | jinja.constants 4 | ~~~~~~~~~~~~~~~ 5 | 6 | Various constants. 7 | 8 | :copyright: (c) 2010 by the Jinja Team. 9 | :license: BSD, see LICENSE for more details. 10 | """ 11 | 12 | 13 | #: list of lorem ipsum words used by the lipsum() helper function 14 | LOREM_IPSUM_WORDS = u'''\ 15 | a ac accumsan ad adipiscing aenean aliquam aliquet amet ante aptent arcu at 16 | auctor augue bibendum blandit class commodo condimentum congue consectetuer 17 | consequat conubia convallis cras cubilia cum curabitur curae cursus dapibus 18 | diam dictum dictumst dignissim dis dolor donec dui duis egestas eget eleifend 19 | elementum elit enim erat eros est et etiam eu euismod facilisi facilisis fames 20 | faucibus felis fermentum feugiat fringilla fusce gravida habitant habitasse hac 21 | hendrerit hymenaeos iaculis id imperdiet in inceptos integer interdum ipsum 22 | justo lacinia lacus laoreet lectus leo libero ligula litora lobortis lorem 23 | luctus maecenas magna magnis malesuada massa mattis mauris metus mi molestie 24 | mollis montes morbi mus nam nascetur natoque nec neque netus nibh nisi nisl non 25 | nonummy nostra nulla nullam nunc odio orci ornare parturient pede pellentesque 26 | penatibus per pharetra phasellus placerat platea porta porttitor posuere 27 | potenti praesent pretium primis proin pulvinar purus quam quis quisque rhoncus 28 | ridiculus risus rutrum sagittis sapien scelerisque sed sem semper senectus sit 29 | sociis sociosqu sodales sollicitudin suscipit suspendisse taciti tellus tempor 30 | tempus tincidunt torquent tortor tristique turpis ullamcorper ultrices 31 | ultricies urna ut varius vehicula vel velit venenatis vestibulum vitae vivamus 32 | viverra volutpat vulputate''' 33 | -------------------------------------------------------------------------------- /ctf1/append/home/level02/jinja2/defaults.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | jinja2.defaults 4 | ~~~~~~~~~~~~~~~ 5 | 6 | Jinja default filters and tags. 7 | 8 | :copyright: (c) 2010 by the Jinja Team. 9 | :license: BSD, see LICENSE for more details. 10 | """ 11 | from jinja2.utils import generate_lorem_ipsum, Cycler, Joiner 12 | 13 | 14 | # defaults for the parser / lexer 15 | BLOCK_START_STRING = '{%' 16 | BLOCK_END_STRING = '%}' 17 | VARIABLE_START_STRING = '{{' 18 | VARIABLE_END_STRING = '}}' 19 | COMMENT_START_STRING = '{#' 20 | COMMENT_END_STRING = '#}' 21 | LINE_STATEMENT_PREFIX = None 22 | LINE_COMMENT_PREFIX = None 23 | TRIM_BLOCKS = False 24 | NEWLINE_SEQUENCE = '\n' 25 | 26 | 27 | # default filters, tests and namespace 28 | from jinja2.filters import FILTERS as DEFAULT_FILTERS 29 | from jinja2.tests import TESTS as DEFAULT_TESTS 30 | DEFAULT_NAMESPACE = { 31 | 'range': xrange, 32 | 'dict': lambda **kw: kw, 33 | 'lipsum': generate_lorem_ipsum, 34 | 'cycler': Cycler, 35 | 'joiner': Joiner 36 | } 37 | 38 | 39 | # export all constants 40 | __all__ = tuple(x for x in locals().keys() if x.isupper()) 41 | -------------------------------------------------------------------------------- /ctf1/append/home/level02/jinja2/exceptions.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | jinja2.exceptions 4 | ~~~~~~~~~~~~~~~~~ 5 | 6 | Jinja exceptions. 7 | 8 | :copyright: (c) 2010 by the Jinja Team. 9 | :license: BSD, see LICENSE for more details. 10 | """ 11 | 12 | 13 | class TemplateError(Exception): 14 | """Baseclass for all template errors.""" 15 | 16 | def __init__(self, message=None): 17 | if message is not None: 18 | message = unicode(message).encode('utf-8') 19 | Exception.__init__(self, message) 20 | 21 | @property 22 | def message(self): 23 | if self.args: 24 | message = self.args[0] 25 | if message is not None: 26 | return message.decode('utf-8', 'replace') 27 | 28 | 29 | class TemplateNotFound(IOError, LookupError, TemplateError): 30 | """Raised if a template does not exist.""" 31 | 32 | # looks weird, but removes the warning descriptor that just 33 | # bogusly warns us about message being deprecated 34 | message = None 35 | 36 | def __init__(self, name, message=None): 37 | IOError.__init__(self) 38 | if message is None: 39 | message = name 40 | self.message = message 41 | self.name = name 42 | self.templates = [name] 43 | 44 | def __str__(self): 45 | return self.message.encode('utf-8') 46 | 47 | # unicode goes after __str__ because we configured 2to3 to rename 48 | # __unicode__ to __str__. because the 2to3 tree is not designed to 49 | # remove nodes from it, we leave the above __str__ around and let 50 | # it override at runtime. 51 | def __unicode__(self): 52 | return self.message 53 | 54 | 55 | class TemplatesNotFound(TemplateNotFound): 56 | """Like :class:`TemplateNotFound` but raised if multiple templates 57 | are selected. This is a subclass of :class:`TemplateNotFound` 58 | exception, so just catching the base exception will catch both. 59 | 60 | .. versionadded:: 2.2 61 | """ 62 | 63 | def __init__(self, names=(), message=None): 64 | if message is None: 65 | message = u'none of the templates given were found: ' + \ 66 | u', '.join(map(unicode, names)) 67 | TemplateNotFound.__init__(self, names and names[-1] or None, message) 68 | self.templates = list(names) 69 | 70 | 71 | class TemplateSyntaxError(TemplateError): 72 | """Raised to tell the user that there is a problem with the template.""" 73 | 74 | def __init__(self, message, lineno, name=None, filename=None): 75 | TemplateError.__init__(self, message) 76 | self.lineno = lineno 77 | self.name = name 78 | self.filename = filename 79 | self.source = None 80 | 81 | # this is set to True if the debug.translate_syntax_error 82 | # function translated the syntax error into a new traceback 83 | self.translated = False 84 | 85 | def __str__(self): 86 | return unicode(self).encode('utf-8') 87 | 88 | # unicode goes after __str__ because we configured 2to3 to rename 89 | # __unicode__ to __str__. because the 2to3 tree is not designed to 90 | # remove nodes from it, we leave the above __str__ around and let 91 | # it override at runtime. 92 | def __unicode__(self): 93 | # for translated errors we only return the message 94 | if self.translated: 95 | return self.message 96 | 97 | # otherwise attach some stuff 98 | location = 'line %d' % self.lineno 99 | name = self.filename or self.name 100 | if name: 101 | location = 'File "%s", %s' % (name, location) 102 | lines = [self.message, ' ' + location] 103 | 104 | # if the source is set, add the line to the output 105 | if self.source is not None: 106 | try: 107 | line = self.source.splitlines()[self.lineno - 1] 108 | except IndexError: 109 | line = None 110 | if line: 111 | lines.append(' ' + line.strip()) 112 | 113 | return u'\n'.join(lines) 114 | 115 | 116 | class TemplateAssertionError(TemplateSyntaxError): 117 | """Like a template syntax error, but covers cases where something in the 118 | template caused an error at compile time that wasn't necessarily caused 119 | by a syntax error. However it's a direct subclass of 120 | :exc:`TemplateSyntaxError` and has the same attributes. 121 | """ 122 | 123 | 124 | class TemplateRuntimeError(TemplateError): 125 | """A generic runtime error in the template engine. Under some situations 126 | Jinja may raise this exception. 127 | """ 128 | 129 | 130 | class UndefinedError(TemplateRuntimeError): 131 | """Raised if a template tries to operate on :class:`Undefined`.""" 132 | 133 | 134 | class SecurityError(TemplateRuntimeError): 135 | """Raised if a template tries to do something insecure if the 136 | sandbox is enabled. 137 | """ 138 | 139 | 140 | class FilterArgumentError(TemplateRuntimeError): 141 | """This error is raised if a filter was called with inappropriate 142 | arguments 143 | """ 144 | -------------------------------------------------------------------------------- /ctf1/append/home/level02/jinja2/meta.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | jinja2.meta 4 | ~~~~~~~~~~~ 5 | 6 | This module implements various functions that exposes information about 7 | templates that might be interesting for various kinds of applications. 8 | 9 | :copyright: (c) 2010 by the Jinja Team, see AUTHORS for more details. 10 | :license: BSD, see LICENSE for more details. 11 | """ 12 | from jinja2 import nodes 13 | from jinja2.compiler import CodeGenerator 14 | 15 | 16 | class TrackingCodeGenerator(CodeGenerator): 17 | """We abuse the code generator for introspection.""" 18 | 19 | def __init__(self, environment): 20 | CodeGenerator.__init__(self, environment, '', 21 | '') 22 | self.undeclared_identifiers = set() 23 | 24 | def write(self, x): 25 | """Don't write.""" 26 | 27 | def pull_locals(self, frame): 28 | """Remember all undeclared identifiers.""" 29 | self.undeclared_identifiers.update(frame.identifiers.undeclared) 30 | 31 | 32 | def find_undeclared_variables(ast): 33 | """Returns a set of all variables in the AST that will be looked up from 34 | the context at runtime. Because at compile time it's not known which 35 | variables will be used depending on the path the execution takes at 36 | runtime, all variables are returned. 37 | 38 | >>> from jinja2 import Environment, meta 39 | >>> env = Environment() 40 | >>> ast = env.parse('{% set foo = 42 %}{{ bar + foo }}') 41 | >>> meta.find_undeclared_variables(ast) 42 | set(['bar']) 43 | 44 | .. admonition:: Implementation 45 | 46 | Internally the code generator is used for finding undeclared variables. 47 | This is good to know because the code generator might raise a 48 | :exc:`TemplateAssertionError` during compilation and as a matter of 49 | fact this function can currently raise that exception as well. 50 | """ 51 | codegen = TrackingCodeGenerator(ast.environment) 52 | codegen.visit(ast) 53 | return codegen.undeclared_identifiers 54 | 55 | 56 | def find_referenced_templates(ast): 57 | """Finds all the referenced templates from the AST. This will return an 58 | iterator over all the hardcoded template extensions, inclusions and 59 | imports. If dynamic inheritance or inclusion is used, `None` will be 60 | yielded. 61 | 62 | >>> from jinja2 import Environment, meta 63 | >>> env = Environment() 64 | >>> ast = env.parse('{% extends "layout.html" %}{% include helper %}') 65 | >>> list(meta.find_referenced_templates(ast)) 66 | ['layout.html', None] 67 | 68 | This function is useful for dependency tracking. For example if you want 69 | to rebuild parts of the website after a layout template has changed. 70 | """ 71 | for node in ast.find_all((nodes.Extends, nodes.FromImport, nodes.Import, 72 | nodes.Include)): 73 | if not isinstance(node.template, nodes.Const): 74 | # a tuple with some non consts in there 75 | if isinstance(node.template, (nodes.Tuple, nodes.List)): 76 | for template_name in node.template.items: 77 | # something const, only yield the strings and ignore 78 | # non-string consts that really just make no sense 79 | if isinstance(template_name, nodes.Const): 80 | if isinstance(template_name.value, basestring): 81 | yield template_name.value 82 | # something dynamic in there 83 | else: 84 | yield None 85 | # something dynamic we don't know about here 86 | else: 87 | yield None 88 | continue 89 | # constant is a basestring, direct template name 90 | if isinstance(node.template.value, basestring): 91 | yield node.template.value 92 | # a tuple or list (latter *should* not happen) made of consts, 93 | # yield the consts that are strings. We could warn here for 94 | # non string values 95 | elif isinstance(node, nodes.Include) and \ 96 | isinstance(node.template.value, (tuple, list)): 97 | for template_name in node.template.value: 98 | if isinstance(template_name, basestring): 99 | yield template_name 100 | # something else we don't care about, we could warn here 101 | else: 102 | yield None 103 | -------------------------------------------------------------------------------- /ctf1/append/home/level02/jinja2/optimizer.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | jinja2.optimizer 4 | ~~~~~~~~~~~~~~~~ 5 | 6 | The jinja optimizer is currently trying to constant fold a few expressions 7 | and modify the AST in place so that it should be easier to evaluate it. 8 | 9 | Because the AST does not contain all the scoping information and the 10 | compiler has to find that out, we cannot do all the optimizations we 11 | want. For example loop unrolling doesn't work because unrolled loops would 12 | have a different scoping. 13 | 14 | The solution would be a second syntax tree that has the scoping rules stored. 15 | 16 | :copyright: (c) 2010 by the Jinja Team. 17 | :license: BSD. 18 | """ 19 | from jinja2 import nodes 20 | from jinja2.visitor import NodeTransformer 21 | 22 | 23 | def optimize(node, environment): 24 | """The context hint can be used to perform an static optimization 25 | based on the context given.""" 26 | optimizer = Optimizer(environment) 27 | return optimizer.visit(node) 28 | 29 | 30 | class Optimizer(NodeTransformer): 31 | 32 | def __init__(self, environment): 33 | self.environment = environment 34 | 35 | def visit_If(self, node): 36 | """Eliminate dead code.""" 37 | # do not optimize ifs that have a block inside so that it doesn't 38 | # break super(). 39 | if node.find(nodes.Block) is not None: 40 | return self.generic_visit(node) 41 | try: 42 | val = self.visit(node.test).as_const() 43 | except nodes.Impossible: 44 | return self.generic_visit(node) 45 | if val: 46 | body = node.body 47 | else: 48 | body = node.else_ 49 | result = [] 50 | for node in body: 51 | result.extend(self.visit_list(node)) 52 | return result 53 | 54 | def fold(self, node): 55 | """Do constant folding.""" 56 | node = self.generic_visit(node) 57 | try: 58 | return nodes.Const.from_untrusted(node.as_const(), 59 | lineno=node.lineno, 60 | environment=self.environment) 61 | except nodes.Impossible: 62 | return node 63 | 64 | visit_Add = visit_Sub = visit_Mul = visit_Div = visit_FloorDiv = \ 65 | visit_Pow = visit_Mod = visit_And = visit_Or = visit_Pos = visit_Neg = \ 66 | visit_Not = visit_Compare = visit_Getitem = visit_Getattr = visit_Call = \ 67 | visit_Filter = visit_Test = visit_CondExpr = fold 68 | del fold 69 | -------------------------------------------------------------------------------- /ctf1/append/home/level02/jinja2/tests.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | jinja2.tests 4 | ~~~~~~~~~~~~ 5 | 6 | Jinja test functions. Used with the "is" operator. 7 | 8 | :copyright: (c) 2010 by the Jinja Team. 9 | :license: BSD, see LICENSE for more details. 10 | """ 11 | import re 12 | from jinja2.runtime import Undefined 13 | 14 | try: 15 | from collections import Mapping as MappingType 16 | except ImportError: 17 | import UserDict 18 | MappingType = (UserDict.UserDict, UserDict.DictMixin, dict) 19 | 20 | # nose, nothing here to test 21 | __test__ = False 22 | 23 | 24 | number_re = re.compile(r'^-?\d+(\.\d+)?$') 25 | regex_type = type(number_re) 26 | 27 | 28 | try: 29 | test_callable = callable 30 | except NameError: 31 | def test_callable(x): 32 | return hasattr(x, '__call__') 33 | 34 | 35 | def test_odd(value): 36 | """Return true if the variable is odd.""" 37 | return value % 2 == 1 38 | 39 | 40 | def test_even(value): 41 | """Return true if the variable is even.""" 42 | return value % 2 == 0 43 | 44 | 45 | def test_divisibleby(value, num): 46 | """Check if a variable is divisible by a number.""" 47 | return value % num == 0 48 | 49 | 50 | def test_defined(value): 51 | """Return true if the variable is defined: 52 | 53 | .. sourcecode:: jinja 54 | 55 | {% if variable is defined %} 56 | value of variable: {{ variable }} 57 | {% else %} 58 | variable is not defined 59 | {% endif %} 60 | 61 | See the :func:`default` filter for a simple way to set undefined 62 | variables. 63 | """ 64 | return not isinstance(value, Undefined) 65 | 66 | 67 | def test_undefined(value): 68 | """Like :func:`defined` but the other way round.""" 69 | return isinstance(value, Undefined) 70 | 71 | 72 | def test_none(value): 73 | """Return true if the variable is none.""" 74 | return value is None 75 | 76 | 77 | def test_lower(value): 78 | """Return true if the variable is lowercased.""" 79 | return unicode(value).islower() 80 | 81 | 82 | def test_upper(value): 83 | """Return true if the variable is uppercased.""" 84 | return unicode(value).isupper() 85 | 86 | 87 | def test_string(value): 88 | """Return true if the object is a string.""" 89 | return isinstance(value, basestring) 90 | 91 | 92 | def test_mapping(value): 93 | """Return true if the object is a mapping (dict etc.). 94 | 95 | .. versionadded:: 2.6 96 | """ 97 | return isinstance(value, MappingType) 98 | 99 | 100 | def test_number(value): 101 | """Return true if the variable is a number.""" 102 | return isinstance(value, (int, long, float, complex)) 103 | 104 | 105 | def test_sequence(value): 106 | """Return true if the variable is a sequence. Sequences are variables 107 | that are iterable. 108 | """ 109 | try: 110 | len(value) 111 | value.__getitem__ 112 | except: 113 | return False 114 | return True 115 | 116 | 117 | def test_sameas(value, other): 118 | """Check if an object points to the same memory address than another 119 | object: 120 | 121 | .. sourcecode:: jinja 122 | 123 | {% if foo.attribute is sameas false %} 124 | the foo attribute really is the `False` singleton 125 | {% endif %} 126 | """ 127 | return value is other 128 | 129 | 130 | def test_iterable(value): 131 | """Check if it's possible to iterate over an object.""" 132 | try: 133 | iter(value) 134 | except TypeError: 135 | return False 136 | return True 137 | 138 | 139 | def test_escaped(value): 140 | """Check if the value is escaped.""" 141 | return hasattr(value, '__html__') 142 | 143 | 144 | TESTS = { 145 | 'odd': test_odd, 146 | 'even': test_even, 147 | 'divisibleby': test_divisibleby, 148 | 'defined': test_defined, 149 | 'undefined': test_undefined, 150 | 'none': test_none, 151 | 'lower': test_lower, 152 | 'upper': test_upper, 153 | 'string': test_string, 154 | 'mapping': test_mapping, 155 | 'number': test_number, 156 | 'sequence': test_sequence, 157 | 'iterable': test_iterable, 158 | 'callable': test_callable, 159 | 'sameas': test_sameas, 160 | 'escaped': test_escaped 161 | } 162 | -------------------------------------------------------------------------------- /ctf1/append/home/level02/jinja2/testsuite/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | jinja2.testsuite 4 | ~~~~~~~~~~~~~~~~ 5 | 6 | All the unittests of Jinja2. These tests can be executed by 7 | either running run-tests.py using multiple Python versions at 8 | the same time. 9 | 10 | :copyright: (c) 2010 by the Jinja Team. 11 | :license: BSD, see LICENSE for more details. 12 | """ 13 | import os 14 | import re 15 | import sys 16 | import unittest 17 | from traceback import format_exception 18 | from jinja2 import loaders 19 | 20 | 21 | here = os.path.dirname(os.path.abspath(__file__)) 22 | 23 | dict_loader = loaders.DictLoader({ 24 | 'justdict.html': 'FOO' 25 | }) 26 | package_loader = loaders.PackageLoader('jinja2.testsuite.res', 'templates') 27 | filesystem_loader = loaders.FileSystemLoader(here + '/res/templates') 28 | function_loader = loaders.FunctionLoader({'justfunction.html': 'FOO'}.get) 29 | choice_loader = loaders.ChoiceLoader([dict_loader, package_loader]) 30 | prefix_loader = loaders.PrefixLoader({ 31 | 'a': filesystem_loader, 32 | 'b': dict_loader 33 | }) 34 | 35 | 36 | class JinjaTestCase(unittest.TestCase): 37 | 38 | ### use only these methods for testing. If you need standard 39 | ### unittest method, wrap them! 40 | 41 | def setup(self): 42 | pass 43 | 44 | def teardown(self): 45 | pass 46 | 47 | def setUp(self): 48 | self.setup() 49 | 50 | def tearDown(self): 51 | self.teardown() 52 | 53 | def assert_equal(self, a, b): 54 | return self.assertEqual(a, b) 55 | 56 | def assert_raises(self, *args, **kwargs): 57 | return self.assertRaises(*args, **kwargs) 58 | 59 | def assert_traceback_matches(self, callback, expected_tb): 60 | try: 61 | callback() 62 | except Exception, e: 63 | tb = format_exception(*sys.exc_info()) 64 | if re.search(expected_tb.strip(), ''.join(tb)) is None: 65 | raise self.fail('Traceback did not match:\n\n%s\nexpected:\n%s' 66 | % (''.join(tb), expected_tb)) 67 | else: 68 | self.fail('Expected exception') 69 | 70 | 71 | def suite(): 72 | from jinja2.testsuite import ext, filters, tests, core_tags, \ 73 | loader, inheritance, imports, lexnparse, security, api, \ 74 | regression, debug, utils, doctests 75 | suite = unittest.TestSuite() 76 | suite.addTest(ext.suite()) 77 | suite.addTest(filters.suite()) 78 | suite.addTest(tests.suite()) 79 | suite.addTest(core_tags.suite()) 80 | suite.addTest(loader.suite()) 81 | suite.addTest(inheritance.suite()) 82 | suite.addTest(imports.suite()) 83 | suite.addTest(lexnparse.suite()) 84 | suite.addTest(security.suite()) 85 | suite.addTest(api.suite()) 86 | suite.addTest(regression.suite()) 87 | suite.addTest(debug.suite()) 88 | suite.addTest(utils.suite()) 89 | 90 | # doctests will not run on python 3 currently. Too many issues 91 | # with that, do not test that on that platform. 92 | if sys.version_info < (3, 0): 93 | suite.addTest(doctests.suite()) 94 | 95 | return suite 96 | -------------------------------------------------------------------------------- /ctf1/append/home/level02/jinja2/testsuite/debug.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | jinja2.testsuite.debug 4 | ~~~~~~~~~~~~~~~~~~~~~~ 5 | 6 | Tests the debug system. 7 | 8 | :copyright: (c) 2010 by the Jinja Team. 9 | :license: BSD, see LICENSE for more details. 10 | """ 11 | import sys 12 | import unittest 13 | 14 | from jinja2.testsuite import JinjaTestCase, filesystem_loader 15 | 16 | from jinja2 import Environment, TemplateSyntaxError 17 | 18 | env = Environment(loader=filesystem_loader) 19 | 20 | 21 | class DebugTestCase(JinjaTestCase): 22 | 23 | if sys.version_info[:2] != (2, 4): 24 | def test_runtime_error(self): 25 | def test(): 26 | tmpl.render(fail=lambda: 1 / 0) 27 | tmpl = env.get_template('broken.html') 28 | self.assert_traceback_matches(test, r''' 29 | File ".*?broken.html", line 2, in (top-level template code|) 30 | \{\{ fail\(\) \}\} 31 | File ".*?debug.pyc?", line \d+, in 32 | tmpl\.render\(fail=lambda: 1 / 0\) 33 | ZeroDivisionError: (int(eger)? )?division (or modulo )?by zero 34 | ''') 35 | 36 | def test_syntax_error(self): 37 | # XXX: the .*? is necessary for python3 which does not hide 38 | # some of the stack frames we don't want to show. Not sure 39 | # what's up with that, but that is not that critical. Should 40 | # be fixed though. 41 | self.assert_traceback_matches(lambda: env.get_template('syntaxerror.html'), r'''(?sm) 42 | File ".*?syntaxerror.html", line 4, in (template|) 43 | \{% endif %\}.*? 44 | (jinja2\.exceptions\.)?TemplateSyntaxError: Encountered unknown tag 'endif'. Jinja was looking for the following tags: 'endfor' or 'else'. The innermost block that needs to be closed is 'for'. 45 | ''') 46 | 47 | def test_regular_syntax_error(self): 48 | def test(): 49 | raise TemplateSyntaxError('wtf', 42) 50 | self.assert_traceback_matches(test, r''' 51 | File ".*debug.pyc?", line \d+, in test 52 | raise TemplateSyntaxError\('wtf', 42\) 53 | (jinja2\.exceptions\.)?TemplateSyntaxError: wtf 54 | line 42''') 55 | 56 | 57 | def suite(): 58 | suite = unittest.TestSuite() 59 | suite.addTest(unittest.makeSuite(DebugTestCase)) 60 | return suite 61 | -------------------------------------------------------------------------------- /ctf1/append/home/level02/jinja2/testsuite/doctests.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | jinja2.testsuite.doctests 4 | ~~~~~~~~~~~~~~~~~~~~~~~~~ 5 | 6 | The doctests. Collects all tests we want to test from 7 | the Jinja modules. 8 | 9 | :copyright: (c) 2010 by the Jinja Team. 10 | :license: BSD, see LICENSE for more details. 11 | """ 12 | import unittest 13 | import doctest 14 | 15 | 16 | def suite(): 17 | from jinja2 import utils, sandbox, runtime, meta, loaders, \ 18 | ext, environment, bccache, nodes 19 | suite = unittest.TestSuite() 20 | suite.addTest(doctest.DocTestSuite(utils)) 21 | suite.addTest(doctest.DocTestSuite(sandbox)) 22 | suite.addTest(doctest.DocTestSuite(runtime)) 23 | suite.addTest(doctest.DocTestSuite(meta)) 24 | suite.addTest(doctest.DocTestSuite(loaders)) 25 | suite.addTest(doctest.DocTestSuite(ext)) 26 | suite.addTest(doctest.DocTestSuite(environment)) 27 | suite.addTest(doctest.DocTestSuite(bccache)) 28 | suite.addTest(doctest.DocTestSuite(nodes)) 29 | return suite 30 | -------------------------------------------------------------------------------- /ctf1/append/home/level02/jinja2/testsuite/res/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ctf-o-matic/capture-the-flag/cbed26b321871b78c6656ee020c2687482d6b540/ctf1/append/home/level02/jinja2/testsuite/res/__init__.py -------------------------------------------------------------------------------- /ctf1/append/home/level02/jinja2/testsuite/res/templates/broken.html: -------------------------------------------------------------------------------- 1 | Before 2 | {{ fail() }} 3 | After 4 | -------------------------------------------------------------------------------- /ctf1/append/home/level02/jinja2/testsuite/res/templates/foo/test.html: -------------------------------------------------------------------------------- 1 | FOO 2 | -------------------------------------------------------------------------------- /ctf1/append/home/level02/jinja2/testsuite/res/templates/syntaxerror.html: -------------------------------------------------------------------------------- 1 | Foo 2 | {% for item in broken %} 3 | ... 4 | {% endif %} 5 | -------------------------------------------------------------------------------- /ctf1/append/home/level02/jinja2/testsuite/res/templates/test.html: -------------------------------------------------------------------------------- 1 | BAR 2 | -------------------------------------------------------------------------------- /ctf1/append/home/level02/jinja2/testsuite/tests.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | jinja2.testsuite.tests 4 | ~~~~~~~~~~~~~~~~~~~~~~ 5 | 6 | Who tests the tests? 7 | 8 | :copyright: (c) 2010 by the Jinja Team. 9 | :license: BSD, see LICENSE for more details. 10 | """ 11 | import unittest 12 | from jinja2.testsuite import JinjaTestCase 13 | 14 | from jinja2 import Markup, Environment 15 | 16 | env = Environment() 17 | 18 | 19 | class TestsTestCase(JinjaTestCase): 20 | 21 | def test_defined(self): 22 | tmpl = env.from_string('{{ missing is defined }}|{{ true is defined }}') 23 | assert tmpl.render() == 'False|True' 24 | 25 | def test_even(self): 26 | tmpl = env.from_string('''{{ 1 is even }}|{{ 2 is even }}''') 27 | assert tmpl.render() == 'False|True' 28 | 29 | def test_odd(self): 30 | tmpl = env.from_string('''{{ 1 is odd }}|{{ 2 is odd }}''') 31 | assert tmpl.render() == 'True|False' 32 | 33 | def test_lower(self): 34 | tmpl = env.from_string('''{{ "foo" is lower }}|{{ "FOO" is lower }}''') 35 | assert tmpl.render() == 'True|False' 36 | 37 | def test_typechecks(self): 38 | tmpl = env.from_string(''' 39 | {{ 42 is undefined }} 40 | {{ 42 is defined }} 41 | {{ 42 is none }} 42 | {{ none is none }} 43 | {{ 42 is number }} 44 | {{ 42 is string }} 45 | {{ "foo" is string }} 46 | {{ "foo" is sequence }} 47 | {{ [1] is sequence }} 48 | {{ range is callable }} 49 | {{ 42 is callable }} 50 | {{ range(5) is iterable }} 51 | {{ {} is mapping }} 52 | {{ mydict is mapping }} 53 | {{ [] is mapping }} 54 | ''') 55 | class MyDict(dict): 56 | pass 57 | assert tmpl.render(mydict=MyDict()).split() == [ 58 | 'False', 'True', 'False', 'True', 'True', 'False', 59 | 'True', 'True', 'True', 'True', 'False', 'True', 60 | 'True', 'True', 'False' 61 | ] 62 | 63 | def test_sequence(self): 64 | tmpl = env.from_string( 65 | '{{ [1, 2, 3] is sequence }}|' 66 | '{{ "foo" is sequence }}|' 67 | '{{ 42 is sequence }}' 68 | ) 69 | assert tmpl.render() == 'True|True|False' 70 | 71 | def test_upper(self): 72 | tmpl = env.from_string('{{ "FOO" is upper }}|{{ "foo" is upper }}') 73 | assert tmpl.render() == 'True|False' 74 | 75 | def test_sameas(self): 76 | tmpl = env.from_string('{{ foo is sameas false }}|' 77 | '{{ 0 is sameas false }}') 78 | assert tmpl.render(foo=False) == 'True|False' 79 | 80 | def test_no_paren_for_arg1(self): 81 | tmpl = env.from_string('{{ foo is sameas none }}') 82 | assert tmpl.render(foo=None) == 'True' 83 | 84 | def test_escaped(self): 85 | env = Environment(autoescape=True) 86 | tmpl = env.from_string('{{ x is escaped }}|{{ y is escaped }}') 87 | assert tmpl.render(x='foo', y=Markup('foo')) == 'False|True' 88 | 89 | 90 | def suite(): 91 | suite = unittest.TestSuite() 92 | suite.addTest(unittest.makeSuite(TestsTestCase)) 93 | return suite 94 | -------------------------------------------------------------------------------- /ctf1/append/home/level02/jinja2/testsuite/utils.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | jinja2.testsuite.utils 4 | ~~~~~~~~~~~~~~~~~~~~~~ 5 | 6 | Tests utilities jinja uses. 7 | 8 | :copyright: (c) 2010 by the Jinja Team. 9 | :license: BSD, see LICENSE for more details. 10 | """ 11 | import gc 12 | import unittest 13 | 14 | import pickle 15 | 16 | from jinja2.testsuite import JinjaTestCase 17 | 18 | from jinja2.utils import LRUCache, escape, object_type_repr 19 | 20 | 21 | class LRUCacheTestCase(JinjaTestCase): 22 | 23 | def test_simple(self): 24 | d = LRUCache(3) 25 | d["a"] = 1 26 | d["b"] = 2 27 | d["c"] = 3 28 | d["a"] 29 | d["d"] = 4 30 | assert len(d) == 3 31 | assert 'a' in d and 'c' in d and 'd' in d and 'b' not in d 32 | 33 | def test_pickleable(self): 34 | cache = LRUCache(2) 35 | cache["foo"] = 42 36 | cache["bar"] = 23 37 | cache["foo"] 38 | 39 | for protocol in range(3): 40 | copy = pickle.loads(pickle.dumps(cache, protocol)) 41 | assert copy.capacity == cache.capacity 42 | assert copy._mapping == cache._mapping 43 | assert copy._queue == cache._queue 44 | 45 | 46 | class HelpersTestCase(JinjaTestCase): 47 | 48 | def test_object_type_repr(self): 49 | class X(object): 50 | pass 51 | self.assert_equal(object_type_repr(42), 'int object') 52 | self.assert_equal(object_type_repr([]), 'list object') 53 | self.assert_equal(object_type_repr(X()), 54 | 'jinja2.testsuite.utils.X object') 55 | self.assert_equal(object_type_repr(None), 'None') 56 | self.assert_equal(object_type_repr(Ellipsis), 'Ellipsis') 57 | 58 | 59 | class MarkupLeakTestCase(JinjaTestCase): 60 | 61 | def test_markup_leaks(self): 62 | counts = set() 63 | for count in xrange(20): 64 | for item in xrange(1000): 65 | escape("foo") 66 | escape("") 67 | escape(u"foo") 68 | escape(u"") 69 | counts.add(len(gc.get_objects())) 70 | assert len(counts) == 1, 'ouch, c extension seems to leak objects' 71 | 72 | 73 | def suite(): 74 | suite = unittest.TestSuite() 75 | suite.addTest(unittest.makeSuite(LRUCacheTestCase)) 76 | suite.addTest(unittest.makeSuite(HelpersTestCase)) 77 | 78 | # this test only tests the c extension 79 | if not hasattr(escape, 'func_code'): 80 | suite.addTest(unittest.makeSuite(MarkupLeakTestCase)) 81 | 82 | return suite 83 | -------------------------------------------------------------------------------- /ctf1/append/home/level02/jinja2/visitor.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | jinja2.visitor 4 | ~~~~~~~~~~~~~~ 5 | 6 | This module implements a visitor for the nodes. 7 | 8 | :copyright: (c) 2010 by the Jinja Team. 9 | :license: BSD. 10 | """ 11 | from jinja2.nodes import Node 12 | 13 | 14 | class NodeVisitor(object): 15 | """Walks the abstract syntax tree and call visitor functions for every 16 | node found. The visitor functions may return values which will be 17 | forwarded by the `visit` method. 18 | 19 | Per default the visitor functions for the nodes are ``'visit_'`` + 20 | class name of the node. So a `TryFinally` node visit function would 21 | be `visit_TryFinally`. This behavior can be changed by overriding 22 | the `get_visitor` function. If no visitor function exists for a node 23 | (return value `None`) the `generic_visit` visitor is used instead. 24 | """ 25 | 26 | def get_visitor(self, node): 27 | """Return the visitor function for this node or `None` if no visitor 28 | exists for this node. In that case the generic visit function is 29 | used instead. 30 | """ 31 | method = 'visit_' + node.__class__.__name__ 32 | return getattr(self, method, None) 33 | 34 | def visit(self, node, *args, **kwargs): 35 | """Visit a node.""" 36 | f = self.get_visitor(node) 37 | if f is not None: 38 | return f(node, *args, **kwargs) 39 | return self.generic_visit(node, *args, **kwargs) 40 | 41 | def generic_visit(self, node, *args, **kwargs): 42 | """Called if no explicit visitor function exists for a node.""" 43 | for node in node.iter_child_nodes(): 44 | self.visit(node, *args, **kwargs) 45 | 46 | 47 | class NodeTransformer(NodeVisitor): 48 | """Walks the abstract syntax tree and allows modifications of nodes. 49 | 50 | The `NodeTransformer` will walk the AST and use the return value of the 51 | visitor functions to replace or remove the old node. If the return 52 | value of the visitor function is `None` the node will be removed 53 | from the previous location otherwise it's replaced with the return 54 | value. The return value may be the original node in which case no 55 | replacement takes place. 56 | """ 57 | 58 | def generic_visit(self, node, *args, **kwargs): 59 | for field, old_value in node.iter_fields(): 60 | if isinstance(old_value, list): 61 | new_values = [] 62 | for value in old_value: 63 | if isinstance(value, Node): 64 | value = self.visit(value, *args, **kwargs) 65 | if value is None: 66 | continue 67 | elif not isinstance(value, Node): 68 | new_values.extend(value) 69 | continue 70 | new_values.append(value) 71 | old_value[:] = new_values 72 | elif isinstance(old_value, Node): 73 | new_node = self.visit(old_value, *args, **kwargs) 74 | if new_node is None: 75 | delattr(node, field) 76 | else: 77 | setattr(node, field, new_node) 78 | return node 79 | 80 | def visit_list(self, node, *args, **kwargs): 81 | """As transformers may return lists in some places this method 82 | can be used to enforce a list as return value. 83 | """ 84 | rv = self.visit(node, *args, **kwargs) 85 | if not isinstance(rv, list): 86 | rv = [rv] 87 | return rv 88 | -------------------------------------------------------------------------------- /ctf1/append/home/level02/start.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | cd $(dirname "$0") 4 | PYTHONPATH=. /levels/level02/level02.py 5 | -------------------------------------------------------------------------------- /ctf1/append/home/level02/werkzeug/contrib/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | werkzeug.contrib 4 | ~~~~~~~~~~~~~~~~ 5 | 6 | Contains user-submitted code that other users may find useful, but which 7 | is not part of the Werkzeug core. Anyone can write code for inclusion in 8 | the `contrib` package. All modules in this package are distributed as an 9 | add-on library and thus are not part of Werkzeug itself. 10 | 11 | This file itself is mostly for informational purposes and to tell the 12 | Python interpreter that `contrib` is a package. 13 | 14 | :copyright: (c) 2011 by the Werkzeug Team, see AUTHORS for more details. 15 | :license: BSD, see LICENSE for more details. 16 | """ 17 | -------------------------------------------------------------------------------- /ctf1/append/home/level02/werkzeug/contrib/limiter.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | werkzeug.contrib.limiter 4 | ~~~~~~~~~~~~~~~~~~~~~~~~ 5 | 6 | A middleware that limits incoming data. This works around problems with 7 | Trac_ or Django_ because those directly stream into the memory. 8 | 9 | .. _Trac: http://trac.edgewall.org/ 10 | .. _Django: http://www.djangoproject.com/ 11 | 12 | :copyright: (c) 2011 by the Werkzeug Team, see AUTHORS for more details. 13 | :license: BSD, see LICENSE for more details. 14 | """ 15 | from warnings import warn 16 | 17 | from werkzeug.wsgi import LimitedStream 18 | 19 | 20 | class StreamLimitMiddleware(object): 21 | """Limits the input stream to a given number of bytes. This is useful if 22 | you have a WSGI application that reads form data into memory (django for 23 | example) and you don't want users to harm the server by uploading tons of 24 | data. 25 | 26 | Default is 10MB 27 | """ 28 | 29 | def __init__(self, app, maximum_size=1024 * 1024 * 10): 30 | self.app = app 31 | self.maximum_size = maximum_size 32 | 33 | def __call__(self, environ, start_response): 34 | limit = min(self.maximum_size, int(environ.get('CONTENT_LENGTH') or 0)) 35 | environ['wsgi.input'] = LimitedStream(environ['wsgi.input'], limit) 36 | return self.app(environ, start_response) 37 | -------------------------------------------------------------------------------- /ctf1/append/home/level02/werkzeug/contrib/profiler.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | werkzeug.contrib.profiler 4 | ~~~~~~~~~~~~~~~~~~~~~~~~~ 5 | 6 | This module provides a simple WSGI profiler middleware for finding 7 | bottlenecks in web application. It uses the :mod:`profile` or 8 | :mod:`cProfile` module to do the profiling and writes the stats to the 9 | stream provided (defaults to stderr). 10 | 11 | Example usage:: 12 | 13 | from werkzeug.contrib.profiler import ProfilerMiddleware 14 | app = ProfilerMiddleware(app) 15 | 16 | :copyright: (c) 2011 by the Werkzeug Team, see AUTHORS for more details. 17 | :license: BSD, see LICENSE for more details. 18 | """ 19 | import sys 20 | try: 21 | try: 22 | from cProfile import Profile 23 | except ImportError: 24 | from profile import Profile 25 | from pstats import Stats 26 | available = True 27 | except ImportError: 28 | available = False 29 | 30 | 31 | class MergeStream(object): 32 | """An object that redirects `write` calls to multiple streams. 33 | Use this to log to both `sys.stdout` and a file:: 34 | 35 | f = open('profiler.log', 'w') 36 | stream = MergeStream(sys.stdout, f) 37 | profiler = ProfilerMiddleware(app, stream) 38 | """ 39 | 40 | def __init__(self, *streams): 41 | if not streams: 42 | raise TypeError('at least one stream must be given') 43 | self.streams = streams 44 | 45 | def write(self, data): 46 | for stream in self.streams: 47 | stream.write(data) 48 | 49 | 50 | class ProfilerMiddleware(object): 51 | """Simple profiler middleware. Wraps a WSGI application and profiles 52 | a request. This intentionally buffers the response so that timings are 53 | more exact. 54 | 55 | For the exact meaning of `sort_by` and `restrictions` consult the 56 | :mod:`profile` documentation. 57 | 58 | :param app: the WSGI application to profile. 59 | :param stream: the stream for the profiled stats. defaults to stderr. 60 | :param sort_by: a tuple of columns to sort the result by. 61 | :param restrictions: a tuple of profiling strictions. 62 | """ 63 | 64 | def __init__(self, app, stream=None, 65 | sort_by=('time', 'calls'), restrictions=()): 66 | if not available: 67 | raise RuntimeError('the profiler is not available because ' 68 | 'profile or pstat is not installed.') 69 | self._app = app 70 | self._stream = stream or sys.stdout 71 | self._sort_by = sort_by 72 | self._restrictions = restrictions 73 | 74 | def __call__(self, environ, start_response): 75 | response_body = [] 76 | 77 | def catching_start_response(status, headers, exc_info=None): 78 | start_response(status, headers, exc_info) 79 | return response_body.append 80 | 81 | def runapp(): 82 | appiter = self._app(environ, catching_start_response) 83 | response_body.extend(appiter) 84 | if hasattr(appiter, 'close'): 85 | appiter.close() 86 | 87 | p = Profile() 88 | p.runcall(runapp) 89 | body = ''.join(response_body) 90 | stats = Stats(p, stream=self._stream) 91 | stats.sort_stats(*self._sort_by) 92 | 93 | self._stream.write('-' * 80) 94 | self._stream.write('\nPATH: %r\n' % environ.get('PATH_INFO')) 95 | stats.print_stats(*self._restrictions) 96 | self._stream.write('-' * 80 + '\n\n') 97 | 98 | return [body] 99 | 100 | 101 | def make_action(app_factory, hostname='localhost', port=5000, 102 | threaded=False, processes=1, stream=None, 103 | sort_by=('time', 'calls'), restrictions=()): 104 | """Return a new callback for :mod:`werkzeug.script` that starts a local 105 | server with the profiler enabled. 106 | 107 | :: 108 | 109 | from werkzeug.contrib import profiler 110 | action_profile = profiler.make_action(make_app) 111 | """ 112 | def action(hostname=('h', hostname), port=('p', port), 113 | threaded=threaded, processes=processes): 114 | """Start a new development server.""" 115 | from werkzeug.serving import run_simple 116 | app = ProfilerMiddleware(app_factory(), stream, sort_by, restrictions) 117 | run_simple(hostname, port, app, False, None, threaded, processes) 118 | return action 119 | -------------------------------------------------------------------------------- /ctf1/append/home/level02/werkzeug/contrib/testtools.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | werkzeug.contrib.testtools 4 | ~~~~~~~~~~~~~~~~~~~~~~~~~~ 5 | 6 | This module implements extended wrappers for simplified testing. 7 | 8 | `TestResponse` 9 | A response wrapper which adds various cached attributes for 10 | simplified assertions on various content types. 11 | 12 | :copyright: (c) 2011 by the Werkzeug Team, see AUTHORS for more details. 13 | :license: BSD, see LICENSE for more details. 14 | """ 15 | from werkzeug.utils import cached_property, import_string 16 | from werkzeug.wrappers import Response 17 | 18 | from warnings import warn 19 | warn(DeprecationWarning('werkzeug.contrib.testtools is deprecated and ' 20 | 'will be removed with Werkzeug 1.0')) 21 | 22 | 23 | class ContentAccessors(object): 24 | """ 25 | A mixin class for response objects that provides a couple of useful 26 | accessors for unittesting. 27 | """ 28 | 29 | def xml(self): 30 | """Get an etree if possible.""" 31 | if 'xml' not in self.mimetype: 32 | raise AttributeError( 33 | 'Not a XML response (Content-Type: %s)' 34 | % self.mimetype) 35 | for module in ['xml.etree.ElementTree', 'ElementTree', 36 | 'elementtree.ElementTree']: 37 | etree = import_string(module, silent=True) 38 | if etree is not None: 39 | return etree.XML(self.body) 40 | raise RuntimeError('You must have ElementTree installed ' 41 | 'to use TestResponse.xml') 42 | xml = cached_property(xml) 43 | 44 | def lxml(self): 45 | """Get an lxml etree if possible.""" 46 | if ('html' not in self.mimetype and 'xml' not in self.mimetype): 47 | raise AttributeError('Not an HTML/XML response') 48 | from lxml import etree 49 | try: 50 | from lxml.html import fromstring 51 | except ImportError: 52 | fromstring = etree.HTML 53 | if self.mimetype=='text/html': 54 | return fromstring(self.data) 55 | return etree.XML(self.data) 56 | lxml = cached_property(lxml) 57 | 58 | def json(self): 59 | """Get the result of simplejson.loads if possible.""" 60 | if 'json' not in self.mimetype: 61 | raise AttributeError('Not a JSON response') 62 | try: 63 | from simplejson import loads 64 | except ImportError: 65 | from json import loads 66 | return loads(self.data) 67 | json = cached_property(json) 68 | 69 | 70 | class TestResponse(Response, ContentAccessors): 71 | """Pass this to `werkzeug.test.Client` for easier unittesting.""" 72 | -------------------------------------------------------------------------------- /ctf1/append/home/level02/werkzeug/debug/shared/FONT_LICENSE: -------------------------------------------------------------------------------- 1 | ------------------------------- 2 | UBUNTU FONT LICENCE Version 1.0 3 | ------------------------------- 4 | 5 | PREAMBLE 6 | This licence allows the licensed fonts to be used, studied, modified and 7 | redistributed freely. The fonts, including any derivative works, can be 8 | bundled, embedded, and redistributed provided the terms of this licence 9 | are met. The fonts and derivatives, however, cannot be released under 10 | any other licence. The requirement for fonts to remain under this 11 | licence does not require any document created using the fonts or their 12 | derivatives to be published under this licence, as long as the primary 13 | purpose of the document is not to be a vehicle for the distribution of 14 | the fonts. 15 | 16 | DEFINITIONS 17 | "Font Software" refers to the set of files released by the Copyright 18 | Holder(s) under this licence and clearly marked as such. This may 19 | include source files, build scripts and documentation. 20 | 21 | "Original Version" refers to the collection of Font Software components 22 | as received under this licence. 23 | 24 | "Modified Version" refers to any derivative made by adding to, deleting, 25 | or substituting -- in part or in whole -- any of the components of the 26 | Original Version, by changing formats or by porting the Font Software to 27 | a new environment. 28 | 29 | "Copyright Holder(s)" refers to all individuals and companies who have a 30 | copyright ownership of the Font Software. 31 | 32 | "Substantially Changed" refers to Modified Versions which can be easily 33 | identified as dissimilar to the Font Software by users of the Font 34 | Software comparing the Original Version with the Modified Version. 35 | 36 | To "Propagate" a work means to do anything with it that, without 37 | permission, would make you directly or secondarily liable for 38 | infringement under applicable copyright law, except executing it on a 39 | computer or modifying a private copy. Propagation includes copying, 40 | distribution (with or without modification and with or without charging 41 | a redistribution fee), making available to the public, and in some 42 | countries other activities as well. 43 | 44 | PERMISSION & CONDITIONS 45 | This licence does not grant any rights under trademark law and all such 46 | rights are reserved. 47 | 48 | Permission is hereby granted, free of charge, to any person obtaining a 49 | copy of the Font Software, to propagate the Font Software, subject to 50 | the below conditions: 51 | 52 | 1) Each copy of the Font Software must contain the above copyright 53 | notice and this licence. These can be included either as stand-alone 54 | text files, human-readable headers or in the appropriate machine- 55 | readable metadata fields within text or binary files as long as those 56 | fields can be easily viewed by the user. 57 | 58 | 2) The font name complies with the following: 59 | (a) The Original Version must retain its name, unmodified. 60 | (b) Modified Versions which are Substantially Changed must be renamed to 61 | avoid use of the name of the Original Version or similar names entirely. 62 | (c) Modified Versions which are not Substantially Changed must be 63 | renamed to both (i) retain the name of the Original Version and (ii) add 64 | additional naming elements to distinguish the Modified Version from the 65 | Original Version. The name of such Modified Versions must be the name of 66 | the Original Version, with "derivative X" where X represents the name of 67 | the new work, appended to that name. 68 | 69 | 3) The name(s) of the Copyright Holder(s) and any contributor to the 70 | Font Software shall not be used to promote, endorse or advertise any 71 | Modified Version, except (i) as required by this licence, (ii) to 72 | acknowledge the contribution(s) of the Copyright Holder(s) or (iii) with 73 | their explicit written permission. 74 | 75 | 4) The Font Software, modified or unmodified, in part or in whole, must 76 | be distributed entirely under this licence, and must not be distributed 77 | under any other licence. The requirement for fonts to remain under this 78 | licence does not affect any document created using the Font Software, 79 | except any version of the Font Software extracted from a document 80 | created using the Font Software may only be distributed under this 81 | licence. 82 | 83 | TERMINATION 84 | This licence becomes null and void if any of the above conditions are 85 | not met. 86 | 87 | DISCLAIMER 88 | THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 89 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF 90 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF 91 | COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE 92 | COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 93 | INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL 94 | DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 95 | FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER 96 | DEALINGS IN THE FONT SOFTWARE. 97 | -------------------------------------------------------------------------------- /ctf1/append/home/level02/werkzeug/debug/shared/console.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ctf-o-matic/capture-the-flag/cbed26b321871b78c6656ee020c2687482d6b540/ctf1/append/home/level02/werkzeug/debug/shared/console.png -------------------------------------------------------------------------------- /ctf1/append/home/level02/werkzeug/debug/shared/less.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ctf-o-matic/capture-the-flag/cbed26b321871b78c6656ee020c2687482d6b540/ctf1/append/home/level02/werkzeug/debug/shared/less.png -------------------------------------------------------------------------------- /ctf1/append/home/level02/werkzeug/debug/shared/more.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ctf-o-matic/capture-the-flag/cbed26b321871b78c6656ee020c2687482d6b540/ctf1/append/home/level02/werkzeug/debug/shared/more.png -------------------------------------------------------------------------------- /ctf1/append/home/level02/werkzeug/debug/shared/source.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ctf-o-matic/capture-the-flag/cbed26b321871b78c6656ee020c2687482d6b540/ctf1/append/home/level02/werkzeug/debug/shared/source.png -------------------------------------------------------------------------------- /ctf1/append/home/level02/werkzeug/debug/shared/ubuntu.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ctf-o-matic/capture-the-flag/cbed26b321871b78c6656ee020c2687482d6b540/ctf1/append/home/level02/werkzeug/debug/shared/ubuntu.ttf -------------------------------------------------------------------------------- /ctf1/append/home/level02/werkzeug/posixemulation.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | r""" 3 | werkzeug.posixemulation 4 | ~~~~~~~~~~~~~~~~~~~~~~~ 5 | 6 | Provides a POSIX emulation for some features that are relevant to 7 | web applications. The main purpose is to simplify support for 8 | systems such as Windows NT that are not 100% POSIX compatible. 9 | 10 | Currently this only implements a :func:`rename` function that 11 | follows POSIX semantics. Eg: if the target file already exists it 12 | will be replaced without asking. 13 | 14 | This module was introduced in 0.6.1 and is not a public interface. 15 | It might become one in later versions of Werkzeug. 16 | 17 | :copyright: (c) 2011 by the Werkzeug Team, see AUTHORS for more details. 18 | :license: BSD, see LICENSE for more details. 19 | """ 20 | import sys 21 | import os 22 | import errno 23 | import time 24 | import random 25 | 26 | 27 | can_rename_open_file = False 28 | if os.name == 'nt': # pragma: no cover 29 | _rename = lambda src, dst: False 30 | _rename_atomic = lambda src, dst: False 31 | 32 | try: 33 | import ctypes 34 | 35 | _MOVEFILE_REPLACE_EXISTING = 0x1 36 | _MOVEFILE_WRITE_THROUGH = 0x8 37 | _MoveFileEx = ctypes.windll.kernel32.MoveFileExW 38 | 39 | def _rename(src, dst): 40 | if not isinstance(src, unicode): 41 | src = unicode(src, sys.getfilesystemencoding()) 42 | if not isinstance(dst, unicode): 43 | dst = unicode(dst, sys.getfilesystemencoding()) 44 | if _rename_atomic(src, dst): 45 | return True 46 | retry = 0 47 | rv = False 48 | while not rv and retry < 100: 49 | rv = _MoveFileEx(src, dst, _MOVEFILE_REPLACE_EXISTING | 50 | _MOVEFILE_WRITE_THROUGH) 51 | if not rv: 52 | time.sleep(0.001) 53 | retry += 1 54 | return rv 55 | 56 | # new in Vista and Windows Server 2008 57 | _CreateTransaction = ctypes.windll.ktmw32.CreateTransaction 58 | _CommitTransaction = ctypes.windll.ktmw32.CommitTransaction 59 | _MoveFileTransacted = ctypes.windll.kernel32.MoveFileTransactedW 60 | _CloseHandle = ctypes.windll.kernel32.CloseHandle 61 | can_rename_open_file = True 62 | 63 | def _rename_atomic(src, dst): 64 | ta = _CreateTransaction(None, 0, 0, 0, 0, 1000, 'Werkzeug rename') 65 | if ta == -1: 66 | return False 67 | try: 68 | retry = 0 69 | rv = False 70 | while not rv and retry < 100: 71 | rv = _MoveFileTransacted(src, dst, None, None, 72 | _MOVEFILE_REPLACE_EXISTING | 73 | _MOVEFILE_WRITE_THROUGH, ta) 74 | if rv: 75 | rv = _CommitTransaction(ta) 76 | break 77 | else: 78 | time.sleep(0.001) 79 | retry += 1 80 | return rv 81 | finally: 82 | _CloseHandle(ta) 83 | except Exception: 84 | pass 85 | 86 | def rename(src, dst): 87 | # Try atomic or pseudo-atomic rename 88 | if _rename(src, dst): 89 | return 90 | # Fall back to "move away and replace" 91 | try: 92 | os.rename(src, dst) 93 | except OSError, e: 94 | if e.errno != errno.EEXIST: 95 | raise 96 | old = "%s-%08x" % (dst, random.randint(0, sys.maxint)) 97 | os.rename(dst, old) 98 | os.rename(src, dst) 99 | try: 100 | os.unlink(old) 101 | except Exception: 102 | pass 103 | else: 104 | rename = os.rename 105 | can_rename_open_file = True 106 | -------------------------------------------------------------------------------- /ctf1/append/home/level02/werkzeug/security.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | werkzeug.security 4 | ~~~~~~~~~~~~~~~~~ 5 | 6 | Security related helpers such as secure password hashing tools. 7 | 8 | :copyright: (c) 2011 by the Werkzeug Team, see AUTHORS for more details. 9 | :license: BSD, see LICENSE for more details. 10 | """ 11 | import os 12 | import hmac 13 | import posixpath 14 | from itertools import izip 15 | from random import SystemRandom 16 | 17 | 18 | SALT_CHARS = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789' 19 | 20 | 21 | _sys_rng = SystemRandom() 22 | _os_alt_seps = list(sep for sep in [os.path.sep, os.path.altsep] 23 | if sep not in (None, '/')) 24 | 25 | 26 | def _find_hashlib_algorithms(): 27 | import hashlib 28 | algos = getattr(hashlib, 'algorithms', None) 29 | if algos is None: 30 | algos = ('md5', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512') 31 | rv = {} 32 | for algo in algos: 33 | func = getattr(hashlib, algo, None) 34 | if func is not None: 35 | rv[algo] = func 36 | return rv 37 | _hash_funcs = _find_hashlib_algorithms() 38 | 39 | 40 | def safe_str_cmp(a, b): 41 | """This function compares strings in somewhat constant time. This 42 | requires that the length of at least one string is known in advance. 43 | 44 | Returns `True` if the two strings are equal or `False` if they are not. 45 | 46 | .. versionadded:: 0.7 47 | """ 48 | if len(a) != len(b): 49 | return False 50 | rv = 0 51 | for x, y in izip(a, b): 52 | rv |= ord(x) ^ ord(y) 53 | return rv == 0 54 | 55 | 56 | def gen_salt(length): 57 | """Generate a random string of SALT_CHARS with specified ``length``.""" 58 | if length <= 0: 59 | raise ValueError('requested salt of length <= 0') 60 | return ''.join(_sys_rng.choice(SALT_CHARS) for _ in xrange(length)) 61 | 62 | 63 | def _hash_internal(method, salt, password): 64 | """Internal password hash helper. Supports plaintext without salt, 65 | unsalted and salted passwords. In case salted passwords are used 66 | hmac is used. 67 | """ 68 | if method == 'plain': 69 | return password 70 | if salt: 71 | if method not in _hash_funcs: 72 | return None 73 | if isinstance(salt, unicode): 74 | salt = salt.encode('utf-8') 75 | h = hmac.new(salt, None, _hash_funcs[method]) 76 | else: 77 | if method not in _hash_funcs: 78 | return None 79 | h = _hash_funcs[method]() 80 | if isinstance(password, unicode): 81 | password = password.encode('utf-8') 82 | h.update(password) 83 | return h.hexdigest() 84 | 85 | 86 | def generate_password_hash(password, method='sha1', salt_length=8): 87 | """Hash a password with the given method and salt with with a string of 88 | the given length. The format of the string returned includes the method 89 | that was used so that :func:`check_password_hash` can check the hash. 90 | 91 | The format for the hashed string looks like this:: 92 | 93 | method$salt$hash 94 | 95 | This method can **not** generate unsalted passwords but it is possible 96 | to set the method to plain to enforce plaintext passwords. If a salt 97 | is used, hmac is used internally to salt the password. 98 | 99 | :param password: the password to hash 100 | :param method: the hash method to use (one that hashlib supports) 101 | :param salt_length: the lengt of the salt in letters 102 | """ 103 | salt = method != 'plain' and gen_salt(salt_length) or '' 104 | h = _hash_internal(method, salt, password) 105 | if h is None: 106 | raise TypeError('invalid method %r' % method) 107 | return '%s$%s$%s' % (method, salt, h) 108 | 109 | 110 | def check_password_hash(pwhash, password): 111 | """check a password against a given salted and hashed password value. 112 | In order to support unsalted legacy passwords this method supports 113 | plain text passwords, md5 and sha1 hashes (both salted and unsalted). 114 | 115 | Returns `True` if the password matched, `False` otherwise. 116 | 117 | :param pwhash: a hashed string like returned by 118 | :func:`generate_password_hash` 119 | :param password: the plaintext password to compare against the hash 120 | """ 121 | if pwhash.count('$') < 2: 122 | return False 123 | method, salt, hashval = pwhash.split('$', 2) 124 | return safe_str_cmp(_hash_internal(method, salt, password), hashval) 125 | 126 | 127 | def safe_join(directory, filename): 128 | """Safely join `directory` and `filename`. If this cannot be done, 129 | this function returns ``None``. 130 | 131 | :param directory: the base directory. 132 | :param filename: the untrusted filename relative to that directory. 133 | """ 134 | filename = posixpath.normpath(filename) 135 | for sep in _os_alt_seps: 136 | if sep in filename: 137 | return None 138 | if os.path.isabs(filename) or filename.startswith('../'): 139 | return None 140 | return os.path.join(directory, filename) 141 | -------------------------------------------------------------------------------- /ctf1/append/home/level02/werkzeug/testsuite/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | werkzeug.testsuite 4 | ~~~~~~~~~~~~~~~~~~ 5 | 6 | Contains all test Werkzeug tests. 7 | 8 | :copyright: (c) 2011 by Armin Ronacher. 9 | :license: BSD, see LICENSE for more details. 10 | """ 11 | 12 | from __future__ import with_statement 13 | 14 | import unittest 15 | from werkzeug.utils import import_string, find_modules 16 | 17 | 18 | def iter_suites(package): 19 | """Yields all testsuites.""" 20 | for module in find_modules(package, include_packages=True): 21 | mod = import_string(module) 22 | if hasattr(mod, 'suite'): 23 | yield mod.suite() 24 | 25 | 26 | def find_all_tests(suite): 27 | """Yields all the tests and their names from a given suite.""" 28 | suites = [suite] 29 | while suites: 30 | s = suites.pop() 31 | try: 32 | suites.extend(s) 33 | except TypeError: 34 | yield s, '%s.%s.%s' % ( 35 | s.__class__.__module__, 36 | s.__class__.__name__, 37 | s._testMethodName 38 | ) 39 | 40 | 41 | class WerkzeugTestCase(unittest.TestCase): 42 | """Baseclass for all the tests that Werkzeug uses. Use these 43 | methods for testing instead of the camelcased ones in the 44 | baseclass for consistency. 45 | """ 46 | 47 | def setup(self): 48 | pass 49 | 50 | def teardown(self): 51 | pass 52 | 53 | def setUp(self): 54 | self.setup() 55 | 56 | def tearDown(self): 57 | unittest.TestCase.tearDown(self) 58 | self.teardown() 59 | 60 | def assert_equal(self, x, y): 61 | return self.assertEqual(x, y) 62 | 63 | def assert_not_equal(self, x, y): 64 | return self.assertNotEqual(x, y) 65 | 66 | def assert_raises(self, exc_type, callable=None, *args, **kwargs): 67 | catcher = _ExceptionCatcher(self, exc_type) 68 | if callable is None: 69 | return catcher 70 | with catcher: 71 | callable(*args, **kwargs) 72 | 73 | 74 | class _ExceptionCatcher(object): 75 | 76 | def __init__(self, test_case, exc_type): 77 | self.test_case = test_case 78 | self.exc_type = exc_type 79 | 80 | def __enter__(self): 81 | return self 82 | 83 | def __exit__(self, exc_type, exc_value, tb): 84 | exception_name = self.exc_type.__name__ 85 | if exc_type is None: 86 | self.test_case.fail('Expected exception of type %r' % 87 | exception_name) 88 | elif not issubclass(exc_type, self.exc_type): 89 | raise exc_type, exc_value, tb 90 | return True 91 | 92 | 93 | class BetterLoader(unittest.TestLoader): 94 | """A nicer loader that solves two problems. First of all we are setting 95 | up tests from different sources and we're doing this programmatically 96 | which breaks the default loading logic so this is required anyways. 97 | Secondly this loader has a nicer interpolation for test names than the 98 | default one so you can just do ``run-tests.py ViewTestCase`` and it 99 | will work. 100 | """ 101 | 102 | def getRootSuite(self): 103 | return suite() 104 | 105 | def loadTestsFromName(self, name, module=None): 106 | root = self.getRootSuite() 107 | if name == 'suite': 108 | return root 109 | 110 | all_tests = [] 111 | for testcase, testname in find_all_tests(root): 112 | if testname == name or \ 113 | testname.endswith('.' + name) or \ 114 | ('.' + name + '.') in testname or \ 115 | testname.startswith(name + '.'): 116 | all_tests.append(testcase) 117 | 118 | if not all_tests: 119 | raise LookupError('could not find test case for "%s"' % name) 120 | 121 | if len(all_tests) == 1: 122 | return all_tests[0] 123 | rv = unittest.TestSuite() 124 | for test in all_tests: 125 | rv.addTest(test) 126 | return rv 127 | 128 | 129 | def suite(): 130 | """A testsuite that has all the Flask tests. You can use this 131 | function to integrate the Flask tests into your own testsuite 132 | in case you want to test that monkeypatches to Flask do not 133 | break it. 134 | """ 135 | suite = unittest.TestSuite() 136 | for other_suite in iter_suites(__name__): 137 | suite.addTest(other_suite) 138 | return suite 139 | 140 | 141 | def main(): 142 | """Runs the testsuite as command line application.""" 143 | try: 144 | unittest.main(testLoader=BetterLoader(), defaultTest='suite') 145 | except Exception, e: 146 | print 'Error: %s' % e 147 | -------------------------------------------------------------------------------- /ctf1/append/home/level02/werkzeug/testsuite/compat.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | werkzeug.testsuite.compat 4 | ~~~~~~~~~~~~~~~~~~~~~~~~~ 5 | 6 | Ensure that old stuff does not break on update. 7 | 8 | :copyright: (c) 2011 by Armin Ronacher. 9 | :license: BSD, see LICENSE for more details. 10 | """ 11 | import unittest 12 | import warnings 13 | from werkzeug.testsuite import WerkzeugTestCase 14 | 15 | from werkzeug.wrappers import Response 16 | from werkzeug.test import create_environ 17 | 18 | 19 | class CompatTestCase(WerkzeugTestCase): 20 | 21 | def test_old_imports(self): 22 | from werkzeug.utils import Headers, MultiDict, CombinedMultiDict, \ 23 | Headers, EnvironHeaders 24 | from werkzeug.http import Accept, MIMEAccept, CharsetAccept, \ 25 | LanguageAccept, ETags, HeaderSet, WWWAuthenticate, \ 26 | Authorization 27 | 28 | def test_exposed_werkzeug_mod(self): 29 | import werkzeug 30 | for key in werkzeug.__all__: 31 | # deprecated, skip it 32 | if key in ('templates', 'Template'): 33 | continue 34 | getattr(werkzeug, key) 35 | 36 | def test_fix_headers_in_response(self): 37 | # ignore some warnings werkzeug emits for backwards compat 38 | for msg in ['called into deprecated fix_headers', 39 | 'fix_headers changed behavior']: 40 | warnings.filterwarnings('ignore', message=msg, 41 | category=DeprecationWarning) 42 | 43 | class MyResponse(Response): 44 | def fix_headers(self, environ): 45 | Response.fix_headers(self, environ) 46 | self.headers['x-foo'] = "meh" 47 | myresp = MyResponse('Foo') 48 | resp = Response.from_app(myresp, create_environ(method='GET')) 49 | assert resp.headers['x-foo'] == 'meh' 50 | assert resp.data == 'Foo' 51 | 52 | warnings.resetwarnings() 53 | 54 | 55 | def suite(): 56 | suite = unittest.TestSuite() 57 | suite.addTest(unittest.makeSuite(CompatTestCase)) 58 | return suite 59 | -------------------------------------------------------------------------------- /ctf1/append/home/level02/werkzeug/testsuite/contrib/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | werkzeug.testsuite.contrib 4 | ~~~~~~~~~~~~~~~~~~~~~~~~~~ 5 | 6 | Tests the contrib modules. 7 | 8 | :copyright: (c) 2011 by Armin Ronacher. 9 | :license: BSD, see LICENSE for more details. 10 | """ 11 | import unittest 12 | from werkzeug.testsuite import iter_suites 13 | 14 | 15 | def suite(): 16 | suite = unittest.TestSuite() 17 | for other_suite in iter_suites(__name__): 18 | suite.addTest(other_suite) 19 | return suite 20 | -------------------------------------------------------------------------------- /ctf1/append/home/level02/werkzeug/testsuite/contrib/iterio.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | werkzeug.testsuite.iterio 4 | ~~~~~~~~~~~~~~~~~~~~~~~~~ 5 | 6 | Tests the iterio object. 7 | 8 | :copyright: (c) 2011 by Armin Ronacher. 9 | :license: BSD, see LICENSE for more details. 10 | """ 11 | import unittest 12 | 13 | from werkzeug.testsuite import WerkzeugTestCase 14 | from werkzeug.contrib.iterio import IterIO, greenlet 15 | 16 | 17 | class IterOTestSuite(WerkzeugTestCase): 18 | 19 | def test_basic(self): 20 | io = IterIO(["Hello", "World", "1", "2", "3"]) 21 | assert io.tell() == 0 22 | assert io.read(2) == "He" 23 | assert io.tell() == 2 24 | assert io.read(3) == "llo" 25 | assert io.tell() == 5 26 | io.seek(0) 27 | assert io.read(5) == "Hello" 28 | assert io.tell() == 5 29 | assert io._buf == "Hello" 30 | assert io.read() == "World123" 31 | assert io.tell() == 13 32 | io.close() 33 | assert io.closed 34 | 35 | io = IterIO(["Hello\n", "World!"]) 36 | assert io.readline() == 'Hello\n' 37 | assert io._buf == 'Hello\n' 38 | assert io.read() == 'World!' 39 | assert io._buf == 'Hello\nWorld!' 40 | assert io.tell() == 12 41 | io.seek(0) 42 | assert io.readlines() == ['Hello\n', 'World!'] 43 | 44 | io = IterIO(["foo\n", "bar"]) 45 | io.seek(-4, 2) 46 | assert io.read(4) == '\nbar' 47 | 48 | self.assert_raises(IOError, io.seek, 2, 100) 49 | io.close() 50 | self.assert_raises(ValueError, io.read) 51 | 52 | 53 | class IterITestSuite(WerkzeugTestCase): 54 | 55 | def test_basic(self): 56 | def producer(out): 57 | out.write('1\n') 58 | out.write('2\n') 59 | out.flush() 60 | out.write('3\n') 61 | iterable = IterIO(producer) 62 | self.assert_equal(iterable.next(), '1\n2\n') 63 | self.assert_equal(iterable.next(), '3\n') 64 | self.assert_raises(StopIteration, iterable.next) 65 | 66 | 67 | def suite(): 68 | suite = unittest.TestSuite() 69 | suite.addTest(unittest.makeSuite(IterOTestSuite)) 70 | if greenlet is not None: 71 | suite.addTest(unittest.makeSuite(IterITestSuite)) 72 | return suite 73 | -------------------------------------------------------------------------------- /ctf1/append/home/level02/werkzeug/testsuite/contrib/securecookie.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | werkzeug.testsuite.securecookie 4 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 5 | 6 | Tests the secure cookie. 7 | 8 | :copyright: (c) 2011 by Armin Ronacher. 9 | :license: BSD, see LICENSE for more details. 10 | """ 11 | import unittest 12 | 13 | from werkzeug.testsuite import WerkzeugTestCase 14 | 15 | from werkzeug.utils import parse_cookie 16 | from werkzeug.wrappers import Request, Response 17 | from werkzeug.contrib.securecookie import SecureCookie 18 | 19 | 20 | class SecureCookieTestCase(WerkzeugTestCase): 21 | 22 | def test_basic_support(self): 23 | c = SecureCookie(secret_key='foo') 24 | assert c.new 25 | assert not c.modified 26 | assert not c.should_save 27 | c['x'] = 42 28 | assert c.modified 29 | assert c.should_save 30 | s = c.serialize() 31 | 32 | c2 = SecureCookie.unserialize(s, 'foo') 33 | assert c is not c2 34 | assert not c2.new 35 | assert not c2.modified 36 | assert not c2.should_save 37 | assert c2 == c 38 | 39 | c3 = SecureCookie.unserialize(s, 'wrong foo') 40 | assert not c3.modified 41 | assert not c3.new 42 | assert c3 == {} 43 | 44 | def test_wrapper_support(self): 45 | req = Request.from_values() 46 | resp = Response() 47 | c = SecureCookie.load_cookie(req, secret_key='foo') 48 | assert c.new 49 | c['foo'] = 42 50 | assert c.secret_key == 'foo' 51 | c.save_cookie(resp) 52 | 53 | req = Request.from_values(headers={ 54 | 'Cookie': 'session="%s"' % parse_cookie(resp.headers['set-cookie'])['session'] 55 | }) 56 | c2 = SecureCookie.load_cookie(req, secret_key='foo') 57 | assert not c2.new 58 | assert c2 == c 59 | 60 | 61 | def suite(): 62 | suite = unittest.TestSuite() 63 | suite.addTest(unittest.makeSuite(SecureCookieTestCase)) 64 | return suite 65 | -------------------------------------------------------------------------------- /ctf1/append/home/level02/werkzeug/testsuite/contrib/sessions.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | werkzeug.testsuite.sessions 4 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~ 5 | 6 | Added tests for the sessions. 7 | 8 | :copyright: (c) 2011 by Armin Ronacher. 9 | :license: BSD, see LICENSE for more details. 10 | """ 11 | import unittest 12 | import shutil 13 | 14 | from werkzeug.testsuite import WerkzeugTestCase 15 | 16 | from werkzeug.contrib.sessions import FilesystemSessionStore 17 | 18 | from tempfile import mkdtemp, gettempdir 19 | 20 | 21 | class SessionTestCase(WerkzeugTestCase): 22 | 23 | def setup(self): 24 | self.session_folder = mkdtemp() 25 | 26 | def teardown(self): 27 | shutil.rmtree(self.session_folder) 28 | 29 | def test_default_tempdir(self): 30 | store = FilesystemSessionStore() 31 | assert store.path == gettempdir() 32 | 33 | def test_basic_fs_sessions(self): 34 | store = FilesystemSessionStore(self.session_folder) 35 | x = store.new() 36 | assert x.new 37 | assert not x.modified 38 | x['foo'] = [1, 2, 3] 39 | assert x.modified 40 | store.save(x) 41 | 42 | x2 = store.get(x.sid) 43 | assert not x2.new 44 | assert not x2.modified 45 | assert x2 is not x 46 | assert x2 == x 47 | x2['test'] = 3 48 | assert x2.modified 49 | assert not x2.new 50 | store.save(x2) 51 | 52 | x = store.get(x.sid) 53 | store.delete(x) 54 | x2 = store.get(x.sid) 55 | # the session is not new when it was used previously. 56 | assert not x2.new 57 | 58 | def test_renewing_fs_session(self): 59 | store = FilesystemSessionStore(self.session_folder, renew_missing=True) 60 | x = store.new() 61 | store.save(x) 62 | store.delete(x) 63 | x2 = store.get(x.sid) 64 | assert x2.new 65 | 66 | def test_fs_session_lising(self): 67 | store = FilesystemSessionStore(self.session_folder, renew_missing=True) 68 | sessions = set() 69 | for x in xrange(10): 70 | sess = store.new() 71 | store.save(sess) 72 | sessions.add(sess.sid) 73 | 74 | listed_sessions = set(store.list()) 75 | assert sessions == listed_sessions 76 | 77 | 78 | def suite(): 79 | suite = unittest.TestSuite() 80 | suite.addTest(unittest.makeSuite(SessionTestCase)) 81 | return suite 82 | -------------------------------------------------------------------------------- /ctf1/append/home/level02/werkzeug/testsuite/contrib/wrappers.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | werkzeug.testsuite.contrib.wrappers 4 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 5 | 6 | Added tests for the sessions. 7 | 8 | :copyright: (c) 2011 by Armin Ronacher. 9 | :license: BSD, see LICENSE for more details. 10 | """ 11 | 12 | from __future__ import with_statement 13 | 14 | import unittest 15 | 16 | from werkzeug.testsuite import WerkzeugTestCase 17 | 18 | from werkzeug.contrib import wrappers 19 | from werkzeug import routing 20 | from werkzeug.wrappers import Request, Response 21 | 22 | 23 | class WrappersTestCase(WerkzeugTestCase): 24 | 25 | def test_reverse_slash_behavior(self): 26 | class MyRequest(wrappers.ReverseSlashBehaviorRequestMixin, Request): 27 | pass 28 | req = MyRequest.from_values('/foo/bar', 'http://example.com/test') 29 | assert req.url == 'http://example.com/test/foo/bar' 30 | assert req.path == 'foo/bar' 31 | assert req.script_root == '/test/' 32 | 33 | # make sure the routing system works with the slashes in 34 | # reverse order as well. 35 | map = routing.Map([routing.Rule('/foo/bar', endpoint='foo')]) 36 | adapter = map.bind_to_environ(req.environ) 37 | assert adapter.match() == ('foo', {}) 38 | adapter = map.bind(req.host, req.script_root) 39 | assert adapter.match(req.path) == ('foo', {}) 40 | 41 | def test_dynamic_charset_request_mixin(self): 42 | class MyRequest(wrappers.DynamicCharsetRequestMixin, Request): 43 | pass 44 | env = {'CONTENT_TYPE': 'text/html'} 45 | req = MyRequest(env) 46 | assert req.charset == 'latin1' 47 | 48 | env = {'CONTENT_TYPE': 'text/html; charset=utf-8'} 49 | req = MyRequest(env) 50 | assert req.charset == 'utf-8' 51 | 52 | env = {'CONTENT_TYPE': 'application/octet-stream'} 53 | req = MyRequest(env) 54 | assert req.charset == 'latin1' 55 | assert req.url_charset == 'latin1' 56 | 57 | MyRequest.url_charset = 'utf-8' 58 | env = {'CONTENT_TYPE': 'application/octet-stream'} 59 | req = MyRequest(env) 60 | assert req.charset == 'latin1' 61 | assert req.url_charset == 'utf-8' 62 | 63 | def return_ascii(x): 64 | return "ascii" 65 | env = {'CONTENT_TYPE': 'text/plain; charset=x-weird-charset'} 66 | req = MyRequest(env) 67 | req.unknown_charset = return_ascii 68 | assert req.charset == 'ascii' 69 | assert req.url_charset == 'utf-8' 70 | 71 | def test_dynamic_charset_response_mixin(self): 72 | class MyResponse(wrappers.DynamicCharsetResponseMixin, Response): 73 | default_charset = 'utf-7' 74 | resp = MyResponse(mimetype='text/html') 75 | assert resp.charset == 'utf-7' 76 | resp.charset = 'utf-8' 77 | assert resp.charset == 'utf-8' 78 | assert resp.mimetype == 'text/html' 79 | assert resp.mimetype_params == {'charset': 'utf-8'} 80 | resp.mimetype_params['charset'] = 'iso-8859-15' 81 | assert resp.charset == 'iso-8859-15' 82 | resp.data = u'Hällo Wörld' 83 | assert ''.join(resp.iter_encoded()) == \ 84 | u'Hällo Wörld'.encode('iso-8859-15') 85 | del resp.headers['content-type'] 86 | try: 87 | resp.charset = 'utf-8' 88 | except TypeError, e: 89 | pass 90 | else: 91 | assert False, 'expected type error on charset setting without ct' 92 | 93 | 94 | def suite(): 95 | suite = unittest.TestSuite() 96 | suite.addTest(unittest.makeSuite(WrappersTestCase)) 97 | return suite 98 | -------------------------------------------------------------------------------- /ctf1/append/home/level02/werkzeug/testsuite/exceptions.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | werkzeug.testsuite.exceptions 4 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 5 | 6 | The tests for the exception classes. 7 | 8 | TODO: 9 | 10 | - This is undertested. HTML is never checked 11 | 12 | :copyright: (c) 2011 by Armin Ronacher. 13 | :license: BSD, see LICENSE for more details. 14 | """ 15 | import unittest 16 | 17 | from werkzeug.testsuite import WerkzeugTestCase 18 | 19 | from werkzeug import exceptions 20 | from werkzeug.wrappers import Response 21 | 22 | 23 | class ExceptionsTestCase(WerkzeugTestCase): 24 | 25 | def test_proxy_exception(self): 26 | orig_resp = Response('Hello World') 27 | try: 28 | exceptions.abort(orig_resp) 29 | except exceptions.HTTPException, e: 30 | resp = e.get_response({}) 31 | else: 32 | self.fail('exception not raised') 33 | self.assert_(resp is orig_resp) 34 | self.assert_equal(resp.data, 'Hello World') 35 | 36 | def test_aborter(self): 37 | abort = exceptions.abort 38 | self.assert_raises(exceptions.BadRequest, abort, 400) 39 | self.assert_raises(exceptions.Unauthorized, abort, 401) 40 | self.assert_raises(exceptions.Forbidden, abort, 403) 41 | self.assert_raises(exceptions.NotFound, abort, 404) 42 | self.assert_raises(exceptions.MethodNotAllowed, abort, 405, ['GET', 'HEAD']) 43 | self.assert_raises(exceptions.NotAcceptable, abort, 406) 44 | self.assert_raises(exceptions.RequestTimeout, abort, 408) 45 | self.assert_raises(exceptions.Gone, abort, 410) 46 | self.assert_raises(exceptions.LengthRequired, abort, 411) 47 | self.assert_raises(exceptions.PreconditionFailed, abort, 412) 48 | self.assert_raises(exceptions.RequestEntityTooLarge, abort, 413) 49 | self.assert_raises(exceptions.RequestURITooLarge, abort, 414) 50 | self.assert_raises(exceptions.UnsupportedMediaType, abort, 415) 51 | self.assert_raises(exceptions.UnprocessableEntity, abort, 422) 52 | self.assert_raises(exceptions.InternalServerError, abort, 500) 53 | self.assert_raises(exceptions.NotImplemented, abort, 501) 54 | self.assert_raises(exceptions.BadGateway, abort, 502) 55 | self.assert_raises(exceptions.ServiceUnavailable, abort, 503) 56 | 57 | myabort = exceptions.Aborter({1: exceptions.NotFound}) 58 | self.assert_raises(LookupError, myabort, 404) 59 | self.assert_raises(exceptions.NotFound, myabort, 1) 60 | 61 | myabort = exceptions.Aborter(extra={1: exceptions.NotFound}) 62 | self.assert_raises(exceptions.NotFound, myabort, 404) 63 | self.assert_raises(exceptions.NotFound, myabort, 1) 64 | 65 | def test_exception_repr(self): 66 | exc = exceptions.NotFound() 67 | self.assert_equal(unicode(exc), '404: Not Found') 68 | self.assert_equal(repr(exc), "") 69 | 70 | exc = exceptions.NotFound('Not There') 71 | self.assert_equal(unicode(exc), '404: Not There') 72 | self.assert_equal(repr(exc), "") 73 | 74 | def test_special_exceptions(self): 75 | exc = exceptions.MethodNotAllowed(['GET', 'HEAD', 'POST']) 76 | h = dict(exc.get_headers({})) 77 | self.assert_equal(h['Allow'], 'GET, HEAD, POST') 78 | self.assert_('The method DELETE is not allowed' in exc.get_description({ 79 | 'REQUEST_METHOD': 'DELETE' 80 | })) 81 | 82 | 83 | def suite(): 84 | suite = unittest.TestSuite() 85 | suite.addTest(unittest.makeSuite(ExceptionsTestCase)) 86 | return suite 87 | -------------------------------------------------------------------------------- /ctf1/append/home/level02/werkzeug/testsuite/internal.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | werkzeug.testsuite.internal 4 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~ 5 | 6 | Internal tests. 7 | 8 | :copyright: (c) 2011 by Armin Ronacher. 9 | :license: BSD, see LICENSE for more details. 10 | """ 11 | import unittest 12 | 13 | from datetime import datetime 14 | from warnings import filterwarnings, resetwarnings 15 | 16 | from werkzeug.testsuite import WerkzeugTestCase 17 | from werkzeug.wrappers import Request, Response 18 | 19 | from werkzeug import _internal as internal 20 | from werkzeug.test import create_environ 21 | 22 | 23 | class InternalTestCase(WerkzeugTestCase): 24 | 25 | def test_date_to_unix(self): 26 | assert internal._date_to_unix(datetime(1970, 1, 1)) == 0 27 | assert internal._date_to_unix(datetime(1970, 1, 1, 1, 0, 0)) == 3600 28 | assert internal._date_to_unix(datetime(1970, 1, 1, 1, 1, 1)) == 3661 29 | x = datetime(2010, 2, 15, 16, 15, 39) 30 | assert internal._date_to_unix(x) == 1266250539 31 | 32 | def test_easteregg(self): 33 | req = Request.from_values('/?macgybarchakku') 34 | resp = Response.force_type(internal._easteregg(None), req) 35 | assert 'About Werkzeug' in resp.data 36 | assert 'the Swiss Army knife of Python web development' in resp.data 37 | 38 | def test_wrapper_internals(self): 39 | req = Request.from_values(data={'foo': 'bar'}, method='POST') 40 | req._load_form_data() 41 | assert req.form.to_dict() == {'foo': 'bar'} 42 | 43 | # second call does not break 44 | req._load_form_data() 45 | assert req.form.to_dict() == {'foo': 'bar'} 46 | 47 | # check reprs 48 | assert repr(req) == "" 49 | resp = Response() 50 | assert repr(resp) == '' 51 | resp.data = 'Hello World!' 52 | assert repr(resp) == '' 53 | resp.response = iter(['Test']) 54 | assert repr(resp) == '' 55 | 56 | # unicode data does not set content length 57 | response = Response([u'Hällo Wörld']) 58 | headers = response.get_wsgi_headers(create_environ()) 59 | assert 'Content-Length' not in headers 60 | 61 | response = Response(['Hällo Wörld']) 62 | headers = response.get_wsgi_headers(create_environ()) 63 | assert 'Content-Length' in headers 64 | 65 | # check for internal warnings 66 | filterwarnings('error', category=Warning) 67 | response = Response() 68 | environ = create_environ() 69 | response.response = 'What the...?' 70 | self.assert_raises(Warning, lambda: list(response.iter_encoded())) 71 | self.assert_raises(Warning, lambda: list(response.get_app_iter(environ))) 72 | response.direct_passthrough = True 73 | self.assert_raises(Warning, lambda: list(response.iter_encoded())) 74 | self.assert_raises(Warning, lambda: list(response.get_app_iter(environ))) 75 | resetwarnings() 76 | 77 | 78 | def suite(): 79 | suite = unittest.TestSuite() 80 | suite.addTest(unittest.makeSuite(InternalTestCase)) 81 | return suite 82 | -------------------------------------------------------------------------------- /ctf1/append/home/level02/werkzeug/testsuite/local.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | werkzeug.testsuite.local 4 | ~~~~~~~~~~~~~~~~~~~~~~~~ 5 | 6 | Local and local proxy tests. 7 | 8 | :copyright: (c) 2011 by Armin Ronacher. 9 | :license: BSD, see LICENSE for more details. 10 | """ 11 | import time 12 | import unittest 13 | from threading import Thread 14 | 15 | from werkzeug.testsuite import WerkzeugTestCase 16 | 17 | from werkzeug import local 18 | 19 | 20 | class LocalTestCase(WerkzeugTestCase): 21 | 22 | def test_basic_local(self): 23 | l = local.Local() 24 | l.foo = 0 25 | values = [] 26 | def value_setter(idx): 27 | time.sleep(0.01 * idx) 28 | l.foo = idx 29 | time.sleep(0.02) 30 | values.append(l.foo) 31 | threads = [Thread(target=value_setter, args=(x,)) 32 | for x in [1, 2, 3]] 33 | for thread in threads: 34 | thread.start() 35 | time.sleep(0.2) 36 | assert sorted(values) == [1, 2, 3] 37 | 38 | def delfoo(): 39 | del l.foo 40 | delfoo() 41 | self.assert_raises(AttributeError, lambda: l.foo) 42 | self.assert_raises(AttributeError, delfoo) 43 | 44 | local.release_local(l) 45 | 46 | def test_local_release(self): 47 | loc = local.Local() 48 | loc.foo = 42 49 | local.release_local(loc) 50 | assert not hasattr(loc, 'foo') 51 | 52 | ls = local.LocalStack() 53 | ls.push(42) 54 | local.release_local(ls) 55 | assert ls.top is None 56 | 57 | def test_local_proxy(self): 58 | foo = [] 59 | ls = local.LocalProxy(lambda: foo) 60 | ls.append(42) 61 | ls.append(23) 62 | ls[1:] = [1, 2, 3] 63 | assert foo == [42, 1, 2, 3] 64 | assert repr(foo) == repr(ls) 65 | assert foo[0] == 42 66 | foo += [1] 67 | assert list(foo) == [42, 1, 2, 3, 1] 68 | 69 | def test_local_stack(self): 70 | ident = local.get_ident() 71 | 72 | ls = local.LocalStack() 73 | assert ident not in ls._local.__storage__ 74 | assert ls.top is None 75 | ls.push(42) 76 | assert ident in ls._local.__storage__ 77 | assert ls.top == 42 78 | ls.push(23) 79 | assert ls.top == 23 80 | ls.pop() 81 | assert ls.top == 42 82 | ls.pop() 83 | assert ls.top is None 84 | assert ls.pop() is None 85 | assert ls.pop() is None 86 | 87 | proxy = ls() 88 | ls.push([1, 2]) 89 | assert proxy == [1, 2] 90 | ls.push((1, 2)) 91 | assert proxy == (1, 2) 92 | ls.pop() 93 | ls.pop() 94 | assert repr(proxy) == '' 95 | 96 | assert ident not in ls._local.__storage__ 97 | 98 | def test_local_proxies_with_callables(self): 99 | foo = 42 100 | ls = local.LocalProxy(lambda: foo) 101 | assert ls == 42 102 | foo = [23] 103 | ls.append(42) 104 | assert ls == [23, 42] 105 | assert foo == [23, 42] 106 | 107 | def test_custom_idents(self): 108 | ident = 0 109 | loc = local.Local() 110 | stack = local.LocalStack() 111 | mgr = local.LocalManager([loc, stack], ident_func=lambda: ident) 112 | 113 | loc.foo = 42 114 | stack.push({'foo': 42}) 115 | ident = 1 116 | loc.foo = 23 117 | stack.push({'foo': 23}) 118 | ident = 0 119 | assert loc.foo == 42 120 | assert stack.top['foo'] == 42 121 | stack.pop() 122 | assert stack.top is None 123 | ident = 1 124 | assert loc.foo == 23 125 | assert stack.top['foo'] == 23 126 | stack.pop() 127 | assert stack.top is None 128 | 129 | 130 | def suite(): 131 | suite = unittest.TestSuite() 132 | suite.addTest(unittest.makeSuite(LocalTestCase)) 133 | return suite 134 | -------------------------------------------------------------------------------- /ctf1/append/home/level02/werkzeug/testsuite/multipart/collect.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """ 3 | Hacky helper application to collect form data. 4 | """ 5 | from werkzeug.serving import run_simple 6 | from werkzeug.wrappers import Request, Response 7 | 8 | 9 | def copy_stream(request): 10 | from os import mkdir 11 | from time import time 12 | folder = 'request-%d' % time() 13 | mkdir(folder) 14 | environ = request.environ 15 | f = file(folder + '/request.txt', 'wb+') 16 | f.write(environ['wsgi.input'].read(int(environ['CONTENT_LENGTH']))) 17 | f.flush() 18 | f.seek(0) 19 | environ['wsgi.input'] = f 20 | request.stat_folder = folder 21 | 22 | 23 | def stats(request): 24 | copy_stream(request) 25 | f1 = request.files['file1'] 26 | f2 = request.files['file2'] 27 | text = request.form['text'] 28 | f1.save(request.stat_folder + '/file1.bin') 29 | f2.save(request.stat_folder + '/file2.bin') 30 | file(request.stat_folder + '/text.txt', 'w').write(text.encode('utf-8')) 31 | return Response('Done.') 32 | 33 | 34 | def upload_file(request): 35 | return Response(''' 36 |

Upload File

37 |
38 |
39 |
40 |
41 | 42 |
43 | ''', mimetype='text/html') 44 | 45 | 46 | def application(environ, start_responseonse): 47 | request = Request(environ) 48 | if request.method == 'POST': 49 | response = stats(request) 50 | else: 51 | response = upload_file(request) 52 | return response(environ, start_responseonse) 53 | 54 | 55 | if __name__ == '__main__': 56 | run_simple('localhost', 5000, application, use_debugger=True) 57 | -------------------------------------------------------------------------------- /ctf1/append/home/level02/werkzeug/testsuite/multipart/firefox3-2png1txt/file1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ctf-o-matic/capture-the-flag/cbed26b321871b78c6656ee020c2687482d6b540/ctf1/append/home/level02/werkzeug/testsuite/multipart/firefox3-2png1txt/file1.png -------------------------------------------------------------------------------- /ctf1/append/home/level02/werkzeug/testsuite/multipart/firefox3-2png1txt/file2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ctf-o-matic/capture-the-flag/cbed26b321871b78c6656ee020c2687482d6b540/ctf1/append/home/level02/werkzeug/testsuite/multipart/firefox3-2png1txt/file2.png -------------------------------------------------------------------------------- /ctf1/append/home/level02/werkzeug/testsuite/multipart/firefox3-2png1txt/request.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ctf-o-matic/capture-the-flag/cbed26b321871b78c6656ee020c2687482d6b540/ctf1/append/home/level02/werkzeug/testsuite/multipart/firefox3-2png1txt/request.txt -------------------------------------------------------------------------------- /ctf1/append/home/level02/werkzeug/testsuite/multipart/firefox3-2png1txt/text.txt: -------------------------------------------------------------------------------- 1 | example text -------------------------------------------------------------------------------- /ctf1/append/home/level02/werkzeug/testsuite/multipart/firefox3-2pnglongtext/file1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ctf-o-matic/capture-the-flag/cbed26b321871b78c6656ee020c2687482d6b540/ctf1/append/home/level02/werkzeug/testsuite/multipart/firefox3-2pnglongtext/file1.png -------------------------------------------------------------------------------- /ctf1/append/home/level02/werkzeug/testsuite/multipart/firefox3-2pnglongtext/file2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ctf-o-matic/capture-the-flag/cbed26b321871b78c6656ee020c2687482d6b540/ctf1/append/home/level02/werkzeug/testsuite/multipart/firefox3-2pnglongtext/file2.png -------------------------------------------------------------------------------- /ctf1/append/home/level02/werkzeug/testsuite/multipart/firefox3-2pnglongtext/request.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ctf-o-matic/capture-the-flag/cbed26b321871b78c6656ee020c2687482d6b540/ctf1/append/home/level02/werkzeug/testsuite/multipart/firefox3-2pnglongtext/request.txt -------------------------------------------------------------------------------- /ctf1/append/home/level02/werkzeug/testsuite/multipart/firefox3-2pnglongtext/text.txt: -------------------------------------------------------------------------------- 1 | --long text 2 | --with boundary 3 | --lookalikes-- -------------------------------------------------------------------------------- /ctf1/append/home/level02/werkzeug/testsuite/multipart/ie6-2png1txt/file1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ctf-o-matic/capture-the-flag/cbed26b321871b78c6656ee020c2687482d6b540/ctf1/append/home/level02/werkzeug/testsuite/multipart/ie6-2png1txt/file1.png -------------------------------------------------------------------------------- /ctf1/append/home/level02/werkzeug/testsuite/multipart/ie6-2png1txt/file2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ctf-o-matic/capture-the-flag/cbed26b321871b78c6656ee020c2687482d6b540/ctf1/append/home/level02/werkzeug/testsuite/multipart/ie6-2png1txt/file2.png -------------------------------------------------------------------------------- /ctf1/append/home/level02/werkzeug/testsuite/multipart/ie6-2png1txt/request.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ctf-o-matic/capture-the-flag/cbed26b321871b78c6656ee020c2687482d6b540/ctf1/append/home/level02/werkzeug/testsuite/multipart/ie6-2png1txt/request.txt -------------------------------------------------------------------------------- /ctf1/append/home/level02/werkzeug/testsuite/multipart/ie6-2png1txt/text.txt: -------------------------------------------------------------------------------- 1 | ie6 sucks :-/ -------------------------------------------------------------------------------- /ctf1/append/home/level02/werkzeug/testsuite/multipart/ie7_full_path_request.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ctf-o-matic/capture-the-flag/cbed26b321871b78c6656ee020c2687482d6b540/ctf1/append/home/level02/werkzeug/testsuite/multipart/ie7_full_path_request.txt -------------------------------------------------------------------------------- /ctf1/append/home/level02/werkzeug/testsuite/multipart/opera8-2png1txt/file1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ctf-o-matic/capture-the-flag/cbed26b321871b78c6656ee020c2687482d6b540/ctf1/append/home/level02/werkzeug/testsuite/multipart/opera8-2png1txt/file1.png -------------------------------------------------------------------------------- /ctf1/append/home/level02/werkzeug/testsuite/multipart/opera8-2png1txt/file2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ctf-o-matic/capture-the-flag/cbed26b321871b78c6656ee020c2687482d6b540/ctf1/append/home/level02/werkzeug/testsuite/multipart/opera8-2png1txt/file2.png -------------------------------------------------------------------------------- /ctf1/append/home/level02/werkzeug/testsuite/multipart/opera8-2png1txt/request.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ctf-o-matic/capture-the-flag/cbed26b321871b78c6656ee020c2687482d6b540/ctf1/append/home/level02/werkzeug/testsuite/multipart/opera8-2png1txt/request.txt -------------------------------------------------------------------------------- /ctf1/append/home/level02/werkzeug/testsuite/multipart/opera8-2png1txt/text.txt: -------------------------------------------------------------------------------- 1 | blafasel öäü -------------------------------------------------------------------------------- /ctf1/append/home/level02/werkzeug/testsuite/multipart/webkit3-2png1txt/file1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ctf-o-matic/capture-the-flag/cbed26b321871b78c6656ee020c2687482d6b540/ctf1/append/home/level02/werkzeug/testsuite/multipart/webkit3-2png1txt/file1.png -------------------------------------------------------------------------------- /ctf1/append/home/level02/werkzeug/testsuite/multipart/webkit3-2png1txt/file2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ctf-o-matic/capture-the-flag/cbed26b321871b78c6656ee020c2687482d6b540/ctf1/append/home/level02/werkzeug/testsuite/multipart/webkit3-2png1txt/file2.png -------------------------------------------------------------------------------- /ctf1/append/home/level02/werkzeug/testsuite/multipart/webkit3-2png1txt/request.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ctf-o-matic/capture-the-flag/cbed26b321871b78c6656ee020c2687482d6b540/ctf1/append/home/level02/werkzeug/testsuite/multipart/webkit3-2png1txt/request.txt -------------------------------------------------------------------------------- /ctf1/append/home/level02/werkzeug/testsuite/multipart/webkit3-2png1txt/text.txt: -------------------------------------------------------------------------------- 1 | this is another text with ümläüts -------------------------------------------------------------------------------- /ctf1/append/home/level02/werkzeug/testsuite/res/test.txt: -------------------------------------------------------------------------------- 1 | FOUND 2 | -------------------------------------------------------------------------------- /ctf1/append/home/level02/werkzeug/testsuite/security.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | werkzeug.testsuite.security 4 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~ 5 | 6 | Tests the security helpers. 7 | 8 | :copyright: (c) 2011 by Armin Ronacher. 9 | :license: BSD, see LICENSE for more details. 10 | """ 11 | import os 12 | import unittest 13 | 14 | from werkzeug.testsuite import WerkzeugTestCase 15 | 16 | from werkzeug.security import check_password_hash, generate_password_hash, \ 17 | safe_join 18 | 19 | 20 | class SecurityTestCase(WerkzeugTestCase): 21 | 22 | def test_password_hashing(self): 23 | hash1 = generate_password_hash('default') 24 | hash2 = generate_password_hash(u'default', method='sha1') 25 | assert hash1 != hash2 26 | assert check_password_hash(hash1, 'default') 27 | assert check_password_hash(hash2, 'default') 28 | assert hash1.startswith('sha1$') 29 | assert hash2.startswith('sha1$') 30 | 31 | fakehash = generate_password_hash('default', method='plain') 32 | assert fakehash == 'plain$$default' 33 | assert check_password_hash(fakehash, 'default') 34 | 35 | mhash = generate_password_hash(u'default', method='md5') 36 | assert mhash.startswith('md5$') 37 | assert check_password_hash(mhash, 'default') 38 | 39 | legacy = 'md5$$c21f969b5f03d33d43e04f8f136e7682' 40 | assert check_password_hash(legacy, 'default') 41 | 42 | legacy = u'md5$$c21f969b5f03d33d43e04f8f136e7682' 43 | assert check_password_hash(legacy, 'default') 44 | 45 | def test_safe_join(self): 46 | assert safe_join('foo', 'bar/baz') == os.path.join('foo', 'bar/baz') 47 | assert safe_join('foo', '../bar/baz') is None 48 | if os.name == 'nt': 49 | assert safe_join('foo', 'foo\\bar') is None 50 | 51 | 52 | def suite(): 53 | suite = unittest.TestSuite() 54 | suite.addTest(unittest.makeSuite(SecurityTestCase)) 55 | return suite 56 | -------------------------------------------------------------------------------- /ctf1/append/home/level02/werkzeug/testsuite/serving.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | werkzeug.testsuite.serving 4 | ~~~~~~~~~~~~~~~~~~~~~~~~~~ 5 | 6 | Added serving tests. 7 | 8 | :copyright: (c) 2011 by Armin Ronacher. 9 | :license: BSD, see LICENSE for more details. 10 | """ 11 | import sys 12 | import time 13 | import urllib 14 | import httplib 15 | import unittest 16 | from functools import update_wrapper 17 | from StringIO import StringIO 18 | 19 | from werkzeug.testsuite import WerkzeugTestCase 20 | 21 | from werkzeug import __version__ as version, serving 22 | from werkzeug.testapp import test_app 23 | from threading import Thread 24 | 25 | 26 | real_make_server = serving.make_server 27 | 28 | 29 | def silencestderr(f): 30 | def new_func(*args, **kwargs): 31 | old_stderr = sys.stderr 32 | sys.stderr = StringIO() 33 | try: 34 | return f(*args, **kwargs) 35 | finally: 36 | sys.stderr = old_stderr 37 | return update_wrapper(new_func, f) 38 | 39 | 40 | def run_dev_server(application): 41 | servers = [] 42 | def tracking_make_server(*args, **kwargs): 43 | srv = real_make_server(*args, **kwargs) 44 | servers.append(srv) 45 | return srv 46 | serving.make_server = tracking_make_server 47 | try: 48 | t = Thread(target=serving.run_simple, args=('localhost', 0, application)) 49 | t.setDaemon(True) 50 | t.start() 51 | time.sleep(0.25) 52 | finally: 53 | serving.make_server = real_make_server 54 | if not servers: 55 | return None, None 56 | server ,= servers 57 | ip, port = server.socket.getsockname()[:2] 58 | if ':' in ip: 59 | ip = '[%s]' % ip 60 | return server, '%s:%d' % (ip, port) 61 | 62 | 63 | class ServingTestCase(WerkzeugTestCase): 64 | 65 | @silencestderr 66 | def test_serving(self): 67 | server, addr = run_dev_server(test_app) 68 | rv = urllib.urlopen('http://%s/?foo=bar&baz=blah' % addr).read() 69 | assert 'WSGI Information' in rv 70 | assert 'foo=bar&baz=blah' in rv 71 | assert ('Werkzeug/%s' % version) in rv 72 | 73 | @silencestderr 74 | def test_broken_app(self): 75 | def broken_app(environ, start_response): 76 | 1/0 77 | server, addr = run_dev_server(broken_app) 78 | rv = urllib.urlopen('http://%s/?foo=bar&baz=blah' % addr).read() 79 | assert 'Internal Server Error' in rv 80 | 81 | @silencestderr 82 | def test_absolute_requests(self): 83 | def asserting_app(environ, start_response): 84 | assert environ['HTTP_HOST'] == 'surelynotexisting.example.com:1337' 85 | assert environ['PATH_INFO'] == '/index.htm' 86 | assert environ['SERVER_PORT'] == addr.split(':')[1] 87 | start_response('200 OK', [('Content-Type', 'text/html')]) 88 | return 'YES' 89 | 90 | server, addr = run_dev_server(asserting_app) 91 | conn = httplib.HTTPConnection(addr) 92 | conn.request('GET', 'http://surelynotexisting.example.com:1337/index.htm') 93 | res = conn.getresponse() 94 | assert res.read() == 'YES' 95 | 96 | 97 | def suite(): 98 | suite = unittest.TestSuite() 99 | suite.addTest(unittest.makeSuite(ServingTestCase)) 100 | return suite 101 | -------------------------------------------------------------------------------- /ctf1/append/home/level05/start.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | cd $(dirname "$0") 4 | PYTHONPATH=. /levels/level05/level05.py server & 5 | PYTHONPATH=. /levels/level05/level05.py worker & 6 | -------------------------------------------------------------------------------- /ctf1/append/opt/bootlocal.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | LOGDIR=/var/log 3 | (/usr/local/etc/init.d/openssh start >>$LOGDIR/custom-sshd.log 2>&1)& 4 | (exec sudo -u level02 /home/level02/start.sh >> $LOGDIR/level02.log 2>&1)& 5 | (exec sudo -u level05 /home/level05/start.sh >> $LOGDIR/level05.log 2>&1)& 6 | -------------------------------------------------------------------------------- /ctf1/append/root/.profile: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | NOAUTOLOGIN=/etc/sysconfig/noautologin 3 | if [ -f "$NOAUTOLOGIN" ]; then 4 | if [ -s "$NOAUTOLOGIN" ]; then 5 | > "$NOAUTOLOGIN" 6 | exit 7 | fi 8 | else 9 | if [ ! -f /etc/sysconfig/superuser ]; then 10 | clear 11 | #TCUSER="$(cat /etc/sysconfig/tcuser)" 12 | #exec /bin/login -f "$TCUSER" 13 | exec /bin/login -f level00 14 | fi 15 | fi 16 | -------------------------------------------------------------------------------- /ctf1/boot/isolinux/boot.msg: -------------------------------------------------------------------------------- 1 | 2 | _ 3 | ( - Micro Core is distributed with ABSOLUTELY NO WARRANTY. 4 | //\ A Busybox & Fltk minimal desktop. 5 | v_/_ http://www.tinycorelinux.com 6 | 7 | Press to begin or F2, F3, or F4 to view boot options. 8 | Shortcuts for alternative keymaps: fr jp hu 9 | Or you can specify a keymap explicitly: mc kmap=THE_KEYMAP 10 | -------------------------------------------------------------------------------- /ctf1/boot/isolinux/isolinux.cfg: -------------------------------------------------------------------------------- 1 | display boot.msg 2 | default microcore 3 | label microcore 4 | kernel /boot/vmlinuz 5 | append initrd=/boot/core.gz loglevel=3 6 | 7 | label mc 8 | kernel /boot/vmlinuz 9 | append initrd=/boot/core.gz loglevel=3 10 | 11 | label fr 12 | kernel /boot/vmlinuz 13 | append initrd=/boot/core.gz loglevel=3 kmap=azerty/fr 14 | 15 | label jp 16 | kernel /boot/vmlinuz 17 | append initrd=/boot/core.gz loglevel=3 kmap=qwerty/jp106 18 | 19 | label hu 20 | kernel /boot/vmlinuz 21 | append initrd=/boot/core.gz loglevel=3 kmap=qwertz/hu 22 | 23 | implicit 0 24 | prompt 1 25 | timeout 300 26 | F1 boot.msg 27 | F2 f2 28 | F3 f3 29 | F4 f4 30 | -------------------------------------------------------------------------------- /ctf1/code/README: -------------------------------------------------------------------------------- 1 | Stripe Capture the Flag Challenge, 2012 2 | 3 | __ 4 | (__) 5 | ||______________________________ 6 | || | 7 | || _ _ | 8 | || ___| |_ _ __(_)_ __ ___ | 9 | || / __| __| '__| | '_ \ / _ \ | 10 | || \__ \ |_| | | | |_) | __/ | 11 | || |___/\__|_| |_| .__/ \___| | 12 | || |_| | 13 | || | 14 | ||~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 15 | || 16 | || 17 | || 18 | || 19 | 20 | 21 | https://stripe.com/blog/capture-the-flag 22 | https://stripe.com/blog/capture-the-flag-wrap-up 23 | -------------------------------------------------------------------------------- /ctf1/code/levels/level01/Makefile: -------------------------------------------------------------------------------- 1 | all: level01 2 | 3 | level02: 4 | gcc -o level01 level01.c 5 | 6 | clean: 7 | rm level01 8 | -------------------------------------------------------------------------------- /ctf1/code/levels/level01/level01.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main(int argc, char **argv) 5 | { 6 | printf("Current time: "); 7 | fflush(stdout); 8 | system("date"); 9 | return 0; 10 | } 11 | -------------------------------------------------------------------------------- /ctf1/code/levels/level02/level02.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # 3 | import flask 4 | from flask import request, make_response, render_template 5 | import os 6 | import random 7 | import string 8 | 9 | PORT = 8002 10 | 11 | app = flask.Flask(__name__) 12 | 13 | wwwdata_dir = os.path.join(os.path.dirname(__file__), 'wwwdata') 14 | if not os.path.isdir(wwwdata_dir): 15 | os.makedirs(wwwdata_dir) 16 | 17 | 18 | def random_string(length): 19 | return ''.join(random.choice(string.letters) for i in xrange(length)) 20 | 21 | 22 | @app.route('/', methods=['GET', 'POST']) 23 | def index(): 24 | params = {} 25 | if request.method == 'POST': 26 | params['name'] = request.form.get('name') 27 | params['age'] = request.form.get('age') 28 | 29 | user_details = request.cookies.get('user_details') 30 | if not user_details: 31 | params['out'] = 'Looks like a first time user. Hello, there!' 32 | filename = random_string(16) + '.txt' 33 | path = os.path.join(wwwdata_dir, filename) 34 | f = open(path, 'w') 35 | f.write('%s is using %s\n' % (request.remote_addr, request.user_agent)) 36 | resp = make_response(render_template('index.html', **params)) 37 | resp.set_cookie('user_details', filename) 38 | else: 39 | filename = user_details 40 | path = os.path.join(wwwdata_dir, filename) 41 | params['out'] = open(path).read() 42 | resp = make_response(render_template('index.html', **params)) 43 | return resp 44 | 45 | if __name__ == '__main__': 46 | app.run(host='0.0.0.0', port=PORT) 47 | -------------------------------------------------------------------------------- /ctf1/code/levels/level02/templates/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | Level02 4 | 5 | 6 |

Welcome to the challenge!

7 |
8 |

{{ out }}

9 | {% if name and age %} 10 |

You're {{ name }}, and your age is {{ age }}.

11 | {% else %} 12 |
13 | Name:
14 | Age:

15 | 16 |
17 | {% endif %} 18 |
19 | 20 | 21 | -------------------------------------------------------------------------------- /ctf1/code/levels/level03/Makefile: -------------------------------------------------------------------------------- 1 | all: level03 2 | 3 | level03: level03.c 4 | gcc -w -g -o level03 level03.c 5 | 6 | clean: 7 | rm level03 8 | -------------------------------------------------------------------------------- /ctf1/code/levels/level03/level03.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | #define NUM_FNS 4 7 | 8 | typedef int (*fn_ptr)(const char *); 9 | 10 | int to_upper(const char *str) 11 | { 12 | printf("Uppercased string: "); 13 | int i = 0; 14 | for (i; str[i]; i++) 15 | putchar(toupper(str[i])); 16 | printf("\n"); 17 | return 0; 18 | } 19 | 20 | int to_lower(const char *str) 21 | { 22 | printf("Lowercased string: "); 23 | int i = 0; 24 | for (i; str[i]; i++) 25 | putchar(tolower(str[i])); 26 | printf("\n"); 27 | return 0; 28 | } 29 | 30 | int capitalize(const char *str) 31 | { 32 | printf("Capitalized string: "); 33 | putchar(toupper(str[0])); 34 | int i = 1; 35 | for (i; str[i]; i++) 36 | putchar(tolower(str[i])); 37 | printf("\n", str); 38 | return 0; 39 | } 40 | 41 | int length(const char *str) 42 | { 43 | int len = 0; 44 | for (len; str[len]; len++) {} 45 | 46 | printf("Length of string '%s': %d\n", str, len); 47 | return 0; 48 | } 49 | 50 | int run(const char *str) 51 | { 52 | // This function is now deprecated. 53 | return system(str); 54 | } 55 | 56 | int truncate_and_call(fn_ptr *fns, int index, char *user_string) 57 | { 58 | char buf[64]; 59 | // Truncate supplied string 60 | strncpy(buf, user_string, sizeof(buf) - 1); 61 | buf[sizeof(buf) - 1] = '\0'; 62 | return fns[index](buf); 63 | } 64 | 65 | int main(int argc, char **argv) 66 | { 67 | int index; 68 | fn_ptr fns[NUM_FNS] = {&to_upper, &to_lower, &capitalize, &length}; 69 | 70 | if (argc != 3) { 71 | printf("Usage: ./level03 INDEX STRING\n"); 72 | printf("Possible indices:\n[0] to_upper\t[1] to_lower\n"); 73 | printf("[2] capitalize\t[3] length\n"); 74 | exit(-1); 75 | } 76 | 77 | // Parse supplied index 78 | index = atoi(argv[1]); 79 | 80 | if (index >= NUM_FNS) { 81 | printf("Invalid index.\n"); 82 | printf("Possible indices:\n[0] to_upper\t[1] to_lower\n"); 83 | printf("[2] capitalize\t[3] length\n"); 84 | exit(-1); 85 | } 86 | 87 | return truncate_and_call(fns, index, argv[2]); 88 | } 89 | -------------------------------------------------------------------------------- /ctf1/code/levels/level04/Makefile: -------------------------------------------------------------------------------- 1 | all: level04 2 | 3 | level04: 4 | gcc -D_FORTIFY_SOURCE=0 -fno-stack-protector -z execstack -o level04 level04.c 5 | 6 | clean: 7 | rm level04 8 | -------------------------------------------------------------------------------- /ctf1/code/levels/level04/level04.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | void fun(char *str) 6 | { 7 | char buf[1024]; 8 | strcpy(buf, str); 9 | } 10 | 11 | int main(int argc, char **argv) 12 | { 13 | if (argc != 2) { 14 | printf("Usage: ./level04 STRING"); 15 | exit(-1); 16 | } 17 | fun(argv[1]); 18 | printf("Oh no! That didn't work!\n"); 19 | return 0; 20 | } 21 | -------------------------------------------------------------------------------- /ctf1/code/levels/level06/Makefile: -------------------------------------------------------------------------------- 1 | all: level06 2 | 3 | level06: level06.c 4 | gcc -o level06 level06.c 5 | 6 | clean: 7 | rm level06 8 | -------------------------------------------------------------------------------- /ctf1/code/levels/level06/level06.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | char 7 | char_at(char *str, int pos) 8 | { 9 | return pos < strlen(str) ? str[pos] : 0; 10 | } 11 | 12 | void 13 | taunt() 14 | { 15 | if (!fork()) { 16 | execl("/bin/echo", "/bin/echo", "Ha ha, your password is incorrect!", NULL); 17 | exit(1); 18 | } 19 | } 20 | 21 | int 22 | main(int argc, char **argv) 23 | { 24 | char *correct, *guess, *file, guess_char, true_char; 25 | int known_incorrect = 0, i; 26 | FILE *f; 27 | 28 | if (argc != 3) { 29 | fprintf(stderr, "Usage: %s file guess\n\nCompares the contents of a file with a guess, and\nmakes fun of you if you didn't get it right.\n", argv[0]); 30 | exit(1); 31 | } 32 | 33 | file = argv[1]; 34 | guess = argv[2]; 35 | 36 | if (!(correct = malloc(1024))) { 37 | fprintf(stderr, "Error allocating buffer\n"); 38 | exit(1); 39 | } 40 | 41 | if (!(f = fopen(file, "r"))) { 42 | fprintf(stderr, "Error opening file: %s\n", file); 43 | exit(1); 44 | } 45 | 46 | if (!fgets(correct, 1024, f)) { 47 | fprintf(stderr, "Error reading file: %s\n", file); 48 | exit(1); 49 | } 50 | 51 | if (correct[strlen(correct)-1] == '\n') 52 | correct[strlen(correct)-1] = '\0'; 53 | 54 | fprintf(stderr, "Welcome to the password checker!\n"); 55 | 56 | for (i = 0; i < strlen(guess); i++) { 57 | guess_char = char_at(guess, i); 58 | true_char = char_at(correct, i); 59 | fprintf(stderr, "."); 60 | if (!known_incorrect && (guess_char != true_char)) { 61 | known_incorrect = 1; 62 | taunt(); 63 | } 64 | } 65 | 66 | if (!known_incorrect && strlen(guess) != strlen(correct)) { 67 | known_incorrect = 1; 68 | taunt(); 69 | } 70 | 71 | fprintf(stderr, "\n"); 72 | 73 | if (!known_incorrect) { 74 | fprintf(stderr, "Wait, how did you know that the password was %s?\n", correct); 75 | } 76 | 77 | return 0; 78 | } 79 | -------------------------------------------------------------------------------- /ctf1/motd/banner.txt: -------------------------------------------------------------------------------- 1 | _______________________________ 2 | \_ ___ \__ ___/\_ _____/ 3 | / \ \/ | | | __) 4 | \ \____| | | \ 5 | \______ /|____| \___ / 6 | \/ \/ 7 | 8 | -------------------------------------------------------------------------------- /ctf1/motd/level00.txt: -------------------------------------------------------------------------------- 1 | Welcome to the Capture The Flag security challenge! 2 | 3 | This is a security wargame inspired by Stripe.com[1] 4 | 5 | In /home/level01/.password is the password of the level01 user. 6 | Your mission, should you choose to accept it, is to read that 7 | file and login as level01 to advance to the next level. 8 | You may find the files in /levels/level01 useful. 9 | 10 | There are a total of 6 levels in this challenge; your goal is 11 | to advance level by level by discovering and exploiting the 12 | vulnerability at each level until you reach level06, the 13 | final level with the flag and glory! 14 | 15 | Happy hacking! 16 | The ctf-o-matic team 17 | 18 | [1] http://stripe.com/blog/capture-the-flag 19 | -------------------------------------------------------------------------------- /ctf1/motd/level01.txt: -------------------------------------------------------------------------------- 1 | Congratulations on making it to level 1! 2 | 3 | The password for the next level is in /home/level02/.password. This 4 | one is a web-based vulnerability, so go ahead and point your browser 5 | to http://localhost:8002/ 6 | 7 | You can find the source code for this level in /levels/level02/. 8 | Who knows, you may find it useful. 9 | 10 | Best of luck! 11 | -------------------------------------------------------------------------------- /ctf1/motd/level02.txt: -------------------------------------------------------------------------------- 1 | Congratulations on making it to level 2! 2 | 3 | The password for the next level is in /home/level03/.password. As 4 | before, you may find the files in /levels/level03 useful. 5 | While the supplied binary mostly just does mundane tasks, we trust 6 | you'll find a way of making it do something much more interesting. 7 | 8 | Best of luck! 9 | -------------------------------------------------------------------------------- /ctf1/motd/level03.txt: -------------------------------------------------------------------------------- 1 | Congratulations on making it to level 3! 2 | 3 | The password for the next level is in /home/level04/.password. As 4 | before, you may find the files in /levels/level04 useful. 5 | The vulnerabilities overfloweth! 6 | 7 | Best of luck! 8 | -------------------------------------------------------------------------------- /ctf1/motd/level04.txt: -------------------------------------------------------------------------------- 1 | Congratulations on making it to level 4! You're almost done! 2 | 3 | The password for the next (and final) level is in: /home/level05/.password 4 | 5 | As it turns out, level05 is running a public uppercasing service. You 6 | can POST data to it, and it'll uppercase the data for you: 7 | 8 | curl localhost:8005 -d 'hello friend' 9 | { 10 | "processing_time": 5.0067901611328125e-06, 11 | "queue_time": 0.41274619102478027, 12 | "result": "HELLO FRIEND" 13 | } 14 | 15 | You can view the source for this service in /levels/level05. As you 16 | can see, the service is structured as a queue server and a queue 17 | worker. 18 | 19 | Could it be that this seemingly innocuous service will be level05's 20 | downfall? 21 | -------------------------------------------------------------------------------- /ctf1/motd/level05.txt: -------------------------------------------------------------------------------- 1 | Congratulations on making it to level 5! This is the final level. The 2 | flag is almost in your grasp. 3 | 4 | The password for the flag is in /home/level06/.password. 5 | 6 | As it turns out, level06 is a pretty arrogant user. He created a 7 | taunting utility and left it in the directory /levels/level06 8 | This utility will read the first line of a specified file, compare 9 | it with your supplied guess, and taunt you unless you guessed correctly. 10 | 11 | You could try using the taunt utility to brute-force the password, but 12 | that would take... well, I don't want to say forever, but 13 | approximately that. I guess you'll have to find another way. 14 | -------------------------------------------------------------------------------- /ctf1/motd/level06.txt: -------------------------------------------------------------------------------- 1 | __ 2 | (__) 3 | ||_______________________ 4 | || | 5 | || Congratulations !!! | 6 | || | 7 | ||~~~~~~~~~~~~~~~~~~~~~~~ 8 | || 9 | || 10 | || 11 | || 12 | 13 | -------------------------------------------------------------------------------- /ctf1/special/README.md: -------------------------------------------------------------------------------- 1 | Some levels require setuid root privileges to be vulnerable, 2 | however, even if a setuid program can be tricked to executing 3 | external programs like /bin/cat, normally it doesn't work. 4 | For example the system() call executes programs with: 5 | 6 | /bin/sh -c prog 7 | 8 | However, /bin/sh in TinyCore is busybox ash, and it drops 9 | setuid privileges. To circumvent this, we modified the 10 | original contest source codes by inserting this: 11 | 12 | // circumvent busybox ash dropping privileges 13 | uid_t uid = geteuid(); 14 | setreuid(uid, uid); 15 | 16 | A nice side effect of this is that this breaks the 17 | published solutions circulated on the internet, 18 | making it a little bit more difficult to cheat. 19 | -------------------------------------------------------------------------------- /ctf1/special/levels/level01/Makefile: -------------------------------------------------------------------------------- 1 | all: level01 2 | 3 | level02: 4 | gcc -o level01 level01.c 5 | 6 | clean: 7 | rm level01 8 | -------------------------------------------------------------------------------- /ctf1/special/levels/level01/level01.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main(int argc, char **argv) 5 | { 6 | // circumvent busybox ash dropping privileges 7 | uid_t uid = geteuid(); 8 | setreuid(uid, uid); 9 | 10 | printf("Current time: "); 11 | fflush(stdout); 12 | system("date"); 13 | return 0; 14 | } 15 | -------------------------------------------------------------------------------- /ctf1/special/levels/level03/Makefile: -------------------------------------------------------------------------------- 1 | all: level03 2 | 3 | level03: level03.c 4 | gcc -w -g -o level03 level03.c 5 | 6 | clean: 7 | rm level03 8 | -------------------------------------------------------------------------------- /ctf1/special/levels/level03/level03.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | #define NUM_FNS 4 7 | 8 | typedef int (*fn_ptr)(const char *); 9 | 10 | int to_upper(const char *str) 11 | { 12 | printf("Uppercased string: "); 13 | int i = 0; 14 | for (i; str[i]; i++) 15 | putchar(toupper(str[i])); 16 | printf("\n"); 17 | return 0; 18 | } 19 | 20 | int to_lower(const char *str) 21 | { 22 | printf("Lowercased string: "); 23 | int i = 0; 24 | for (i; str[i]; i++) 25 | putchar(tolower(str[i])); 26 | printf("\n"); 27 | return 0; 28 | } 29 | 30 | int capitalize(const char *str) 31 | { 32 | printf("Capitalized string: "); 33 | putchar(toupper(str[0])); 34 | int i = 1; 35 | for (i; str[i]; i++) 36 | putchar(tolower(str[i])); 37 | printf("\n", str); 38 | return 0; 39 | } 40 | 41 | int length(const char *str) 42 | { 43 | int len = 0; 44 | for (len; str[len]; len++) {} 45 | 46 | printf("Length of string '%s': %d\n", str, len); 47 | return 0; 48 | } 49 | 50 | int run(const char *str) 51 | { 52 | // This function is now deprecated. 53 | return system(str); 54 | } 55 | 56 | int truncate_and_call(fn_ptr *fns, int index, char *user_string) 57 | { 58 | char buf[64]; 59 | // Truncate supplied string 60 | strncpy(buf, user_string, sizeof(buf) - 1); 61 | buf[sizeof(buf) - 1] = '\0'; 62 | return fns[index](buf); 63 | } 64 | 65 | int main(int argc, char **argv) 66 | { 67 | int index; 68 | fn_ptr fns[NUM_FNS] = {&to_upper, &to_lower, &capitalize, &length}; 69 | 70 | // circumvent busybox ash dropping privileges 71 | uid_t uid = geteuid(); 72 | setreuid(uid, uid); 73 | 74 | if (argc != 3) { 75 | printf("Usage: ./level03 INDEX STRING\n"); 76 | printf("Possible indices:\n[0] to_upper\t[1] to_lower\n"); 77 | printf("[2] capitalize\t[3] length\n"); 78 | exit(-1); 79 | } 80 | 81 | // Parse supplied index 82 | index = atoi(argv[1]); 83 | 84 | if (index >= NUM_FNS) { 85 | printf("Invalid index.\n"); 86 | printf("Possible indices:\n[0] to_upper\t[1] to_lower\n"); 87 | printf("[2] capitalize\t[3] length\n"); 88 | exit(-1); 89 | } 90 | 91 | return truncate_and_call(fns, index, argv[2]); 92 | } 93 | -------------------------------------------------------------------------------- /ctf1/special/levels/level04/Makefile: -------------------------------------------------------------------------------- 1 | all: level04 2 | 3 | level04: 4 | gcc -D_FORTIFY_SOURCE=0 -fno-stack-protector -z execstack -o level04 level04.c 5 | 6 | clean: 7 | rm level04 8 | -------------------------------------------------------------------------------- /ctf1/special/levels/level04/level04.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | void fun(char *str) 6 | { 7 | char buf[1024]; 8 | strcpy(buf, str); 9 | } 10 | 11 | int main(int argc, char **argv) 12 | { 13 | // circumvent busybox ash dropping privileges 14 | uid_t uid = geteuid(); 15 | setreuid(uid, uid); 16 | 17 | if (argc != 2) { 18 | printf("Usage: ./level04 STRING"); 19 | exit(-1); 20 | } 21 | fun(argv[1]); 22 | printf("Oh no! That didn't work!\n"); 23 | return 0; 24 | } 25 | -------------------------------------------------------------------------------- /images/end.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ctf-o-matic/capture-the-flag/cbed26b321871b78c6656ee020c2687482d6b540/images/end.png -------------------------------------------------------------------------------- /images/start.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ctf-o-matic/capture-the-flag/cbed26b321871b78c6656ee020c2687482d6b540/images/start.png -------------------------------------------------------------------------------- /scripts/build.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh -e 2 | # 3 | # File: 4 | # Purpose: 5 | # 6 | 7 | cd $(dirname "$0"); . ./common.sh; cd .. 8 | 9 | $as_user ./scripts/get-livecd.sh 10 | 11 | sudo ./scripts/unpack-iso.sh 12 | 13 | sudo ./scripts/unpack-squashfs.sh 14 | 15 | sudo ./scripts/setup-ctf1.sh 16 | 17 | # eof 18 | -------------------------------------------------------------------------------- /scripts/clean.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh -e 2 | # 3 | # File: 4 | # Purpose: 5 | # 6 | 7 | cd $(dirname "$0"); . ./common.sh; cd .. 8 | 9 | exit_if_nonroot 10 | 11 | rm -fr $extract $newiso $work_ctf1 12 | 13 | # eof 14 | -------------------------------------------------------------------------------- /scripts/common.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # 3 | # File: common.sh 4 | # Purpose: common configuration and shell functions 5 | # 6 | 7 | # tiny core related 8 | # http://distro.ibiblio.org/tinycorelinux/downloads.html 9 | livecd_url=http://distro.ibiblio.org/tinycorelinux/4.x/x86/release/Core-current.iso 10 | tcz_url=http://distro.ibiblio.org/tinycorelinux/4.x/x86/tcz 11 | 12 | # internally used dirs and paths 13 | work=./work 14 | tcz_dir=$work/tcz 15 | livecd0=$work/livecd.iso 16 | livecd1=$work/remastered.iso 17 | mnt=$work/mnt 18 | extract=$work/extract 19 | newiso=$work/newiso 20 | squashfs=$newiso/boot/core.gz 21 | build_info=$extract/tmp/build.info 22 | 23 | # ctf1 related 24 | ctf1=./ctf1 25 | ctf1_code=$ctf1/code 26 | ctf1_special=$ctf1/special 27 | ctf1_append=$ctf1/append 28 | ctf1_motd=$ctf1/motd 29 | work_ctf1=$work/ctf1 30 | 31 | test "$SUDO_USER" && as_user="sudo -u $SUDO_USER" || as_user= 32 | 33 | 34 | msg() { 35 | echo '[*]' $* 36 | } 37 | 38 | cmd() { 39 | echo '[cmd]' $* 40 | $* 41 | } 42 | 43 | error() { 44 | echo '[E]' $* 45 | exit 1 46 | } 47 | 48 | exit_if_nonroot() { 49 | test $(id -u) = 0 || error this script needs to run as root 50 | } 51 | 52 | get_tcz() { 53 | $as_user mkdir -pv $tcz_dir 54 | for package; do 55 | target=$tcz_dir/$package.tcz 56 | if test ! -f $target; then 57 | msg fetching package $package ... 58 | $as_user curl -o $target $tcz_url/$package.tcz 59 | fi 60 | dep=$target.dep 61 | if test ! -f $dep; then 62 | msg fetching dep list of $package ... 63 | $as_user curl -o $dep $tcz_url/$package.tcz.dep || touch $dep 64 | grep -q 404 $dep && >$dep 65 | if test -s $dep; then 66 | get_tcz $(sed -e s/.tcz$// $dep) 67 | fi 68 | fi 69 | done 70 | } 71 | 72 | install_tcz() { 73 | get_tcz $@ 74 | exit_if_nonroot 75 | for package; do 76 | target=$tcz_dir/$package.tcz 77 | tce_marker=$extract/usr/local/tce.installed/$package 78 | if ! test -f $tce_marker; then 79 | msg installing package $package ... 80 | unsquashfs -f -d $extract $target 81 | if test -s $tce_marker; then 82 | chroot $extract /usr/local/tce.installed/$package 83 | else 84 | touch $tce_marker 85 | fi 86 | fi 87 | dep=$target.dep 88 | if test -s $dep; then 89 | install_tcz $(sed -e s/.tcz$// $dep) 90 | fi 91 | done 92 | } 93 | 94 | 95 | for i in "$@"; do 96 | case "$i" in 97 | -h|--help) usage ; exit 1 ;; 98 | esac 99 | done 100 | 101 | # eof 102 | -------------------------------------------------------------------------------- /scripts/get-livecd.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh -e 2 | # 3 | # File: 4 | # Purpose: 5 | # 6 | 7 | cd $(dirname "$0"); . ./common.sh; cd .. 8 | 9 | mkdir -p $(dirname "$livecd0") 10 | 11 | test -f $livecd0 || cmd curl -o $livecd0 $livecd_url 12 | 13 | # eof 14 | -------------------------------------------------------------------------------- /scripts/install-openssh.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh -e 2 | # 3 | # File: 4 | # Purpose: 5 | # 6 | 7 | cd $(dirname "$0"); . ./common.sh; cd .. 8 | 9 | install_tcz openssh 10 | 11 | exit_if_nonroot 12 | 13 | sshd_config=$extract/usr/local/etc/ssh/sshd_config 14 | test -f $sshd_config || cp $sshd_config.example $sshd_config 15 | 16 | # eof 17 | -------------------------------------------------------------------------------- /scripts/install-python.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh -e 2 | # 3 | # File: 4 | # Purpose: 5 | # 6 | 7 | cd $(dirname "$0"); . ./common.sh; cd .. 8 | 9 | install_tcz python 10 | 11 | exit_if_nonroot 12 | 13 | rm -f $extract/usr/local/share/python/files/files.tar.gz 14 | 15 | # eof 16 | -------------------------------------------------------------------------------- /scripts/install-tcz.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh -e 2 | # 3 | # File: scripts/install-tcz.sh 4 | # Purpose: install tcz packages (using the install_tcz common method) 5 | # 6 | 7 | cd $(dirname "$0"); . ./common.sh; cd .. 8 | 9 | install_tcz $@ 10 | 11 | # eof 12 | -------------------------------------------------------------------------------- /scripts/pack-iso.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh -e 2 | # 3 | # File: 4 | # Purpose: 5 | # 6 | 7 | cd $(dirname "$0"); . ./common.sh; cd .. 8 | 9 | exit_if_nonroot 10 | 11 | # add build info 12 | printf '\n%60s\n' "$(date)" > $build_info 13 | printf '%60s\n\n' "$(git rev-list HEAD -n1)" >> $build_info 14 | boot_msg0=boot/isolinux/boot.msg 15 | cat $ctf1/$boot_msg0 $build_info > $newiso/$boot_msg0 16 | 17 | # detect mkisofs executable, name genisoimage in debian 18 | mkisofs=$(which mkisofs genisoimage blah | head -n 1) 19 | 20 | tmp=$work/squashfs.gz 21 | { cd $extract; find | cpio -o -H newc; } | gzip -2 > $tmp 22 | cmd advdef -z4 $tmp 23 | cmd mv $tmp $squashfs 24 | cmd $mkisofs -l -J -R -V TC-custom -no-emul-boot -boot-load-size 4 \ 25 | -boot-info-table -b boot/isolinux/isolinux.bin \ 26 | -c boot/isolinux/boot.cat -o $livecd1 $newiso 27 | 28 | msg creating $livecd1.md5 29 | md5sum $livecd1 > $livecd1.md5 30 | 31 | msg creating $livecd1.info 32 | (cd $extract; grep . home/*/.password) > $livecd1.info 33 | 34 | # eof 35 | -------------------------------------------------------------------------------- /scripts/rebuild.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh -e 2 | # 3 | # File: 4 | # Purpose: 5 | # 6 | 7 | cd $(dirname "$0"); . ./common.sh; cd .. 8 | 9 | sudo ./scripts/clean.sh 10 | 11 | ./scripts/build.sh 12 | 13 | sudo ./scripts/pack-iso.sh 14 | 15 | # eof 16 | -------------------------------------------------------------------------------- /scripts/setup-ctf1.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh -e 2 | # 3 | # File: 4 | # Purpose: 5 | # 6 | 7 | cd $(dirname "$0"); . ./common.sh; cd .. 8 | 9 | exit_if_nonroot 10 | 11 | # install software 12 | ./scripts/install-python.sh # required by contest 13 | install_tcz curl # hacking tool 14 | install_tcz binutils # hacking tool 15 | install_tcz gdb # hacking tool 16 | install_tcz ruby # hacking tool 17 | install_tcz nano || : # easier editor than vi... 18 | install_tcz kmaps # for international use 19 | ./scripts/install-openssh.sh # just for convenience 20 | 21 | # copy original source codes to work 22 | work_code=$work_ctf1/code/levels 23 | mkdir -p $work_code 24 | rsync -rv $ctf1_code/levels/level* $work_code/ 25 | 26 | work_special=$work_ctf1/special/levels 27 | mkdir -p $work_special 28 | rsync -rv $ctf1_special/levels/level* $work_special/ 29 | 30 | # build programs for i686 31 | for i in $work_code/level*; do 32 | test -f $i/Makefile && (cd $i; $as_user make CFLAGS="-m32") 33 | done 34 | 35 | # build extra programs 36 | for i in $work_special/level*; do 37 | test -f $i/Makefile && (cd $i; $as_user make CFLAGS="-m32") 38 | done 39 | 40 | # create users 41 | create_users0=/tmp/create-users.sh 42 | create_users=$extract$create_users0 43 | for i in 0 1 2 3 4 5 6; do 44 | pass=$(pwgen 8 1) 45 | echo "# level0$i" 46 | echo "adduser -s /bin/sh -u 110$i -D level0$i" 47 | echo "echo level0$i:$pass | chpasswd --md5" 48 | echo "echo $pass > /home/level0$i/.password" 49 | echo 50 | done | tee $create_users 51 | 52 | # add users to groups 53 | for i in 0 1 2 3 4 5; do 54 | echo "addgroup level0$i level0$((i+1))" 55 | done | tee -a $create_users 56 | 57 | # run create user script in chroot 58 | chmod 755 $create_users 59 | chroot $extract $create_users0 60 | rm $create_users 61 | 62 | # copy ctf1 files 63 | mkdir -p $extract/levels/level00 64 | rsync -rv $ctf1_append/* $extract/ 65 | 66 | # copy ctf1 code 67 | rsync -rv $work_code/ $extract/levels 68 | #rsync -rv $work_special/ $extract/levels --exclude '*.c' 69 | rsync -rv $work_special/ $extract/levels 70 | 71 | # fix permissions 72 | chmod -R go-w $extract/home/level0? 73 | chmod -R go-rx $extract/home/level0[1-9] 74 | chmod -R g-s $extract/home/level0? 75 | chmod 0750 $extract/levels/level0? 76 | 77 | # fix ownerships 78 | chown -R 0.50 $extract/root 79 | chown 0.50 $extract/levels 80 | 81 | # create message files 82 | for i in 0 1 2 3 4 5 6; do 83 | cat $ctf1_motd/banner.txt $ctf1_motd/level0$i.txt > $extract/home/level0$i/motd.txt 84 | echo clear >> $extract/home/level0$i/.profile 85 | echo 'cat ~/motd.txt' >> $extract/home/level0$i/.profile 86 | done 87 | 88 | # fix ownerships 89 | for i in 0 1 2 3 4 5 6; do 90 | chown -R 110$i.110$i $extract/home/level0$i 91 | chown -R 110$i.110$i $extract/levels/level0$i 92 | to_setuid=$extract/levels/level0$i/level0$i 93 | test -f $to_setuid && chmod 4755 $to_setuid 94 | done 95 | 96 | # customize boot screen 97 | rsync -rv $ctf1/boot/ $newiso/boot 98 | 99 | # eof 100 | -------------------------------------------------------------------------------- /scripts/unpack-iso.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh -e 2 | # 3 | # File: 4 | # Purpose: 5 | # 6 | 7 | cd $(dirname "$0"); . ./common.sh; cd .. 8 | 9 | exit_if_nonroot 10 | 11 | mkdir -pv $mnt 12 | 13 | if ! ls $squashfs >/dev/null 2>/dev/null; then 14 | mount | grep $livecd0 >/dev/null || cmd mount $livecd0 $mnt 15 | cmd mkdir -p $newiso 16 | cmd rsync -av $mnt/* $newiso/ 17 | cmd umount $mnt 18 | fi 19 | 20 | # eof 21 | -------------------------------------------------------------------------------- /scripts/unpack-squashfs.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh -e 2 | # 3 | # File: 4 | # Purpose: 5 | # 6 | 7 | cd $(dirname "$0"); . ./common.sh; cd .. 8 | 9 | exit_if_nonroot 10 | 11 | if ! ls $extract/proc >/dev/null 2>/dev/null; then 12 | cmd mkdir -p $extract 13 | zcat $squashfs | { cd $extract; cpio -i -H newc -d; } 14 | fi 15 | 16 | # eof 17 | --------------------------------------------------------------------------------