├── .gitignore
├── LICENSE
├── README.md
└── src
├── example_client_kex_init_fuzzer.py
├── example_ident_fail.py
├── example_kex_valid.py
├── example_server_kex_init_fuzzer.py
└── scapy
└── layers
└── ssh.py
/.gitignore:
--------------------------------------------------------------------------------
1 | # Byte-compiled / optimized / DLL files
2 | __pycache__/
3 | *.py[cod]
4 |
5 | # C extensions
6 | *.so
7 |
8 | # Distribution / packaging
9 | .Python
10 | env/
11 | build/
12 | develop-eggs/
13 | dist/
14 | downloads/
15 | eggs/
16 | lib/
17 | lib64/
18 | parts/
19 | sdist/
20 | var/
21 | *.egg-info/
22 | .installed.cfg
23 | *.egg
24 |
25 | # PyInstaller
26 | # Usually these files are written by a python script from a template
27 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
28 | *.manifest
29 | *.spec
30 |
31 | # Installer logs
32 | pip-log.txt
33 | pip-delete-this-directory.txt
34 |
35 | # Unit test / coverage reports
36 | htmlcov/
37 | .tox/
38 | .coverage
39 | .cache
40 | nosetests.xml
41 | coverage.xml
42 |
43 | # Translations
44 | *.mo
45 | *.pot
46 |
47 | # Django stuff:
48 | *.log
49 |
50 | # Sphinx documentation
51 | docs/_build/
52 |
53 | # PyBuilder
54 | target/
55 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 2, June 1991
3 |
4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
6 | Everyone is permitted to copy and distribute verbatim copies
7 | of this license document, but changing it is not allowed.
8 |
9 | Preamble
10 |
11 | The licenses for most software are designed to take away your
12 | freedom to share and change it. By contrast, the GNU General Public
13 | License is intended to guarantee your freedom to share and change free
14 | software--to make sure the software is free for all its users. This
15 | General Public License applies to most of the Free Software
16 | Foundation's software and to any other program whose authors commit to
17 | using it. (Some other Free Software Foundation software is covered by
18 | the GNU Lesser General Public License instead.) You can apply it to
19 | your programs, too.
20 |
21 | When we speak of free software, we are referring to freedom, not
22 | price. Our General Public Licenses are designed to make sure that you
23 | have the freedom to distribute copies of free software (and charge for
24 | this service if you wish), that you receive source code or can get it
25 | if you want it, that you can change the software or use pieces of it
26 | in new free programs; and that you know you can do these things.
27 |
28 | To protect your rights, we need to make restrictions that forbid
29 | anyone to deny you these rights or to ask you to surrender the rights.
30 | These restrictions translate to certain responsibilities for you if you
31 | distribute copies of the software, or if you modify it.
32 |
33 | For example, if you distribute copies of such a program, whether
34 | gratis or for a fee, you must give the recipients all the rights that
35 | you have. You must make sure that they, too, receive or can get the
36 | source code. And you must show them these terms so they know their
37 | rights.
38 |
39 | We protect your rights with two steps: (1) copyright the software, and
40 | (2) offer you this license which gives you legal permission to copy,
41 | distribute and/or modify the software.
42 |
43 | Also, for each author's protection and ours, we want to make certain
44 | that everyone understands that there is no warranty for this free
45 | software. If the software is modified by someone else and passed on, we
46 | want its recipients to know that what they have is not the original, so
47 | that any problems introduced by others will not reflect on the original
48 | authors' reputations.
49 |
50 | Finally, any free program is threatened constantly by software
51 | patents. We wish to avoid the danger that redistributors of a free
52 | program will individually obtain patent licenses, in effect making the
53 | program proprietary. To prevent this, we have made it clear that any
54 | patent must be licensed for everyone's free use or not licensed at all.
55 |
56 | The precise terms and conditions for copying, distribution and
57 | modification follow.
58 |
59 | GNU GENERAL PUBLIC LICENSE
60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
61 |
62 | 0. This License applies to any program or other work which contains
63 | a notice placed by the copyright holder saying it may be distributed
64 | under the terms of this General Public License. The "Program", below,
65 | refers to any such program or work, and a "work based on the Program"
66 | means either the Program or any derivative work under copyright law:
67 | that is to say, a work containing the Program or a portion of it,
68 | either verbatim or with modifications and/or translated into another
69 | language. (Hereinafter, translation is included without limitation in
70 | the term "modification".) Each licensee is addressed as "you".
71 |
72 | Activities other than copying, distribution and modification are not
73 | covered by this License; they are outside its scope. The act of
74 | running the Program is not restricted, and the output from the Program
75 | is covered only if its contents constitute a work based on the
76 | Program (independent of having been made by running the Program).
77 | Whether that is true depends on what the Program does.
78 |
79 | 1. You may copy and distribute verbatim copies of the Program's
80 | source code as you receive it, in any medium, provided that you
81 | conspicuously and appropriately publish on each copy an appropriate
82 | copyright notice and disclaimer of warranty; keep intact all the
83 | notices that refer to this License and to the absence of any warranty;
84 | and give any other recipients of the Program a copy of this License
85 | along with the Program.
86 |
87 | You may charge a fee for the physical act of transferring a copy, and
88 | you may at your option offer warranty protection in exchange for a fee.
89 |
90 | 2. You may modify your copy or copies of the Program or any portion
91 | of it, thus forming a work based on the Program, and copy and
92 | distribute such modifications or work under the terms of Section 1
93 | above, provided that you also meet all of these conditions:
94 |
95 | a) You must cause the modified files to carry prominent notices
96 | stating that you changed the files and the date of any change.
97 |
98 | b) You must cause any work that you distribute or publish, that in
99 | whole or in part contains or is derived from the Program or any
100 | part thereof, to be licensed as a whole at no charge to all third
101 | parties under the terms of this License.
102 |
103 | c) If the modified program normally reads commands interactively
104 | when run, you must cause it, when started running for such
105 | interactive use in the most ordinary way, to print or display an
106 | announcement including an appropriate copyright notice and a
107 | notice that there is no warranty (or else, saying that you provide
108 | a warranty) and that users may redistribute the program under
109 | these conditions, and telling the user how to view a copy of this
110 | License. (Exception: if the Program itself is interactive but
111 | does not normally print such an announcement, your work based on
112 | the Program is not required to print an announcement.)
113 |
114 | These requirements apply to the modified work as a whole. If
115 | identifiable sections of that work are not derived from the Program,
116 | and can be reasonably considered independent and separate works in
117 | themselves, then this License, and its terms, do not apply to those
118 | sections when you distribute them as separate works. But when you
119 | distribute the same sections as part of a whole which is a work based
120 | on the Program, the distribution of the whole must be on the terms of
121 | this License, whose permissions for other licensees extend to the
122 | entire whole, and thus to each and every part regardless of who wrote it.
123 |
124 | Thus, it is not the intent of this section to claim rights or contest
125 | your rights to work written entirely by you; rather, the intent is to
126 | exercise the right to control the distribution of derivative or
127 | collective works based on the Program.
128 |
129 | In addition, mere aggregation of another work not based on the Program
130 | with the Program (or with a work based on the Program) on a volume of
131 | a storage or distribution medium does not bring the other work under
132 | the scope of this License.
133 |
134 | 3. You may copy and distribute the Program (or a work based on it,
135 | under Section 2) in object code or executable form under the terms of
136 | Sections 1 and 2 above provided that you also do one of the following:
137 |
138 | a) Accompany it with the complete corresponding machine-readable
139 | source code, which must be distributed under the terms of Sections
140 | 1 and 2 above on a medium customarily used for software interchange; or,
141 |
142 | b) Accompany it with a written offer, valid for at least three
143 | years, to give any third party, for a charge no more than your
144 | cost of physically performing source distribution, a complete
145 | machine-readable copy of the corresponding source code, to be
146 | distributed under the terms of Sections 1 and 2 above on a medium
147 | customarily used for software interchange; or,
148 |
149 | c) Accompany it with the information you received as to the offer
150 | to distribute corresponding source code. (This alternative is
151 | allowed only for noncommercial distribution and only if you
152 | received the program in object code or executable form with such
153 | an offer, in accord with Subsection b above.)
154 |
155 | The source code for a work means the preferred form of the work for
156 | making modifications to it. For an executable work, complete source
157 | code means all the source code for all modules it contains, plus any
158 | associated interface definition files, plus the scripts used to
159 | control compilation and installation of the executable. However, as a
160 | special exception, the source code distributed need not include
161 | anything that is normally distributed (in either source or binary
162 | form) with the major components (compiler, kernel, and so on) of the
163 | operating system on which the executable runs, unless that component
164 | itself accompanies the executable.
165 |
166 | If distribution of executable or object code is made by offering
167 | access to copy from a designated place, then offering equivalent
168 | access to copy the source code from the same place counts as
169 | distribution of the source code, even though third parties are not
170 | compelled to copy the source along with the object code.
171 |
172 | 4. You may not copy, modify, sublicense, or distribute the Program
173 | except as expressly provided under this License. Any attempt
174 | otherwise to copy, modify, sublicense or distribute the Program is
175 | void, and will automatically terminate your rights under this License.
176 | However, parties who have received copies, or rights, from you under
177 | this License will not have their licenses terminated so long as such
178 | parties remain in full compliance.
179 |
180 | 5. You are not required to accept this License, since you have not
181 | signed it. However, nothing else grants you permission to modify or
182 | distribute the Program or its derivative works. These actions are
183 | prohibited by law if you do not accept this License. Therefore, by
184 | modifying or distributing the Program (or any work based on the
185 | Program), you indicate your acceptance of this License to do so, and
186 | all its terms and conditions for copying, distributing or modifying
187 | the Program or works based on it.
188 |
189 | 6. Each time you redistribute the Program (or any work based on the
190 | Program), the recipient automatically receives a license from the
191 | original licensor to copy, distribute or modify the Program subject to
192 | these terms and conditions. You may not impose any further
193 | restrictions on the recipients' exercise of the rights granted herein.
194 | You are not responsible for enforcing compliance by third parties to
195 | this License.
196 |
197 | 7. If, as a consequence of a court judgment or allegation of patent
198 | infringement or for any other reason (not limited to patent issues),
199 | conditions are imposed on you (whether by court order, agreement or
200 | otherwise) that contradict the conditions of this License, they do not
201 | excuse you from the conditions of this License. If you cannot
202 | distribute so as to satisfy simultaneously your obligations under this
203 | License and any other pertinent obligations, then as a consequence you
204 | may not distribute the Program at all. For example, if a patent
205 | license would not permit royalty-free redistribution of the Program by
206 | all those who receive copies directly or indirectly through you, then
207 | the only way you could satisfy both it and this License would be to
208 | refrain entirely from distribution of the Program.
209 |
210 | If any portion of this section is held invalid or unenforceable under
211 | any particular circumstance, the balance of the section is intended to
212 | apply and the section as a whole is intended to apply in other
213 | circumstances.
214 |
215 | It is not the purpose of this section to induce you to infringe any
216 | patents or other property right claims or to contest validity of any
217 | such claims; this section has the sole purpose of protecting the
218 | integrity of the free software distribution system, which is
219 | implemented by public license practices. Many people have made
220 | generous contributions to the wide range of software distributed
221 | through that system in reliance on consistent application of that
222 | system; it is up to the author/donor to decide if he or she is willing
223 | to distribute software through any other system and a licensee cannot
224 | impose that choice.
225 |
226 | This section is intended to make thoroughly clear what is believed to
227 | be a consequence of the rest of this License.
228 |
229 | 8. If the distribution and/or use of the Program is restricted in
230 | certain countries either by patents or by copyrighted interfaces, the
231 | original copyright holder who places the Program under this License
232 | may add an explicit geographical distribution limitation excluding
233 | those countries, so that distribution is permitted only in or among
234 | countries not thus excluded. In such case, this License incorporates
235 | the limitation as if written in the body of this License.
236 |
237 | 9. The Free Software Foundation may publish revised and/or new versions
238 | of the General Public License from time to time. Such new versions will
239 | be similar in spirit to the present version, but may differ in detail to
240 | address new problems or concerns.
241 |
242 | Each version is given a distinguishing version number. If the Program
243 | specifies a version number of this License which applies to it and "any
244 | later version", you have the option of following the terms and conditions
245 | either of that version or of any later version published by the Free
246 | Software Foundation. If the Program does not specify a version number of
247 | this License, you may choose any version ever published by the Free Software
248 | Foundation.
249 |
250 | 10. If you wish to incorporate parts of the Program into other free
251 | programs whose distribution conditions are different, write to the author
252 | to ask for permission. For software which is copyrighted by the Free
253 | Software Foundation, write to the Free Software Foundation; we sometimes
254 | make exceptions for this. Our decision will be guided by the two goals
255 | of preserving the free status of all derivatives of our free software and
256 | of promoting the sharing and reuse of software generally.
257 |
258 | NO WARRANTY
259 |
260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
268 | REPAIR OR CORRECTION.
269 |
270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
278 | POSSIBILITY OF SUCH DAMAGES.
279 |
280 | END OF TERMS AND CONDITIONS
281 |
282 | How to Apply These Terms to Your New Programs
283 |
284 | If you develop a new program, and you want it to be of the greatest
285 | possible use to the public, the best way to achieve this is to make it
286 | free software which everyone can redistribute and change under these terms.
287 |
288 | To do so, attach the following notices to the program. It is safest
289 | to attach them to the start of each source file to most effectively
290 | convey the exclusion of warranty; and each file should have at least
291 | the "copyright" line and a pointer to where the full notice is found.
292 |
293 | {description}
294 | Copyright (C) {year} {fullname}
295 |
296 | This program is free software; you can redistribute it and/or modify
297 | it under the terms of the GNU General Public License as published by
298 | the Free Software Foundation; either version 2 of the License, or
299 | (at your option) any later version.
300 |
301 | This program is distributed in the hope that it will be useful,
302 | but WITHOUT ANY WARRANTY; without even the implied warranty of
303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
304 | GNU General Public License for more details.
305 |
306 | You should have received a copy of the GNU General Public License along
307 | with this program; if not, write to the Free Software Foundation, Inc.,
308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
309 |
310 | Also add information on how to contact you by electronic and paper mail.
311 |
312 | If the program is interactive, make it output a short notice like this
313 | when it starts in an interactive mode:
314 |
315 | Gnomovision version 69, Copyright (C) year name of author
316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
317 | This is free software, and you are welcome to redistribute it
318 | under certain conditions; type `show c' for details.
319 |
320 | The hypothetical commands `show w' and `show c' should show the appropriate
321 | parts of the General Public License. Of course, the commands you use may
322 | be called something other than `show w' and `show c'; they could even be
323 | mouse-clicks or menu items--whatever suits your program.
324 |
325 | You should also get your employer (if you work as a programmer) or your
326 | school, if any, to sign a "copyright disclaimer" for the program, if
327 | necessary. Here is a sample; alter the names:
328 |
329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program
330 | `Gnomovision' (which makes passes at compilers) written by James Hacker.
331 |
332 | {signature of Ty Coon}, 1 April 1989
333 | Ty Coon, President of Vice
334 |
335 | This General Public License does not permit incorporating your program into
336 | proprietary programs. If your program is a subroutine library, you may
337 | consider it more useful to permit linking proprietary applications with the
338 | library. If this is what you want to do, use the GNU Lesser General
339 | Public License instead of this License.
340 |
341 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | scapy-ssh
2 | =========
3 |
4 | ssh key exchange layer for scapy
5 |
--------------------------------------------------------------------------------
/src/example_client_kex_init_fuzzer.py:
--------------------------------------------------------------------------------
1 | #! /usr/bin/env python
2 | # -*- coding: UTF-8 -*-
3 | # Author : tintinweb@oststrom.com
4 |
5 |
6 | def padding_fix(p):
7 | padd= 8-len(p)%8
8 | if p.haslayer(Raw):
9 | p[Raw].load += 'P'*padd
10 | else:
11 | p=p/('P'*padd)
12 | return p
13 |
14 | if __name__=="__main__":
15 | from scapy.all import *
16 |
17 | # for local testing only ---->
18 | import sys
19 | sys.path.append("scapy/layers")
20 | from ssh import *
21 | # <------
22 |
23 | import socket
24 |
25 | for i in range(1000):
26 | try:
27 | target = ('192.168.220.131',22)
28 | s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
29 | s.connect(target)
30 |
31 | p = SSH()/SSHIdent(ident="SSH-2.\r\n")
32 |
33 |
34 | p.show()
35 |
36 | print "sending payload"
37 | s.sendall(str(p))
38 | resp = s.recv(1024)
39 | print "received, %s"%repr(resp)
40 |
41 | SSH(resp).show()
42 |
43 |
44 |
45 | p=SSHMessage()/fuzz( \
46 | SSHKexInit(encryption_algorithms_client_to_server=(','+SSH_ALGO_CIPHERS[1])*2, \
47 | languages_client_to_server="de,uk,de,uk", \
48 | #languages_client_to_server_length=999,\
49 | languages_server_to_client="xx", \
50 | kex_first_packet_follows=2,
51 | reserved=0x0a0b0c0d)/('aa'*2) \
52 | )
53 |
54 | #p=SSHMessage()/SSHKexInit(languages_client_to_server='at')/'aaa'
55 | p = padding_fix(p)
56 |
57 | p.show2()
58 | print "sending payload"
59 | s.sendall(str(p))
60 | resp = s.recv(1024)
61 | print "received, %s"%repr(resp)
62 |
63 | SSH(resp).show()
64 | s.close()
65 | raw_input()
66 | except: pass
--------------------------------------------------------------------------------
/src/example_ident_fail.py:
--------------------------------------------------------------------------------
1 | #! /usr/bin/env python
2 | # -*- coding: UTF-8 -*-
3 | # Author : tintinweb@oststrom.com
4 |
5 |
6 | def padding_fix(p):
7 | padd= 8-len(p)%8
8 | if p.haslayer(Raw):
9 | p[Raw].load += 'P'*padd
10 | else:
11 | p=p/('P'*padd)
12 | return p
13 |
14 | if __name__=="__main__":
15 | from scapy.all import *
16 |
17 | # for local testing only ---->
18 | import sys
19 | sys.path.append("scapy/layers")
20 | from ssh import *
21 | # <------
22 |
23 | import socket
24 |
25 |
26 | target = ('192.168.220.131',22)
27 | s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
28 | s.connect(target)
29 |
30 | p = SSH()/SSHIdent(ident="SSH-2.0-") # missing \r\n
31 |
32 |
33 | p.show()
34 |
35 | print "sending payload"
36 | s.sendall(str(p))
37 |
38 | resp = s.recv(1024)
39 | print "received, %s"%repr(resp)
40 | SSH(resp).show()
41 |
42 | s.close()
43 |
--------------------------------------------------------------------------------
/src/example_kex_valid.py:
--------------------------------------------------------------------------------
1 | #! /usr/bin/env python
2 | # -*- coding: UTF-8 -*-
3 | # Author : tintinweb@oststrom.com
4 |
5 |
6 | def padding_fix(p):
7 | padd= 8-len(p)%8
8 | if p.haslayer(Raw):
9 | p[Raw].load += 'P'*padd
10 | else:
11 | p=p/('P'*padd)
12 | return p
13 |
14 | if __name__=="__main__":
15 | from scapy.all import *
16 |
17 | # for local testing only ---->
18 | import sys
19 | sys.path.append("scapy/layers")
20 | from ssh import *
21 | # <------
22 |
23 | import socket
24 |
25 | try:
26 | target = ('192.168.220.131',22)
27 | s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
28 | s.connect(target)
29 |
30 | p = SSH()/SSHIdent(ident="SSH-2.0-x\r\n")
31 |
32 |
33 | p.show()
34 |
35 | print "sending payload"
36 | s.sendall(str(p))
37 |
38 | resp = s.recv(1024)
39 | print "received, %s"%repr(resp)
40 | SSH(resp).show()
41 |
42 |
43 |
44 | p=SSHMessage()/SSHKexInit( \
45 | #encryption_algorithms_client_to_server=SSH_ALGO_CIPHERS[0], \
46 | #encryption_algorithms_server_to_client=SSH_ALGO_CIPHERS[0], \
47 | #kex_algorithms=SSH_ALGO_CIPHERS[0], \
48 | languages_client_to_server="de,uk,de,uk", \
49 | #languages_client_to_server_length=999,\
50 | #languages_server_to_client="xx", \
51 | #kex_first_packet_follows=2, \
52 | reserved=0) \
53 | #/('a'*100)
54 |
55 | p = padding_fix(p)
56 |
57 | p.show2()
58 | print "sending payload"
59 | s.sendall(str(p))
60 | for i in range(3):
61 | resp = s.recv(1024)
62 | print "received, %s"%repr(resp)
63 |
64 | SSH(resp).show()
65 | s.close()
66 |
67 | except: pass
--------------------------------------------------------------------------------
/src/example_server_kex_init_fuzzer.py:
--------------------------------------------------------------------------------
1 | #! /usr/bin/env python
2 | # -*- coding: UTF-8 -*-
3 | # Author : tintinweb@oststrom.com
4 |
5 |
6 | def padding_fix(p):
7 | padd= 8-len(p)%8
8 | if p.haslayer(Raw):
9 | p[Raw].load += 'P'*padd
10 | else:
11 | p=p/('P'*padd)
12 | return p
13 |
14 | if __name__=="__main__":
15 |
16 | import sys
17 | sys.path.append("../scapy/layers")
18 | from scapy.all import *
19 | from ssh import *
20 |
21 | import socket
22 | import sys
23 | from thread import *
24 |
25 |
26 | #
27 | HOST = '' # Symbolic name meaning all available interfaces
28 | PORT = 22 # Arbitrary non-privileged port
29 |
30 | s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
31 | print 'Socket created'
32 |
33 | #Bind socket to local host and port
34 | try:
35 | s.bind((HOST, PORT))
36 | except socket.error as msg:
37 | print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
38 | sys.exit()
39 |
40 | print 'Socket bind complete'
41 |
42 | #Start listening on socket
43 | s.listen(10)
44 | print 'Socket now listening'
45 |
46 | #Function for handling connections. This will be used to create threads
47 | def clientthread(conn):
48 | #Sending message to connected client
49 | conn.send('Welcome to the server. Type something and hit enter\n') #send only takes string
50 |
51 | #infinite loop so that function do not terminate and thread do not end.
52 | while True:
53 |
54 | #Receiving from client
55 | data = conn.recv(1024)
56 | reply = 'OK...' + data
57 | if not data:
58 | break
59 |
60 | print reply
61 |
62 | reply = SSH()/SSHIdent(ident="SSH-2.\r\n")/fuzz(Raw())
63 | conn.sendall(str(reply))
64 |
65 | reply=SSHMessage()/fuzz( \
66 | SSHKexInit(encryption_algorithms_client_to_server=(','+SSH_ALGO_CIPHERS[1])*2, \
67 | languages_client_to_server="de,uk,de,uk", \
68 | #languages_client_to_server_length=999,\
69 | languages_server_to_client="xx", \
70 | kex_first_packet_follows=2,
71 | reserved=0x0a0b0c0d)/('aa'*2) \
72 | )
73 | conn.sendall(str(reply))
74 |
75 | #came out of loop
76 | conn.close()
77 |
78 | #now keep talking with the client
79 | while 1:
80 | #wait to accept a connection - blocking call
81 | conn, addr = s.accept()
82 | print 'Connected with ' + addr[0] + ':' + str(addr[1])
83 |
84 | #start new thread takes 1st argument as a function name to be run, second is the tuple of arguments to the function.
85 | start_new_thread(clientthread ,(conn,))
86 |
87 | s.close()
88 |
89 | exit()
--------------------------------------------------------------------------------
/src/scapy/layers/ssh.py:
--------------------------------------------------------------------------------
1 | #! /usr/bin/env python
2 | # -*- coding: UTF-8 -*-
3 | # Author : tintinweb@oststrom.com
4 | # http://www.secdev.org/projects/scapy/doc/build_dissect.html
5 | #https://tools.ietf.org/html/rfc4253
6 | from scapy.packet import Packet, bind_layers
7 | from scapy.fields import *
8 | from scapy.layers.inet import TCP, Raw
9 | import os, time, hashlib
10 |
11 |
12 | class StrCustomTerminatorField(StrField):
13 | def __init__(self, name, default, fmt="H", remain=0,terminator="\x00\x00", consume_terminator=True):
14 | StrField.__init__(self,name,default,fmt,remain)
15 | self.terminator=terminator
16 | self.consume_terminator=consume_terminator
17 | def addfield(self, pkt, s, val):
18 | return s+self.i2m(pkt, val)+self.terminator
19 | def getfield(self, pkt, s):
20 | l = s.find(self.terminator)
21 | if l < 0:
22 | #XXX terminator not found
23 | return "",s
24 | if self.consume_terminator:
25 | return s[l+len(self.terminator):],self.m2i(pkt, s[:l])
26 | return s[l:],self.m2i(pkt, s[:l])
27 | def randval(self):
28 | return RandTermString(RandNum(0,1200),self.terminator)
29 |
30 | class HintField(StrField):
31 | def __init__(self, name, default, fmt="H", remain=0):
32 | StrField.__init__(self,name,default,fmt,remain)
33 | def i2len(self, pkt, i):
34 | return 0
35 | def i2m(self, pkt, x):
36 | return ''
37 | class DynamicStrField(Field):
38 | def __init__(self, name, default, fmt="H", remain=0, adjust=lambda pkt,x:x):
39 | Field.__init__(self,name,default,fmt)
40 | self.remain = remain
41 | self.adjust = adjust
42 | def i2len(self, pkt, i):
43 | return len(i)
44 | def i2m(self, pkt, x):
45 | if x is None:
46 | x = ""
47 | elif type(x) is not str:
48 | x=str(x)
49 |
50 | x=self.adjust(pkt,x)
51 | return x
52 | def addfield(self, pkt, s, val):
53 | return s+self.i2m(pkt, val)
54 | def getfield(self, pkt, s):
55 | if self.remain == 0:
56 | return "",self.m2i(pkt, s)
57 | else:
58 | return s[-self.remain:],self.m2i(pkt, s[:-self.remain])
59 | def randval(self):
60 | return RandBin(RandNum(0,1200))
61 |
62 | class BLenField(LenField):
63 | def __init__(self, name, default, fmt = "I", adjust=lambda pkt,x:x, numbytes=None, length_of=None, count_of=None):
64 | self.name = name
65 | self.adjust=adjust
66 | self.numbytes=numbytes
67 | self.length_of= length_of
68 | self.count_of = count_of
69 | LenField.__init__(self, name, default, fmt)
70 |
71 | if fmt[0] in "@=<>!":
72 | self.fmt = fmt
73 | else:
74 | self.fmt = "!"+fmt
75 | self.default = self.any2i(None,default)
76 | self.sz = struct.calcsize(self.fmt) if not numbytes else numbytes
77 | self.owners = []
78 |
79 | def addfield(self, pkt, s, val):
80 | """Add an internal value to a string"""
81 | pack = struct.pack(self.fmt, self.i2m(pkt,val))
82 | if self.numbytes:
83 | pack=pack[len(pack)-self.numbytes:]
84 | return s+pack
85 | def getfield(self, pkt, s):
86 | """Extract an internal value from a string"""
87 | upack_data = s[:self.sz]
88 | # prepend struct.calcsize()-len(data) bytes to satisfy struct.unpack
89 | upack_data = '\x00'*(struct.calcsize(self.fmt)-self.sz) + upack_data
90 |
91 | return s[self.sz:], self.m2i(pkt, struct.unpack(self.fmt, upack_data)[0])
92 |
93 | def i2m(self, pkt, x):
94 | if x is None:
95 | if not (self.length_of or self.count_of):
96 | x = len(pkt.payload)
97 | x = self.adjust(pkt,x)
98 | return x
99 |
100 | if self.length_of is not None:
101 | fld,fval = pkt.getfield_and_val(self.length_of)
102 | f = fld.i2len(pkt, fval)
103 | else:
104 | fld,fval = pkt.getfield_and_val(self.count_of)
105 | f = fld.i2count(pkt, fval)
106 | x = self.adjust(pkt,f)
107 | return x
108 |
109 | class XBLenField(BLenField):
110 | def i2repr(self, pkt, x):
111 | return lhex(self.i2h(pkt, x))
112 |
113 | class XLenField(LenField):
114 | def i2repr(self, pkt, x):
115 | return lhex(self.i2h(pkt, x))
116 |
117 | class XFieldLenField(FieldLenField):
118 | def i2repr(self, pkt, x):
119 | return lhex(self.i2h(pkt, x))
120 |
121 |
122 |
123 | SSH_MESSAGE_TYPES = { 0x01:"disconnect",
124 | 0x14:"kex_init",
125 | 0x15:"new_keys",
126 | 0xff:"unknown"}
127 | SSH_TYPE_BOOL = {0x00:True,
128 | 0xff:False}
129 |
130 | SSH_ALGO_CIPHERS = "none,aes128-ctr,aes192-ctr,aes256-ctr,arcfour256,arcfour128,aes128-gcm@openssh.com,aes256-gcm@openssh.com,aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,aes192-cbc,aes256-cbc,arcfour".split(",")
131 | SSH_ALGO_HMACS = "none,hmac-md5-etm@openssh.com,hmac-sha1-etm@openssh.com,umac-64-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com,hmac-ripemd160-etm@openssh.com,hmac-sha1-96-etm@openssh.com,hmac-md5-96-etm@openssh.com,hmac-md5,hmac-sha1,umac-64@openssh.com,umac-128@openssh.com,hmac-sha2-256,hmac-sha2-512,hmac-ripemd160,hmac-sha1-96,hmac-md5-96".split(",")
132 | SSH_ALGO_KEX = "none,ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha1,diffie-hellman-group1-sha1".split(",")
133 | SSH_ALGO_COMPRESSION = "none,zlib,zlib@openssh.com,none".split(",")
134 | SSH_ALGO_HOSTKEY = "none,ecdsa-sha2-nistp521,ssh-rsa,ssh-dss".split(",")
135 |
136 |
137 |
138 | def ssh_name_list(name, fmt="!I",numbytes=None, default=''):
139 | return [ XBLenField("%s_length"%name,None, length_of="%s"%name, fmt=fmt, numbytes=numbytes),
140 | StrLenField("%s"%name,default,length_from=lambda x:getattr(x,"%s_length"%name)),]
141 |
142 | class SSHIdent(Packet):
143 | name = "SSH Ident"
144 | fields_desc = [
145 | StrField("ident","SSH-2.0-ScapySSHLayer\r\n"),
146 | ]
147 |
148 | def ssh_calculate_mac(pkt, x):
149 | if len(x):
150 | return x
151 | if not pkt.mac in ('md5','sha-1'):
152 | return x
153 | return getattr(hashlib,pkt.mac)(pkt.data).digest()
154 |
155 | class SSHEncryptedPacket(Packet):
156 | name = "SSH Encrypted Packet"
157 | fields_desc = [
158 | StrField("data",None),
159 | DynamicStrField("mac",None,adjust=ssh_calculate_mac),
160 | #HintField("encryption",None),
161 | #HintField("mac",'md5'),
162 | #HintField("compression",None),
163 | ]
164 |
165 |
166 | class SSHMessage(Packet):
167 | name = "SSH Message"
168 | fields_desc = [
169 | XBLenField("length",None, fmt="!I", adjust=lambda pkt,x: x+2 if pkt.lastlayer().haslayer(Raw) else x+2),
170 | XBLenField("padding_length",None, fmt="!B", adjust=lambda pkt,x: len(pkt.lastlayer()) if pkt.lastlayer().haslayer(Raw) else 0),
171 | ByteEnumField("type", 0xff, SSH_MESSAGE_TYPES),
172 | ]
173 |
174 |
175 | class SSHKexInit(Packet):
176 | name = "SSH Key Exchange Init"
177 | fields_desc = [ StrFixedLenField("cookie",os.urandom(16),16),] \
178 | + ssh_name_list("kex_algorithms",default=",".join(SSH_ALGO_KEX)) \
179 | + ssh_name_list("server_host_key_algorithms",default=",".join(SSH_ALGO_HOSTKEY)) \
180 | + ssh_name_list("encryption_algorithms_client_to_server",default=",".join(SSH_ALGO_CIPHERS)) \
181 | + ssh_name_list("encryption_algorithms_server_to_client",default=",".join(SSH_ALGO_CIPHERS)) \
182 | + ssh_name_list("mac_algorithms_client_to_server",default=",".join(SSH_ALGO_HMACS)) \
183 | + ssh_name_list("mac_algorithms_server_to_client",default=",".join(SSH_ALGO_HMACS)) \
184 | + ssh_name_list("compression_algorithms_client_to_server",default=",".join(SSH_ALGO_COMPRESSION)) \
185 | + ssh_name_list("compression_algorithms_server_to_client",default=",".join(SSH_ALGO_COMPRESSION)) \
186 | + ssh_name_list("languages_client_to_server") \
187 | + ssh_name_list("languages_server_to_client") \
188 | + [
189 | ByteEnumField("kex_first_packet_follows", 0x00, SSH_TYPE_BOOL),
190 | IntField("reserved", 0x00),
191 | ]
192 |
193 | SSH_DISCONNECT_REASONS={ 1:'HOST_NOT_ALLOWED_TO_CONNECT',
194 | 2:'PROTOCOL_ERROR',
195 | 3:'KEY_EXCHANGE_FAILED',
196 | 4:'RESERVED',
197 | 5:'MAC_ERROR',
198 | 6:'COMPRESSION_ERROR',
199 | 7:'SERVICE_NOT_AVAILABLE',
200 | 8:'PROTOCOL_VERSION_NOT_SUPPORTED',
201 | 9:'HOST_KEY_NOT_VERIFIABLE',
202 | 10:'CONNECTION_LOST',
203 | 11:'BY_APPLICATION',
204 | 12:'TOO_MANY_CONNECTIONS',
205 | 13:'AUTH_CANCELLED_BY_USER',
206 | 14:'NO_MORE_AUTH_METHODS_AVAILABLE',
207 | 15:'ILLEGAL_USER_NAME',
208 | }
209 |
210 | class SSHDisconnect(Packet):
211 | name = "SSH Disconnect"
212 | fields_desc = [
213 | IntEnumField("reason", 0xff, SSH_DISCONNECT_REASONS),
214 | StrCustomTerminatorField("description","",terminator="\x00\x00\x00\x00"),
215 | StrCustomTerminatorField("language","",terminator="\x00",consume_terminator=False),
216 | ]
217 |
218 | class SSH(Packet):
219 | name = "SSH"
220 |
221 |
222 | def is_ascii(s):
223 | return all(ord(c) < 128 for c in s)
224 |
225 | def guess_payload_class(self, payload):
226 |
227 | try:
228 | if payload.startswith("SSH-"):
229 | return SSHIdent
230 |
231 | dummy = SSHMessage(payload,_internal=1)
232 | if len(payload)<=dummy.length+4:
233 | return SSHMessage
234 |
235 | except:
236 | pass
237 | return SSHEncryptedPacket
238 |
239 |
240 |
241 | # bind magic
242 |
243 | bind_layers(TCP, SSH, dport=22)
244 | bind_layers(TCP, SSH, sport=22)
245 |
246 | bind_layers(SSH, SSHMessage)
247 | bind_layers(SSHMessage, SSHKexInit, {'type':0x14})
248 | bind_layers(SSHMessage, SSHDisconnect, {'type':0x01})
249 | bind_layers(SSH, SSHEncryptedPacket)
250 |
--------------------------------------------------------------------------------