├── president-feedback ├── log │ └── .gitkeep ├── requirements.txt ├── README.md ├── super.conf ├── Dockerfile ├── backend.py ├── devnull.html ├── main.py ├── arifmetics.py └── index.html ├── timehackers ├── checker │ ├── checker.log │ ├── ghostdriver.log │ └── checker.py ├── web │ ├── img │ │ └── hackerman.jpg │ ├── static │ │ ├── .DS_Store │ │ ├── $uper$ecret@dmin.js │ │ └── main.css │ ├── .htaccess │ ├── backgrounds │ │ ├── cloth-alike.png │ │ ├── grey-sandbag.png │ │ ├── kinda-jean.png │ │ ├── white-carbon.png │ │ ├── white-wave.png │ │ ├── polyester-lite.png │ │ ├── stitched-wool.png │ │ └── 45-degree-fabric.png │ ├── fonts │ │ └── times_new_yorker.ttf │ ├── functions.php │ ├── templates │ │ ├── logout.php │ │ └── main.php │ ├── config.php │ ├── api.php │ ├── index.php │ ├── admin.php │ ├── contact.php │ └── simple-php-captcha.php ├── docker_files │ ├── ports.conf │ ├── status.conf │ ├── supervisord.conf │ ├── start.sh │ ├── default │ ├── db_init.sh │ ├── 000-default.conf │ ├── nginx.conf │ └── apache2.conf ├── README.md └── Dockerfile ├── president-blog ├── data │ └── cache │ │ └── .gitkeep ├── config │ ├── autoload │ │ ├── .gitignore │ │ ├── README.md │ │ ├── local.php.dist │ │ ├── development.local.php │ │ ├── global.php │ │ ├── development.local.php.dist │ │ └── zend-developer-tools.local-development.php │ ├── modules.config.php │ ├── development.config.php.dist │ └── application.config.php ├── module │ └── Application │ │ ├── view │ │ ├── application │ │ │ └── index │ │ │ │ ├── qweqwe.phtml │ │ │ │ ├── index.phtml │ │ │ │ ├── blog.phtml │ │ │ │ ├── admin.phtml │ │ │ │ ├── report.phtml │ │ │ │ └── index2.phtml │ │ ├── error │ │ │ ├── index.phtml │ │ │ └── 404.phtml │ │ └── layout │ │ │ └── layout.phtml │ │ ├── src │ │ ├── Service │ │ │ ├── PostsServiceInterface.php │ │ │ └── PostsService.php │ │ ├── Mapper │ │ │ └── PostMapperInterface.php │ │ ├── Model │ │ │ ├── PostsTable.php │ │ │ └── Post.php │ │ ├── Controller │ │ │ ├── Factory │ │ │ │ └── IndexControllerFactory.php │ │ │ └── IndexController.php │ │ ├── Factory │ │ │ └── PostServiceFactory.php │ │ └── Module.php │ │ ├── test │ │ └── Controller │ │ │ └── IndexControllerTest.php │ │ └── config │ │ └── module.config.php ├── public │ ├── img │ │ ├── favicon.ico │ │ └── zf-logo-mark.svg │ ├── fonts │ │ ├── glyphicons-halflings-regular.eot │ │ ├── glyphicons-halflings-regular.ttf │ │ ├── glyphicons-halflings-regular.woff │ │ └── glyphicons-halflings-regular.woff2 │ ├── .htaccess │ ├── css │ │ └── style.css │ ├── web.config │ └── index.php ├── .gitignore ├── README.md ├── database.sh ├── phpunit.xml.dist ├── Dockerfile ├── phpcs.xml ├── composer.json ├── LICENSE.md ├── apache.conf └── file.sql ├── e-voting ├── requirements.txt ├── Dockerfile ├── LEGEND.md ├── solver.py ├── elgamal.py ├── cipher.py ├── server.py └── elgamal_cipher.py ├── signature-server ├── requirements.txt ├── Dockerfile ├── LEGEND.md ├── README.md ├── solver.py ├── server.py └── crypto.py ├── README.md ├── election-department-service ├── src │ ├── sandbox.h │ ├── heap.h │ ├── service.h │ ├── utils.h │ ├── candidate.h │ ├── io.h │ ├── Makefile │ ├── sandbox.c │ ├── io.c │ ├── hashtable.h │ ├── utils.c │ ├── hashtable.c │ ├── service.c │ └── heap.c ├── flag.txt ├── pwn ├── pwn-strip └── Dockerfile ├── pq-messenger ├── gradle │ └── wrapper │ │ ├── gradle-wrapper.jar │ │ └── gradle-wrapper.properties ├── Dockerfile ├── src │ └── main │ │ └── java │ │ └── task │ │ ├── ProtocolException.java │ │ ├── Messages.java │ │ ├── Server.java │ │ ├── Handler.java │ │ ├── Protocol.java │ │ └── Main.java ├── LEGEND.md ├── build.gradle ├── README.md ├── gradlew.bat └── gradlew └── mprsa ├── flag.txt ├── LEGEND.md ├── deploy.py ├── solver.py └── mprsa.py /president-feedback/log/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /timehackers/checker/checker.log: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /president-blog/data/cache/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /timehackers/checker/ghostdriver.log: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /e-voting/requirements.txt: -------------------------------------------------------------------------------- 1 | curio 2 | pycrypto -------------------------------------------------------------------------------- /president-blog/config/autoload/.gitignore: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /signature-server/requirements.txt: -------------------------------------------------------------------------------- 1 | curio==0.7 2 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # 2017-quals 2 | Tasks from CTFZone 2017 quals 3 | -------------------------------------------------------------------------------- /election-department-service/src/sandbox.h: -------------------------------------------------------------------------------- 1 | void setup_sandbox(); -------------------------------------------------------------------------------- /president-feedback/requirements.txt: -------------------------------------------------------------------------------- 1 | pyfiglet 2 | sanic 3 | curio 4 | -------------------------------------------------------------------------------- /election-department-service/flag.txt: -------------------------------------------------------------------------------- 1 | ctfzone{b2535d40b6049a005bf3011429b1cd7a} 2 | -------------------------------------------------------------------------------- /signature-server/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM python:3.6-onbuild 2 | CMD ["python", "server.py"] 3 | -------------------------------------------------------------------------------- /president-blog/module/Application/view/application/index/qweqwe.phtml: -------------------------------------------------------------------------------- 1 | myVar; ?> -------------------------------------------------------------------------------- /election-department-service/pwn: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ctf-zone/2017-quals/HEAD/election-department-service/pwn -------------------------------------------------------------------------------- /timehackers/web/img/hackerman.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ctf-zone/2017-quals/HEAD/timehackers/web/img/hackerman.jpg -------------------------------------------------------------------------------- /timehackers/web/static/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ctf-zone/2017-quals/HEAD/timehackers/web/static/.DS_Store -------------------------------------------------------------------------------- /timehackers/web/.htaccess: -------------------------------------------------------------------------------- 1 | options -Indexes 2 | Header unset Pragma 3 | Header unset Cache-Control 4 | Header unset Expires 5 | -------------------------------------------------------------------------------- /election-department-service/pwn-strip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ctf-zone/2017-quals/HEAD/election-department-service/pwn-strip -------------------------------------------------------------------------------- /president-blog/public/img/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ctf-zone/2017-quals/HEAD/president-blog/public/img/favicon.ico -------------------------------------------------------------------------------- /election-department-service/src/heap.h: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void *alloc(size_t size); 4 | 5 | void release(void *p); 6 | -------------------------------------------------------------------------------- /president-blog/.gitignore: -------------------------------------------------------------------------------- 1 | .vagrant/ 2 | vendor/ 3 | config/development.config.php 4 | data/cache/* 5 | !data/cache/.gitkeep 6 | phpunit.xml 7 | -------------------------------------------------------------------------------- /timehackers/web/backgrounds/cloth-alike.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ctf-zone/2017-quals/HEAD/timehackers/web/backgrounds/cloth-alike.png -------------------------------------------------------------------------------- /timehackers/web/backgrounds/grey-sandbag.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ctf-zone/2017-quals/HEAD/timehackers/web/backgrounds/grey-sandbag.png -------------------------------------------------------------------------------- /timehackers/web/backgrounds/kinda-jean.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ctf-zone/2017-quals/HEAD/timehackers/web/backgrounds/kinda-jean.png -------------------------------------------------------------------------------- /timehackers/web/backgrounds/white-carbon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ctf-zone/2017-quals/HEAD/timehackers/web/backgrounds/white-carbon.png -------------------------------------------------------------------------------- /timehackers/web/backgrounds/white-wave.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ctf-zone/2017-quals/HEAD/timehackers/web/backgrounds/white-wave.png -------------------------------------------------------------------------------- /timehackers/web/fonts/times_new_yorker.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ctf-zone/2017-quals/HEAD/timehackers/web/fonts/times_new_yorker.ttf -------------------------------------------------------------------------------- /pq-messenger/gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ctf-zone/2017-quals/HEAD/pq-messenger/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /timehackers/web/backgrounds/polyester-lite.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ctf-zone/2017-quals/HEAD/timehackers/web/backgrounds/polyester-lite.png -------------------------------------------------------------------------------- /timehackers/web/backgrounds/stitched-wool.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ctf-zone/2017-quals/HEAD/timehackers/web/backgrounds/stitched-wool.png -------------------------------------------------------------------------------- /president-feedback/README.md: -------------------------------------------------------------------------------- 1 | # Deploy 2 | ``` 3 | sudo docker build -t web-pwn . 4 | sudo docker run -d -p 8000:8000 --name web-pwn web-pwn 5 | ``` 6 | -------------------------------------------------------------------------------- /timehackers/web/backgrounds/45-degree-fabric.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ctf-zone/2017-quals/HEAD/timehackers/web/backgrounds/45-degree-fabric.png -------------------------------------------------------------------------------- /e-voting/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM python:3 2 | 3 | ADD . /usr/src 4 | WORKDIR /usr/src 5 | 6 | RUN pip3 install --no-cache-dir -r requirements.txt 7 | 8 | CMD ["python", "server.py"] -------------------------------------------------------------------------------- /president-blog/public/fonts/glyphicons-halflings-regular.eot: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ctf-zone/2017-quals/HEAD/president-blog/public/fonts/glyphicons-halflings-regular.eot -------------------------------------------------------------------------------- /president-blog/public/fonts/glyphicons-halflings-regular.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ctf-zone/2017-quals/HEAD/president-blog/public/fonts/glyphicons-halflings-regular.ttf -------------------------------------------------------------------------------- /president-blog/public/fonts/glyphicons-halflings-regular.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ctf-zone/2017-quals/HEAD/president-blog/public/fonts/glyphicons-halflings-regular.woff -------------------------------------------------------------------------------- /president-blog/public/fonts/glyphicons-halflings-regular.woff2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ctf-zone/2017-quals/HEAD/president-blog/public/fonts/glyphicons-halflings-regular.woff2 -------------------------------------------------------------------------------- /president-blog/README.md: -------------------------------------------------------------------------------- 1 | # Deploy 2 | To run container 3 | ``` 4 | sudo docker build -t web-300 . 5 | sudo docker run -d -p 80:80 --name web-300 web-300 '/var/www/database.sh' 6 | ``` 7 | -------------------------------------------------------------------------------- /timehackers/docker_files/ports.conf: -------------------------------------------------------------------------------- 1 | Listen 8080 2 | 3 | 4 | Listen 443 5 | 6 | 7 | 8 | Listen 443 9 | 10 | -------------------------------------------------------------------------------- /election-department-service/src/service.h: -------------------------------------------------------------------------------- 1 | #define CHECK 1 2 | #define STORE 2 3 | #define DELETE 3 4 | #define LIST 4 5 | #define VOTE 5 6 | 7 | void service_loop(int *pipefd); 8 | -------------------------------------------------------------------------------- /election-department-service/src/utils.h: -------------------------------------------------------------------------------- 1 | int send_string(int fd, const char *string); 2 | 3 | char *recv_string(int fd); 4 | 5 | char *sec_recv_string(int fd); 6 | 7 | void sec_exit(int ret); -------------------------------------------------------------------------------- /timehackers/docker_files/status.conf: -------------------------------------------------------------------------------- 1 | 2 | 3 | Order Deny,Allow 4 | Deny from all 5 | 6 | -------------------------------------------------------------------------------- /timehackers/web/functions.php: -------------------------------------------------------------------------------- 1 | %s", $error); 5 | exit(); 6 | } 7 | ?> -------------------------------------------------------------------------------- /election-department-service/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM ubuntu:16.04 2 | 3 | COPY pwn-strip /usr/bin 4 | COPY flag.txt /home 5 | 6 | RUN apt-get update && apt-get install -y socat 7 | CMD ["socat", "tcp-listen:1337,reuseaddr,fork", "exec:pwn-strip"] 8 | -------------------------------------------------------------------------------- /president-blog/database.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | service postgresql start 3 | su -c 'psql -c "create database task200" && psql task200 < file.sql' postgres 4 | service postfix start 5 | service apache2 start 6 | tail -f /var/log/apache2/access.log -------------------------------------------------------------------------------- /mprsa/flag.txt: -------------------------------------------------------------------------------- 1 | Mr.D (12:10): 2 | Okey, see you later ;) 3 | 4 | Mr.D (19:30): 5 | So can you help me? 6 | 7 | Anonymous (19:31): 8 | Yeah, we will have 10,000 falsified voters. Transfer 100000$ to my bank account: ctfzone{3177809746931830} 9 | -------------------------------------------------------------------------------- /pq-messenger/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM openjdk:8 2 | ADD ./build/distributions/pq-messenger.tar /usr/src/ 3 | COPY ./keys /usr/src/pq-messenger/keys 4 | 5 | WORKDIR /usr/src/pq-messenger 6 | CMD ["./bin/pq-messenger", "start", "-keysdir", "./keys"] 7 | 8 | -------------------------------------------------------------------------------- /president-blog/module/Application/src/Service/PostsServiceInterface.php: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | 4 | size_t fprint_string(int fd, const char *str); 5 | 6 | size_t print_string(const char *str); 7 | 8 | size_t read_string(char *str, size_t len); 9 | 10 | size_t read_int(); 11 | -------------------------------------------------------------------------------- /pq-messenger/gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Thu Jun 01 21:25:38 MSK 2017 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=https\://services.gradle.org/distributions/gradle-3.5-bin.zip 7 | -------------------------------------------------------------------------------- /president-blog/phpunit.xml.dist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | ./module/Application/test 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /election-department-service/src/Makefile: -------------------------------------------------------------------------------- 1 | CFLAGS = -Wall -Werror 2 | 3 | SRC = $(wildcard *.c) 4 | 5 | pwn: $(SRC) 6 | gcc -o $@ $^ $(CFLAGS) -g 7 | 8 | pwn-debug: $(SRC) 9 | gcc -o $@ $^ $(CFLAGS) -DDEBUG -g 10 | 11 | pwn-strip: $(SRC) 12 | gcc -o $@ $^ $(CFLAGS) -s 13 | 14 | .PHONY: pwn pwn-debug 15 | -------------------------------------------------------------------------------- /signature-server/LEGEND.md: -------------------------------------------------------------------------------- 1 | We managed to obtain the source codes of our rival's digital signature service. Is it possible to get their secret key? 2 | 3 | Server address: `185.143.173.36:1337` 4 | Server source codes: [source.zip]() 5 | Flag format: `ctfzone{SECRET.decode('hex')}` 6 | 7 | FLAG: `ctfzone{Y0uAr3G00dAtL477!c35}` 8 | -------------------------------------------------------------------------------- /timehackers/web/templates/logout.php: -------------------------------------------------------------------------------- 1 | 7 | Success! Session has been cleared. 8 | 9 | '; 10 | header("Refresh: 2; url=admin.php"); 11 | } -------------------------------------------------------------------------------- /timehackers/docker_files/supervisord.conf: -------------------------------------------------------------------------------- 1 | [supervisord] 2 | [supervisord] 3 | logfile = /tmp/supervisord.log 4 | logfile_maxbytes = 50MB 5 | nodaemon=true 6 | 7 | [program:nginx] 8 | command=/usr/sbin/nginx -g "daemon off;" 9 | 10 | [program:apache2] 11 | command=/usr/sbin/apache2ctl -DFOREGROUND 12 | 13 | [program:mysqld] 14 | command=/etc/init.d/mysqld start -------------------------------------------------------------------------------- /pq-messenger/LEGEND.md: -------------------------------------------------------------------------------- 1 | We suspect that our rivals' attempts to create quantum computer. 2 | Due to this we decided to use new encrypted messaging system which is based 3 | on post-quantum algorithms. We have a beta version of this system and we 4 | need you to test it. 5 | 6 | Server address: `78.155.219.232:1337` 7 | Server source codes: [source.zip]() 8 | 9 | FLAG: `ctfzone{4r3_y0u_r34dy_f0r_p057-qu4n7um_w0r1d?}` -------------------------------------------------------------------------------- /president-blog/module/Application/view/application/index/index.phtml: -------------------------------------------------------------------------------- 1 |
2 |

Blog of Mr. Future President

3 | 4 |

5 | Congratulations! You are reading the best blog in the world 6 | 7 |

8 | 9 |

Also we have twitter »

10 |
-------------------------------------------------------------------------------- /president-blog/config/autoload/README.md: -------------------------------------------------------------------------------- 1 | About this directory: 2 | ===================== 3 | 4 | By default, this application is configured to load all configs in 5 | `./config/autoload/{,*.}{global,local}.php`. Doing this provides a 6 | location for a developer to drop in configuration override files provided by 7 | modules, as well as cleanly provide individual, application-wide config files 8 | for things like database connections, etc. 9 | -------------------------------------------------------------------------------- /signature-server/README.md: -------------------------------------------------------------------------------- 1 | # Start 2 | 3 | ```sh 4 | SECRET=x python server.py 5 | ``` 6 | 7 | # Docker 8 | 9 | ## Build 10 | 11 | ```sh 12 | docker build -t signature-server . 13 | ``` 14 | 15 | ## Run 16 | 17 | ```sh 18 | docker run -d \ 19 | -p 1337:1337 \ 20 | --restart=always \ 21 | -e SECRET=509180828780457295905677127542596834069749904181 \ 22 | --name signature-server \ 23 | signature-server 24 | ``` 25 | -------------------------------------------------------------------------------- /pq-messenger/src/main/java/task/Messages.java: -------------------------------------------------------------------------------- 1 | package task; 2 | 3 | class Messages { 4 | public static final String HELLO = 5 | "-----------------------------\n" + 6 | "Post-Quantum messaging system\n"; 7 | 8 | public static final String MENU = 9 | "-----------------------------\n" + 10 | "Options:\n" + 11 | " [S]end message\n" + 12 | " [Q]uit\n" + 13 | "-> "; 14 | } 15 | -------------------------------------------------------------------------------- /mprsa/LEGEND.md: -------------------------------------------------------------------------------- 1 | We suspect that one of the candidates plans to bribe people in order to get more votes. We have intercepted a part of his correspondence but, unfortunately, all messages are encrypted. Our man from this election campaign has informed us that they use MPRSA cryptosystem for secure communication. 2 | 3 | * Cryptosystem in use: [mprsa.py](mprsa.py) 4 | * Candidate public data: [public.txt](public.txt) 5 | * Encrypted message: [data.enc](data.enc) -------------------------------------------------------------------------------- /timehackers/web/config.php: -------------------------------------------------------------------------------- 1 | connect_errno) 14 | { 15 | printf("Error while connecting to DB. Report about it to orgs!"); 16 | exit(-1); 17 | } 18 | ?> 19 | -------------------------------------------------------------------------------- /timehackers/web/static/$uper$ecret@dmin.js: -------------------------------------------------------------------------------- 1 | function get_password(username) { 2 | $.ajax({ 3 | type: "POST", 4 | url: "/api.php", 5 | data: {"token":csrf_token,"action":"get_password","username":username}, 6 | dataType: "json", 7 | success:function (data) { 8 | if (data["error"] === '') 9 | { 10 | $("#" + username).text(data["result"]); 11 | } 12 | else 13 | alert('Error: ' + data["error"]); 14 | } 15 | }); 16 | } 17 | -------------------------------------------------------------------------------- /president-blog/module/Application/src/Mapper/PostMapperInterface.php: -------------------------------------------------------------------------------- 1 | /dev/null 5 | echo 'Starting apache2..' 6 | service apache2 start 2>/dev/null 7 | echo 'Starting mysql..' 8 | service mysql start 2>/dev/null 9 | echo 'Starting checker..' 10 | sudo -u checker nohup /home/checker/checker.py > /home/checker/checker.log 2>/home/checker/checker.log & 11 | 12 | trap 'printf "\nBye!"; exit;' SIGINT SIGTERM 13 | printf '\nEntering loop. Press Ctrl+C for exit!\n\n...' 14 | while : 15 | do 16 | sleep 1 17 | done -------------------------------------------------------------------------------- /election-department-service/src/sandbox.c: -------------------------------------------------------------------------------- 1 | #include "sandbox.h" 2 | 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | 9 | void setup_sandbox() 10 | { 11 | #ifndef DEBUG 12 | if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0)) 13 | { 14 | perror("prctl(NO_NEW_PRIVS)"); 15 | exit(EXIT_FAILURE); 16 | } 17 | 18 | if (prctl(PR_SET_SECCOMP, SECCOMP_MODE_STRICT)) 19 | { 20 | perror("prctl(PR_SET_SECCOMP)"); 21 | exit(EXIT_FAILURE); 22 | } 23 | #endif 24 | } 25 | -------------------------------------------------------------------------------- /president-blog/module/Application/view/application/index/blog.phtml: -------------------------------------------------------------------------------- 1 |
2 | posts as $post): ?> 3 |
4 |
5 |
6 |

title; ?>

7 |
8 |
9 |

10 | body; ?> 11 |

12 | 13 |
14 |
15 |
16 | 17 | 18 | 19 | 20 | 21 |
-------------------------------------------------------------------------------- /president-blog/config/autoload/local.php.dist: -------------------------------------------------------------------------------- 1 | zf-logo-mark -------------------------------------------------------------------------------- /president-blog/config/modules.config.php: -------------------------------------------------------------------------------- 1 | 2 |
3 |
4 |

Login:

5 |

6 |

Password:

7 |

8 |

9 | error): ?> 10 |
Wrong password
11 | 12 |
13 |
14 | -------------------------------------------------------------------------------- /pq-messenger/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'java' 2 | apply plugin: 'application' 3 | 4 | mainClassName = 'task.Main' 5 | sourceCompatibility = 1.8 6 | targetCompatibility = 1.8 7 | 8 | repositories { 9 | jcenter() 10 | } 11 | 12 | dependencies { 13 | compile 'org.bouncycastle:bcprov-jdk15on:1.57' 14 | compile 'com.typesafe.akka:akka-actor_2.11:2.5.2' 15 | compile 'com.beust:jcommander:1.72' 16 | } 17 | 18 | compileJava { 19 | options.encoding = 'UTF-8' 20 | options.compilerArgs << "-Xlint:unchecked" << "-Xlint:deprecation" 21 | } 22 | 23 | run { 24 | if (project.hasProperty("appArgs")) { 25 | args Eval.me(appArgs) 26 | } 27 | } 28 | 29 | jar { 30 | baseName = 'task' 31 | } 32 | -------------------------------------------------------------------------------- /president-blog/module/Application/src/Service/PostsService.php: -------------------------------------------------------------------------------- 1 | 1, 11 | 'title' => 'Hello World #1', 12 | 'text' => 'This is our first blog post!' 13 | ) 14 | ); 15 | protected $postMapper; 16 | 17 | // public function __construct(PostMapperInterface $postMapper) 18 | // { 19 | // $this->postMapper = $postMapper; 20 | // } 21 | 22 | 23 | 24 | 25 | public function findAllPosts() 26 | { 27 | return "array()"; 28 | // return $this->postMapper->findAll(); 29 | } 30 | } -------------------------------------------------------------------------------- /president-feedback/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM python:3 2 | 3 | ADD . /web-pwn 4 | WORKDIR /web-pwn 5 | 6 | RUN apt-get update && apt-get install -y supervisor && sed -i 's/^\(\[supervisord\]\)$/\1\nnodaemon=true/' /etc/supervisor/supervisord.conf 7 | RUN pip3 install --no-cache-dir -r requirements.txt && useradd -ms /bin/bash task 8 | RUN cp super.conf /etc/supervisor/conf.d \ 9 | && touch /web-pwn/access.log \ 10 | && touch /web-pwn/error.log \ 11 | && chown -R task:task /web-pwn/access.log \ 12 | && chown -R task:task /web-pwn/error.log \ 13 | && chown -R task:task /web-pwn/log 14 | 15 | CMD ["/usr/bin/supervisord", "-c", "/etc/supervisor/supervisord.conf"] 16 | #CMD ["supervisorctl", "reload"] 17 | #CMD ["python", "backend.py"] 18 | -------------------------------------------------------------------------------- /president-blog/config/development.config.php.dist: -------------------------------------------------------------------------------- 1 | [ 11 | ], 12 | // Configuration overrides during development mode 13 | 'module_listener_options' => [ 14 | 'config_glob_paths' => [realpath(__DIR__) . '/autoload/{,*.}{global,local}-development.php'], 15 | 'config_cache_enabled' => false, 16 | 'module_map_cache_enabled' => false, 17 | ], 18 | ]; 19 | -------------------------------------------------------------------------------- /pq-messenger/README.md: -------------------------------------------------------------------------------- 1 | # Build 2 | 3 | ```sh 4 | ./gradlew build 5 | ./gradlew distTar 6 | ``` 7 | 8 | # Usage 9 | 10 | ## Generate keys 11 | 12 | ```sh 13 | ./gradlew run -PappArgs="['genkeys', '-outdir', './keys']" 14 | ``` 15 | 16 | ## Encrypt data 17 | 18 | ```sh 19 | ./gradlew run -PappArgs="['encrypt', '-keysdir', './keys', 'ctfzone{4r3_y0u_r34dy_f0r_p057-qu4n7um_w0r1d?}']" 20 | ``` 21 | 22 | ## Start server 23 | 24 | ```sh 25 | ./gradlew run -PappArgs="['start', '-keysdir', './keys']" 26 | ``` 27 | 28 | # Docker 29 | 30 | ## Build 31 | 32 | Before this you need to build distributive and generate keys. 33 | 34 | ```sh 35 | docker build -t pq-messenger . 36 | ``` 37 | 38 | ## Run 39 | 40 | ```sh 41 | docker run -d -p 1337:1337 --name pq-messenger pq-messenger 42 | ``` 43 | -------------------------------------------------------------------------------- /e-voting/LEGEND.md: -------------------------------------------------------------------------------- 1 | Organizers use this application for votes encryption. Each vote is a piece of data that looks like [‘ID’: x; ‘VOTE’: ‘ctfzone{xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx}’], where ID – user identifier, VOTE – elector identifier. 2 | 3 | We were informed that one user managed to vote for one candidate several times. Unfortunately, we cannot decrypt the votes and organizers refuse to assist. Please, help to understand who has this guy voted for. 4 | 5 | The security of this cryptosystem is based on the difficulty of finding discrete logarithms modulo a large prime. The system parameters consist of a prime P and an integer G, whose powers modulo P generate a large number of elements, as in Diffie-Hellman. Application has next functions: 6 | 7 | * Encrypt: encrypt(int(ptext, 16)) 8 | * Decrypt: format(decrypt(int(ctext)), "x") -------------------------------------------------------------------------------- /president-blog/public/.htaccess: -------------------------------------------------------------------------------- 1 | RewriteEngine On 2 | # The following rule tells Apache that if the requested filename 3 | # exists, simply serve it. 4 | RewriteCond %{REQUEST_FILENAME} -s [OR] 5 | RewriteCond %{REQUEST_FILENAME} -l [OR] 6 | RewriteCond %{REQUEST_FILENAME} -d 7 | RewriteRule ^.*$ - [L] 8 | # The following rewrites all other queries to index.php. The 9 | # condition ensures that if you are using Apache aliases to do 10 | # mass virtual hosting or installed the project in a subdirectory, 11 | # the base path will be prepended to allow proper resolution of 12 | # the index.php file; it will work in non-aliased environments 13 | # as well, providing a safe, one-size fits all solution. 14 | RewriteCond %{REQUEST_URI}::$1 ^(/.+)/(.*)::\2$ 15 | RewriteRule ^(.*) - [E=BASE:%1] 16 | RewriteRule ^(.*)$ %{ENV:BASE}/index.php [L] 17 | -------------------------------------------------------------------------------- /timehackers/web/static/main.css: -------------------------------------------------------------------------------- 1 | .navbar-dark { 2 | background-color: #303030; 3 | border-color: transparent; 4 | } 5 | 6 | .container-body { 7 | width: 700px; 8 | } 9 | 10 | .footer { 11 | text-align: center; 12 | } 13 | 14 | .panel-search { 15 | padding-top: 15px; 16 | padding-left: 10px; 17 | padding-bottom: 0px; 18 | } 19 | 20 | .search-input { 21 | height: 30px; 22 | } 23 | 24 | .search-button { 25 | height: 30px; 26 | width: 150px; 27 | padding-top: 3px; 28 | padding-bottom: 3px; 29 | } 30 | 31 | .search-form-control { 32 | height: 30px; 33 | padding-top: 3px; 34 | padding-bottom: 3px; 35 | } 36 | 37 | .navbar-admin { 38 | #display: inline-block; 39 | float: none; 40 | vertical-align: top; 41 | } 42 | 43 | .navbar-collapse-admin { 44 | text-align: center; 45 | } 46 | 47 | textarea.form-control { 48 | resize: none; 49 | } -------------------------------------------------------------------------------- /timehackers/README.md: -------------------------------------------------------------------------------- 1 | ## Task text: 2 | 3 | Luckily, we were able to trace multiple attacks on our servers during the election campaign back to the hacker group. Now you have to hack their website and figure out who they are and whom they are working for. Here is their website: 4 | 5 | - http://timehackers.ctf-zone.org:80/ 6 | - http://timehackers.ctf-zone.org:8080/ 7 | 8 | ## How to run task using docker container: 9 | 10 | 1. Create image 11 | 12 | ``` 13 | docker build --tag=timehackers --no-cache . 14 | ``` 15 | 16 | 2. Run docker image 17 | 18 | ``` 19 | docker run -p 8080:8080 -p 80:80 timehackers 20 | ``` 21 | 22 | 3. Edit /etc/hosts 23 | 24 | ``` 25 | $SERVER_IP$ timehackers.ctf-zone.org 26 | ``` 27 | 28 | Where **$SERVER_IP$** - IP of your host server. 29 | 30 | ## Flag: 31 | 32 | Flag: 33 | 34 | ``` 35 | ctfzone{b3_c@R3fuL_w17h_C@cH1ng} 36 | ``` 37 | 38 | ## Solution: 39 | 40 | Will be here later ;) -------------------------------------------------------------------------------- /president-blog/module/Application/src/Model/PostsTable.php: -------------------------------------------------------------------------------- 1 | adapter = $adapter; 14 | } 15 | 16 | public function fetchAll() { 17 | $resultSet = $this->select(function (Select $select) { 18 | $select->order('created ASC'); 19 | }); 20 | // $entities = array(); 21 | // foreach ($resultSet as $row) { 22 | // $entity = new Entity\StickyNote(); 23 | // $entity->setId($row->id) 24 | // ->setNote($row->note) 25 | // ->setCreated($row->created); 26 | // $entities[] = $entity; 27 | // } 28 | return array(); 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /president-blog/module/Application/src/Controller/Factory/IndexControllerFactory.php: -------------------------------------------------------------------------------- 1 | get('config'); 21 | $sm = $container->get(SessionManager::class); 22 | $sm->start(); 23 | Container::setDefaultManager($sm); 24 | 25 | $containter = new Container('ContainerNamespace', $sm); 26 | 27 | $db = new Adapter($config['db']); 28 | return new IndexController($db, $sm, $containter); 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /president-blog/module/Application/src/Factory/PostServiceFactory.php: -------------------------------------------------------------------------------- 1 | get('Appliaction\Mapper\PostMapperInterface') 21 | ); 22 | } 23 | public function __invoke(ContainerInterface $container, $requestedName, array $options = null) 24 | { 25 | // get your dependency 26 | $postService = $container->get(AlbumTable::class),; 27 | // inject it int the constructor 28 | return new IndexController($postService); 29 | } 30 | } -------------------------------------------------------------------------------- /president-blog/public/css/style.css: -------------------------------------------------------------------------------- 1 | body { 2 | padding-top: 60px; 3 | padding-bottom: 40px; 4 | } 5 | 6 | .zf-green { 7 | color: #68b604; 8 | } 9 | 10 | .btn-success { 11 | background-color: #57a900; 12 | background-image: -moz-linear-gradient(top, #70d900, #57a900); 13 | background-image: -ms-linear-gradient(top, #70d900, #57a900); 14 | background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#70d900), to(#57a900)); 15 | background-image: -webkit-linear-gradient(top, #70d900, #57a900); 16 | background-image: -o-linear-gradient(top, #70d900, #57a900); 17 | background-image: linear-gradient(top, #70d900, #57a900); 18 | filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#70d900', endColorstr='#57a900', GradientType=0); 19 | } 20 | 21 | .btn-success:hover, 22 | .btn-success:active, 23 | .btn-success.active, 24 | .btn-success.disabled, 25 | .btn-success[disabled] { 26 | background-color: #57a900; 27 | } 28 | 29 | div.container a.navbar-brand > img { 30 | display: inline; 31 | margin-right: 4px; 32 | margin-top: -2px; 33 | } 34 | -------------------------------------------------------------------------------- /election-department-service/src/io.c: -------------------------------------------------------------------------------- 1 | #include "io.h" 2 | 3 | #include 4 | #include 5 | 6 | size_t fprint_string(int fd, const char *str) 7 | { 8 | if (str == NULL) 9 | return 0; 10 | 11 | size_t len = strlen(str); 12 | return write(fd, str, len); 13 | } 14 | 15 | size_t print_string(const char *str) 16 | { 17 | return fprint_string(STDOUT_FILENO, str); 18 | } 19 | 20 | size_t read_string(char *str, size_t len) 21 | { 22 | char chr; 23 | size_t cur_len = 0; 24 | 25 | while (cur_len < len) 26 | { 27 | int res = read(STDIN_FILENO, &chr, 1); 28 | if (res < 0) 29 | break; 30 | 31 | if (chr == '\n') 32 | break; 33 | 34 | str[cur_len] = chr; 35 | cur_len += res; 36 | } 37 | 38 | // One byte overflow here 39 | str[cur_len] = '\0'; 40 | 41 | return cur_len; 42 | } 43 | 44 | size_t read_int() 45 | { 46 | char str[32]; 47 | read_string(str, sizeof(str)); 48 | return strtoull(str, NULL, 10); 49 | } 50 | -------------------------------------------------------------------------------- /president-blog/module/Application/view/application/index/report.phtml: -------------------------------------------------------------------------------- 1 |
2 |
3 |
4 |

Email will be generated and sent with following parametrs

5 |

Destination:

6 |

Subject:

7 |

Encoding:

8 | 9 |

10 | sent === "yes"): ?> 11 |
Email was sent
12 | 13 | sent === "no"): ?> 14 |
Email was not sent
15 | 16 |
17 |
18 |
19 | -------------------------------------------------------------------------------- /president-feedback/backend.py: -------------------------------------------------------------------------------- 1 | import re 2 | from curio import run, tcp_server 3 | from pyfiglet import Figlet 4 | 5 | 6 | def supported_operations(): 7 | return {"+", "-", "*", "//"} 8 | 9 | 10 | def translate(s): 11 | return Figlet().renderText(s) 12 | 13 | 14 | reg = re.compile(r"\d+\s?(%s)\s?\d+" % "|".join("\%s" % c for c in supported_operations())) 15 | 16 | 17 | async def echo_client(client, addr): 18 | while True: 19 | data = await client.recv(100000) 20 | 21 | op = data.decode().split(" ", 1)[0].strip() 22 | if op == "translate": 23 | expr = data.decode().split(" ", 1)[-1].strip() 24 | if reg.match(expr): 25 | res = translate(expr) 26 | else: 27 | res = "ERROR Not supported expression" 28 | elif op == "supported_operations": 29 | res = " ".join(supported_operations()) 30 | else: 31 | res = "ERROR no such method" 32 | await client.sendall((res + "\n").encode()) 33 | 34 | 35 | if __name__ == '__main__': 36 | run(tcp_server, '', 25000, echo_client) 37 | -------------------------------------------------------------------------------- /president-blog/phpcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | Zend Framework coding standard 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | public/index.php 26 | 27 | 28 | 29 | config 30 | module 31 | public/index.php 32 | 33 | -------------------------------------------------------------------------------- /election-department-service/src/hashtable.h: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | typedef struct hashtable * hashtable_t; 4 | typedef struct iterator * iterator_t; 5 | 6 | hashtable_t hashtable_create(size_t capacity, 7 | size_t (*hash)(const void *key), 8 | int (*equals)(const void *key1, const void *key2), 9 | void (*release)(void *key, void *data)); 10 | 11 | void hashtable_reset(hashtable_t hashtable); 12 | 13 | void hashtable_free(hashtable_t hashtable); 14 | 15 | void hashtable_insert(hashtable_t hashtable, void *key, void *data); 16 | 17 | void *hashtable_get(hashtable_t hashtable, const void *key); 18 | 19 | int hashtable_contains(hashtable_t hashtable, const void *key); 20 | 21 | void hashtable_delete(hashtable_t hashtable, const void *key); 22 | 23 | // hashtable callbacks for string keys 24 | size_t string_hash(const void *key); 25 | 26 | int string_equals(const void *key1, const void *key2); 27 | 28 | // iterator 29 | iterator_t iterator_create(hashtable_t table); 30 | 31 | void iterator_delete(iterator_t iter); 32 | 33 | void *iterator_next(iterator_t iter); 34 | -------------------------------------------------------------------------------- /president-blog/public/web.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 12 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /timehackers/docker_files/db_init.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | service mysql start 4 | 5 | mysql --user=root --password="n1Yq3IOz7nq2" -e " \ 6 | CREATE DATABASE web; 7 | USE web; 8 | CREATE TABLE feedbacks(id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, message TEXT, timestamp TIMESTAMP, session_id TEXT, uid TEXT, is_checked INT); 9 | CREATE TABLE users(user_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, username TEXT, password TEXT, email TEXT); 10 | CREATE USER 'web'@'localhost' IDENTIFIED BY 'N8zu3Qt2w5Vh'; 11 | CREATE USER 'checker'@'localhost' IDENTIFIED BY 'yB2z51jw2qU5'; 12 | GRANT SELECT,INSERT ON web.feedbacks TO 'web'@'localhost'; 13 | GRANT SELECT ON web.users TO 'web'@'localhost'; 14 | GRANT SELECT,UPDATE ON web.feedbacks TO 'checker'@'localhost'; 15 | INSERT INTO web.users (username, password, email) VALUES ('admin', '0mgH@rdP@sS', 'admin@timehackers'); 16 | INSERT INTO web.users (username, password, email) VALUES ('jonny', 'j0HhNy1337', 'jonny@timehackers'); 17 | INSERT INTO web.users (username, password, email) VALUES ('pro_hacker', 'M@kE_L0Ve_St0P_H@cK', 'pro_hacker@timehackers');" -------------------------------------------------------------------------------- /timehackers/web/api.php: -------------------------------------------------------------------------------- 1 | '', 8 | 'error' => '' 9 | ]; 10 | 11 | if (isset($_SESSION['CSRFToken']) && isset($_POST['token']) && $_SESSION['CSRFToken'] === $_POST['token']) 12 | { 13 | if (isset($_SESSION['is_auth']) && $_SESSION['is_auth']) 14 | { 15 | include_once("config.php"); 16 | include_once("functions.php"); 17 | 18 | if (isset($_POST['action'])) 19 | { 20 | switch ($_POST['action']) 21 | { 22 | case 'get_password': 23 | $login = $mysqli->real_escape_string($_POST['username']); 24 | $query = "SELECT password FROM users WHERE username = '{$login}'"; 25 | $sql_result = $mysqli->query($query); 26 | if ($sql_result->num_rows == 1) { 27 | $row = $sql_result->fetch_assoc(); 28 | $result['result'] = $row['password']; 29 | } 30 | echo json_encode($result); 31 | break; 32 | default: 33 | $result['error'] = 'undefined action'; 34 | echo json_encode($result); 35 | break; 36 | } 37 | } 38 | } 39 | else 40 | { 41 | $result['error'] = 'not authorized'; 42 | echo json_encode($result); 43 | } 44 | } 45 | else 46 | { 47 | $result['error'] = "CSRFToken '".$_POST['token']."' is not correct"; 48 | echo json_encode($result); 49 | } 50 | ?> 51 | -------------------------------------------------------------------------------- /e-voting/solver.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | import socket 4 | from re import findall 5 | from sys import argv 6 | import urllib.request 7 | 8 | 9 | RECV_SIZE = 4096 10 | 11 | client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 12 | client_socket.connect((argv[1], int(argv[2]))) 13 | 14 | data = client_socket.recv(RECV_SIZE) 15 | ctext1 = [int(i) for i in findall("\(([0-9]+)\s([0-9]+)\)", data.decode())[0]] 16 | print("[+] : Got encrypted message") 17 | 18 | # Show menu 19 | client_socket.recv(RECV_SIZE) 20 | 21 | client_socket.send(b"E\n") 22 | client_socket.recv(RECV_SIZE) 23 | 24 | client_socket.send(b"1\n") 25 | print("[+] : Encrypting message \"1\"") 26 | 27 | data = client_socket.recv(RECV_SIZE) 28 | ctext2 = [int(i) for i in findall("\(([0-9]+)\s([0-9]+)\)", data.decode())[0]] 29 | print("[+] : Got encrypted our message") 30 | 31 | ctext3 = "{0} {1}".format(str(ctext1[0] * ctext2[0]), str(ctext1[1] * ctext2[1])) 32 | client_socket.recv(RECV_SIZE) 33 | client_socket.send(b"D\n") 34 | print("[+] : Computing (ctext1[0] * ctext2[0]), (ctext1[1] * ctext2[1])") 35 | 36 | client_socket.recv(RECV_SIZE) 37 | client_socket.send("{0}\n".format(ctext3).encode()) 38 | 39 | data = client_socket.recv(RECV_SIZE) 40 | 41 | data = findall("\['ID':\s[0-9]+;\s'VOTE':\s'(ctfzone\{.*\})'\]", data.decode()) 42 | print("[+] : Got flag: {0}".format(data[0])) 43 | 44 | client_socket.close() 45 | -------------------------------------------------------------------------------- /president-blog/public/index.php: -------------------------------------------------------------------------------- 1 | run(); 41 | -------------------------------------------------------------------------------- /president-blog/config/autoload/development.local.php: -------------------------------------------------------------------------------- 1 | 9 | * $ composer development-enable 10 | * 11 | * 12 | * from the project root to copy this file to development.local.php and enable 13 | * the settings it contains. 14 | * 15 | * You may also create files matching the glob pattern `{,*.}{global,local}-development.php`. 16 | */ 17 | 18 | return [ 19 | 'view_manager' => [ 20 | 'display_not_found_reason' => false, 21 | 'display_exceptions' => false, 22 | 'doctype' => 'HTML5', 23 | 'not_found_template' => 'error/404', 24 | // 'exception_template' => 'error/index', 25 | // 'template_map' => [ 26 | // 'layout/layout' => __DIR__ . '/../../module/Application/view/layout/layout.phtml', 27 | // 'application/index/index' => __DIR__ . '/../../module/Application/view/application/index/index.phtml', 28 | // 'error/404' => __DIR__ . '/../../module/Application/view/error/404.phtml', 29 | // 'error/index' => __DIR__ . '/../../module/Application/view/error/index.phtml', 30 | // ], 31 | // 'template_path_stack' => [ 32 | // __DIR__ . '/../../module/Application/view', 33 | // ], 34 | ], 35 | ]; 36 | -------------------------------------------------------------------------------- /timehackers/web/index.php: -------------------------------------------------------------------------------- 1 | 5 | 6 | 7 | 8 | 9 | TimeHackers Cr3w 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 |
21 | 33 |
34 |
35 |
36 |
About
37 |
38 |
39 |
40 |
41 | 42 |
43 | 44 | 45 | -------------------------------------------------------------------------------- /president-blog/module/Application/src/Model/Post.php: -------------------------------------------------------------------------------- 1 | id; 32 | } 33 | 34 | /** 35 | * @param int $id 36 | */ 37 | public function setId($id) 38 | { 39 | $this->id = $id; 40 | } 41 | 42 | /** 43 | * {@inheritDoc} 44 | */ 45 | public function getTitle() 46 | { 47 | return $this->title; 48 | } 49 | 50 | /** 51 | * @param string $title 52 | */ 53 | public function setTitle($title) 54 | { 55 | $this->title = $title; 56 | } 57 | 58 | /** 59 | * {@inheritDoc} 60 | */ 61 | public function getText() 62 | { 63 | return $this->text; 64 | } 65 | 66 | /** 67 | * @param string $text 68 | */ 69 | public function setText($text) 70 | { 71 | $this->text = $text; 72 | } 73 | 74 | public function getDate() 75 | { 76 | return $this->date; 77 | } 78 | 79 | public function setDate($date) 80 | { 81 | $this->date = $date 82 | } 83 | 84 | } -------------------------------------------------------------------------------- /president-blog/composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "zendframework/skeleton-application", 3 | "description": "Skeleton Application for Zend Framework zend-mvc applications", 4 | "type": "project", 5 | "license": "BSD-3-Clause", 6 | "keywords": [ 7 | "framework", 8 | "mvc", 9 | "zf" 10 | ], 11 | "homepage": "http://framework.zend.com/", 12 | "minimum-stability": "dev", 13 | "prefer-stable": true, 14 | "require": { 15 | "php": "^5.6 || ^7.0", 16 | "zendframework/zend-component-installer": "^1.0 || ^0.7 || ^1.0.0-dev@dev", 17 | "zendframework/zend-mvc": "^3.0.1", 18 | "zendframework/zend-db": "*", 19 | "zendframework/zend-session": "*", 20 | "zfcampus/zf-development-mode": "^3.0" 21 | }, 22 | "autoload": { 23 | "psr-4": { 24 | "Application\\": "module/Application/src/" 25 | } 26 | }, 27 | "autoload-dev": { 28 | "psr-4": { 29 | "ApplicationTest\\": "module/Application/test/" 30 | } 31 | }, 32 | "extra": [], 33 | "scripts": { 34 | "cs-check": "phpcs", 35 | "cs-fix": "phpcbf", 36 | "development-disable": "zf-development-mode disable", 37 | "development-enable": "zf-development-mode enable", 38 | "development-status": "zf-development-mode status", 39 | "post-create-project-cmd": [ 40 | "@development-enable" 41 | ], 42 | "serve": "php -S 0.0.0.0:8080 -t public public/index.php", 43 | "test": "phpunit" 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /e-voting/elgamal.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | from elgamal_cipher import ElGamal 3 | from random import randrange 4 | import hashlib 5 | 6 | 7 | class ElgamalException(Exception): 8 | pass 9 | 10 | 11 | class Elgamal(object): 12 | def __init__(self, key_size): 13 | self.cipher = ElGamal() 14 | self.key_size = key_size 15 | self.cipher.generate_keys(self.key_size) 16 | 17 | self.secret = b"20cb6dc50637daf556517795a02c0bf5" 18 | m = hashlib.md5() 19 | m.update(self.secret) 20 | 21 | # Will be fc575129f3935d5b456ed55ef8173574 22 | self.flag = m.hexdigest() 23 | self.encrypted_flag = self.encrypt(self.encode_str(self.flag)) 24 | 25 | def keygen(self, key_size): 26 | self.cipher.generate_keys(key_size=key_size) 27 | p = self.cipher.get_public_key()["p"] 28 | r = randrange(2, p) 29 | self.cipher.set_deterministic(r) 30 | 31 | def decrypt(self, c, k): 32 | m = self.cipher.decrypt(x=[c, k]) 33 | if self.encrypted_flag[0] == c and self.encrypted_flag[1] == k: 34 | raise ElgamalException() 35 | return m 36 | 37 | def encrypt(self, m): 38 | if m.bit_length() > self.key_size: 39 | return None 40 | c, k = self.cipher.encrypt(m) 41 | return c, k 42 | 43 | @staticmethod 44 | def encode_str(text): 45 | return int(text, 16) 46 | 47 | @staticmethod 48 | def decode_str(text): 49 | return format(int(text), "x") 50 | 51 | def get_flag(self): 52 | return self.flag 53 | -------------------------------------------------------------------------------- /e-voting/cipher.py: -------------------------------------------------------------------------------- 1 | class Cipher: 2 | def __init__(self, keys=None): 3 | if keys: 4 | self.keys = keys 5 | return None 6 | 7 | def encrypt(self, x): 8 | return None 9 | 10 | def decrypt(self, c): 11 | return None 12 | 13 | def generate_keys(self, key_size): 14 | return None 15 | 16 | def has_keys(self): 17 | return True if self.keys and "pub" in self.keys and "priv" in self.keys else False 18 | 19 | def get_public_key(self): 20 | if self.keys is None: 21 | raise Exception("There is no keys!") 22 | if "pub" not in self.keys: 23 | raise Exception("There is no public key!") 24 | 25 | return self.keys["pub"] 26 | 27 | def get_private_key(self): 28 | if self.keys is None: 29 | raise Exception("There is no keys!") 30 | if "priv" not in self.keys: 31 | raise Exception("There is no private key!") 32 | 33 | return self.keys["priv"] 34 | 35 | def add_to_public_key(self, name, value): 36 | if self.keys is None: 37 | raise Exception("There is no keys!") 38 | if "pub" not in self.keys: 39 | raise Exception("There is no public key!") 40 | 41 | self.keys["pub"][name] = value 42 | 43 | def add_to_private_key(self, name, value): 44 | if self.keys is None: 45 | raise Exception("There is no keys!") 46 | if "priv" not in self.keys: 47 | raise Exception("There is no private key!") 48 | 49 | self.keys["priv"][name] = value 50 | -------------------------------------------------------------------------------- /president-blog/LICENSE.md: -------------------------------------------------------------------------------- 1 | Copyright (c) 2005-2016, Zend Technologies USA, Inc. 2 | 3 | All rights reserved. 4 | 5 | Redistribution and use in source and binary forms, with or without modification, 6 | are permitted provided that the following conditions are met: 7 | 8 | - Redistributions of source code must retain the above copyright notice, 9 | this list of conditions and the following disclaimer. 10 | 11 | - Redistributions in binary form must reproduce the above copyright notice, 12 | this list of conditions and the following disclaimer in the documentation 13 | and/or other materials provided with the distribution. 14 | 15 | - Neither the name of Zend Technologies USA, Inc. nor the names of its 16 | contributors may be used to endorse or promote products derived from this 17 | software without specific prior written permission. 18 | 19 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 20 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 21 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 22 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR 23 | ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 24 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 25 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 26 | ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 28 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | -------------------------------------------------------------------------------- /mprsa/solver.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | from mprsa import MPRSA 3 | from re import findall 4 | from gmpy2 import mpq 5 | from deploy import FLAG 6 | 7 | def convergents_win(cf): 8 | r, s, P, q = 0, 1, 1, 0 9 | for c in cf: 10 | r, s, P, q = P, q, c * P + r, c * q + s 11 | yield P, q 12 | 13 | 14 | def contfrac_win(P, q): 15 | while q: 16 | n = P // q 17 | yield n 18 | q, P = P - q * n, q 19 | 20 | 21 | def contfrac(P, q): 22 | while q: 23 | m = P // q 24 | yield m 25 | q, P = P - q * m, q 26 | 27 | 28 | def win(e, n): 29 | limitD = int(pow(0.33 * mpq(n), 0.25)) 30 | myM = 1000 31 | contf = list(convergents_win(contfrac_win(e, n))) 32 | for i in range(len(contf)): 33 | current = contf[i] 34 | if current[1] > limitD: 35 | break 36 | isC = pow(myM, e, n) 37 | myM2 = pow(isC, current[1], n) 38 | if myM == myM2: 39 | return int(current[0]), int(current[1]) 40 | return 0, 0 41 | 42 | 43 | with open("data.enc", "r") as f: 44 | c = int(f.read().rstrip()) 45 | 46 | with open("public.txt", "r") as f: 47 | pk = f.read() 48 | n = int(findall(r"n\s+\=\s+([0-9]+)", pk)[0]) 49 | e = int(findall(r"e\s+\=\s+([0-9]+)", pk)[0]) 50 | 51 | d = win(e, n)[1] 52 | if d != 0: 53 | mprsa = MPRSA() 54 | mprsa.import_keys((e, n), (d, n)) 55 | ptext = mprsa.decryption(c) 56 | if FLAG == ptext: 57 | print("[+] : Got flag\n{0}".format(ptext.decode())) 58 | else: 59 | print("[-] Failed to find secret flag") 60 | else: 61 | print("[-] Failed to find secret flag") 62 | -------------------------------------------------------------------------------- /timehackers/docker_files/000-default.conf: -------------------------------------------------------------------------------- 1 | 2 | # The ServerName directive sets the request scheme, hostname and port that 3 | # the server uses to identify itself. This is used when creating 4 | # redirection URLs. In the context of virtual hosts, the ServerName 5 | # specifies what hostname must appear in the request's Host: header to 6 | # match this virtual host. For the default virtual host (this file) this 7 | # value is not decisive as it is used as a last resort host regardless. 8 | # However, you must set it for any further virtual host explicitly. 9 | #ServerName www.example.com 10 | 11 | ServerAdmin webmaster@localhost 12 | DocumentRoot /var/www/html 13 | 14 | SetEnv no-gzip 1 15 | 16 | # Available loglevels: trace8, ..., trace1, debug, info, notice, warn, 17 | # error, crit, alert, emerg. 18 | # It is also possible to configure the loglevel for particular 19 | # modules, e.g. 20 | #LogLevel info ssl:warn 21 | 22 | ErrorLog ${APACHE_LOG_DIR}/error.log 23 | CustomLog ${APACHE_LOG_DIR}/access.log combined 24 | 25 | # For most configuration files from conf-available/, which are 26 | # enabled or disabled at a global level, it is possible to 27 | # include a line for only one particular virtual host. For example the 28 | # following line enables the CGI configuration for this host only 29 | # after it has been globally disabled with "a2disconf". 30 | #Include conf-available/serve-cgi-bin.conf 31 | 32 | 33 | # vim: syntax=apache ts=4 sw=4 sts=4 sr noet -------------------------------------------------------------------------------- /president-feedback/devnull.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 11 | 12 | 13 | 30 |
31 |
32 |
33 | 36 |
37 |
38 |
39 | 40 | 41 | -------------------------------------------------------------------------------- /president-blog/config/autoload/global.php: -------------------------------------------------------------------------------- 1 | [ 21 | // 'use_cookies' => true, 22 | // 'cookie_httponly' => true, 23 | // ], 24 | 'session_config' => [ 25 | 'cookie_lifetime' => 60*60*1, 26 | 'gc_maxlifetime' => 60*60*24*30, 27 | ], 28 | 'session_storage' => [ 29 | 'type' => SessionArrayStorage::class 30 | ], 31 | 'db' => [ 32 | 'driver' => 'Pdo', 33 | 'dsn' => "pgsql:host=127.0.0.1;dbname=task200", 34 | 'username' => 'task200', 35 | 'password' => 'rahPhila7ud1th', 36 | ], 37 | 'service_manager' => [ 38 | 'factories' => [ 39 | 'Zend\Db\Adapter\Adapter' 40 | => 'Zend\Db\Adapter\AdapterServiceFactory', 41 | ], 42 | ], 43 | 'session_manager' => [ 44 | // Session validators (used for security). 45 | 'validators' => [ 46 | RemoteAddr::class, 47 | HttpUserAgent::class, 48 | ] 49 | ], 50 | 'session_containers' => [ 51 | 'ContainerNamespace' 52 | ], 53 | ]; 54 | -------------------------------------------------------------------------------- /president-blog/apache.conf: -------------------------------------------------------------------------------- 1 | 2 | # The ServerName directive sets the request scheme, hostname and port that 3 | # the server uses to identify itself. This is used when creating 4 | # redirection URLs. In the context of virtual hosts, the ServerName 5 | # specifies what hostname must appear in the request's Host: header to 6 | # match this virtual host. For the default virtual host (this file) this 7 | # value is not decisive as it is used as a last resort host regardless. 8 | # However, you must set it for any further virtual host explicitly. 9 | #ServerName www.example.com 10 | 11 | ServerAdmin webmaster@localhost 12 | DocumentRoot /var/www/public 13 | 14 | DirectoryIndex index.php 15 | AllowOverride All 16 | Order allow,deny 17 | Allow from all 18 | 19 | 20 | 21 | # Available loglevels: trace8, ..., trace1, debug, info, notice, warn, 22 | # error, crit, alert, emerg. 23 | # It is also possible to configure the loglevel for particular 24 | # modules, e.g. 25 | #LogLevel info ssl:warn 26 | 27 | ErrorLog ${APACHE_LOG_DIR}/error.log 28 | CustomLog ${APACHE_LOG_DIR}/access.log combined 29 | 30 | # For most configuration files from conf-available/, which are 31 | # enabled or disabled at a global level, it is possible to 32 | # include a line for only one particular virtual host. For example the 33 | # following line enables the CGI configuration for this host only 34 | # after it has been globally disabled with "a2disconf". 35 | #Include conf-available/serve-cgi-bin.conf 36 | 37 | 38 | # vim: syntax=apache ts=4 sw=4 sts=4 sr noet 39 | -------------------------------------------------------------------------------- /signature-server/solver.py: -------------------------------------------------------------------------------- 1 | from sys import argv 2 | from sage.all import * 3 | from socket import create_connection 4 | from hashlib import sha1 5 | 6 | sock = create_connection((argv[1], int(argv[2]))) 7 | 8 | # Skip hello and menu 9 | sock.recv(100) 10 | 11 | data = [] 12 | 13 | for i in xrange(50): 14 | # Skip menu 15 | sock.recv(100) 16 | sock.send('s\n') 17 | # Skip 'Enter message to sign: ' 18 | sock.recv(1000) 19 | msg = '%d' % i 20 | sock.send(msg + '\n') 21 | d = sock.recv(1000) 22 | r, s, a = tuple(map(int, d.split(','))) 23 | h = int(sha1(msg).hexdigest(), 16) 24 | data.append((h, r, s, a)) 25 | 26 | q = 0x100000000000000000001f4c8f927aed3ca752257 27 | l = 5 28 | N = len(data) 29 | 30 | def Babai_closest_vector(M, G, target): 31 | small = target 32 | for _ in xrange(1): 33 | for i in reversed(range(M.nrows())): 34 | c = ((small * G[i]) / (G[i] * G[i])).round() 35 | small -= M[i] * c 36 | return target - small 37 | 38 | u = [] 39 | t = [] 40 | 41 | for (h, r, s, a) in data: 42 | si = inverse_mod(Integer(s), q) 43 | li = inverse_mod(2 ** l, q) 44 | ti = li * (r * si) % q 45 | ui = li * (a - si * h) % q 46 | t.append(ti) 47 | u.append(ui) 48 | 49 | d = QQ(q) / (2 ** (l + 1)) 50 | 51 | L = Matrix(QQ, N+1, N+1) 52 | 53 | for i in xrange(N): 54 | L[i, i] = q 55 | 56 | for i in xrange(N): 57 | L[N, i] = t[i] 58 | 59 | L[N, N] = QQ(1) / (2 ** (l + 1)) 60 | 61 | M = L.LLL() 62 | G = M.gram_schmidt()[0] 63 | 64 | for i in xrange(N): 65 | u[i] += d 66 | u.append(0) 67 | 68 | target = vector(QQ, u) 69 | res = Babai_closest_vector(M, G, target) 70 | x = (res[-1] * (2 ** (l + 1))) % q 71 | 72 | print 'ctfzone{%s}' % hex(x).decode('hex') 73 | 74 | sock.close() 75 | -------------------------------------------------------------------------------- /election-department-service/src/utils.c: -------------------------------------------------------------------------------- 1 | #include "utils.h" 2 | #include "heap.h" 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | 9 | #ifdef DEBUG 10 | #include 11 | #endif 12 | 13 | int send_string(int fd, const char *string) 14 | { 15 | size_t len = string != NULL ? strlen(string) : 0; 16 | 17 | #ifdef DEBUG 18 | printf("send_string: len: %lu\n", len); 19 | printf("send_string: buf: %s\n", string ? string : ""); 20 | #endif 21 | 22 | int res = write(fd, &len, sizeof(len)); 23 | if (res != sizeof(len)) 24 | return res; 25 | 26 | return write(fd, string, len); 27 | } 28 | 29 | static char *_recv_string(int fd, void *(*malloc_func)(size_t), void (*free_func)(void *)) 30 | { 31 | size_t len; 32 | int res = read(fd, &len, sizeof(len)); 33 | if (res != sizeof(len)) 34 | return NULL; 35 | 36 | #ifdef DEBUG 37 | printf("recv_string: len: %lu\n", len); 38 | #endif 39 | 40 | char *buf = malloc_func(len + 1); 41 | size_t i = 0; 42 | char *p = buf; 43 | while (i < len) 44 | { 45 | res = read(fd, &p[i], 1); 46 | if (res < 0) 47 | { 48 | free_func(buf); 49 | return NULL; 50 | } 51 | 52 | if (p[i] == '\0') 53 | break; 54 | 55 | i++; 56 | } 57 | 58 | buf[i] = '\0'; 59 | 60 | #ifdef DEBUG 61 | printf("recv_string: buf: %s\n", buf); 62 | #endif 63 | 64 | return buf; 65 | } 66 | 67 | char *recv_string(int fd) 68 | { 69 | return _recv_string(fd, malloc, free); 70 | } 71 | 72 | char *sec_recv_string(int fd) 73 | { 74 | return _recv_string(fd, alloc, release); 75 | } 76 | 77 | void sec_exit(int ret) 78 | { 79 | syscall(SYS_exit, ret); 80 | } 81 | -------------------------------------------------------------------------------- /president-feedback/main.py: -------------------------------------------------------------------------------- 1 | import json 2 | import curio 3 | import inspect 4 | import logging 5 | from sanic import Sanic 6 | from sanic.response import html, redirect 7 | 8 | from arifmetics import Arifmetics 9 | app = Sanic(__name__) 10 | 11 | 12 | with open("index.html") as f: 13 | index_tmpl = f.read() 14 | 15 | with open("devnull.html") as f: 16 | devnull_tmpl = f.read() 17 | 18 | 19 | @app.route('/') 20 | async def index(request): 21 | with open("index.html") as f: 22 | tmpl = f.read() 23 | # if request.args.get("success"): 24 | # return html(tmpl.format(success=True)) 25 | # else: 26 | return html(tmpl) 27 | 28 | 29 | @app.route('/dev/null', methods=["POST"]) 30 | async def devnull(request): 31 | return html(devnull_tmpl) 32 | 33 | 34 | @app.websocket('/feed') 35 | async def feed(request, ws): 36 | arifm = Arifmetics("127.0.0.1", 25000) 37 | while True: 38 | try: 39 | data = await ws.recv() 40 | try: 41 | data = json.loads(data) 42 | method = getattr(arifm, data["method"], None) 43 | if inspect.iscoroutinefunction(method): 44 | res = await method(*data.get("args", [])) 45 | else: 46 | res = method(*data.get("args", [])) 47 | data = { 48 | "result": res, 49 | "method": data["method"], 50 | "status": "ok" 51 | } 52 | except Exception as e: 53 | data = { 54 | "status": "error", 55 | "info": str(e) 56 | } 57 | await ws.send(json.dumps(data)) 58 | except Exception as e: 59 | # logging.error(error) 60 | raise 61 | 62 | 63 | if __name__ == "__main__": 64 | app.run(host="0.0.0.0", port=8000, debug=True) 65 | 66 | -------------------------------------------------------------------------------- /pq-messenger/src/main/java/task/Server.java: -------------------------------------------------------------------------------- 1 | package task; 2 | 3 | import akka.actor.ActorRef; 4 | import akka.actor.Props; 5 | import akka.actor.UntypedAbstractActor; 6 | import akka.io.Tcp; 7 | import akka.io.Tcp.CommandFailed; 8 | import akka.io.Tcp.Connected; 9 | import akka.io.TcpMessage; 10 | import akka.util.ByteString; 11 | 12 | import java.net.InetSocketAddress; 13 | import java.util.Base64; 14 | 15 | public class Server extends UntypedAbstractActor { 16 | 17 | private int port; 18 | private Protocol protocol; 19 | 20 | public static Props props(int port, Protocol protocol) { 21 | return Props.create(Server.class, port, protocol); 22 | } 23 | 24 | public Server(int port, Protocol protocol) { 25 | this.port = port; 26 | this.protocol = protocol; 27 | } 28 | 29 | @Override 30 | public void preStart() throws Exception { 31 | final ActorRef tcp = Tcp.get(getContext().system()).manager(); 32 | 33 | tcp.tell(TcpMessage.bind(getSelf(), 34 | new InetSocketAddress("0.0.0.0", port), 100), getSelf()); 35 | } 36 | 37 | @Override 38 | public void onReceive(Object msg) throws Exception { 39 | if (msg instanceof CommandFailed) { 40 | getContext().stop(getSelf()); 41 | } else if (msg instanceof Connected) { 42 | final Connected conn = (Connected) msg; 43 | 44 | final ActorRef handler = getContext().actorOf( 45 | Handler.props(protocol)); 46 | 47 | getSender().tell(TcpMessage.register(handler), getSelf()); 48 | 49 | // Hello message 50 | getSender().tell(TcpMessage.write(ByteString.fromArray(Messages.HELLO.getBytes())), getSelf()); 51 | 52 | // Menu 53 | getSender().tell(TcpMessage.write(ByteString.fromArray(Messages.MENU.getBytes())), getSelf()); 54 | 55 | } 56 | } 57 | 58 | 59 | } 60 | -------------------------------------------------------------------------------- /signature-server/server.py: -------------------------------------------------------------------------------- 1 | from curio import run, tcp_server 2 | from crypto import Curve, Point, multiply, normalize, invmod, rand 3 | from os import environ 4 | from hashlib import sha1 5 | from secrets import randbelow, compare_digest 6 | 7 | SECRET = int(environ.get('SECRET'), 10) 8 | 9 | HELLO_MESSAGE = b''' 10 | ------------------------------- 11 | Welcome to ECDSA service! 12 | ''' 13 | 14 | MENU = b''' 15 | ------------------------------- 16 | Options: 17 | [S]ign message 18 | [Q]uit 19 | -> ''' 20 | 21 | def sign_message(msg, SECRET): 22 | E = Curve(0xffffffffffffffffffffffffffffffff7fffffff, 23 | 0xffffffffffffffffffffffffffffffff7ffffffc, 24 | 0x1c97befc54bd7a8b65acf89f81d4d4adc565fa45) 25 | 26 | G = Point(E, 27 | 0x4a96b5688ef573284664698968c38bb913cbfc82, 28 | 0x23a628553168947d59dcc912042351377ac5fb32) 29 | 30 | q = 0x100000000000000000001f4c8f927aed3ca752257 31 | 32 | h = int(sha1(msg).hexdigest(), 16) 33 | 34 | while True: 35 | k = rand(1, q) 36 | Q = normalize(multiply(G, k)) 37 | r = Q.x % q 38 | if r != 0: 39 | break 40 | 41 | s = invmod(k, q) * (h + r * SECRET) % q 42 | return (r, s, k & 0x1f) 43 | 44 | async def handle_client(client, addr): 45 | await client.sendall(HELLO_MESSAGE) 46 | 47 | while True: 48 | await client.sendall(MENU) 49 | 50 | data = await client.recv(10000) 51 | if not data: 52 | break 53 | 54 | choice = data.strip().upper() 55 | 56 | if choice == b'S': 57 | await client.sendall(b'Enter message to sign: ') 58 | msg = await client.recv(10000) 59 | if not msg: 60 | break 61 | await client.sendall(b'%d, %d, %d\n' % sign_message(msg.strip(), SECRET)) 62 | elif choice == b'Q': 63 | await client.sendall(b"Bye-Bye!\n") 64 | break 65 | 66 | if __name__ == '__main__': 67 | run(tcp_server, '', 1337, handle_client) 68 | -------------------------------------------------------------------------------- /timehackers/checker/checker.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python2.7 2 | # -*- coding: utf-8 -*- 3 | 4 | import MySQLdb 5 | import time 6 | import requests 7 | import selenium.webdriver 8 | from selenium.webdriver.common.desired_capabilities import DesiredCapabilities 9 | import os 10 | import re 11 | 12 | 13 | os.environ["QT_QPA_PLATFORM"] = "offscreen" 14 | db = MySQLdb.connect('localhost','checker','yB2z51jw2qU5','web') 15 | db.autocommit(True) 16 | query_select = 'SELECT id,message FROM `feedbacks` WHERE is_checked = 0' 17 | query_update = 'UPDATE `feedbacks` SET is_checked = 1 WHERE id = $id$' 18 | 19 | 20 | login = "admin" 21 | password = "0mgH@rdP@sS" 22 | user_agent = 'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:52.0) Gecko/20100101 Firefox/52.0' 23 | admin_url = 'http://timehackers.ctf-zone.org/admin.php' 24 | 25 | 26 | def check(url): 27 | response = requests.post(admin_url, 28 | data={'login':login,'password':password}, 29 | headers={'User-Agent':user_agent}) 30 | dcap = dict(DesiredCapabilities.PHANTOMJS) 31 | dcap["phantomjs.page.settings.userAgent"] = (user_agent) 32 | driver = selenium.webdriver.PhantomJS(desired_capabilities=dcap, service_log_path='/dev/null') 33 | driver.set_page_load_timeout(5) 34 | for cookie in response.cookies: 35 | driver.add_cookie({ 36 | 'name': cookie.name, 37 | 'value': cookie.value, 38 | 'path': '/', 39 | 'domain': '.' + cookie.domain 40 | }) 41 | driver.get(url) 42 | 43 | 44 | while (True): 45 | cursor = db.cursor() 46 | try: 47 | cursor.execute(query_select) 48 | results = cursor.fetchall() 49 | for row in results: 50 | try: 51 | message = row[1] 52 | found = re.search('(?i)(http|https):\/\/([^ ]+)', message) 53 | if found: 54 | url = found.group(0) 55 | check(url) 56 | except Exception as e2: 57 | print 'except: %s' % e2 58 | query = query_update.replace('$id$',str(row[0])) 59 | cursor.execute(query) 60 | db.commit() 61 | except Exception as e: 62 | print 'exception: %s' % e 63 | time.sleep(1) 64 | 65 | 66 | db.close() 67 | -------------------------------------------------------------------------------- /president-blog/module/Application/test/Controller/IndexControllerTest.php: -------------------------------------------------------------------------------- 1 | setApplicationConfig(ArrayUtils::merge( 25 | include __DIR__ . '/../../../../config/application.config.php', 26 | $configOverrides 27 | )); 28 | 29 | parent::setUp(); 30 | } 31 | 32 | public function testIndexActionCanBeAccessed() 33 | { 34 | $this->dispatch('/', 'GET'); 35 | $this->assertResponseStatusCode(200); 36 | $this->assertModuleName('application'); 37 | $this->assertControllerName(IndexController::class); // as specified in router's controller name alias 38 | $this->assertControllerClass('IndexController'); 39 | $this->assertMatchedRouteName('home'); 40 | } 41 | 42 | public function testIndexActionViewModelTemplateRenderedWithinLayout() 43 | { 44 | $this->dispatch('/', 'GET'); 45 | $this->assertQuery('.container .jumbotron'); 46 | } 47 | 48 | public function testInvalidRouteDoesNotCrash() 49 | { 50 | $this->dispatch('/invalid/route', 'GET'); 51 | $this->assertResponseStatusCode(404); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /president-blog/config/autoload/development.local.php.dist: -------------------------------------------------------------------------------- 1 | 9 | * $ composer development-enable 10 | * 11 | * 12 | * from the project root to copy this file to development.local.php and enable 13 | * the settings it contains. 14 | * 15 | * You may also create files matching the glob pattern `{,*.}{global,local}-development.php`. 16 | */ 17 | 18 | return [ 19 | 'view_manager' => [ 20 | 'display_exceptions' => true, 21 | ], 22 | ]; 23 | 31 | * $ composer development-enable 32 | * 33 | * 34 | * from the project root to copy this file to development.local.php and enable 35 | * the settings it contains. 36 | * 37 | * You may also create files matching the glob pattern `{,*.}{global,local}-development.php`. 38 | */ 39 | 40 | return [ 41 | 'view_manager' => [ 42 | 'display_not_found_reason' => false, 43 | 'display_exceptions' => false, 44 | 'doctype' => 'HTML5', 45 | 'not_found_template' => 'error/404', 46 | 'exception_template' => 'error/index', 47 | 'template_map' => [ 48 | 'layout/layout' => __DIR__ . '/../../module/Application/view/layout/layout.phtml', 49 | 'application/index/index' => __DIR__ . '/../../module/Application/view/application/index/index.phtml', 50 | 'error/404' => __DIR__ . '/../../module/Application/view/error/404.phtml', 51 | 'error/index' => __DIR__ . '/../../module/Application/view/error/index.phtml', 52 | ], 53 | 'template_path_stack' => [ 54 | __DIR__ . '/../../module/Application/view', 55 | ], 56 | ], 57 | ]; 58 | -------------------------------------------------------------------------------- /president-blog/module/Application/view/error/index.phtml: -------------------------------------------------------------------------------- 1 |

An error occurred

2 |

message ?>

3 | 4 | display_exceptions)) : ?> 5 | exception) 6 | && ($this->exception instanceof \Exception || $this->exception instanceof \Error)) : ?> 7 |
8 | 9 |

Additional information:

10 |

exception) ?>

11 |
12 |
File:
13 |
14 |
exception->getFile() ?>:exception->getLine() ?>
15 |
16 |
Message:
17 |
18 |
escapeHtml($this->exception->getMessage()) ?>
19 |
20 |
Stack trace:
21 |
22 |
escapeHtml($this->exception->getTraceAsString()) ?>
23 |
24 |
25 | 26 | exception->getPrevious()) : ?> 27 |
28 | 29 |

Previous exceptions:

30 |
    31 | 32 | 33 |
  • 34 |

    35 |
    36 |
    File:
    37 |
    38 |
    getFile() ?>:getLine() ?>
    39 |
    40 |
    Message:
    41 |
    42 |
    escapeHtml($ex->getMessage()) ?>
    43 |
    44 |
    Stack trace:
    45 |
    46 |
    escapeHtml($ex->getTraceAsString()) ?>
    47 |
    48 |
    49 |
  • 50 | getPrevious(); 52 | if (++$icount >= 50) { 53 | echo '
  • There may be more exceptions, but we do not have enough memory to process it.
  • '; 54 | break; 55 | } 56 | ?> 57 | 58 |
59 | 60 | 61 |

No Exception available

62 | 63 | 64 | -------------------------------------------------------------------------------- /president-feedback/arifmetics.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | from hashlib import md5 3 | from random import choice, randint 4 | from threading import Thread 5 | 6 | 7 | SALT = b"ctfzone{87a55d7e34aae098be0316df6b8035e4}" 8 | 9 | 10 | class Event_ts(asyncio.Event): 11 | def set(self): 12 | self._loop.call_soon_threadsafe(super().set) 13 | 14 | 15 | def threaded(event, task, hash, table): 16 | event.set() 17 | table[hash] = eval(task) 18 | 19 | 20 | class Arifmetics: 21 | _sock = None 22 | _last = None 23 | 24 | def __init__(self, server, port): 25 | self._server = server 26 | self._port = port 27 | self._table = {} 28 | 29 | async def reconnect(self): 30 | self._sock = await asyncio.open_connection(self._server, self._port) 31 | 32 | async def operations(self): 33 | if self._sock is None: 34 | await self.reconnect() 35 | self._sock[1].write(b"supported_operations\n") 36 | r = await self._sock[0].read(1024) 37 | return r.decode().strip() 38 | 39 | async def generate(self): 40 | if self._sock is None: 41 | await self.reconnect() 42 | operations = await self.operations() 43 | expr = "%s %s %s" % ( 44 | randint(1, 2**8), 45 | choice(operations.split()), 46 | randint(1, 2**7) 47 | ) 48 | self._sock[1].write(b"translate %s" % expr.encode()) 49 | r = await self._sock[0].read(102400) 50 | text = r.decode() 51 | hash = md5(r + SALT).hexdigest() 52 | e = Event_ts() 53 | Thread(target=threaded, args=(e, expr, hash, self._table)).start() 54 | await e.wait() 55 | return {"text": text, "hash": hash} 56 | 57 | def check(self, digest, result): 58 | if digest in self._table and self._table[digest] == int(result): 59 | return "Valid" 60 | else: 61 | return "Wrong" 62 | 63 | def help(self): 64 | return "\n".join([m for m in dir(self) if not m.startswith("_")]) 65 | 66 | 67 | if __name__ == "__main__": 68 | c = Arifmetics("127.0.0.1", 25000) 69 | c._reconnect() 70 | -------------------------------------------------------------------------------- /mprsa/mprsa.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | from Crypto.Util import number 3 | from binascii import hexlify, unhexlify 4 | from gmpy2 import next_prime, powmod, gcdext, gcd 5 | from itertools import count 6 | from random import randint 7 | 8 | 9 | class MPRSA(object): 10 | def __init__(self): 11 | self.public_key = None 12 | self.secret_key = None 13 | 14 | def key_gen(self, bits, prime_numbers=4): 15 | delta = randint(5, 15) 16 | bit_prime = int(bits // prime_numbers) 17 | 18 | P = [next_prime(number.getPrime(bit_prime) + 1)] 19 | for i in range(1, prime_numbers): 20 | P.append(next_prime(P[i - 1] * delta)) 21 | 22 | n = self.__compute_module(P) 23 | phi = self.__compute_phi(P) 24 | 25 | for d_next in count(int(pow(P[0] // 2, 0.5)), -1): 26 | g, e, __ = gcdext(d_next, phi) 27 | if (1 < e < n) and (g == 1) and (gcd(phi, e) == 1): 28 | d = d_next 29 | break 30 | 31 | self.public_key = (e, n) 32 | self.secret_key = (d, n) 33 | 34 | def import_keys(self, public_key, secret_key): 35 | self.public_key = public_key 36 | self.secret_key = secret_key 37 | 38 | def export_keys(self): 39 | return self.public_key, self.secret_key 40 | 41 | @staticmethod 42 | def __compute_module(primes): 43 | n = 1 44 | for prime in primes: 45 | n *= prime 46 | return n 47 | 48 | @staticmethod 49 | def __compute_phi(primes): 50 | phi = 1 51 | for prime in primes: 52 | phi *= (prime - 1) 53 | return phi 54 | 55 | @staticmethod 56 | def __encode_message(data): 57 | return int(hexlify(data), 16) 58 | 59 | @staticmethod 60 | def __decode_message(data): 61 | return unhexlify(format(data, "x")) 62 | 63 | def encryption(self, ptext): 64 | data = self.__encode_message(ptext) 65 | return powmod(data, self.public_key[0], self.public_key[1]) 66 | 67 | def decryption(self, ctext): 68 | data = powmod(ctext, self.secret_key[0], self.secret_key[1]) 69 | return MPRSA.__decode_message(data) 70 | -------------------------------------------------------------------------------- /timehackers/web/templates/main.php: -------------------------------------------------------------------------------- 1 | 4 | 5 | 13 | 14 |
15 |
16 | Active Sessions 17 |
18 |
19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 |
Id
User-Agent
IP
1
127.0.0.1
34 |
35 |
36 |
37 |
Users
38 |
39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | query($query); 50 | if ($result->num_rows > 0) { 51 | while ($row = $result->fetch_row()) { 52 | echo ""; 53 | } 54 | } 55 | ?> 56 |
UsernamePasswordEmail
{$row[0]}
***********
{$row[1]}
57 |
58 |
59 | 3 | 4 | RUN apt-get update 5 | 6 | # configurating vuln web-server 7 | RUN { \ 8 | echo mysql-server mysql-server/root_password password 'n1Yq3IOz7nq2'; \ 9 | echo mysql-server mysql-server/root_password_again password 'n1Yq3IOz7nq2'; \ 10 | } | debconf-set-selections 11 | RUN export DEBIAN_FRONTEND="noninteractive" 12 | RUN apt-get install -y mysql-server && \ 13 | apt-get install -y nginx && \ 14 | apt-get install -y apache2 && \ 15 | apt-get install -y php && \ 16 | apt-get install -y libapache2-mod-php && \ 17 | apt-get install -y php-mcrypt && \ 18 | apt-get install -y php-gd && \ 19 | apt-get install -y php7.0-mysql && \ 20 | a2dismod -f deflate && \ 21 | a2enmod headers 22 | COPY docker_files/ports.conf /etc/apache2/ports.conf 23 | COPY docker_files/default /etc/nginx/sites-available/default 24 | COPY docker_files/nginx.conf /etc/nginx/nginx.conf 25 | COPY docker_files/000-default.conf /etc/apache2/sites-available/000-default.conf 26 | COPY docker_files/apache2.conf /etc/apache2/apache2.conf 27 | COPY docker_files/status.conf /etc/apache2/mods-available/status.conf 28 | COPY docker_files/db_init.sh /root/db_init.sh 29 | RUN chmod 700 /root/db_init.sh && \ 30 | ./root/db_init.sh 31 | COPY web /var/www/html 32 | RUN rm /var/www/html/index.html 33 | 34 | # configurating checker 35 | RUN apt-get install -y python2.7 && \ 36 | apt-get install -y phantomjs && \ 37 | apt-get install -y python-pip && \ 38 | pip install selenium==3.4.3 && \ 39 | apt-get install -y python-mysqldb && \ 40 | pip install requests==2.13.0 && \ 41 | apt-get install sudo && \ 42 | mkdir /home/checker 43 | COPY checker /home/checker 44 | RUN adduser --disabled-password --gecos "" checker && \ 45 | chmod 620 /home/checker/checker.log && \ 46 | chmod 620 /home/checker/ghostdriver.log && \ 47 | chmod 750 /home/checker/checker.py && \ 48 | chown -R root:checker /home/checker 49 | 50 | # adding flag 51 | RUN mkdir /flag && \ 52 | echo 'ctfzone{b3_c@R3fuL_w17h_C@cH1ng}' > '/flag/Th3_M0sT_S3cR3T_fL@g_2448' 53 | 54 | # clean caches 55 | 56 | # run services 57 | EXPOSE 80 8080 58 | COPY docker_files/start.sh /root/start.sh 59 | RUN chmod 700 /root/start.sh 60 | CMD ["/root/start.sh"] -------------------------------------------------------------------------------- /pq-messenger/gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | set DIRNAME=%~dp0 12 | if "%DIRNAME%" == "" set DIRNAME=. 13 | set APP_BASE_NAME=%~n0 14 | set APP_HOME=%DIRNAME% 15 | 16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 17 | set DEFAULT_JVM_OPTS= 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windows variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | 53 | :win9xME_args 54 | @rem Slurp the command line arguments. 55 | set CMD_LINE_ARGS= 56 | set _SKIP=2 57 | 58 | :win9xME_args_slurp 59 | if "x%~1" == "x" goto execute 60 | 61 | set CMD_LINE_ARGS=%* 62 | 63 | :execute 64 | @rem Setup the command line 65 | 66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 67 | 68 | @rem Execute Gradle 69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 70 | 71 | :end 72 | @rem End local scope for the variables with windows NT shell 73 | if "%ERRORLEVEL%"=="0" goto mainEnd 74 | 75 | :fail 76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 77 | rem the _cmd.exe /c_ return code! 78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 79 | exit /b 1 80 | 81 | :mainEnd 82 | if "%OS%"=="Windows_NT" endlocal 83 | 84 | :omega 85 | -------------------------------------------------------------------------------- /president-blog/module/Application/src/Module.php: -------------------------------------------------------------------------------- 1 | getApplication(); 23 | $serviceManager = $application->getServiceManager(); 24 | $sessionManager = $serviceManager->get(SessionManager::class); 25 | 26 | // $config = $event->getApplication() 27 | // ->getServiceManager() 28 | // ->get('Configuration'); 29 | 30 | // $sessionConfig = new SessionConfig(); 31 | // $sessionConfig->setOptions($config['session']); 32 | // $sessionManager = new SessionManager($sessionConfig); 33 | // $sessionManager->start(); 34 | // $application = $event->getApplication(); 35 | // $svcMgr = $application->getServiceManager(); 36 | 37 | // // Instantiate the session manager and 38 | // // make it the default one 39 | // // 40 | // $sessionManager = $svcMgr->get(SessionManager::class); 41 | } 42 | 43 | public function getConfig() 44 | { 45 | return include __DIR__ . '/../config/module.config.php'; 46 | } 47 | public function getServiceConfig() { 48 | // return array( 49 | // 'factories' => array( 50 | // 'Posts\Model\PostsTable' => function($sm) { 51 | // $dbAdapter = $sm->get('Zend\Db\Adapter\Adapter'); 52 | // $table = new PostsTable($dbAdapter); 53 | // return $table; 54 | // }, 55 | // ), 56 | // ); 57 | return array( 58 | 'controllers' => array( 59 | 'factories' => [ 60 | 'Application\Controller\IndexController' => 'Application\Controller\Factory\IndexControllerFactory', 61 | ] 62 | ), 63 | 'factories' => array( 64 | 'Application\Model\PostsTable' => function($sm) { 65 | $tableGateway = $sm->get('PostsTable'); 66 | $table = new PostsTable($tableGateway); 67 | return $table; 68 | } 69 | ) 70 | ); 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /pq-messenger/src/main/java/task/Handler.java: -------------------------------------------------------------------------------- 1 | package task; 2 | 3 | import akka.actor.Props; 4 | import akka.actor.UntypedAbstractActor; 5 | import akka.io.Tcp.ConnectionClosed; 6 | import akka.io.Tcp.Received; 7 | import akka.io.TcpMessage; 8 | import akka.util.ByteString; 9 | 10 | import java.util.Base64; 11 | import javax.swing.plaf.nimbus.State; 12 | 13 | public class Handler extends UntypedAbstractActor { 14 | 15 | private Protocol protocol; 16 | 17 | public enum State {COMMAND, MESSAGE} 18 | 19 | private State state; 20 | 21 | public static Props props(Protocol protocol) { 22 | return Props.create(Handler.class, protocol); 23 | } 24 | 25 | public Handler(Protocol protocol) { 26 | this.protocol = protocol; 27 | } 28 | 29 | @Override 30 | public void preStart() throws Exception { 31 | state = State.COMMAND; 32 | } 33 | 34 | @Override 35 | public void onReceive(Object msg) throws Exception { 36 | if (msg instanceof Received) { 37 | 38 | switch (state) { 39 | case COMMAND: 40 | final String choice = ((Received) msg).data().utf8String().toUpperCase().trim(); 41 | 42 | switch (choice) { 43 | case "S": 44 | getSender().tell(TcpMessage.write(ByteString.fromArray("Enter message:\n".getBytes())), getSelf()); 45 | state = State.MESSAGE; 46 | break; 47 | case "Q": 48 | getSender().tell(TcpMessage.write(ByteString.fromArray("Bye-bye\n".getBytes())), getSelf()); 49 | getContext().stop(getSelf()); 50 | break; 51 | } 52 | break; 53 | 54 | case MESSAGE: 55 | final String encryptedMessageBase64 = ((Received) msg).data().utf8String().trim(); 56 | try { 57 | byte[] encryptedMessage = Base64.getDecoder().decode(encryptedMessageBase64); 58 | byte[] message = protocol.decrypt(encryptedMessage); 59 | getSender().tell(TcpMessage.write(ByteString.fromArray("OK\n".getBytes())), getSelf()); 60 | } catch(Exception e) { 61 | getSender().tell(TcpMessage.write(ByteString.fromArray((e.getMessage() + "\n").getBytes())), getSelf()); 62 | } 63 | state = State.COMMAND; 64 | getSender().tell(TcpMessage.write(ByteString.fromArray(Messages.MENU.getBytes())), getSelf()); 65 | break; 66 | } 67 | } else if (msg instanceof ConnectionClosed) { 68 | getContext().stop(getSelf()); 69 | } 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /president-blog/module/Application/view/layout/layout.phtml: -------------------------------------------------------------------------------- 1 | doctype() ?> 2 | 3 | 4 | 5 | 6 | headTitle('Vote for Mr. Futre President')->setSeparator(' - ')->setAutoEscape(false) ?> 7 | 8 | headMeta() 9 | ->appendName('viewport', 'width=device-width, initial-scale=1.0') 10 | ->appendHttpEquiv('X-UA-Compatible', 'IE=edge') 11 | ?> 12 | 13 | 14 | headLink(['rel' => 'shortcut icon', 'type' => 'image/vnd.microsoft.icon', 'href' => $this->basePath() . '/img/favicon.ico']) 15 | ->prependStylesheet($this->basePath('css/style.css')) 16 | ->prependStylesheet($this->basePath('css/bootstrap-theme.min.css')) 17 | ->prependStylesheet($this->basePath('css/bootstrap.min.css')) 18 | ?> 19 | 20 | 21 | headScript() 22 | ->prependFile($this->basePath('js/bootstrap.min.js')) 23 | ->prependFile($this->basePath('js/jquery-3.1.0.min.js')) 24 | ?> 25 | 26 | 27 | 49 |
50 | content ?> 51 |
52 |
53 |

© 2005 - by Zend Technologies Ltd. All rights reserved.

54 |
55 |
56 | inlineScript() ?> 57 | 58 | 59 | -------------------------------------------------------------------------------- /e-voting/server.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | from curio import run, tcp_server 3 | from elgamal import Elgamal, ElgamalException 4 | 5 | MENU = b""" 6 | ------------------------------- 7 | Options: 8 | [E]ncrypt message 9 | [D]ecrypt message 10 | [Q]uit 11 | 12 | -> """ 13 | 14 | 15 | async def hello_message(client, elg): 16 | message = "Last vote: ({0} {1})\n".format(*elg.encrypted_flag) 17 | await client.sendall(message.encode()) 18 | 19 | 20 | async def encrypt_worker(client, elg): 21 | await client.sendall("Input your HEX message for encrypt: ".encode()) 22 | data = await client.recv(2048) 23 | try: 24 | ctext = elg.encrypt(elg.encode_str(data.rstrip())) 25 | except Exception as e: 26 | await client.sendall("Error: {0}\n".format(e).encode()) 27 | else: 28 | if ctext: 29 | await client.sendall("Your encrypted message:\n({0} {1})\n".format(ctext[0], ctext[1]).encode()) 30 | else: 31 | await client.sendall("None - Message too long\n".encode()) 32 | 33 | 34 | async def decrypt_worker(client, elg): 35 | await client.sendall("Input your message for decrypt, format: C1 C2: ".encode()) 36 | data = await client.recv(2048) 37 | try: 38 | ctext = data.decode().rstrip().split(" ") 39 | c1, c2 = int(ctext[0]), int(ctext[1]) 40 | ptext = elg.decrypt(c1, c2) 41 | except IndexError: 42 | await client.sendall("Error: value error, format: C1 C2\n".encode()) 43 | except ElgamalException: 44 | await client.sendall("None - can not decrypt another user's message\n".encode()) 45 | except Exception as e: 46 | await client.sendall("Error: {0}\n".format(e).encode()) 47 | else: 48 | if ptext: 49 | ptext = elg.decode_str(ptext) 50 | if ptext == elg.flag: 51 | await client.sendall("['ID': 13; 'VOTE': '{0}']".format("ctfzone{" + ptext + "}").encode()) 52 | else: 53 | await client.sendall("Your decrypted message:\n{0}\n".format(ptext).encode()) 54 | else: 55 | await client.sendall("None\n".encode()) 56 | 57 | 58 | async def handle_client(client, addr): 59 | print("Connection from", addr) 60 | elg = Elgamal(key_size=256) 61 | await hello_message(client, elg) 62 | while True: 63 | await client.sendall(MENU) 64 | data = await client.recv(256) 65 | if not data: 66 | break 67 | 68 | choise = data.strip().upper() 69 | if choise == b"E": 70 | await encrypt_worker(client, elg) 71 | elif choise == b"D": 72 | await decrypt_worker(client, elg) 73 | elif choise == b"Q": 74 | await client.sendall(b"Bye-Bye!\n") 75 | break 76 | print("Connection closed") 77 | 78 | 79 | if __name__ == "__main__": 80 | run(tcp_server, "", 1337, handle_client) -------------------------------------------------------------------------------- /president-blog/config/application.config.php: -------------------------------------------------------------------------------- 1 | require __DIR__ . '/modules.config.php', 11 | 12 | // These are various options for the listeners attached to the ModuleManager 13 | 'module_listener_options' => [ 14 | // This should be an array of paths in which modules reside. 15 | // If a string key is provided, the listener will consider that a module 16 | // namespace, the value of that key the specific path to that module's 17 | // Module class. 18 | 'module_paths' => [ 19 | './module', 20 | './vendor', 21 | ], 22 | 23 | // An array of paths from which to glob configuration files after 24 | // modules are loaded. These effectively override configuration 25 | // provided by modules themselves. Paths may use GLOB_BRACE notation. 26 | 'config_glob_paths' => [ 27 | realpath(__DIR__) . '/autoload/{{,*.}global,{,*.}local}.php', 28 | ], 29 | 30 | // Whether or not to enable a configuration cache. 31 | // If enabled, the merged configuration will be cached and used in 32 | // subsequent requests. 33 | 'config_cache_enabled' => true, 34 | 35 | // The key used to create the configuration cache file name. 36 | 'config_cache_key' => 'application.config.cache', 37 | 38 | // Whether or not to enable a module class map cache. 39 | // If enabled, creates a module class map cache which will be used 40 | // by in future requests, to reduce the autoloading process. 41 | 'module_map_cache_enabled' => true, 42 | 43 | // The key used to create the class map cache file name. 44 | 'module_map_cache_key' => 'application.module.cache', 45 | 46 | // The path in which to cache merged configuration. 47 | 'cache_dir' => 'data/cache/', 48 | 49 | // Whether or not to enable modules dependency checking. 50 | // Enabled by default, prevents usage of modules that depend on other modules 51 | // that weren't loaded. 52 | // 'check_dependencies' => true, 53 | ], 54 | 55 | // Used to create an own service manager. May contain one or more child arrays. 56 | // 'service_listener_options' => [ 57 | // [ 58 | // 'service_manager' => $stringServiceManagerName, 59 | // 'config_key' => $stringConfigKey, 60 | // 'interface' => $stringOptionalInterface, 61 | // 'method' => $stringRequiredMethodName, 62 | // ], 63 | // ], 64 | 65 | // Initial configuration with which to seed the ServiceManager. 66 | // Should be compatible with Zend\ServiceManager\Config. 67 | // 'service_manager' => [], 68 | ]; 69 | -------------------------------------------------------------------------------- /signature-server/crypto.py: -------------------------------------------------------------------------------- 1 | from secrets import randbelow 2 | 3 | def rand(a, b): 4 | while True: 5 | x = randbelow(b) 6 | if x > a: 7 | break 8 | return x 9 | 10 | def xgcd(a, b): 11 | if a == 0: return 0, 1, b 12 | if b == 0: return 1, 0, a 13 | 14 | px, ppx = 0, 1 15 | py, ppy = 1, 0 16 | 17 | while b: 18 | q = a // b 19 | a, b = b, a % b 20 | x = ppx - q * px 21 | y = ppy - q * py 22 | ppx, px = px, x 23 | ppy, py = py, y 24 | 25 | return ppx, ppy, a 26 | 27 | def invmod(a, n): 28 | if n < 2: 29 | raise ValueError("modulus must be greater than 1") 30 | 31 | x, y, g = xgcd(a, n) 32 | 33 | if g != 1: 34 | raise ValueError("no invmod for given @a and @n") 35 | else: 36 | return x % n 37 | 38 | class Curve: 39 | def __init__(self, N, a, b): 40 | self.N = N 41 | self.a = a 42 | self.b = b 43 | 44 | def __str__(self): 45 | return 'Elliptic curve: y^2 = x^3 + {a}*x + {b} over Finite Field of size {N}'.format(a=self.a, b=self.b, N=self.N) 46 | 47 | def discriminant(self): 48 | return (4 * (self.a ** 3) + 27 * (self.b ** 2)) % self.N 49 | 50 | class Point: 51 | def __init__(self, E, x, y, z=1): 52 | self.E = E 53 | self.x = x 54 | self.y = y 55 | self.z = z 56 | 57 | @property 58 | def N(self): 59 | return self.E.N 60 | 61 | @property 62 | def a(self): 63 | return self.E.a 64 | 65 | def __str__(self): 66 | return 'Point: ({x}, {y}, {z})'.format(x=self.x, y=self.y, z=self.z) 67 | 68 | def is_on_curve(E, P): 69 | Q = normalize(P) 70 | return (Q.y ** 2 - Q.x ** 3 - E.a * Q.x - E.b) % E.N == 0 71 | 72 | def normalize(P): 73 | zi = invmod(P.z, P.N) 74 | return Point(P.E, (zi * P.x) % P.N, (zi * P.y) % P.N, 1) 75 | 76 | def double(P): 77 | if P.y == 0: 78 | return Point(P.E, 0, 1, 0) 79 | w = (P.a * (P.z ** 2) + 3 * (P.x ** 2)) % P.N 80 | s = (P.y * P.z) % P.N 81 | b = (P.x * P.y * s) % P.N 82 | h = ((w ** 2) - 8 * b) % P.N 83 | x = (2 * h * s) % P.N 84 | y = (w * (4 * b - h) - 8 * (P.y ** 2) * (s ** 2)) % P.N 85 | z = (8 * (s ** 3)) % P.N 86 | return Point(P.E, x, y, z) 87 | 88 | def add(P, Q): 89 | u1 = (Q.y * P.z) % P.N 90 | u2 = (P.y * Q.z) % P.N 91 | v1 = (Q.x * P.z) % P.N 92 | v2 = (P.x * Q.z) % P.N 93 | if (v1 == v2): 94 | if (u1 != u2): 95 | return Point(P.E, 0, 1, 0) 96 | else: 97 | return double(P) 98 | u = (u1 - u2) % P.N 99 | v = (v1 - v2) % P.N 100 | w = (P.z * Q.z) % P.N 101 | a = ((u ** 2) * w - (v ** 3) - 2 * (v ** 2) * v2) % P.N 102 | x = (v * a) % P.N 103 | y = (u * ((v ** 2) * v2 - a) - (v ** 3) * u2) % P.N 104 | z = ((v ** 3) * w) % P.N 105 | return Point(P.E, x, y, z) 106 | 107 | def multiply(P, d): 108 | X1 = P 109 | X2 = double(P) 110 | for b in bin(d)[3:]: 111 | if b == '0': 112 | X2 = add(X1, X2) 113 | X1 = double(X1) 114 | else: 115 | X1 = add(X1, X2) 116 | X2 = double(X2) 117 | return X1 118 | -------------------------------------------------------------------------------- /e-voting/elgamal_cipher.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | from Crypto.Util import number 3 | from random import randrange 4 | from cipher import Cipher 5 | 6 | 7 | class ElGamal(Cipher): 8 | def __init__(self, keys=None, exponential_mode=False): 9 | self.exponential_mode = exponential_mode 10 | self.keys = keys 11 | 12 | def generate_keys(self, key_size=1024): 13 | p = None 14 | while p is None: 15 | try: 16 | p = number.getPrime(key_size) 17 | except Exception as err: 18 | print(err) 19 | 20 | alpha = randrange(1, p) 21 | d = randrange(2, p - 1) 22 | beta = pow(alpha, d, p) 23 | 24 | self.keys = {"pub": { 25 | "p": p, 26 | "alpha": alpha, 27 | "beta": beta}, 28 | "priv": { 29 | "d": d 30 | } 31 | } 32 | 33 | return self.keys 34 | 35 | def set_deterministic(self, km=None): 36 | if km is None: 37 | pub = Cipher.get_public_key(self) 38 | i = randrange(2, pub["p"] - 1) 39 | km = pow(pub["beta"], i, pub["p"]) 40 | Cipher.add_to_public_key(self, "km", km) 41 | return km 42 | 43 | def encrypt(self, m): 44 | assert self.__is_int(m) 45 | 46 | pub = Cipher.get_public_key(self) 47 | 48 | assert "p" in pub 49 | assert "alpha" in pub 50 | assert "beta" in pub 51 | 52 | p = pub["p"] 53 | alpha = pub["alpha"] 54 | beta = pub["beta"] 55 | km = pub["km"] if "km" in pub else None 56 | 57 | if self.exponential_mode: 58 | if m < 0: 59 | x = self.__modinv(pow(alpha, -m, p), p) 60 | else: 61 | x = pow(alpha, m, p) 62 | else: 63 | x = m 64 | 65 | if not km: 66 | i = randrange(2, p - 1) 67 | ke = pow(alpha, i, p) 68 | km = pow(beta, i, p) 69 | 70 | c = (x * km) % p 71 | return c, ke 72 | else: 73 | c = (x * km) % p 74 | return c 75 | 76 | def decrypt(self, x): 77 | pub = Cipher.get_public_key(self) 78 | priv = Cipher.get_private_key(self) 79 | 80 | assert "p" in pub 81 | assert "d" in priv 82 | 83 | p = pub["p"] 84 | d = priv["d"] 85 | if (type(x) == list or type(x) == tuple) and len(x) == 2: 86 | c = x[0] 87 | ke = x[1] 88 | else: 89 | c = x 90 | km = pub["km"] if "km" in pub else pow(ke, d, p) 91 | 92 | inv = self.__modinv(km, p) 93 | 94 | return c * inv % p 95 | 96 | def generate_lookup_table(self, a=0, b=10 ** 3): 97 | pub = Cipher.get_public_key(self) 98 | 99 | alpha = pub["alpha"] 100 | p = pub["p"] 101 | 102 | table = {} 103 | for i in xrange(a, b): 104 | c = pow(alpha, i, p) 105 | table[c] = i 106 | return table 107 | 108 | def __modinv(self, x, p): 109 | return pow(x, p - 2, p) 110 | 111 | def __is_int(self, x): 112 | try: 113 | int(x) 114 | return True 115 | except: 116 | return False 117 | -------------------------------------------------------------------------------- /president-blog/module/Application/view/application/index/index2.phtml: -------------------------------------------------------------------------------- 1 |
2 |

Blog of Mr. Future President

3 | 4 |

5 | Congratulations! You are reading the best blog in the world 6 | 7 |

8 | 9 |

Also we have twitter »

10 |
11 | 12 |
13 | 14 |
15 |
16 |
17 |

Follow Development

18 |
19 |
20 |

21 | Zend Framework is under active development. If you are 22 | interested in following the development of ZF, you can check 23 | ZF dev blog, 24 | and ZF issue tracker 25 | (link requires a GitHub account). This is a great resource 26 | for staying up to date with the latest developments! 27 |

28 | 29 |

ZF Development Portal »

30 |
31 |
32 |
33 | 34 |
35 |
36 |
37 |

Discover Modules

38 |
39 |
40 |

41 | The community is working on developing a community site to 42 | serve as a repository and gallery for ZF modules. The 43 | project is available on GitHub. 44 | The site is currently live and currently contains a list of 45 | some of the modules already available for ZF. 46 |

47 | 48 |

Explore ZF Modules »

49 |
50 |
51 |
52 | 53 |
54 |
55 |
56 |

Help & Support

57 |
58 |
59 |

60 | If you need any help or support while developing with ZF, 61 | you may reach us via IRC: #zftalk on Freenode. 62 | We'd love to hear any questions or feedback you may have 63 | regarding this release. Alternatively, you may subscribe 64 | and post questions to the mailing lists. 65 |

66 | 67 |

Ping us on IRC »

68 |
69 |
70 |
71 |
72 | -------------------------------------------------------------------------------- /president-blog/module/Application/config/module.config.php: -------------------------------------------------------------------------------- 1 | [ 16 | 'factories' => [ 17 | 'Application\Controller\Index' => 'Application\Controller\Factory\IndexControllerFactory', 18 | ], 19 | ], 20 | 'router' => [ 21 | 'routes' => [ 22 | 'home' => [ 23 | 'type' => Literal::class, 24 | 'options' => [ 25 | 'route' => '/', 26 | 'defaults' => [ 27 | 'controller' => 'Application\Controller\Index', 28 | 'action' => 'index', 29 | ], 30 | ], 31 | ], 32 | 'blog' => [ 33 | 'type' => Literal::class, 34 | 'options' => [ 35 | 'route' => '/blog', 36 | 'defaults' => [ 37 | 'controller' => 'Application\Controller\Index', 38 | 'action' => 'blog', 39 | ], 40 | ], 41 | ], 42 | 'admin' => [ 43 | 'type' => Literal::class, 44 | 'options' => [ 45 | 'route' => '/admin2000', 46 | 'defaults' => [ 47 | 'controller' => 'Application\Controller\Index', 48 | 'action' => 'admin', 49 | ], 50 | ], 51 | ], 52 | 'report' => [ 53 | 'type' => Literal::class, 54 | 'options' => [ 55 | 'route' => '/report_sender', 56 | 'defaults' => [ 57 | 'controller' => 'Application\Controller\Index', 58 | 'action' => 'report', 59 | ], 60 | ], 61 | ], 62 | 'r2' => [ 63 | 'type' => Literal::class, 64 | 'options' => [ 65 | 'route' => '*', 66 | 'defaults' => [ 67 | 'controller' => 'Application\Controller\Index', 68 | 'action' => 'admin', 69 | ], 70 | ], 71 | ], 72 | ], 73 | ], 74 | 'service_manager' => array( 75 | 'invokables' => array( 76 | 'Application\Service\PostsServiceInterface' => 'Application\Service\PostsService', 77 | ) 78 | ), 79 | 80 | 'view_manager' => [ 81 | 'display_not_found_reason' => false, 82 | 'display_exceptions' => false, 83 | 'doctype' => 'HTML5', 84 | 'not_found_template' => 'error/404', 85 | 'exception_template' => 'error/index', 86 | 'template_map' => [ 87 | 'layout/layout' => __DIR__ . '/../view/layout/layout.phtml', 88 | 'application/index/index' => __DIR__ . '/../view/application/index/index.phtml', 89 | 'error/404' => __DIR__ . '/../view/error/404.phtml', 90 | 'error/index' => __DIR__ . '/../view/error/index.phtml', 91 | ], 92 | 'template_path_stack' => [ 93 | __DIR__ . '/../view', 94 | ], 95 | ], 96 | ]; 97 | -------------------------------------------------------------------------------- /president-blog/module/Application/view/error/404.phtml: -------------------------------------------------------------------------------- 1 | 4 |

A 404 error occurred

5 |

message ?>

6 | 7 | reason)) : 8 | switch ($this->reason) { 9 | case Application::ERROR_CONTROLLER_CANNOT_DISPATCH: 10 | $reasonMessage = 'The requested controller was unable to dispatch the request.'; 11 | break; 12 | case Application::ERROR_MIDDLEWARE_CANNOT_DISPATCH: 13 | $reasonMessage = 'The requested middleware was unable to dispatch the request.'; 14 | break; 15 | case Application::ERROR_CONTROLLER_NOT_FOUND: 16 | $reasonMessage = 'The requested controller could not be mapped to an existing controller class.'; 17 | break; 18 | case Application::ERROR_CONTROLLER_INVALID: 19 | $reasonMessage = 'The requested controller was not dispatchable.'; 20 | break; 21 | case Application::ERROR_ROUTER_NO_MATCH: 22 | $reasonMessage = 'The requested URL could not be matched by routing.'; 23 | break; 24 | default: 25 | $reasonMessage = 'We cannot determine at this time why a 404 was generated.'; 26 | break; 27 | } 28 | ?> 29 |

30 | 31 | 32 | controller)) : ?> 33 |
34 |
Controller:
35 |
36 | escapeHtml($this->controller) ?> 37 | controller_class) && $this->controller_class != $this->controller) { 39 | printf('(resolves to %s)', $this->escapeHtml($this->controller_class)); 40 | } 41 | ?> 42 |
43 |
44 | 45 | 46 | display_exceptions)) : ?> 47 | exception) 48 | && ($this->exception instanceof \Exception || $this->exception instanceof \Error)) : ?> 49 |
50 | 51 |

Additional information:

52 |

exception) ?>

53 |
54 |
File:
55 |
56 |
exception->getFile() ?>:exception->getLine() ?>
57 |
58 |
Message:
59 |
60 |
escapeHtml($this->exception->getMessage()) ?>
61 |
62 |
Stack trace:
63 |
64 |
escapeHtml($this->exception->getTraceAsString()) ?>
65 |
66 |
67 | 68 | exception->getPrevious()) : ?> 69 |
70 | 71 |

Previous exceptions:

72 |
    73 | 74 | 75 |
  • 76 |

    77 |
    78 |
    File:
    79 |
    80 |
    getFile() ?>:getLine() ?>
    81 |
    82 |
    Message:
    83 |
    84 |
    escapeHtml($ex->getMessage()) ?>
    85 |
    86 |
    Stack trace:
    87 |
    88 |
    escapeHtml($ex->getTraceAsString()) ?>
    89 |
    90 |
    91 |
  • 92 | getPrevious(); 94 | if (++$icount >= 50) { 95 | echo '
  • There may be more exceptions, but we do not have enough memory to process it.
  • '; 96 | break; 97 | } 98 | ?> 99 | 100 |
101 | 102 | 103 |

No Exception available

104 | 105 | 106 | -------------------------------------------------------------------------------- /timehackers/web/admin.php: -------------------------------------------------------------------------------- 1 | 8 | 9 | 10 | 11 | 12 | TimeHackers Cr3w 13 | 14 | 15 | 16 | 17 | 18 | 19 | '; 23 | } 24 | ?> 25 | 28 | 29 | 30 | 31 |
32 |
33 | 45 |
46 |
47 | 48 | real_escape_string($_POST['login']); 67 | $password = $mysqli->real_escape_string($_POST['password']); 68 | $query = "SELECT user_id FROM `users` WHERE username='{$login}' AND password='{$password}'"; 69 | $result = $mysqli->query($query); 70 | if ($result->num_rows > 0) 71 | { 72 | $_SESSION['is_auth'] = True; 73 | $_SESSION['user_agent'] = $_SERVER['HTTP_USER_AGENT']; 74 | $_SESSION['ip'] = $_SERVER['X-Real-IP']; 75 | echo ' 76 |
77 | Success! Welcome to admin panel. 78 |
79 | '; 80 | header("Refresh: 2; url=admin.php"); 81 | } 82 | else 83 | { 84 | echo ' 85 |
86 | Error! Wrong login or password. 87 |
88 | '; 89 | header("Refresh: 2; url=admin.php"); 90 | } 91 | } 92 | else 93 | { ?> 94 |
95 |
Login
96 |
97 |
98 |
99 | 100 |
101 | 102 |
103 |
104 |
105 | 106 |
107 | 108 |
109 |
110 |
111 |
112 | 113 |
114 |
115 |
116 | 117 |
118 |
119 | 122 | 123 | 124 |
125 | 126 | 127 | -------------------------------------------------------------------------------- /president-blog/module/Application/src/Controller/IndexController.php: -------------------------------------------------------------------------------- 1 | db = $db; 26 | $this->sm = $sm; 27 | $this->containter = $cn; 28 | } 29 | 30 | public function indexAction() { 31 | return new ViewModel(); 32 | } 33 | 34 | public function getPosts() { 35 | $res = $this->db->query('SELECT * FROM posts')->execute(); 36 | $resultSet = new ResultSet(); 37 | $resultSet->initialize($res); 38 | return $resultSet; 39 | } 40 | 41 | public function blogAction() { 42 | $view = new ViewModel(); 43 | $view->posts = $this->getPosts(); 44 | 45 | return $view; 46 | } 47 | 48 | public function adminAction() { 49 | $vm = new ViewModel(); 50 | $request = $this->getRequest(); 51 | $vm->error = False; 52 | if ($request->isPost()) { 53 | $login = $this->getRequest()->getPost("login"); 54 | $password = $this->getRequest()->getPost("password"); 55 | 56 | $query = $this->db->query("SELECT * FROM users where login = '$login' and password = '$password'"); 57 | $resultSet = new ResultSet(); 58 | try { 59 | $resultSet->initialize($query->execute()); 60 | foreach ($resultSet as $user) { 61 | $container = new Container('ContainerNamespace'); 62 | $container->user = $user->login; 63 | return $this->redirect()->toRoute('report'); 64 | } 65 | $vm->error = True; 66 | } 67 | catch (InvalidQueryException $e){ 68 | $vm->error = True; 69 | } 70 | 71 | } 72 | 73 | return $vm; 74 | } 75 | public function reportAction() { 76 | 77 | $container = new Container('ContainerNamespace'); 78 | if ($container->user != "admin") { 79 | return $this->redirect()->toRoute('admin'); 80 | } 81 | $vm = new ViewModel(); 82 | $vm->subject = "Report from ". date('d-m-Y H-i'); 83 | $vm->sent = False; 84 | $request = $this->getRequest(); 85 | $vm->sent = ""; 86 | if ($request->isPost()) { 87 | 88 | $subject = $this->getRequest()->getPost("subject"); 89 | $encoding = $this->getRequest()->getPost("encoding") or 'UTF-8'; 90 | $to = "briskly@ya.ru"; 91 | $headers = "Subject: " . $subject. "\r\n" . 92 | 'From: webmaster@example.com' . "\r\n". 93 | 'Content-type: text/xml'. "\r\n"; 94 | $message = "Testing something new\n"; 95 | 96 | $str = " 97 | 98 | 99 | date 100 | $subject 101 | 102 | 103 | 104 | 105 | "; 106 | $xml = @simplexml_load_string($str, null, LIBXML_NOENT | LIBXML_DTDLOAD); 107 | if ($xml) { 108 | $posts = $xml->xpath("/report/posts")[0]; 109 | foreach ($this->getPosts() as $post) { 110 | $element = $posts->addChild("post"); 111 | $element->addChild("title", $post->title); 112 | $element->addChild("body", $post->body); 113 | 114 | } 115 | $message = $xml->asXML(); 116 | $subject = ""; 117 | mail($to, $subject, $message, $headers); 118 | $vm->sent = "yes"; 119 | } else { 120 | $vm->sent = "no"; 121 | } 122 | 123 | 124 | 125 | 126 | 127 | } 128 | 129 | return $vm; 130 | } 131 | } 132 | -------------------------------------------------------------------------------- /president-feedback/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 41 | 42 | 43 | 60 |
61 |
62 |
63 |
64 |
65 |

Contact Mr.Future President

66 |
67 |
68 |
69 |
70 | 71 | 72 |
73 |
74 | 75 | 76 |
77 |
78 | 79 | 81 |
82 | 83 |
84 |
85 |
86 | 87 |
88 | 89 | 90 | 91 | 92 |
93 |
94 | 95 |
96 |
97 |
98 |
99 |
100 |
101 | 102 | 103 | -------------------------------------------------------------------------------- /pq-messenger/src/main/java/task/Protocol.java: -------------------------------------------------------------------------------- 1 | package task; 2 | 3 | import java.io.ByteArrayOutputStream; 4 | import java.security.KeyPair; 5 | import java.security.KeyPairGenerator; 6 | import java.security.MessageDigest; 7 | import java.security.PrivateKey; 8 | import java.security.PublicKey; 9 | import java.security.SecureRandom; 10 | import java.util.Arrays; 11 | 12 | import javax.crypto.Cipher; 13 | import javax.crypto.Mac; 14 | import javax.crypto.spec.IvParameterSpec; 15 | import javax.crypto.spec.SecretKeySpec; 16 | 17 | 18 | public class Protocol { 19 | private SecureRandom random; 20 | private Cipher ac; 21 | private KeyPair keyPair; 22 | private Cipher sc; 23 | private Mac mac; 24 | private MessageDigest kdf; 25 | 26 | public Protocol(KeyPair keyPair) throws Exception { 27 | random = new SecureRandom(); 28 | ac = Cipher.getInstance("McEliece"); 29 | sc = Cipher.getInstance("AES/CBC/PKCS5PADDING"); 30 | mac = Mac.getInstance("HmacSHA256"); 31 | kdf = MessageDigest.getInstance("SHA-256"); 32 | 33 | if (keyPair == null) { 34 | KeyPairGenerator kpg = KeyPairGenerator.getInstance("McEliece"); 35 | kpg.initialize(0, random); 36 | this.keyPair = kpg.generateKeyPair(); 37 | } else { 38 | this.keyPair = keyPair; 39 | } 40 | } 41 | 42 | public PublicKey getPublicKey() { 43 | return keyPair.getPublic(); 44 | } 45 | 46 | public PrivateKey getPrivateKey() { 47 | return keyPair.getPrivate(); 48 | } 49 | 50 | public byte[] encrypt(byte[] in) throws Exception { 51 | ac.init(Cipher.ENCRYPT_MODE, keyPair.getPublic()); 52 | 53 | // Generate and encrypt token 54 | byte[] token = new byte[ac.getBlockSize()]; 55 | random.nextBytes(token); 56 | 57 | byte[] encryptedToken = ac.doFinal(token); 58 | 59 | // Derive keys 60 | kdf.reset(); 61 | 62 | byte[] digest = kdf.digest(token); 63 | 64 | // Encryption 65 | byte[] scKey = Arrays.copyOfRange(digest, 0, 16); 66 | 67 | byte[] iv = new byte[sc.getBlockSize()]; 68 | random.nextBytes(iv); 69 | 70 | IvParameterSpec ivSpec = new IvParameterSpec(iv); 71 | SecretKeySpec scKeySpec = new SecretKeySpec(scKey, "AES"); 72 | 73 | sc.init(Cipher.ENCRYPT_MODE, scKeySpec, ivSpec); 74 | 75 | byte[] encryptedData = sc.doFinal(in); 76 | 77 | // HMAC 78 | byte[] macKey = Arrays.copyOfRange(digest, 16, 32); 79 | 80 | SecretKeySpec macKeySpec = new SecretKeySpec(macKey, "HmacSHA256"); 81 | 82 | mac.reset(); 83 | mac.init(macKeySpec); 84 | mac.update(iv); 85 | mac.update(encryptedData); 86 | 87 | byte[] macDigest = new byte[mac.getMacLength()]; 88 | mac.doFinal(macDigest, 0); 89 | 90 | // Final 91 | ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); 92 | 93 | outputStream.write(encryptedToken); 94 | outputStream.write(iv); 95 | outputStream.write(encryptedData); 96 | outputStream.write(macDigest); 97 | 98 | return outputStream.toByteArray(); 99 | } 100 | 101 | public byte[] decrypt(byte[] in) throws Exception { 102 | ac.init(Cipher.DECRYPT_MODE, keyPair.getPrivate()); 103 | 104 | int minLength = ac.getBlockSize() + 2 * sc.getBlockSize() + mac.getMacLength(); 105 | 106 | if (in.length < minLength) { 107 | throw new ProtocolException("Message is too small!"); 108 | } 109 | 110 | byte[] encryptedToken = Arrays.copyOfRange(in, 0, ac.getBlockSize()); 111 | byte[] iv = Arrays.copyOfRange(in, ac.getBlockSize(), ac.getBlockSize() + sc.getBlockSize()); 112 | byte[] encryptedData = Arrays.copyOfRange(in, ac.getBlockSize() + sc.getBlockSize(), in.length - mac.getMacLength()); 113 | byte[] macDigest = Arrays.copyOfRange(in, in.length - mac.getMacLength(), in.length); 114 | 115 | // Decrypt token 116 | byte[] token = ac.doFinal(encryptedToken); 117 | 118 | // Derive keys 119 | kdf.reset(); 120 | 121 | byte[] digest = kdf.digest(token); 122 | 123 | // HMAC verify 124 | byte[] macKey = Arrays.copyOfRange(digest, 16, 32); 125 | SecretKeySpec macKeySpec = new SecretKeySpec(macKey, "HmacSHA256"); 126 | 127 | mac.reset(); 128 | mac.init(macKeySpec); 129 | mac.update(iv); 130 | mac.update(encryptedData); 131 | 132 | byte[] macDigestComputed = new byte[mac.getMacLength()]; 133 | mac.doFinal(macDigestComputed, 0); 134 | 135 | if (!Arrays.equals(macDigest, macDigestComputed)) { 136 | throw new ProtocolException("Message HMAC mismatch!"); 137 | } 138 | 139 | // Decrypt 140 | byte[] scKey = Arrays.copyOfRange(digest, 0, 16); 141 | 142 | IvParameterSpec ivSpec = new IvParameterSpec(iv); 143 | SecretKeySpec scKeySpec = new SecretKeySpec(scKey, "AES"); 144 | 145 | sc.init(Cipher.DECRYPT_MODE, scKeySpec, ivSpec); 146 | 147 | byte[] data = sc.doFinal(encryptedData); 148 | 149 | return data; 150 | } 151 | } 152 | -------------------------------------------------------------------------------- /president-blog/file.sql: -------------------------------------------------------------------------------- 1 | -- 2 | -- PostgreSQL database dump 3 | -- 4 | 5 | -- Dumped from database version 9.6.2 6 | -- Dumped by pg_dump version 9.6.2 7 | 8 | SET statement_timeout = 0; 9 | SET lock_timeout = 0; 10 | SET idle_in_transaction_session_timeout = 0; 11 | SET client_encoding = 'UTF8'; 12 | SET standard_conforming_strings = on; 13 | SET check_function_bodies = false; 14 | SET client_min_messages = warning; 15 | SET row_security = off; 16 | 17 | -- 18 | -- Name: plpgsql; Type: EXTENSION; Schema: -; Owner: 19 | -- 20 | 21 | CREATE EXTENSION IF NOT EXISTS plpgsql WITH SCHEMA pg_catalog; 22 | 23 | 24 | -- 25 | -- Name: EXTENSION plpgsql; Type: COMMENT; Schema: -; Owner: 26 | -- 27 | 28 | COMMENT ON EXTENSION plpgsql IS 'PL/pgSQL procedural language'; 29 | 30 | 31 | SET search_path = public, pg_catalog; 32 | 33 | SET default_tablespace = ''; 34 | 35 | SET default_with_oids = false; 36 | 37 | -- 38 | -- Name: posts; Type: TABLE; Schema: public; Owner: postgres 39 | -- 40 | 41 | CREATE TABLE posts ( 42 | id bigint NOT NULL, 43 | title text NOT NULL, 44 | body text NOT NULL, 45 | date timestamp without time zone 46 | ); 47 | 48 | 49 | ALTER TABLE posts OWNER TO postgres; 50 | 51 | -- 52 | -- Name: posts_id_seq; Type: SEQUENCE; Schema: public; Owner: postgres 53 | -- 54 | 55 | CREATE SEQUENCE posts_id_seq 56 | START WITH 1 57 | INCREMENT BY 1 58 | NO MINVALUE 59 | NO MAXVALUE 60 | CACHE 1; 61 | 62 | 63 | ALTER TABLE posts_id_seq OWNER TO postgres; 64 | 65 | -- 66 | -- Name: posts_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: postgres 67 | -- 68 | 69 | ALTER SEQUENCE posts_id_seq OWNED BY posts.id; 70 | 71 | 72 | -- 73 | -- Name: users; Type: TABLE; Schema: public; Owner: postgres 74 | -- 75 | 76 | CREATE TABLE users ( 77 | id bigint NOT NULL, 78 | login character varying(20) NOT NULL, 79 | password text NOT NULL 80 | ); 81 | 82 | 83 | ALTER TABLE users OWNER TO postgres; 84 | 85 | -- 86 | -- Name: users_id_seq; Type: SEQUENCE; Schema: public; Owner: postgres 87 | -- 88 | 89 | CREATE SEQUENCE users_id_seq 90 | START WITH 1 91 | INCREMENT BY 1 92 | NO MINVALUE 93 | NO MAXVALUE 94 | CACHE 1; 95 | 96 | 97 | ALTER TABLE users_id_seq OWNER TO postgres; 98 | 99 | -- 100 | -- Name: users_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: postgres 101 | -- 102 | 103 | ALTER SEQUENCE users_id_seq OWNED BY users.id; 104 | 105 | 106 | -- 107 | -- Name: posts id; Type: DEFAULT; Schema: public; Owner: postgres 108 | -- 109 | 110 | ALTER TABLE ONLY posts ALTER COLUMN id SET DEFAULT nextval('posts_id_seq'::regclass); 111 | 112 | 113 | -- 114 | -- Name: users id; Type: DEFAULT; Schema: public; Owner: postgres 115 | -- 116 | 117 | ALTER TABLE ONLY users ALTER COLUMN id SET DEFAULT nextval('users_id_seq'::regclass); 118 | 119 | 120 | -- 121 | -- Data for Name: posts; Type: TABLE DATA; Schema: public; Owner: postgres 122 | -- 123 | 124 | COPY posts (id, title, body, date) FROM stdin; 125 | 2 I`m gonna to be a president On September 15, 2016, the People delivered a historic victory and took our country back. This victory was the result of a Movement to put our country first, to save the our country economy, and to make America once again a shining city on the hill. But our Movement cannot stop now - we still have much work to do.

This is why ourCampaign Committee, Mr.Future President, Inc., is still here.

We will provide a beacon for this historic Movement as our lights continue to shine brightly for you ­­- the hardworking patriots who have paid the price for our freedom. While out capital flourished, our countries jobs were shipped overseas, our families struggled, and our factories closed - that all ended.

This Campaign will be a voice for all out citizents, in every city near and far, who support a more prosperous, safe and strong our country. That’s why our Campaign cannot stop now - our Movement is just getting started.

Together, we will Make our country Great Again! 2016-09-15 00:00:00 126 | \. 127 | 128 | 129 | -- 130 | -- Name: posts_id_seq; Type: SEQUENCE SET; Schema: public; Owner: postgres 131 | -- 132 | 133 | SELECT pg_catalog.setval('posts_id_seq', 1, false); 134 | 135 | 136 | -- 137 | -- Data for Name: users; Type: TABLE DATA; Schema: public; Owner: postgres 138 | -- 139 | 140 | COPY users (id, login, password) FROM stdin; 141 | 1 admin verystrongpassword 142 | \. 143 | 144 | 145 | -- 146 | -- Name: users_id_seq; Type: SEQUENCE SET; Schema: public; Owner: postgres 147 | -- 148 | 149 | SELECT pg_catalog.setval('users_id_seq', 1, false); 150 | 151 | 152 | 153 | -- 154 | -- Name: posts posts_pkey; Type: CONSTRAINT; Schema: public; Owner: postgres 155 | -- 156 | 157 | ALTER TABLE ONLY posts 158 | ADD CONSTRAINT posts_pkey PRIMARY KEY (id); 159 | 160 | 161 | -- 162 | -- Name: users users_pkey; Type: CONSTRAINT; Schema: public; Owner: postgres 163 | -- 164 | 165 | ALTER TABLE ONLY users 166 | ADD CONSTRAINT users_pkey PRIMARY KEY (id); 167 | 168 | 169 | -- 170 | -- Name: posts; Type: ACL; Schema: public; Owner: postgres 171 | -- 172 | 173 | create user task200 with password 'rahPhila7ud1th'; 174 | 175 | GRANT ALL ON TABLE posts TO task200; 176 | 177 | 178 | -- 179 | -- Name: users; Type: ACL; Schema: public; Owner: postgres 180 | -- 181 | 182 | GRANT ALL ON TABLE users TO task200; 183 | 184 | 185 | -- 186 | -- PostgreSQL database dump complete 187 | -- 188 | 189 | -------------------------------------------------------------------------------- /timehackers/web/contact.php: -------------------------------------------------------------------------------- 1 | 9 | 10 | 11 | 12 | 13 | TimeHackers Cr3w 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 |
24 |
25 | 37 |
38 |
39 | real_escape_string($_POST['message']); 45 | $session_id = $mysqli->real_escape_string(session_id()); 46 | $uid = md5(uniqid()); 47 | $query = "INSERT INTO `feedbacks` (`message`,`is_checked`,`timestamp`,`session_id`,`uid`) VALUES ('{$message}',0,now(),'{$session_id}','{$uid}');"; 48 | $mysqli->query($query); 49 | echo ' 50 |
51 | Success! Your message sended. Message UID: '.$uid.' 52 |
53 | '; 54 | } 55 | else 56 | { 57 | echo ' 58 |
59 | Error! Captcha is not correct. 60 |
61 | '; 62 | } 63 | $_SESSION['captcha'] = simple_php_captcha(); 64 | } 65 | ?> 66 |
67 |
Contact form
68 |
69 |
70 |
71 |
72 | 73 | 74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 | 85 |
86 |
87 |
88 |
Your Messages:
89 |
90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | real_escape_string(session_id()); 101 | $query = "SELECT timestamp,uid,is_checked FROM feedbacks WHERE session_id = '{$session_id}' ORDER BY id DESC"; 102 | $result = $mysqli->query($query); 103 | if ($result->num_rows > 0) { 104 | while ($row = $result->fetch_row()) { 105 | if ( intval($row[2]) === 1 ) 106 | $status = '
Checked
'; 107 | else 108 | $status = '
Waiting
'; 109 | echo " 110 | 111 | 112 | 113 | 114 | 115 | "; 116 | } 117 | } 118 | else 119 | { 120 | echo " 121 | 122 | 123 | 124 | 125 | 126 | "; 127 | } 128 | ?> 129 | 130 |
Time
UID
Status
{$row[0]}
{$row[1]}
{$status}
-
-
-
131 |
132 |
133 |
134 | 135 | 136 | 137 | -------------------------------------------------------------------------------- /election-department-service/src/hashtable.c: -------------------------------------------------------------------------------- 1 | #include "hashtable.h" 2 | 3 | #include 4 | #include 5 | 6 | struct bucket 7 | { 8 | struct bucket *next; 9 | void *key; 10 | void *data; 11 | }; 12 | 13 | struct hashtable 14 | { 15 | size_t count; 16 | size_t nbuckets; 17 | struct bucket **buckets; 18 | size_t (*hash)(const void *key); 19 | int (*equals)(const void *key1, const void *key2); 20 | void (*release)(void *key, void *data); 21 | }; 22 | 23 | struct iterator 24 | { 25 | hashtable_t table; 26 | int cur_idx; 27 | struct bucket *cur_bucket; 28 | }; 29 | 30 | hashtable_t hashtable_create(size_t capacity, 31 | size_t (*hash)(const void *key), 32 | int (*equals)(const void *key1, const void *key2), 33 | void (*release)(void *key, void *data)) 34 | { 35 | hashtable_t hashtable = (hashtable_t)malloc(sizeof(struct hashtable)); 36 | hashtable->count = 0; 37 | hashtable->nbuckets = capacity < 4 ? 4 : capacity; 38 | hashtable->buckets = (struct bucket **)calloc(capacity, sizeof(struct bucket *)); 39 | hashtable->hash = hash; 40 | hashtable->equals = equals; 41 | 42 | return hashtable; 43 | } 44 | 45 | void hashtable_reset(hashtable_t hashtable) 46 | { 47 | for (size_t i = 0; i < hashtable->nbuckets; i++) 48 | { 49 | struct bucket *b = hashtable->buckets[i]; 50 | while (b != NULL) 51 | { 52 | b = b->next; 53 | hashtable->release(b->key, b->data); 54 | free(b); 55 | } 56 | hashtable->buckets[i] = NULL; 57 | } 58 | } 59 | 60 | void hashtable_free(hashtable_t hashtable) 61 | { 62 | hashtable_reset(hashtable); 63 | free(hashtable->buckets); 64 | free(hashtable); 65 | } 66 | 67 | static void hashtable_grow(hashtable_t hashtable, size_t capacity) 68 | { 69 | struct bucket **old = hashtable->buckets; 70 | struct bucket **new = (struct bucket **)calloc(capacity, sizeof(struct bucket *)); 71 | 72 | for (size_t i = 0; i < hashtable->nbuckets; i++) 73 | { 74 | for (struct bucket *b = old[i]; b != NULL; b = b->next) 75 | { 76 | size_t new_idx = hashtable->hash(b->key) % capacity; 77 | b->next = new[new_idx]; 78 | new[new_idx] = b; 79 | } 80 | } 81 | 82 | hashtable->nbuckets = capacity; 83 | hashtable->buckets = new; 84 | } 85 | 86 | void hashtable_insert(hashtable_t hashtable, void *key, void *data) 87 | { 88 | size_t i = hashtable->hash(key) % hashtable->nbuckets; 89 | 90 | if (hashtable_contains(hashtable, key)) 91 | return; 92 | 93 | struct bucket *b = (struct bucket *)malloc(sizeof(struct bucket));; 94 | b->next = hashtable->buckets[i]; 95 | b->key = key; 96 | b->data = data; 97 | 98 | hashtable->buckets[i] = b; 99 | hashtable->count++; 100 | 101 | if (hashtable->count > hashtable->nbuckets) 102 | hashtable_grow(hashtable, hashtable->nbuckets * 2); 103 | } 104 | 105 | void *hashtable_get(hashtable_t hashtable, const void *key) 106 | { 107 | size_t i = hashtable->hash(key) % hashtable->nbuckets; 108 | 109 | void *res = NULL; 110 | for (struct bucket *b = hashtable->buckets[i]; b != NULL; b = b->next) 111 | { 112 | if (hashtable->equals(b->key, key)) 113 | { 114 | res = b->data; 115 | break; 116 | } 117 | } 118 | 119 | return res; 120 | } 121 | 122 | int hashtable_contains(hashtable_t hashtable, const void *key) 123 | { 124 | return hashtable_get(hashtable, key) != NULL; 125 | } 126 | 127 | void hashtable_delete(hashtable_t hashtable, const void *key) 128 | { 129 | size_t i = hashtable->hash(key) % hashtable->nbuckets; 130 | 131 | struct bucket *prev = NULL; 132 | for (struct bucket *b = hashtable->buckets[i]; b != NULL; prev = b, b = b->next) 133 | { 134 | if (hashtable->equals(b->key, key)) 135 | { 136 | if (prev == NULL) 137 | { 138 | hashtable->buckets[i] = b->next; 139 | } 140 | else 141 | { 142 | prev->next = b->next; 143 | } 144 | 145 | free(b); 146 | break; 147 | } 148 | } 149 | } 150 | 151 | // hashtable callbacks 152 | size_t string_hash(const void *key) 153 | { 154 | const char *str = (const char *)key; 155 | size_t hash = 5381; 156 | int c; 157 | while ((c = *str++)) 158 | hash = ((hash << 5) + hash) + c; 159 | 160 | return hash; 161 | } 162 | 163 | int string_equals(const void *key1, const void *key2) 164 | { 165 | return strcmp((const char *)key1, (const char *)key2) == 0; 166 | } 167 | 168 | // iterator 169 | iterator_t iterator_create(hashtable_t table) 170 | { 171 | iterator_t iter = (iterator_t)malloc(sizeof(struct iterator)); 172 | iter->table = table; 173 | iter->cur_idx = -1; 174 | iter->cur_bucket = NULL; 175 | return iter; 176 | } 177 | 178 | void iterator_delete(iterator_t iter) 179 | { 180 | free(iter); 181 | } 182 | 183 | void *iterator_next(iterator_t iter) 184 | { 185 | struct bucket *b = iter->cur_bucket; 186 | while (b == NULL) 187 | { 188 | iter->cur_idx += 1; 189 | if (iter->cur_idx == iter->table->nbuckets) 190 | return NULL; 191 | 192 | b = iter->table->buckets[iter->cur_idx]; 193 | } 194 | 195 | iter->cur_bucket = b->next; 196 | 197 | return b->data; 198 | } 199 | -------------------------------------------------------------------------------- /election-department-service/src/service.c: -------------------------------------------------------------------------------- 1 | #include "service.h" 2 | #include "hashtable.h" 3 | #include "candidate.h" 4 | #include "utils.h" 5 | 6 | #include 7 | 8 | #ifdef DEBUG 9 | #include 10 | #endif 11 | 12 | static void service_check_candidate(hashtable_t table, int *pipefd) 13 | { 14 | int read_fd = pipefd[0]; 15 | int write_fd = pipefd[1]; 16 | 17 | const char *citizen_id = recv_string(read_fd); 18 | if (citizen_id == NULL) 19 | return; 20 | 21 | int res = hashtable_contains(table, citizen_id); 22 | free((void *)citizen_id); 23 | write(write_fd, &res, sizeof(res)); 24 | } 25 | 26 | static void candidate_cleanup(struct candidate *c) 27 | { 28 | free((void *)c->firstname); 29 | free((void *)c->lastname); 30 | free((void *)c->citizen_id); 31 | free((void *)c->address); 32 | } 33 | 34 | static void service_store_candidate(hashtable_t table, int *pipefd) 35 | { 36 | int read_fd = pipefd[0]; 37 | int write_fd = pipefd[1]; 38 | 39 | char *firstname = recv_string(read_fd); 40 | if (firstname == NULL) 41 | return; 42 | 43 | char *lastname = recv_string(read_fd); 44 | if (lastname == NULL) 45 | return; 46 | 47 | char *citizen_id = recv_string(read_fd); 48 | if (citizen_id == NULL) 49 | return; 50 | 51 | char *address = recv_string(read_fd); 52 | if (address == NULL) 53 | return; 54 | 55 | if (!hashtable_contains(table, citizen_id)) 56 | { 57 | struct candidate *c = (struct candidate*)malloc(sizeof(struct candidate)); 58 | c->firstname = firstname; 59 | c->lastname = lastname; 60 | c->citizen_id = citizen_id; 61 | c->address = address; 62 | c->cleanup = candidate_cleanup; 63 | 64 | hashtable_insert(table, citizen_id, c); 65 | } 66 | 67 | int res = 0; 68 | write(write_fd, &res, sizeof(res)); 69 | } 70 | 71 | static void service_delete_candidate(hashtable_t table, int *pipefd) 72 | { 73 | int read_fd = pipefd[0]; 74 | int write_fd = pipefd[1]; 75 | 76 | const char *citizen_id = recv_string(read_fd); 77 | if (citizen_id == NULL) 78 | return; 79 | 80 | hashtable_delete(table, citizen_id); 81 | free((void *)citizen_id); 82 | 83 | int res = 0; 84 | write(write_fd, &res, sizeof(res)); 85 | } 86 | 87 | static void service_list_candidates(hashtable_t table, int *pipefd) 88 | { 89 | int write_fd = pipefd[1]; 90 | 91 | iterator_t iter = iterator_create(table); 92 | void *p; 93 | int res; 94 | while ((p = iterator_next(iter))) 95 | { 96 | struct candidate *c = (struct candidate*)p; 97 | 98 | #ifdef DEBUG 99 | printf("candidate: %p\n", c); 100 | printf("firstname: %s\n", c->firstname); 101 | printf("lastname: %s\n", c->lastname); 102 | printf("citizen_id: %s\n", c->citizen_id); 103 | printf("address: %s\n", c->address); 104 | printf("votes: %d\n", c->votes); 105 | #endif 106 | 107 | res = 1; 108 | if (write(write_fd, &res, sizeof(res)) != sizeof(res)) 109 | return; 110 | 111 | if (send_string(write_fd, c->firstname) < 0) 112 | return; 113 | 114 | if (send_string(write_fd, c->lastname) < 0) 115 | return; 116 | 117 | if (send_string(write_fd, c->citizen_id) < 0) 118 | return; 119 | 120 | if (send_string(write_fd, c->address) < 0) 121 | return; 122 | 123 | if (write(write_fd, &c->votes, sizeof(c->votes)) != sizeof(c->votes)) 124 | return; 125 | 126 | } 127 | iterator_delete(iter); 128 | 129 | res = 0; 130 | write(write_fd, &res, sizeof(res)); 131 | } 132 | 133 | static void service_vote_candidate(hashtable_t table, int *pipefd) 134 | { 135 | int read_fd = pipefd[0]; 136 | int write_fd = pipefd[1]; 137 | 138 | const char *citizen_id = recv_string(read_fd); 139 | if (citizen_id == NULL) 140 | return; 141 | 142 | struct candidate *c = (struct candidate *)hashtable_get(table, citizen_id); 143 | if (c != NULL) 144 | c->votes += 1; 145 | 146 | free((void *)citizen_id); 147 | 148 | int res = (c == NULL) ? -1 : 0; 149 | write(write_fd, &res, sizeof(res)); 150 | } 151 | 152 | void hashtable_release(void *key, void *data) 153 | { 154 | struct candidate *c = (struct candidate *)data; 155 | if (key != c->citizen_id) 156 | free((void *)key); 157 | 158 | c->cleanup(c); 159 | free((void *)c); 160 | } 161 | 162 | void service_loop(int *pipefd) 163 | { 164 | int read_fd = pipefd[0]; 165 | 166 | hashtable_t table = hashtable_create(16, 167 | string_hash, 168 | string_equals, 169 | hashtable_release); 170 | 171 | while (1) 172 | { 173 | int opcode; 174 | int res = read(read_fd, &opcode, sizeof(opcode)); 175 | if (res != sizeof(opcode)) 176 | continue; 177 | 178 | #ifdef DEBUG 179 | printf("got opcode: %d\n", opcode); 180 | #endif 181 | 182 | switch (opcode) 183 | { 184 | case CHECK: 185 | service_check_candidate(table, pipefd); 186 | break; 187 | case STORE: 188 | service_store_candidate(table, pipefd); 189 | break; 190 | case DELETE: 191 | service_delete_candidate(table, pipefd); 192 | break; 193 | case LIST: 194 | service_list_candidates(table, pipefd); 195 | break; 196 | case VOTE: 197 | service_vote_candidate(table, pipefd); 198 | break; 199 | } 200 | } 201 | } 202 | -------------------------------------------------------------------------------- /pq-messenger/gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Attempt to set APP_HOME 10 | # Resolve links: $0 may be a link 11 | PRG="$0" 12 | # Need this for relative symlinks. 13 | while [ -h "$PRG" ] ; do 14 | ls=`ls -ld "$PRG"` 15 | link=`expr "$ls" : '.*-> \(.*\)$'` 16 | if expr "$link" : '/.*' > /dev/null; then 17 | PRG="$link" 18 | else 19 | PRG=`dirname "$PRG"`"/$link" 20 | fi 21 | done 22 | SAVED="`pwd`" 23 | cd "`dirname \"$PRG\"`/" >/dev/null 24 | APP_HOME="`pwd -P`" 25 | cd "$SAVED" >/dev/null 26 | 27 | APP_NAME="Gradle" 28 | APP_BASE_NAME=`basename "$0"` 29 | 30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 31 | DEFAULT_JVM_OPTS="" 32 | 33 | # Use the maximum available, or set MAX_FD != -1 to use that value. 34 | MAX_FD="maximum" 35 | 36 | warn ( ) { 37 | echo "$*" 38 | } 39 | 40 | die ( ) { 41 | echo 42 | echo "$*" 43 | echo 44 | exit 1 45 | } 46 | 47 | # OS specific support (must be 'true' or 'false'). 48 | cygwin=false 49 | msys=false 50 | darwin=false 51 | nonstop=false 52 | case "`uname`" in 53 | CYGWIN* ) 54 | cygwin=true 55 | ;; 56 | Darwin* ) 57 | darwin=true 58 | ;; 59 | MINGW* ) 60 | msys=true 61 | ;; 62 | NONSTOP* ) 63 | nonstop=true 64 | ;; 65 | esac 66 | 67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 68 | 69 | # Determine the Java command to use to start the JVM. 70 | if [ -n "$JAVA_HOME" ] ; then 71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 72 | # IBM's JDK on AIX uses strange locations for the executables 73 | JAVACMD="$JAVA_HOME/jre/sh/java" 74 | else 75 | JAVACMD="$JAVA_HOME/bin/java" 76 | fi 77 | if [ ! -x "$JAVACMD" ] ; then 78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 79 | 80 | Please set the JAVA_HOME variable in your environment to match the 81 | location of your Java installation." 82 | fi 83 | else 84 | JAVACMD="java" 85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 86 | 87 | Please set the JAVA_HOME variable in your environment to match the 88 | location of your Java installation." 89 | fi 90 | 91 | # Increase the maximum file descriptors if we can. 92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 93 | MAX_FD_LIMIT=`ulimit -H -n` 94 | if [ $? -eq 0 ] ; then 95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 96 | MAX_FD="$MAX_FD_LIMIT" 97 | fi 98 | ulimit -n $MAX_FD 99 | if [ $? -ne 0 ] ; then 100 | warn "Could not set maximum file descriptor limit: $MAX_FD" 101 | fi 102 | else 103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 104 | fi 105 | fi 106 | 107 | # For Darwin, add options to specify how the application appears in the dock 108 | if $darwin; then 109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 110 | fi 111 | 112 | # For Cygwin, switch paths to Windows format before running java 113 | if $cygwin ; then 114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 116 | JAVACMD=`cygpath --unix "$JAVACMD"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Escape application args 158 | save ( ) { 159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 160 | echo " " 161 | } 162 | APP_ARGS=$(save "$@") 163 | 164 | # Collect all arguments for the java command, following the shell quoting and substitution rules 165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 166 | 167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong 168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then 169 | cd "$(dirname "$0")" 170 | fi 171 | 172 | exec "$JAVACMD" "$@" 173 | -------------------------------------------------------------------------------- /president-blog/config/autoload/zend-developer-tools.local-development.php: -------------------------------------------------------------------------------- 1 | [ 15 | /** 16 | * General Profiler settings 17 | */ 18 | 'profiler' => [ 19 | /** 20 | * Enables or disables the profiler. 21 | * 22 | * Expects: bool 23 | * Default: true 24 | */ 25 | 'enabled' => true, 26 | 27 | /** 28 | * Enables or disables the strict mode. If the strict mode is enabled, any error will throw an exception, 29 | * otherwise all errors will be added to the report (and shown in the toolbar). 30 | * 31 | * Expects: bool 32 | * Default: true 33 | */ 34 | 'strict' => true, 35 | 36 | /** 37 | * If enabled, the profiler tries to flush the content before the it starts collecting data. This option 38 | * will be ignored if the Toolbar is enabled. 39 | * 40 | * Note: The flush listener listens to the MvcEvent::EVENT_FINISH event with a priority of -9400. You have 41 | * to disable this function if you wish to modify the output with a lower priority. 42 | * 43 | * Expects: bool 44 | * Default: false 45 | */ 46 | 'flush_early' => false, 47 | 48 | /** 49 | * The cache directory is used in the version check and for every storage type that writes to the disk. 50 | * Note: The default value assumes that the current working directory is the application root. 51 | * 52 | * Expects: string 53 | * Default: 'data/cache' 54 | */ 55 | 'cache_dir' => 'data/cache', 56 | 57 | /** 58 | * If a matches is defined, the profiler will be disabled if the request does not match the pattern. 59 | * 60 | * Example: 'matcher' => array('ip' => '127.0.0.1') 61 | * OR 62 | * 'matcher' => array('url' => array('path' => '/admin') 63 | * Note: The matcher is not implemented yet! 64 | */ 65 | 'matcher' => [], 66 | 67 | /** 68 | * Contains a list with all collector the profiler should run. Zend Developer Tools ships with 69 | * 'db' (Zend\Db), 'time', 'event', 'memory', 'exception', 'request' and 'mail' (Zend\Mail). If you wish to 70 | * disable a default collector, simply set the value to null or false. 71 | * 72 | * Example: 'collectors' => array('db' => null) 73 | * Expects: array 74 | */ 75 | 'collectors' => [], 76 | ], 77 | 'events' => [ 78 | /** 79 | * Set to true to enable event-level logging for collectors that will support it. This enables a wildcard 80 | * listener onto the shared event manager that will allow profiling of user-defined events as well as the 81 | * built-in ZF events. 82 | * 83 | * Expects: bool 84 | * Default: false 85 | */ 86 | 'enabled' => true, 87 | 88 | /** 89 | * Contains a list with all event-level collectors that should run. Zend Developer Tools ships with 'time' 90 | * and 'memory'. If you wish to disable a default collector, simply set the value to null or false. 91 | * 92 | * Example: 'collectors' => array('memory' => null) 93 | * Expects: array 94 | */ 95 | 'collectors' => [], 96 | 97 | /** 98 | * Contains event identifiers used with the event listener. Zend Developer Tools defaults to listen to all 99 | * events. If you wish to disable the default all-inclusive identifier, simply set the value to null or 100 | * false. 101 | * 102 | * Example: 'identifiers' => array('all' => null, 'dispatchable' => 'Zend\Stdlib\DispatchableInterface') 103 | * Expects: array 104 | */ 105 | 'identifiers' => [], 106 | ], 107 | /** 108 | * General Toolbar settings 109 | */ 110 | 'toolbar' => [ 111 | /** 112 | * Enables or disables the Toolbar. 113 | * 114 | * Expects: bool 115 | * Default: false 116 | */ 117 | 'enabled' => true, 118 | 119 | /** 120 | * If enabled, every empty collector will be hidden. 121 | * 122 | * Expects: bool 123 | * Default: false 124 | */ 125 | 'auto_hide' => false, 126 | 127 | /** 128 | * The Toolbar position. 129 | * 130 | * Expects: string ('bottom' or 'top') 131 | * Default: bottom 132 | */ 133 | 'position' => 'bottom', 134 | 135 | /** 136 | * If enabled, the Toolbar will check if your current Zend Framework version is up-to-date. 137 | * Note: The check will only occur once every hour. 138 | * 139 | * Expects: bool 140 | * Default: false 141 | */ 142 | 'version_check' => false, 143 | 144 | /** 145 | * Contains a list with all collector toolbar templates. The name of the array key must be same as the name 146 | * of the collector. 147 | * 148 | * Example: 'profiler' => array( 149 | * 'collectors' => array( 150 | * // My_Collector_Example::getName() -> mycollector 151 | * 'MyCollector' => 'My_Collector_Example', 152 | * ) 153 | * ), 154 | * 'toolbar' => array( 155 | * 'entries' => array( 156 | * 'mycollector' => 'example/toolbar/my-collector', 157 | * ) 158 | * ), 159 | * Expects: array 160 | */ 161 | 'entries' => [], 162 | ], 163 | ], 164 | ]; 165 | -------------------------------------------------------------------------------- /pq-messenger/src/main/java/task/Main.java: -------------------------------------------------------------------------------- 1 | package task; 2 | 3 | import akka.actor.ActorRef; 4 | import akka.actor.ActorSystem; 5 | 6 | import com.beust.jcommander.JCommander; 7 | import com.beust.jcommander.Parameter; 8 | import com.beust.jcommander.Parameters; 9 | 10 | import java.io.FileWriter; 11 | import java.io.IOException; 12 | import java.io.Writer; 13 | import java.nio.file.Files; 14 | import java.nio.file.Path; 15 | import java.nio.file.Paths; 16 | import java.security.KeyFactory; 17 | import java.security.KeyPair; 18 | import java.security.Security; 19 | import java.security.spec.PKCS8EncodedKeySpec; 20 | import java.security.spec.X509EncodedKeySpec; 21 | import java.util.Base64; 22 | import java.util.List; 23 | 24 | import org.bouncycastle.pqc.crypto.mceliece.McElieceCipher; 25 | import org.bouncycastle.pqc.jcajce.provider.BouncyCastlePQCProvider; 26 | 27 | import scala.concurrent.Await; 28 | import scala.concurrent.duration.Duration; 29 | 30 | public class Main { 31 | 32 | public static final int PORT = 1337; 33 | 34 | @Parameter(names = "--help", description = "Show help", help = true) 35 | public boolean help; 36 | 37 | @Parameters(commandDescription = "Generate keys and save them to files") 38 | public static class GenKeysCommand { 39 | @Parameter(names = "-outdir", description = "Directory where keys will be saved", required = true) 40 | public String outDir; 41 | } 42 | 43 | @Parameters(commandDescription = "Encrypt string") 44 | public static class EncryptCommand { 45 | @Parameter(names = "-keysdir", description = "Directory with keys", required = true) 46 | public String keysDir; 47 | 48 | @Parameter(description = "", required = true) 49 | public String str; 50 | } 51 | 52 | @Parameters(commandDescription = "Start server") 53 | public static class StartCommand { 54 | @Parameter(names = "-keysdir", description = "Directory with keys", required = true) 55 | public String keysDir; 56 | } 57 | 58 | public static void main(String[] args) { 59 | 60 | Main main = new Main(); 61 | GenKeysCommand gc = new GenKeysCommand(); 62 | EncryptCommand ec = new EncryptCommand(); 63 | StartCommand sc = new StartCommand(); 64 | 65 | JCommander jc = JCommander.newBuilder() 66 | .addObject(main) 67 | .addCommand("genkeys", gc) 68 | .addCommand("encrypt", ec) 69 | .addCommand("start", sc) 70 | .build(); 71 | 72 | String cmd = null; 73 | try { 74 | jc.parse(args); 75 | cmd = jc.getParsedCommand(); 76 | } catch(Exception e) { 77 | System.out.println(e.getMessage()); 78 | jc.usage(); 79 | System.exit(1); 80 | } 81 | 82 | if (main.help || cmd == null) { 83 | jc.usage(); 84 | System.exit(0); 85 | } 86 | 87 | 88 | Security.addProvider(new BouncyCastlePQCProvider()); 89 | 90 | switch(cmd) { 91 | case "genkeys": 92 | main.genKeys(gc); 93 | break; 94 | 95 | case "encrypt": 96 | main.encrypt(ec); 97 | break; 98 | 99 | case "start": 100 | main.start(sc); 101 | break; 102 | } 103 | 104 | } 105 | 106 | public void exportPEMObject(byte[] data, String filename, String name) throws IOException { 107 | FileWriter fw = new FileWriter(filename); 108 | 109 | fw.write(String.format("-----BEGIN %s-----\n", name.toUpperCase())); 110 | 111 | String encoded = Base64.getEncoder().encodeToString(data); 112 | for (int i = 0; i < encoded.length() / 64; i++) { 113 | fw.write(encoded.substring(i*64, (i+1)*64) + "\n"); 114 | } 115 | int rest = encoded.length() % 64; 116 | fw.write(encoded.substring(encoded.length() - rest, encoded.length()) + "\n"); 117 | fw.write(String.format("-----END %s-----\n", name.toUpperCase())); 118 | fw.flush(); 119 | } 120 | 121 | public byte[] importPemObject(String filename) throws IOException { 122 | List lines = Files.readAllLines(Paths.get(filename)); 123 | lines.remove(0); 124 | lines.remove(lines.size() - 1); 125 | String encoded = String.join("", lines); 126 | 127 | return Base64.getDecoder().decode(encoded); 128 | } 129 | 130 | public void genKeys(GenKeysCommand c) { 131 | try { 132 | Path dir = Paths.get(c.outDir); 133 | Protocol protocol = new Protocol(null); 134 | 135 | exportPEMObject(protocol.getPublicKey().getEncoded(), 136 | dir.resolve("pubkey.pem").toString(), "Public Key"); 137 | 138 | exportPEMObject(protocol.getPrivateKey().getEncoded(), 139 | dir.resolve("privkey.pem").toString(), "Private key"); 140 | 141 | } catch (Exception e) { 142 | System.out.println("genkeys error: " + e.getMessage()); 143 | e.printStackTrace(); 144 | } 145 | } 146 | 147 | public Protocol initWithKeys(String keysDir) throws Exception { 148 | Path dir = Paths.get(keysDir); 149 | 150 | byte[] pubKeyBytes = importPemObject(dir.resolve("pubkey.pem").toString()); 151 | X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(pubKeyBytes); 152 | 153 | byte[] privKeyBytes = importPemObject(dir.resolve("privkey.pem").toString()); 154 | PKCS8EncodedKeySpec privKeySpec = new PKCS8EncodedKeySpec(privKeyBytes); 155 | 156 | KeyFactory kf = KeyFactory.getInstance("McEliece"); 157 | KeyPair keyPair = new KeyPair(kf.generatePublic(pubKeySpec), 158 | kf.generatePrivate(privKeySpec)); 159 | 160 | return new Protocol(keyPair); 161 | } 162 | 163 | public void encrypt(EncryptCommand c) { 164 | try { 165 | Protocol protocol = initWithKeys(c.keysDir); 166 | byte[] encrypted = protocol.encrypt(c.str.getBytes()); 167 | String encoded = Base64.getEncoder().encodeToString(encrypted); 168 | System.out.println(encoded); 169 | } catch (Exception e) { 170 | System.out.println("encrypt error: " + e.getMessage()); 171 | e.printStackTrace(); 172 | } 173 | } 174 | 175 | public void start(StartCommand c) { 176 | try { 177 | 178 | Protocol protocol = initWithKeys(c.keysDir); 179 | 180 | ActorSystem system = ActorSystem.create("ServerActorSystem"); 181 | ActorRef server = system.actorOf(Server.props(PORT, protocol), "server"); 182 | Await.result(system.whenTerminated(), Duration.Inf()); 183 | 184 | } catch (Exception e) { 185 | System.out.println("start error: " + e.getMessage()); 186 | e.printStackTrace(); 187 | } 188 | } 189 | } 190 | -------------------------------------------------------------------------------- /election-department-service/src/heap.c: -------------------------------------------------------------------------------- 1 | #include "heap.h" 2 | #include "io.h" 3 | #include "utils.h" 4 | 5 | #include 6 | #include 7 | #include 8 | #include 9 | 10 | struct chunk; 11 | typedef struct chunk* chunkptr_t; 12 | 13 | struct chunk 14 | { 15 | size_t prev_size; 16 | size_t size; 17 | chunkptr_t fd; 18 | chunkptr_t bk; 19 | }; 20 | 21 | #define HEAP_SIZE 0x1000000 22 | 23 | #define ALIGNMENT (2 * sizeof(size_t)) 24 | #define ALIGN_MASK (ALIGNMENT - 1) 25 | 26 | #define CHUNK_SIZE (sizeof(struct chunk)) 27 | #define HEADER_SIZE (2 * sizeof(size_t)) 28 | 29 | #define check_alignment(m) (((size_t)(m) & ALIGN_MASK) == 0) 30 | #define align_size(m) \ 31 | (((m) + HEADER_SIZE < CHUNK_SIZE) ? \ 32 | sizeof(struct chunk) : \ 33 | ((m) + HEADER_SIZE + ALIGN_MASK) & ~ALIGN_MASK) 34 | 35 | #define PREV_INUSE 0x1 36 | #define IS_LAST 0x2 37 | 38 | #define SIZE_BITS (PREV_INUSE | IS_LAST) 39 | 40 | #define chunk2mem(p) ((void*)((char*)(p) + HEADER_SIZE)) 41 | #define mem2chunk(mem) ((chunkptr_t)((char*)(mem) - HEADER_SIZE)) 42 | #define chunksize(p) ((p)->size & ~SIZE_BITS) 43 | #define next_chunk(p) ((chunkptr_t) (((char *)(p)) + chunksize(p))) 44 | #define prev_chunk(p) ((chunkptr_t) (((char *)(p)) - p->prev_size)) 45 | 46 | #define prev_inuse(p) ((p)->size & PREV_INUSE) 47 | #define set_prev_inuse(p) (p)->size |= PREV_INUSE 48 | #define clear_prev_inuse(p) (p)->size &= ~PREV_INUSE 49 | 50 | #define inuse(p) prev_inuse(next_chunk(p)) 51 | #define set_inuse(p) set_prev_inuse(next_chunk(p)) 52 | #define clear_inuse(p) clear_prev_inuse(next_chunk(p)) 53 | 54 | #define islast_chunk(p) ((p)->size & IS_LAST) 55 | #define set_islast_chunk(p) (p)->size |= IS_LAST 56 | #define clear_islast_chunk(p) (p)->size &= ~IS_LAST 57 | 58 | #define set_size(p, s) (p)->size = s | ((p)->size & SIZE_BITS) 59 | 60 | static void *g_ptr; 61 | static size_t g_size; 62 | 63 | static chunkptr_t g_free_list; 64 | 65 | __attribute__((constructor)) 66 | void init_heap() 67 | { 68 | g_size = HEAP_SIZE; 69 | g_ptr = mmap(NULL, g_size + PAGE_SIZE, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0); 70 | if (g_ptr == MAP_FAILED) 71 | { 72 | perror("mmap"); 73 | sec_exit(EXIT_FAILURE); 74 | } 75 | 76 | g_free_list = (chunkptr_t)g_ptr; 77 | 78 | g_free_list->prev_size = 0; 79 | g_free_list->size = g_size; 80 | g_free_list->fd = NULL; 81 | g_free_list->bk = NULL; 82 | 83 | set_prev_inuse(g_free_list); 84 | set_islast_chunk(g_free_list); 85 | clear_inuse(g_free_list); 86 | } 87 | 88 | static void printerr(const char *str) 89 | { 90 | fprint_string(STDERR_FILENO, str); 91 | abort(); 92 | } 93 | 94 | static void unlink_chunk(chunkptr_t p) 95 | { 96 | chunkptr_t next = p->fd; 97 | chunkptr_t prev = p->bk; 98 | 99 | if (prev == NULL) 100 | { 101 | g_free_list = next; 102 | } 103 | else 104 | { 105 | prev->fd = next; 106 | } 107 | 108 | if (next != NULL) 109 | next->bk = prev; 110 | } 111 | 112 | #ifdef DEBUG 113 | void dump_chunk(chunkptr_t p) 114 | { 115 | printf("p: %p\n", p); 116 | printf("p->prev_size: %lu\n", p->prev_size); 117 | printf("p->size: %lu\n", p->size); 118 | printf("p->fd: %p\n", p->fd); 119 | printf("p->bk: %p\n", p->bk); 120 | } 121 | 122 | void dump_heap() 123 | { 124 | printf("free list:\n"); 125 | chunkptr_t p; 126 | for (p = g_free_list; p != NULL; p = p->fd) 127 | { 128 | printf("--------------------------------\n"); 129 | dump_chunk(p); 130 | } 131 | printf("--------------------------------\n"); 132 | } 133 | #endif 134 | 135 | void *alloc(size_t size) 136 | { 137 | #ifdef DEBUG 138 | printf("alloc(%lu)\n", size); 139 | dump_heap(); 140 | #endif 141 | size = align_size(size); 142 | 143 | chunkptr_t p; 144 | for (p = g_free_list; p != NULL; p = p->fd) 145 | { 146 | if (chunksize(p) >= size) 147 | break; 148 | } 149 | 150 | // out of memory 151 | if (p == NULL) 152 | return NULL; 153 | 154 | size_t rem_size = chunksize(p) - size; 155 | if (rem_size <= HEADER_SIZE) 156 | { 157 | set_inuse(p); 158 | unlink_chunk(p); 159 | #ifdef DEBUG 160 | printf("alloc: chunk: %p mem: %p\n", p, chunk2mem(p)); 161 | dump_heap(); 162 | #endif 163 | return chunk2mem(p); 164 | } 165 | 166 | chunkptr_t next = p->fd; 167 | chunkptr_t prev = p->bk; 168 | 169 | // split chunk 170 | chunkptr_t new_chunk = (chunkptr_t)((char*)p + size); 171 | new_chunk->fd = next; 172 | new_chunk->bk = prev; 173 | 174 | set_size(new_chunk, rem_size); 175 | set_prev_inuse(new_chunk); 176 | 177 | set_size(p, size); 178 | 179 | if (next != NULL) 180 | { 181 | next->bk = new_chunk; 182 | } 183 | else 184 | { 185 | set_islast_chunk(new_chunk); 186 | clear_islast_chunk(p); 187 | } 188 | 189 | if (prev != NULL) 190 | { 191 | prev->fd = new_chunk; 192 | } 193 | else 194 | { 195 | g_free_list = new_chunk; 196 | } 197 | 198 | #ifdef DEBUG 199 | printf("alloc: chunk: %p mem: %p\n", p, chunk2mem(p)); 200 | dump_heap(); 201 | #endif 202 | 203 | return chunk2mem(p); 204 | } 205 | 206 | void release(void *p) 207 | { 208 | #ifdef DEBUG 209 | printf("release(%p)\n", p); 210 | if (p != NULL) 211 | { 212 | printf("chunk:\n"); 213 | dump_chunk(mem2chunk(p)); 214 | dump_heap(); 215 | } 216 | #endif 217 | 218 | if (p == NULL) 219 | return; 220 | 221 | chunkptr_t chunk = mem2chunk(p); 222 | size_t size = chunksize(chunk); 223 | int is_last = islast_chunk(chunk); 224 | int is_consolidated = 0; 225 | 226 | chunkptr_t prev = prev_chunk(chunk); 227 | chunkptr_t next = NULL; 228 | 229 | if (!is_last) 230 | next = next_chunk(chunk); 231 | 232 | if (!check_alignment(size)) 233 | printerr("release(): invalid size"); 234 | 235 | // consolidate backward 236 | if (!prev_inuse(chunk)) 237 | { 238 | size += chunksize(prev); 239 | unlink_chunk(prev); 240 | chunk = prev; 241 | is_consolidated = 1; 242 | } 243 | 244 | if (!is_last) 245 | { 246 | // consolidate forward 247 | if (!inuse(next)) 248 | { 249 | size += chunksize(next); 250 | unlink_chunk(next); 251 | is_consolidated = 1; 252 | } 253 | } 254 | 255 | // add chunk to the head of free_list 256 | chunk->bk = NULL; 257 | chunk->fd = g_free_list; 258 | if (g_free_list != NULL) 259 | g_free_list->bk = chunk; 260 | g_free_list = chunk; 261 | 262 | set_size(chunk, size); 263 | 264 | next = next_chunk(chunk); 265 | if (is_consolidated || next->prev_size == 0) 266 | next->prev_size = size; 267 | clear_prev_inuse(next); 268 | 269 | #ifdef DEBUG 270 | printf("release done\n"); 271 | dump_heap(); 272 | #endif 273 | } 274 | -------------------------------------------------------------------------------- /timehackers/web/simple-php-captcha.php: -------------------------------------------------------------------------------- 1 | '', 22 | 'min_length' => 5, 23 | 'max_length' => 5, 24 | 'backgrounds' => array( 25 | $bg_path . '45-degree-fabric.png', 26 | $bg_path . 'cloth-alike.png', 27 | $bg_path . 'grey-sandbag.png', 28 | $bg_path . 'kinda-jean.png', 29 | $bg_path . 'polyester-lite.png', 30 | $bg_path . 'stitched-wool.png', 31 | $bg_path . 'white-carbon.png', 32 | $bg_path . 'white-wave.png' 33 | ), 34 | 'fonts' => array( 35 | $font_path . 'times_new_yorker.ttf' 36 | ), 37 | 'characters' => 'ABCDEFGHJKLMNPRSTUVWXYZabcdefghjkmnprstuvwxyz23456789', 38 | 'min_font_size' => 28, 39 | 'max_font_size' => 28, 40 | 'color' => '#666', 41 | 'angle_min' => 0, 42 | 'angle_max' => 10, 43 | 'shadow' => true, 44 | 'shadow_color' => '#fff', 45 | 'shadow_offset_x' => -1, 46 | 'shadow_offset_y' => 1 47 | ); 48 | 49 | // Overwrite defaults with custom config values 50 | if( is_array($config) ) { 51 | foreach( $config as $key => $value ) $captcha_config[$key] = $value; 52 | } 53 | 54 | // Restrict certain values 55 | if( $captcha_config['min_length'] < 1 ) $captcha_config['min_length'] = 1; 56 | if( $captcha_config['angle_min'] < 0 ) $captcha_config['angle_min'] = 0; 57 | if( $captcha_config['angle_max'] > 10 ) $captcha_config['angle_max'] = 10; 58 | if( $captcha_config['angle_max'] < $captcha_config['angle_min'] ) $captcha_config['angle_max'] = $captcha_config['angle_min']; 59 | if( $captcha_config['min_font_size'] < 10 ) $captcha_config['min_font_size'] = 10; 60 | if( $captcha_config['max_font_size'] < $captcha_config['min_font_size'] ) $captcha_config['max_font_size'] = $captcha_config['min_font_size']; 61 | 62 | // Generate CAPTCHA code if not set by user 63 | if( empty($captcha_config['code']) ) { 64 | $captcha_config['code'] = ''; 65 | $length = mt_rand($captcha_config['min_length'], $captcha_config['max_length']); 66 | while( strlen($captcha_config['code']) < $length ) { 67 | $captcha_config['code'] .= substr($captcha_config['characters'], mt_rand() % (strlen($captcha_config['characters'])), 1); 68 | } 69 | } 70 | 71 | // Generate HTML for image src 72 | if ( strpos($_SERVER['SCRIPT_FILENAME'], $_SERVER['DOCUMENT_ROOT']) ) { 73 | $image_src = substr(__FILE__, strlen( realpath($_SERVER['DOCUMENT_ROOT']) )) . '?_CAPTCHA&t=' . urlencode(microtime()); 74 | $image_src = '/' . ltrim(preg_replace('/\\\\/', '/', $image_src), '/'); 75 | } else { 76 | $_SERVER['WEB_ROOT'] = str_replace($_SERVER['SCRIPT_NAME'], '', $_SERVER['SCRIPT_FILENAME']); 77 | $image_src = substr(__FILE__, strlen( realpath($_SERVER['WEB_ROOT']) )) . '?_CAPTCHA&t=' . urlencode(microtime()); 78 | $image_src = '/' . ltrim(preg_replace('/\\\\/', '/', $image_src), '/'); 79 | } 80 | 81 | $_SESSION['_CAPTCHA']['config'] = serialize($captcha_config); 82 | 83 | return array( 84 | 'code' => $captcha_config['code'], 85 | 'image_src' => $image_src 86 | ); 87 | 88 | } 89 | 90 | 91 | if( !function_exists('hex2rgb') ) { 92 | function hex2rgb($hex_str, $return_string = false, $separator = ',') { 93 | $hex_str = preg_replace("/[^0-9A-Fa-f]/", '', $hex_str); // Gets a proper hex string 94 | $rgb_array = array(); 95 | if( strlen($hex_str) == 6 ) { 96 | $color_val = hexdec($hex_str); 97 | $rgb_array['r'] = 0xFF & ($color_val >> 0x10); 98 | $rgb_array['g'] = 0xFF & ($color_val >> 0x8); 99 | $rgb_array['b'] = 0xFF & $color_val; 100 | } elseif( strlen($hex_str) == 3 ) { 101 | $rgb_array['r'] = hexdec(str_repeat(substr($hex_str, 0, 1), 2)); 102 | $rgb_array['g'] = hexdec(str_repeat(substr($hex_str, 1, 1), 2)); 103 | $rgb_array['b'] = hexdec(str_repeat(substr($hex_str, 2, 1), 2)); 104 | } else { 105 | return false; 106 | } 107 | return $return_string ? implode($separator, $rgb_array) : $rgb_array; 108 | } 109 | } 110 | 111 | // Draw the image 112 | if( isset($_GET['_CAPTCHA']) ) { 113 | 114 | session_start(); 115 | 116 | $captcha_config = unserialize($_SESSION['_CAPTCHA']['config']); 117 | if( !$captcha_config ) exit(); 118 | 119 | unset($_SESSION['_CAPTCHA']); 120 | 121 | // Pick random background, get info, and start captcha 122 | $background = $captcha_config['backgrounds'][mt_rand(0, count($captcha_config['backgrounds']) -1)]; 123 | list($bg_width, $bg_height, $bg_type, $bg_attr) = getimagesize($background); 124 | 125 | $captcha = imagecreatefrompng($background); 126 | 127 | $color = hex2rgb($captcha_config['color']); 128 | $color = imagecolorallocate($captcha, $color['r'], $color['g'], $color['b']); 129 | 130 | // Determine text angle 131 | $angle = mt_rand( $captcha_config['angle_min'], $captcha_config['angle_max'] ) * (mt_rand(0, 1) == 1 ? -1 : 1); 132 | 133 | // Select font randomly 134 | $font = $captcha_config['fonts'][mt_rand(0, count($captcha_config['fonts']) - 1)]; 135 | 136 | // Verify font file exists 137 | if( !file_exists($font) ) throw new Exception('Font file not found: ' . $font); 138 | 139 | //Set the font size. 140 | $font_size = mt_rand($captcha_config['min_font_size'], $captcha_config['max_font_size']); 141 | $text_box_size = imagettfbbox($font_size, $angle, $font, $captcha_config['code']); 142 | 143 | // Determine text position 144 | $box_width = abs($text_box_size[6] - $text_box_size[2]); 145 | $box_height = abs($text_box_size[5] - $text_box_size[1]); 146 | $text_pos_x_min = 0; 147 | $text_pos_x_max = ($bg_width) - ($box_width); 148 | $text_pos_x = mt_rand($text_pos_x_min, $text_pos_x_max); 149 | $text_pos_y_min = $box_height; 150 | $text_pos_y_max = ($bg_height) - ($box_height / 2); 151 | if ($text_pos_y_min > $text_pos_y_max) { 152 | $temp_text_pos_y = $text_pos_y_min; 153 | $text_pos_y_min = $text_pos_y_max; 154 | $text_pos_y_max = $temp_text_pos_y; 155 | } 156 | $text_pos_y = mt_rand($text_pos_y_min, $text_pos_y_max); 157 | 158 | // Draw shadow 159 | if( $captcha_config['shadow'] ){ 160 | $shadow_color = hex2rgb($captcha_config['shadow_color']); 161 | $shadow_color = imagecolorallocate($captcha, $shadow_color['r'], $shadow_color['g'], $shadow_color['b']); 162 | imagettftext($captcha, $font_size, $angle, $text_pos_x + $captcha_config['shadow_offset_x'], $text_pos_y + $captcha_config['shadow_offset_y'], $shadow_color, $font, $captcha_config['code']); 163 | } 164 | 165 | // Draw text 166 | imagettftext($captcha, $font_size, $angle, $text_pos_x, $text_pos_y, $color, $font, $captcha_config['code']); 167 | 168 | // Output image 169 | header("Content-type: image/png"); 170 | imagepng($captcha); 171 | 172 | } -------------------------------------------------------------------------------- /timehackers/docker_files/apache2.conf: -------------------------------------------------------------------------------- 1 | # This is the main Apache server configuration file. It contains the 2 | # configuration directives that give the server its instructions. 3 | # See http://httpd.apache.org/docs/2.4/ for detailed information about 4 | # the directives and /usr/share/doc/apache2/README.Debian about Debian specific 5 | # hints. 6 | # 7 | # 8 | # Summary of how the Apache 2 configuration works in Debian: 9 | # The Apache 2 web server configuration in Debian is quite different to 10 | # upstream's suggested way to configure the web server. This is because Debian's 11 | # default Apache2 installation attempts to make adding and removing modules, 12 | # virtual hosts, and extra configuration directives as flexible as possible, in 13 | # order to make automating the changes and administering the server as easy as 14 | # possible. 15 | 16 | # It is split into several files forming the configuration hierarchy outlined 17 | # below, all located in the /etc/apache2/ directory: 18 | # 19 | # /etc/apache2/ 20 | # |-- apache2.conf 21 | # | `-- ports.conf 22 | # |-- mods-enabled 23 | # | |-- *.load 24 | # | `-- *.conf 25 | # |-- conf-enabled 26 | # | `-- *.conf 27 | # `-- sites-enabled 28 | # `-- *.conf 29 | # 30 | # 31 | # * apache2.conf is the main configuration file (this file). It puts the pieces 32 | # together by including all remaining configuration files when starting up the 33 | # web server. 34 | # 35 | # * ports.conf is always included from the main configuration file. It is 36 | # supposed to determine listening ports for incoming connections which can be 37 | # customized anytime. 38 | # 39 | # * Configuration files in the mods-enabled/, conf-enabled/ and sites-enabled/ 40 | # directories contain particular configuration snippets which manage modules, 41 | # global configuration fragments, or virtual host configurations, 42 | # respectively. 43 | # 44 | # They are activated by symlinking available configuration files from their 45 | # respective *-available/ counterparts. These should be managed by using our 46 | # helpers a2enmod/a2dismod, a2ensite/a2dissite and a2enconf/a2disconf. See 47 | # their respective man pages for detailed information. 48 | # 49 | # * The binary is called apache2. Due to the use of environment variables, in 50 | # the default configuration, apache2 needs to be started/stopped with 51 | # /etc/init.d/apache2 or apache2ctl. Calling /usr/bin/apache2 directly will not 52 | # work with the default configuration. 53 | 54 | 55 | # Global configuration 56 | # 57 | 58 | # 59 | # ServerRoot: The top of the directory tree under which the server's 60 | # configuration, error, and log files are kept. 61 | # 62 | # NOTE! If you intend to place this on an NFS (or otherwise network) 63 | # mounted filesystem then please read the Mutex documentation (available 64 | # at ); 65 | # you will save yourself a lot of trouble. 66 | # 67 | # Do NOT add a slash at the end of the directory path. 68 | # 69 | #ServerRoot "/etc/apache2" 70 | 71 | # 72 | # The accept serialization lock file MUST BE STORED ON A LOCAL DISK. 73 | # 74 | Mutex file:${APACHE_LOCK_DIR} default 75 | 76 | # 77 | # PidFile: The file in which the server should record its process 78 | # identification number when it starts. 79 | # This needs to be set in /etc/apache2/envvars 80 | # 81 | PidFile ${APACHE_PID_FILE} 82 | 83 | # 84 | # Timeout: The number of seconds before receives and sends time out. 85 | # 86 | Timeout 300 87 | 88 | # 89 | # KeepAlive: Whether or not to allow persistent connections (more than 90 | # one request per connection). Set to "Off" to deactivate. 91 | # 92 | KeepAlive On 93 | 94 | # 95 | # MaxKeepAliveRequests: The maximum number of requests to allow 96 | # during a persistent connection. Set to 0 to allow an unlimited amount. 97 | # We recommend you leave this number high, for maximum performance. 98 | # 99 | MaxKeepAliveRequests 100 100 | 101 | # 102 | # KeepAliveTimeout: Number of seconds to wait for the next request from the 103 | # same client on the same connection. 104 | # 105 | KeepAliveTimeout 5 106 | 107 | 108 | # These need to be set in /etc/apache2/envvars 109 | User ${APACHE_RUN_USER} 110 | Group ${APACHE_RUN_GROUP} 111 | 112 | # 113 | # HostnameLookups: Log the names of clients or just their IP addresses 114 | # e.g., www.apache.org (on) or 204.62.129.132 (off). 115 | # The default is off because it'd be overall better for the net if people 116 | # had to knowingly turn this feature on, since enabling it means that 117 | # each client request will result in AT LEAST one lookup request to the 118 | # nameserver. 119 | # 120 | HostnameLookups Off 121 | 122 | # ErrorLog: The location of the error log file. 123 | # If you do not specify an ErrorLog directive within a 124 | # container, error messages relating to that virtual host will be 125 | # logged here. If you *do* define an error logfile for a 126 | # container, that host's errors will be logged there and not here. 127 | # 128 | ErrorLog ${APACHE_LOG_DIR}/error.log 129 | 130 | # 131 | # LogLevel: Control the severity of messages logged to the error_log. 132 | # Available values: trace8, ..., trace1, debug, info, notice, warn, 133 | # error, crit, alert, emerg. 134 | # It is also possible to configure the log level for particular modules, e.g. 135 | # "LogLevel info ssl:warn" 136 | # 137 | LogLevel warn 138 | 139 | # Include module configuration: 140 | IncludeOptional mods-enabled/*.load 141 | IncludeOptional mods-enabled/*.conf 142 | 143 | # Include list of ports to listen on 144 | Include ports.conf 145 | 146 | 147 | # Sets the default security model of the Apache2 HTTPD server. It does 148 | # not allow access to the root filesystem outside of /usr/share and /var/www. 149 | # The former is used by web applications packaged in Debian, 150 | # the latter may be used for local directories served by the web server. If 151 | # your system is serving content from a sub-directory in /srv you must allow 152 | # access here, or in any related virtual host. 153 | 154 | Options FollowSymLinks 155 | AllowOverride None 156 | Require all denied 157 | 158 | 159 | 160 | AllowOverride None 161 | Require all granted 162 | 163 | 164 | 165 | Options Indexes FollowSymLinks 166 | AllowOverride All 167 | Require all granted 168 | 169 | 170 | # 171 | # Options Indexes FollowSymLinks 172 | # AllowOverride None 173 | # Require all granted 174 | # 175 | 176 | 177 | 178 | 179 | # AccessFileName: The name of the file to look for in each directory 180 | # for additional configuration directives. See also the AllowOverride 181 | # directive. 182 | # 183 | AccessFileName .htaccess 184 | 185 | # 186 | # The following lines prevent .htaccess and .htpasswd files from being 187 | # viewed by Web clients. 188 | # 189 | 190 | Require all denied 191 | 192 | 193 | 194 | # 195 | # The following directives define some format nicknames for use with 196 | # a CustomLog directive. 197 | # 198 | # These deviate from the Common Log Format definitions in that they use %O 199 | # (the actual bytes sent including headers) instead of %b (the size of the 200 | # requested file), because the latter makes it impossible to detect partial 201 | # requests. 202 | # 203 | # Note that the use of %{X-Forwarded-For}i instead of %h is not recommended. 204 | # Use mod_remoteip instead. 205 | # 206 | LogFormat "%v:%p %h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" vhost_combined 207 | LogFormat "%h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" combined 208 | LogFormat "%h %l %u %t \"%r\" %>s %O" common 209 | LogFormat "%{Referer}i -> %U" referer 210 | LogFormat "%{User-agent}i" agent 211 | 212 | # Include of directories ignores editors' and dpkg's backup files, 213 | # see README.Debian for details. 214 | 215 | # Include generic snippets of statements 216 | IncludeOptional conf-enabled/*.conf 217 | 218 | # Include the virtual host configurations: 219 | IncludeOptional sites-enabled/*.conf 220 | 221 | # vim: syntax=apache ts=4 sw=4 sts=4 sr noet --------------------------------------------------------------------------------