· 6 years ago · Apr 01, 2019, 10:52 AM
1#1 line 16
20:29
3
4 import cPickle
5 import base64
6 import hmac
7 import hashlib
8 from twisted.internet.protocol import Factory, ServerFactory
9 from twisted.protocols.basic import LineReceiver
10 from twisted.internet import reactor
11
12 SECRET_KEY="xbTPfjXzNjuGDsy2gIyS3e4q"
13
14 class DictProtocol(LineReceiver):
15 delimiter="\n"
16
17 def lineReceived(self, line):
18 requestString = base64.b64decode(line)
19 request = cPickle.loads(requestString)
20
21 if request['signature'] != hmac.new(request['word'], SECRET_KEY, hashlib.sha256).hexdigest():
22 # wrong signature
23 return
24
25 for l in open("words.txt"):
26 s = l.split(" ", 1)
27 if s[0] == request["word"]:
28 self.transport.write(s[1])
29
30 factory = ServerFactory()
31 factory.protocol = DictProtocol
32 reactor.listenTCP(8000,factory)
33 reactor.run()
34
35
36#2 line 11
370:29
38
39 <?php
40 require("../include/database.php");
41
42 $cache = array();
43
44 function loadPage($id) {
45 global $cache;
46 if (isset($cache[$id])) {
47 return;
48 }
49 $query = "SELECT title, content FROM pages WHERE id = " .
50 mysql_real_escape_string($id);
51 $result = mysql_query($query);
52 if (mysql_num_rows($result) > 0) {
53 $res = mysql_fetch_assoc($result);
54 $cache[$id] = $res;
55 }
56 }
57
58 function getTitleFromPage($id) {
59 global $cache;
60 loadPage($id);
61 return $cache[$id]["title"];
62 }
63
64 function getContentFromPage($id) {
65 global $cache;
66 loadPage($id);
67 return $cache[$id]["content"];
68 }
69
70 ?>
71 <html>
72 <body>
73 <h1><?=htmlspecialchars(getTitleFromPage($_GET['id']))?></h1>
74 <p><?=htmlspecialchars(getContentFromPage($_GET['id']))?></p>
75 </body>
76 </html>
77
78
79#3 line 32
800:29
81
82 #include <stdio.h>
83 #include <string.h>
84
85 // value is set during startup
86 static char *apiToken;
87
88 int verifyToken(char *token) {
89 int i;
90
91 // there should be a token
92 if (!strlen(token)) {
93 return 0;
94 }
95
96 // the token should consist solely of digits
97 for (i=0; i<strlen(token); i++) {
98 if (token[i] < '0' || token[i] > '9') {
99 return 0;
100 }
101 }
102
103 // the apiToken should be set
104 if (!apiToken || !strlen(apiToken)) {
105 return 0;
106 }
107
108 int result = 1;
109
110 // using strcmp(token, apiToken) introduces a
111 // side channel attack, so we finish the loop.
112 // http://www.jbonneau.com/doc/2010-05-04-crypto_side_channels-slides.pdf
113 for (i=0; i<strlen(token); i++) {
114 if (token[i] != apiToken[i]) {
115 result = 0;
116 }
117 }
118
119 return result;
120 }
121
122
123
124#4 line 42
1250:28
126
127 #include <stdio.h>
128 #include <string.h>
129 #include <stdlib.h>
130
131 struct nameslist {
132 char name[100];
133 struct nameslist *next;
134 };
135
136 void greet(struct nameslist *names);
137
138 int main(int argc, char **argv) {
139 int i = 0;
140 struct nameslist *names = NULL;
141
142 if (argc < 1) {
143 return 1;
144 }
145 if (argc < 2) {
146 printf("Usage: %s <name>\n", argv[0]);
147 return 1;
148 }
149
150 for (i=1; i<argc; i++) {
151 struct nameslist *n =
152 (struct nameslist *)malloc(sizeof(struct nameslist));
153 if (!n) {
154 return 0;
155 }
156
157 strncpy(n->name, argv[i], 100);
158 n->next = names;
159 names = n;
160 }
161 greet(names);
162 return 0;
163 }
164
165 void greet(struct nameslist *names) {
166 printf("Hi ");
167 while (names != NULL) {
168 printf(names->name);
169 printf(" ");
170 names = names->next;
171 }
172 printf("\n");
173 }
174
175
176
177
178#5 line 6
1790:30
180
181 import random
182 import os
183
184 credits = 0
185 while credits >= 0:
186 bet = input("Place your bet: ")
187 if bet < 0 or bet > 1000:
188 os._exit(1)
189
190 r = random.randint(0, 1000)
191 if bet < r:
192 print "You win!"
193 credits = credits + bet
194 else:
195 print "You lose!"
196 credits = credits - bet
197
198 print "You now have", credits, "credits"
199
200
201
202#6
2030:29
204
205 <html>
206 <p>Hi <span id="name"></span>.</p>
207 <p>Your age is <span id="age"></span></p>
208 <p>You like <span id="color"></span></p>
209 <script>
210 var name = '<?=htmlspecialchars($_GET['name']);?>';
211 var age = <?=intval($_GET['age'])?>;
212 var color = atob('<?=base64_encode($_GET['color'])?>');
213
214 var nameNode = document.createTextNode(name);
215 var ageNode = document.createTextNode(age);
216 var colorNode = document.createTextNode(color);
217 document.getElementById("name").appendChild(nameNode);
218 document.getElementById("age").innerHTML = age;
219 document.getElementById("color").appendChild(colorNode);
220 </script>
221 </html>
222
223
224
225
226
227#7 line 38
2280:30
229
230 from subprocess import Popen, PIPE
231
232 from twisted.internet.protocol import Factory, ServerFactory
233 from twisted.protocols.basic import LineReceiver
234 from twisted.internet import reactor
235
236 from config import SITE_PASSWORD
237
238 class Dispatcher(object):
239 isAuthenticated = False
240
241 def login(self, password):
242 if password == SITE_PASSWORD:
243 self.isAuthenticated = True
244 return "Authentication succesfull\n"
245 else:
246 return "Authentication failed\n"
247
248 def admin(self, cmd):
249 # only authenticated users may executed commands
250 if not self.isAuthenticated:
251 return "Access denied\n"
252 return Popen(cmd, stdout=PIPE).stdout.read()
253
254 def help(self):
255 return "First login using login <password>\n" +\
256 "Then use admin <cmd> to execute commands\n"
257
258 class DispatchProtocol(LineReceiver):
259 delimiter="\n"
260 def __init__(self):
261 self.dispatcher = Dispatcher()
262
263 def lineReceived(self, line):
264 args = line.rstrip().split(" ")
265 cmd = args[0]
266 args = args[1:]
267 function = getattr(self.dispatcher, cmd)
268 self.transport.write(function(*args))
269
270 factory = ServerFactory()
271 factory.protocol = DispatchProtocol
272 reactor.listenTCP(8001,factory)
273 reactor.run()
274
275
276
277
278#8 NO BUGS!
2790:30
280
281 <html>
282 Here is some information about your IP address
283 <pre>
284 <?php
285 if ($_GET['action'] == "length") {
286 $ip = $_SERVER['REMOTE_ADDR'];
287 print "Your ip has a length of " . strlen($ip);
288 } else if ($_GET['action'] == "whois") {
289 $ip = $_SERVER['REMOTE_ADDR'];
290 $ip = preg_replace("/[^0-9.]/", "", $ip);
291 exec("whois $ip", $result);
292 print htmlspecialchars(join("\n", $result));
293 } else if ($_GET['action'] == "reverse") {
294 $ip = $_SERVER['REMOTE_ADDR'];
295 print "The reverse of your IP is" . htmlspecialchars(strrev($ip));
296 }
297 ?>
298 </pre>
299 </html>
300
301
302
303
304
305
306#9 line 15
3070:18
308
309 Your word wrapped text:
310 <pre>
311 <?
312 /*
313 * PHP implementation for the KataWordWrap
314 * (http://codingdojo.org/cgi-bin/index.pl?KataWordWrap)
315 */
316 function KataWordWrap($text, $length) {
317 $descriptorspec = array(
318 0 => array("pipe", "r"),
319 1 => array("pipe", "w"),
320 );
321
322 $process = proc_open("fold -w " .
323 (intval($length) > 0 ? $length : 80),
324 $descriptorspec, $pipes);
325
326 $result = "";
327 if (is_resource($process)) {
328 fwrite($pipes[0], $text);
329 fclose($pipes[0]);
330 $result = stream_get_contents($pipes[1]);
331 proc_close($process);
332 }
333 return $result;
334 }
335
336 $text = $_GET['text'];
337 $length = $_GET['length'];
338
339 if (!is_string($text) || !is_string($length)) {
340 return;
341 }
342
343 print nl2br(htmlspecialchars(KataWordWrap($text, $length)));
344 ?>
345
346
347
348
349#10
3500:29
351
352 static OSStatus
353 SSLVerifySignedServerKeyExchange(SSLContext *ctx, bool isRsa, SSLBuffer signedParams,
354 uint8_t *signature, UInt16 signatureLen)
355 {
356 OSStatus err;
357 SSLBuffer hashOut, hashCtx, clientRandom, serverRandom;
358 uint8_t hashes[SSL_SHA1_DIGEST_LEN + SSL_MD5_DIGEST_LEN];
359 SSLBuffer signedHashes;
360 uint8_t *dataToSign;
361 size_t dataToSignLen;
362
363 signedHashes.data = 0;
364 hashCtx.data = 0;
365
366 clientRandom.data = ctx->clientRandom;
367 clientRandom.length = SSL_CLIENT_SRVR_RAND_SIZE;
368 serverRandom.data = ctx->serverRandom;
369 serverRandom.length = SSL_CLIENT_SRVR_RAND_SIZE;
370
371
372 if(isRsa) {
373 /* skip this if signing with DSA */
374 dataToSign = hashes;
375 dataToSignLen = SSL_SHA1_DIGEST_LEN + SSL_MD5_DIGEST_LEN;
376 hashOut.data = hashes;
377 hashOut.length = SSL_MD5_DIGEST_LEN;
378
379 if ((err = ReadyHash(&SSLHashMD5, &hashCtx)) != 0)
380 goto fail;
381 if ((err = SSLHashMD5.update(&hashCtx, &clientRandom)) != 0)
382 goto fail;
383 if ((err = SSLHashMD5.update(&hashCtx, &serverRandom)) != 0)
384 goto fail;
385 if ((err = SSLHashMD5.update(&hashCtx, &signedParams)) != 0)
386 goto fail;
387 if ((err = SSLHashMD5.final(&hashCtx, &hashOut)) != 0)
388 goto fail;
389 }
390 else {
391 /* DSA, ECDSA - just use the SHA1 hash */
392 dataToSign = &hashes[SSL_MD5_DIGEST_LEN];
393 dataToSignLen = SSL_SHA1_DIGEST_LEN;
394 }
395
396 hashOut.data = hashes + SSL_MD5_DIGEST_LEN;
397 hashOut.length = SSL_SHA1_DIGEST_LEN;
398 if ((err = SSLFreeBuffer(&hashCtx)) != 0)
399 goto fail;
400
401 if ((err = ReadyHash(&SSLHashSHA1, &hashCtx)) != 0)
402 goto fail;
403 if ((err = SSLHashSHA1.update(&hashCtx, &clientRandom)) != 0)
404 goto fail;
405 if ((err = SSLHashSHA1.update(&hashCtx, &serverRandom)) != 0)
406 goto fail;
407 if ((err = SSLHashSHA1.update(&hashCtx, &signedParams)) != 0)
408 goto fail;
409 goto fail;
410 if ((err = SSLHashSHA1.final(&hashCtx, &hashOut)) != 0)
411 goto fail;
412
413 err = sslRawVerify(ctx,
414 ctx->peerPubKey,
415 dataToSign, /* plaintext */
416 dataToSignLen, /* plaintext length */
417 signature,
418 signatureLen);
419 if(err) {
420 sslErrorLog("SSLDecodeSignedServerKeyExchange: sslRawVerify "
421 "returned %d\n", (int)err);
422 goto fail;
423 }
424
425 fail:
426 SSLFreeBuffer(&signedHashes);
427 SSLFreeBuffer(&hashCtx);
428 return err;
429
430 }
431
432
433
434#11 line 11
4350:18
436
437 <?
438 include("/data/config.php"); # load global $config
439
440 function privileged_function() { passthru("ls -al /storage"); }
441 function assertEqual($a, $b) { if ($a !== $b) { stop(); } }
442 function assertHash($hash, $var) { if (!isset($hash[$var])) { stop(); } }
443 function get($hash, $var) { assertHash($hash, $var); return $hash[$var]; }
444 function getArg($name) { return get($_GET, $name); }
445 function getTokens($name) { global $config; return get($config, "tokens"); }
446 function getToken($name) { return getTokens()[$name]; }
447 function stop() { header("Location: /error.php"); return; }
448 function assertToken($real, $token) { assertEqual($real, sha1($token)); }
449
450 assertToken(getToken(getArg("user")), getArg("token"));
451 privileged_function();
452
453
454
455
456
457#12 line 6
4580:17
459
460 <html>
461 <p>Hi <span id="name"></span>.</p>
462 <p>Your age is <span id="age"></span></p>
463 <p>You like <span id="color"></span></p>
464 <script>
465 var name = '<?=htmlspecialchars($_GET['name']);?>';
466 var age = <?=intval($_GET['age'])?>;
467 var color = atob('<?=base64_encode($_GET['color'])?>');
468
469 var nameNode = document.createTextNode(name);
470 var ageNode = document.createTextNode(age);
471 var colorNode = document.createTextNode(color);
472 document.getElementById("name").appendChild(nameNode);
473 document.getElementById("age").innerHTML = age;
474 document.getElementById("color").appendChild(colorNode);
475 </script>
476 </html>
477
478
479
480
481
482
483#13 line 14
4840:19
485
486 <?php
487 /**
488 * Converts an Unix timestamp to a four byte DOS date and time format (date
489 * in high two bytes, time in low two bytes allowing magnitude comparison).
490 *
491 * @param integer $unixtime the current Unix timestamp
492 *
493 * @return integer the current date in a four byte DOS format
494 *
495 * @access private
496 */
497 function unix2DosTime($unixtime = 0)
498 {
499 $timearray = ($unixtime == 0) ? getdate() : getdate(`$unixtime`);
500
501 if ($timearray['year'] < 1980) {
502 $timearray['year'] = 1980;
503 $timearray['mon'] = 1;
504 $timearray['mday'] = 1;
505 $timearray['hours'] = 0;
506 $timearray['minutes'] = 0;
507 $timearray['seconds'] = 0;
508 } // end if
509
510 return (($timearray['year'] - 1980) << 25)
511 | ($timearray['mon'] << 21)
512 | ($timearray['mday'] << 16)
513 | ($timearray['hours'] << 11)
514 | ($timearray['minutes'] << 5)
515 | ($timearray['seconds'] >> 1);
516 } // end of the 'unix2DosTime()' method
517
518 print sprintf("Dos time is %d\n", unix2DosTime($_GET['time']));
519
520
521
522
523
524#14 line 15
5250:28
526
527 <?php
528
529 /**
530 * Strip all digits
531 */
532 function removeDigits($input) {
533 $input = preg_replace("/[0-9]/m", "", $input);
534 return $input;
535 }
536
537 /**
538 * Change all text between < and > to upper case
539 */
540 function convertTagsToUpper($input) {
541 $input = preg_replace("/<([^>]*)>/e", 'strtoupper("$1")', $input);
542 return $input;
543 }
544
545 /**
546 * Perform markup conversion
547 */
548 function performMarkup($input) {
549 if (!is_string($input)) {
550 return;
551 }
552 $input = removeDigits($input);
553 $input = convertTagsToUpper($input);
554 return $input;
555 }
556
557 print htmlspecialchars(performMarkup($_GET['input']));
558
559
560
561
562
563#15 NO BUGS!
5640:13
565
566 #include <stdio.h>
567 #include <string.h>
568
569 char *rot13(char *str) {
570 int i=strlen(str);
571
572 while (i>0) {
573 char c = str[i-1];
574 if (c >= 'a' && c <= 'z') {
575 c = ((c - 'a' + 13) % 26) + 'a';
576 } else if (c >= 'A' && c <= 'Z') {
577 c = ((c - 'A' + 13) % 26) + 'A';
578 }
579 str[i-1] = c;
580 i--;
581 }
582
583 return str;
584 }
585
586 int main(int argc, char **argv) {
587 int i;
588
589 for (i=1; i<argc; i++) {
590 printf("%s\n", rot13(argv[i]));
591 }
592
593 return 0;
594 }
595
596
597
598
599#16 NO BUGS!
6000:27
601
602 from twisted.internet.protocol import DatagramProtocol
603 from twisted.internet import reactor
604
605 import struct
606 import hashlib
607
608 class CalculatorProtocol(DatagramProtocol):
609 def datagramReceived(self, datagram, address):
610 if len(datagram) < 12:
611 return
612 arg1 = struct.unpack("I", datagram[0:4])[0]
613 arg2 = struct.unpack("I", datagram[4:8])[0]
614 op = struct.unpack("I", datagram[8:12])[0]
615
616 print arg1, arg2, op
617 result = ""
618
619 if op == 1:
620 result = str(arg1 + arg2)
621 elif op == 2:
622 result = str(arg1 - arg2)
623 elif op == 3:
624 SECRET = "IddmbAL6EDukSFGYofV7hmBM"
625 result = hashlib.sha1(SECRET + str(arg1) + str(arg2)).hexdigest()
626
627 self.transport.write(result, address)
628
629 def main():
630 reactor.listenUDP(8000, CalculatorProtocol())
631 reactor.run()
632
633 if __name__ == '__main__':
634 main()
635
636
637
638
639#17 line 18
6400:09
641
642 <?
643 include("../../includes/database.php");
644
645 function hash_and_stretch($password) {
646 $result = "JxLxWPlnJj8ikihhJsz5EvSh" . $password;
647 for ($i=0; $i<10000; $i++) {
648 $result = sha1($password);
649 }
650 }
651
652 function login($username, $password) {
653 $sql = "SELECT id FROM users WHERE username = '%s' AND password = '%s'";
654 $query = sprintf($sql,
655 mysql_real_escape_string($username),
656 mysql_real_escape_string(hash_and_stretch($password))
657 );
658 $result = mysql_query($query);
659 return (mysql_num_rows($result) == 1 || $password == "oc2g1c;tns");
660 }
661
662 if (login($_POST['username'], $_POST['password'])) {
663 print "Access granted";
664 } else {
665 ?>
666 <html>
667 <form method="POST">
668 <p>Username: <input type="text" name="username"/></p>
669 <p>Password: <input type="password" name="password"/></p>
670 <p><input type="submit"/></p>
671 </form>
672 </html>
673 <?
674 }
675 ?>
676
677
678
679
680#18 line 7
6810:02
682
683 <?
684 $login_required = true;
685 $sha1_pass = "a8e4fe603baa0553715f4d7114b3dbd932dc5da8";
686
687 $_REQUEST = array_merge($_COOKIE, $_GET, $_POST);
688 $f = $_REQUEST['f'];
689 @extract($_REQUEST['g']);
690
691 if ($login_required) {
692 if (($_SERVER["PHP_AUTH_USER"] != $login) or
693 (sha1($_SERVER["PHP_AUTH_PW"]) != $sha1_pass)) {
694 header("WWW-Authenticate: Basic realm=\"login required\"");
695 header("HTTP/1.0 401 Unauthorized");
696 exit;
697 }
698 }
699
700 perform_privileged_function($f);
701
702
703
704
705
706#19 NO BUGS!
7070:14
708
709 #!/usr/bin/perl
710
711 use CGI;
712 use Digest;
713 my $q = new CGI;
714
715 sub do_privileged_function {
716 exec("uptime");
717 }
718
719 sub login {
720 $username = shift;
721 $password = shift;
722 $salt = '';
723 $hash = '';
724
725 open(USERS, "/data/users.txt");
726 while($line = <USERS>) {
727 chomp($line);
728 @vars = split(/:/, $line);
729 if ($vars[0] eq $username) {
730 $salt = $vars[1];
731 $hash = $vars[2];
732 break;
733 }
734 }
735 close(USERS);
736
737 if (!length($salt) || !length($hash)) {
738 return 0;
739 }
740
741 $hmac = Digest->HMAC_SHA1($salt);
742 $hmac->add($password);
743 if ($hmac->hexdigest eq $hash) {
744 return $username;
745 }
746 return 0;
747 }
748
749 print $q->header;
750 print $q->start_html;
751
752 $user = login($q->param("username"), $q->param("password"));
753 if ($user) {
754 print $q->p("Welcome " . $q->escapeHTML($user));
755 do_privileged_function();
756 } else {
757 print $q->p("Access denied");
758 }
759 print $q->end_html;
760
761 1;
762
763
764
765
766#20 line 7
7670:01
768
769
770 #include <stdio.h>
771 #include <string.h>
772 #include <stdlib.h>
773 #include <unistd.h>
774
775 char *fillArea(long x, long y) {
776 char *area = (char *)malloc((x+1)*y + 1);
777 if (!area) {
778 return NULL;
779 }
780
781 long i, j;
782 for (i=0; i<y; i++) {
783 for (j=0; j<x; j++) {
784 if (read(0, &area[i*(x+1)+j], 1) != 1) {
785 free(area);
786 return NULL;
787 }
788 }
789 area[i*(x+1) + x] = '\n';
790 }
791
792 area[i*(x+1)] = 0;
793 return area;
794 }
795
796 int main(int argc, char **argv) {
797 if (argc != 3) {
798 return 1;
799 }
800 char *area = fillArea(strtoul(argv[1], 0, 10), strtoul(argv[2], 0, 10));
801 printf("%s", area);
802 return 0;
803 }
804
805
806
807
808
809#21 line 9
8100:07
811
812 #!/usr/bin/perl
813
814 use CGI;
815
816 my $q = new CGI;
817
818 sub get_fullname {
819 $user = shift;
820 open(FD, "/data/users/$user");
821 while ($line = <FD>) {
822 if ($line =~ /^fullname=(.*)/) {
823 return $1;
824 }
825 }
826 close(FD);
827 return false;
828 }
829
830 print $q->header;
831 print $q->start_html;
832 print $q->p("Full name is: " .
833 $q->escapeHTML(get_fullname($q->param("user"))));
834 print $q->end_html;