端口扫描-进阶

Author Avatar
Geroge Lee 7月 11, 2017
  • 在其它设备中阅读本文章

0x00 序

前几天实训做了个端口扫描,也没怎么写过长的脚本,真好有个机会自己练习一下,反正也没啥,就当玩了,都怪自己编程太差,犯了不少错,踏过好些坑 Orz

0x01 要求

半开连接的TCP协议,FIN扫描,基于全连接的TCP协议,采用多线程对远程主机进行扫描

0x02 代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
#! /usr/bin/python
# coding:utf-8
import sys
import os
import socket
import prettytable
import argparse
import logging
import threading
import Queue
logging.getLogger("scapy.runtime").setLevel(logging.ERROR) #抑制scapy警告
from scapy.all import *
conf.verb=0 # enable verbose mode - Is this actually working?
conf.nofilter=1
Q = Queue.Queue()
def tcp_connect_scan(dst_ip, dst_port, dst_timeout):
src_port = RandShort()
tcp_connect_scan_resp = sr1(IP(dst=dst_ip)/TCP(sport=src_port,dport=dst_port,flags="S"),timeout=dst_timeout)
if(str(type(tcp_connect_scan_resp))=="<type 'NoneType'>"):
return "Closed"
elif(tcp_connect_scan_resp.haslayer(TCP)):
if(tcp_connect_scan_resp.getlayer(TCP).flags == 0x12):
send_rst = sr(IP(dst=dst_ip)/TCP(sport=src_port,dport=dst_port,flags="AR"), timeout=dst_timeout)
return "Open"
elif(tcp_connect_scan_resp.getlayer(TCP).flags == 0x14):
return "Closed"
else:
return "CHECK"
def fin_scan(dst_ip, dst_port, dst_timeout):
fin_scan_resp = sr1(IP(dst=dst_ip)/TCP(dport=dst_port, flags="F"), timeout=dst_timeout)
if (str(type(fin_scan_resp))=="<type 'NoneType'>"):
return "Open|Filtered"
elif(fin_scan_resp.haslayer(TCP)):
if(fin_scan_resp.getlayer(TCP).flags == 0x14):
#RST
return "Closed"
elif(fin_scan_resp.haslayer(ICMP)):
# 无法确定
if(int(fin_scan_resp.getlayer(ICMP).type)==3 and int(fin_scan_resp.getlayer(ICMP).code) in [1,2,3,9,10,13]):
return "Filtered"
else:
return "CHECK"
def syn_scan(dst_ip, dst_port, dst_timeout):
src_port = RandShort()
syn_scan_resp = sr1(IP(dst=dst_ip)/TCP(sport=src_port, dport=dst_port, flags="S"), timeout=dst_timeout)
if(str(type(syn_scan_resp))=="<type 'NoneType'>"):
return "Closed"
elif(syn_scan_resp.haslayer(TCP)):
if (syn_scan_resp.getlayer(TCP).flags == 0x12):
sent_rst = sr(IP(dst=dst_ip)/TCP(sport=src_port, dport=dst_port, flags="R"), timeout=dst_timeout)
return "Open"
elif(syn_scan_resp.getlayer(TCP).flags == 0x14):
return "Closed"
elif(syn_scan_resp.haslayer(ICMP).type==3 and int(syn_scan_resp.getlayer(ICMP).code) in [1,2,3,10,13]):
return "Filtered"
else:
return "CHECK"
def banner():
START_STR = """
____ _ ____
| _ \ ___ _ __| |_/ ___| ___ __ _ _ __
| |_) / _ \| '__| __\___ \ / __/ _` | '_ \
| __/ (_) | | | |_ ___) | (_| (_| | | | |
|_| \___/|_| \__|____/ \___\__,_|_| |_|
version 1.0
"""
print START_STR
def parser():
global target
global ports
global timeout
global record
global select
global thread
parser = argparse.ArgumentParser(description=banner())
parser.add_argument("target", help="Target address")
parser.add_argument("-p", metavar="", help="Single port e.g. 80")
parser.add_argument("-pl", metavar="", help="Port list e.g. 22,80,3306")
parser.add_argument("-pr", metavar="", help="Port range e.g. 20-30")
parser.add_argument("-o", metavar="", type=str, default=None, help="Output txt e.g. 1.txt (default NULL)")
parser.add_argument("-s", metavar="", type=str, default=1, help="Select the scan mode e.g. SYN 1 |FIN 2 |TCP 3(default SYN)")
parser.add_argument("-t", metavar="", type=int, default=2, help="Timeout value (default 2)")
parser.add_argument("-thread", metavar="", type=int, default=8, help="Thread num(default 3)")
args = parser.parse_args()
target = getip(args.target)
if not(survive(target)):
exit(0)
ports = []
if args.p:
p = args.p
ports.append(p)
if args.pl:
pl = (args.pl).split(",")
ports += pl
if args.pr:
pr = (args.pr).split("-")
pr.sort()
pr_item1 = int(pr[0])
pr_item2 = int(pr[1])+1
new_pr = range(pr_item1, pr_item2,1)
ports += new_pr
timeout = int(args.t)
record = args.o
if(not len(ports)>0):
ports = ['80','22','3306','3389','1433','27017']
#print "未指定端口。\n使用-h或--help查看帮助菜单"
#exit(0)
ports = list(set(ports))
new_ports = []
for item in ports:
new_ports.append(int(item))
ports = new_ports
ports.sort()
select = int(args.s)
thread = args.thread
print "[+] Target : %s\n" % target
print "[*] Scan started\n"
if(select == 1):
print "正在使用SYN扫描"+'\n'
elif(select == 2):
print "正在使用FIN扫描"+'\n'
elif(select == 3):
print "正在使用TCP扫描"+'\n'
def getip(domain):
#获得主机ip
myaddr = socket.getaddrinfo(domain,'http')[0][4][0]
return myaddr
def survive(Target):
#判断ip是否存活
a = os.popen('ping -c 1 '+Target)
b = str(a.read())
c = b.find("ttl")
#if not(((str((os.popen('ping -c 1 '+Target)).read)).find("ttl"))== -1) :
if not(c == -1):
return 1
else:
print "%s 主机不可达"%Target
return 0
def portscan(item):
"""
按种类扫描
"""
global x
x = prettytable.PrettyTable(["Port No.", 'description'])
x.align["Port No."] = "l"
if(select == 1): #SYN
result = syn_scan(target, int(item), timeout)
x.add_row([item,result])
elif(select == 2): #FIN
result = fin_scan(target, int(item), timeout)
x.add_row([item,result])
elif(select == 3): #TCP
result = tcp_connect_scan(target, int(item), timeout)
x.add_row([item, result])
class Mythread(threading.Thread):
def __init__(self, func) :
super(Mythread, self).__init__()
self.func = func
def run(self) :
self.func()
def worker():
"""
定义任务队列
"""
global Q
global item
while not Q.empty():
item = Q.get() #获得任务
portscan(item) #按种类扫描
time.sleep(1)
def Threadpool(ports, thread):
"""
线程池的实现
"""
global threadnum
threadnum = thread
threads = [] #存放队列的数组
for port in ports: #将需要扫描的端口加入队列Q中
Q.put(port)
#print port
for i in xrange(threadnum):
thread = Mythread(worker)
thread.start()
threads.append(thread)
#print threads
for thread in threads:
thread.join()
def start(record):
"""
输出结果并且保存
"""
print x
print "\n[*] Scan end\n"
if record:
with open(record,'a+') as f:
f.write(target+'\n')
f.write(str(x)+'\n')
def main():
parser()
Threadpool(ports,thread)
start(record)
if __name__ == "__main__":
main()