Modbus协议扫描器的分析

modbus 协议分析


Modbus Packet Structure 协议格式

Trans ID ProtoID(0) Length UnitID FunctCode Data len(0-253byte)
\x00\x00 \x00\x00 \x00\x00 \x11 \x00

协议扫描代码

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
import socket
import array
import optparse
from IPy import IP
import sys

def main():

p = optparse.OptionParser( description=' Finds modbus devices in IP range and determines slave id.\nOutputs in ip:port <tab> sid format.',
prog='modscan',
version='modscan 0.1',
usage = "usage: %prog [options] IPRange")
p.add_option('--port', '-p', type='int', dest="port", default=502, help='modbus port DEFAULT:502')
p.add_option('--timeout', '-t', type='int', dest="timeout", default=500, help='socket timeout (mills) DEFAULT:500')
p.add_option('--aggressive', '-a', action ='store_true', help='continues checking past first found SID')
p.add_option('--function', '-f', type='int', dest="function", default=17, help='MODBUS Function Code DEFAULT:17')
p.add_option('--data', type='string', dest="fdata", help='MODBUS Function Data. Unicode escaped "\x00\x01"')
p.add_option('-v', '--verbose', action ='store_true', help='returns verbose output')
p.add_option('-d', '--debug', action ='store_true', help='returns extremely verbose output')

options, arguments = p.parse_args()

#make sure we have at least 1 argument (IP Addresses)
if len(arguments) == 1:

#build basic packet for this test

"""
Modbus Packet Structure
\x00\x00 \x00\x00 \x00\x00 \x11 \x00 <=================>
Trans ID ProtoID(0) Length UnitID FunctCode Data len(0-253byte)
"""

#this must be stored in a unsigned byte aray so we can make the assignment later... no string[] in python :(
rsid = array.array('B')
rsid.fromstring("\x00\x00\x00\x00\x00\x02\x01\x01")
#设置modbus功能码
#set function
rsid[7]=options.function

#add function data
if (options.fdata):
aFData = array.array('B')

#we must decode the escaped unicode before calling fromstring otherwise the literal \xXX will be interpreted
aFData.fromstring(options.fdata.decode('unicode-escape') )
rsid += aFData

#update length
rsid[5]=len(aFData)+2
#为什么还要加两个???表示很诧异

#assign IP range
iprange=IP(arguments[0])

#print friendly user message
print "Starting Scan..."

#primary loop over IP addresses
for ip in iprange:

#print str(ip)+" made it"
#loop over possible sid values (1-247)
for sid in range (1, 247):

#error messaging
fError=0
msg = str(ip)+":"+str(options.port)+"\t"+str(sid)

#print "msg="+msg

#Wrap connect in a try box
try:
#socket object instantiation
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

#set socket timeout, value from cmd is in mills
s.settimeout(float(options.timeout) / float(1000))

#connect requires ip addresses in string format so it must be cast
s.connect((str(ip), options.port))

except socket.error:
#clean up
fError=1
msg += "\tFAILED TO CONNECT"
s.close()
break
#end try


#send query to device
try:
#set slave id
rsid[6]=sid

#send data to device
s.send(rsid)

except socket.error:
#failed send close socket
fError=1
msg += "\tFAILED TO SEND"
s.close()
break
#end try

try:

#recieve data
data = s.recv(1024)

except socket.timeout:
fError=1
msg += "\tFAILED TO RECV"
break
#end try

#examine response
if data:
#parse response
resp = array.array('B')
resp.fromstring(data)

if (options.debug):
print "Recieved: "+str(resp)
print (int(resp[7]) == int(options.function))

#if the function matches the one sent we are all good
if (int(resp[7]) == int(options.function)):
print msg

#in aggressive mode we keep going
if (not options.aggressive):
break

#If the function matches the one sent + 0x80 a positive response error code is detected
elif int(resp[7]) == (int(options.function)+128):
#if debug output message
msg += "\tPositive Error Response"
if (options.debug):
print msg
else:
#if debug output message
if (options.debug):
print msg
else:
fError=1
msg += "\tFAILED TO RECIEVE"
s.close()
break

#end SID for


#report based on verbosity
if (options.verbose and fError):
print msg
elif (options.debug):
print msg
#end IP for

#close socket, no longer needed
#s.shutdown(socket.SHUT_RDWR)
s.close()

print "Scan Complete."

#bad number of arguments. print help
else:
p.print_help()


if __name__ == '__main__':
try : main()
except KeyboardInterrupt:
print "Scan canceled by user."
print "Thank you for using ModScan"
except :
sys.exit()