├── CONTRIBUTING.md
├── LICENSE
├── README.md
└── tcp_killer.py
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | # How to Contribute
2 |
3 | We'd love to accept your patches and contributions to this project. There are just a few small guidelines you need to follow.
4 |
5 | ## Contributor License Agreement
6 |
7 | Contributions to this project must be accompanied by a Contributor License Agreement. You (or your employer) retain the copyright to your contribution, this simply gives us permission to use and redistribute your contributions as part of the project. Head over to to see your current agreements on file or to sign a new one.
8 |
9 | You generally only need to submit a CLA once, so if you've already submitted one (even if it was for a different project), you probably don't need to do it again.
10 |
11 | ## Code reviews
12 |
13 | All submissions, including submissions by project members, require review. We use GitHub pull requests for this purpose. Consult [GitHub Help](https://help.github.com/articles/about-pull-requests/) for more information on using pull requests.
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 |
2 | Apache License
3 | Version 2.0, January 2004
4 | http://www.apache.org/licenses/
5 |
6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7 |
8 | 1. Definitions.
9 |
10 | "License" shall mean the terms and conditions for use, reproduction,
11 | and distribution as defined by Sections 1 through 9 of this document.
12 |
13 | "Licensor" shall mean the copyright owner or entity authorized by
14 | the copyright owner that is granting the License.
15 |
16 | "Legal Entity" shall mean the union of the acting entity and all
17 | other entities that control, are controlled by, or are under common
18 | control with that entity. For the purposes of this definition,
19 | "control" means (i) the power, direct or indirect, to cause the
20 | direction or management of such entity, whether by contract or
21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
22 | outstanding shares, or (iii) beneficial ownership of such entity.
23 |
24 | "You" (or "Your") shall mean an individual or Legal Entity
25 | exercising permissions granted by this License.
26 |
27 | "Source" form shall mean the preferred form for making modifications,
28 | including but not limited to software source code, documentation
29 | source, and configuration files.
30 |
31 | "Object" form shall mean any form resulting from mechanical
32 | transformation or translation of a Source form, including but
33 | not limited to compiled object code, generated documentation,
34 | and conversions to other media types.
35 |
36 | "Work" shall mean the work of authorship, whether in Source or
37 | Object form, made available under the License, as indicated by a
38 | copyright notice that is included in or attached to the work
39 | (an example is provided in the Appendix below).
40 |
41 | "Derivative Works" shall mean any work, whether in Source or Object
42 | form, that is based on (or derived from) the Work and for which the
43 | editorial revisions, annotations, elaborations, or other modifications
44 | represent, as a whole, an original work of authorship. For the purposes
45 | of this License, Derivative Works shall not include works that remain
46 | separable from, or merely link (or bind by name) to the interfaces of,
47 | the Work and Derivative Works thereof.
48 |
49 | "Contribution" shall mean any work of authorship, including
50 | the original version of the Work and any modifications or additions
51 | to that Work or Derivative Works thereof, that is intentionally
52 | submitted to Licensor for inclusion in the Work by the copyright owner
53 | or by an individual or Legal Entity authorized to submit on behalf of
54 | the copyright owner. For the purposes of this definition, "submitted"
55 | means any form of electronic, verbal, or written communication sent
56 | to the Licensor or its representatives, including but not limited to
57 | communication on electronic mailing lists, source code control systems,
58 | and issue tracking systems that are managed by, or on behalf of, the
59 | Licensor for the purpose of discussing and improving the Work, but
60 | excluding communication that is conspicuously marked or otherwise
61 | designated in writing by the copyright owner as "Not a Contribution."
62 |
63 | "Contributor" shall mean Licensor and any individual or Legal Entity
64 | on behalf of whom a Contribution has been received by Licensor and
65 | subsequently incorporated within the Work.
66 |
67 | 2. Grant of Copyright License. Subject to the terms and conditions of
68 | this License, each Contributor hereby grants to You a perpetual,
69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70 | copyright license to reproduce, prepare Derivative Works of,
71 | publicly display, publicly perform, sublicense, and distribute the
72 | Work and such Derivative Works in Source or Object form.
73 |
74 | 3. Grant of Patent License. Subject to the terms and conditions of
75 | this License, each Contributor hereby grants to You a perpetual,
76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77 | (except as stated in this section) patent license to make, have made,
78 | use, offer to sell, sell, import, and otherwise transfer the Work,
79 | where such license applies only to those patent claims licensable
80 | by such Contributor that are necessarily infringed by their
81 | Contribution(s) alone or by combination of their Contribution(s)
82 | with the Work to which such Contribution(s) was submitted. If You
83 | institute patent litigation against any entity (including a
84 | cross-claim or counterclaim in a lawsuit) alleging that the Work
85 | or a Contribution incorporated within the Work constitutes direct
86 | or contributory patent infringement, then any patent licenses
87 | granted to You under this License for that Work shall terminate
88 | as of the date such litigation is filed.
89 |
90 | 4. Redistribution. You may reproduce and distribute copies of the
91 | Work or Derivative Works thereof in any medium, with or without
92 | modifications, and in Source or Object form, provided that You
93 | meet the following conditions:
94 |
95 | (a) You must give any other recipients of the Work or
96 | Derivative Works a copy of this License; and
97 |
98 | (b) You must cause any modified files to carry prominent notices
99 | stating that You changed the files; and
100 |
101 | (c) You must retain, in the Source form of any Derivative Works
102 | that You distribute, all copyright, patent, trademark, and
103 | attribution notices from the Source form of the Work,
104 | excluding those notices that do not pertain to any part of
105 | the Derivative Works; and
106 |
107 | (d) If the Work includes a "NOTICE" text file as part of its
108 | distribution, then any Derivative Works that You distribute must
109 | include a readable copy of the attribution notices contained
110 | within such NOTICE file, excluding those notices that do not
111 | pertain to any part of the Derivative Works, in at least one
112 | of the following places: within a NOTICE text file distributed
113 | as part of the Derivative Works; within the Source form or
114 | documentation, if provided along with the Derivative Works; or,
115 | within a display generated by the Derivative Works, if and
116 | wherever such third-party notices normally appear. The contents
117 | of the NOTICE file are for informational purposes only and
118 | do not modify the License. You may add Your own attribution
119 | notices within Derivative Works that You distribute, alongside
120 | or as an addendum to the NOTICE text from the Work, provided
121 | that such additional attribution notices cannot be construed
122 | as modifying the License.
123 |
124 | You may add Your own copyright statement to Your modifications and
125 | may provide additional or different license terms and conditions
126 | for use, reproduction, or distribution of Your modifications, or
127 | for any such Derivative Works as a whole, provided Your use,
128 | reproduction, and distribution of the Work otherwise complies with
129 | the conditions stated in this License.
130 |
131 | 5. Submission of Contributions. Unless You explicitly state otherwise,
132 | any Contribution intentionally submitted for inclusion in the Work
133 | by You to the Licensor shall be under the terms and conditions of
134 | this License, without any additional terms or conditions.
135 | Notwithstanding the above, nothing herein shall supersede or modify
136 | the terms of any separate license agreement you may have executed
137 | with Licensor regarding such Contributions.
138 |
139 | 6. Trademarks. This License does not grant permission to use the trade
140 | names, trademarks, service marks, or product names of the Licensor,
141 | except as required for reasonable and customary use in describing the
142 | origin of the Work and reproducing the content of the NOTICE file.
143 |
144 | 7. Disclaimer of Warranty. Unless required by applicable law or
145 | agreed to in writing, Licensor provides the Work (and each
146 | Contributor provides its Contributions) on an "AS IS" BASIS,
147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148 | implied, including, without limitation, any warranties or conditions
149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150 | PARTICULAR PURPOSE. You are solely responsible for determining the
151 | appropriateness of using or redistributing the Work and assume any
152 | risks associated with Your exercise of permissions under this License.
153 |
154 | 8. Limitation of Liability. In no event and under no legal theory,
155 | whether in tort (including negligence), contract, or otherwise,
156 | unless required by applicable law (such as deliberate and grossly
157 | negligent acts) or agreed to in writing, shall any Contributor be
158 | liable to You for damages, including any direct, indirect, special,
159 | incidental, or consequential damages of any character arising as a
160 | result of this License or out of the use or inability to use the
161 | Work (including but not limited to damages for loss of goodwill,
162 | work stoppage, computer failure or malfunction, or any and all
163 | other commercial damages or losses), even if such Contributor
164 | has been advised of the possibility of such damages.
165 |
166 | 9. Accepting Warranty or Additional Liability. While redistributing
167 | the Work or Derivative Works thereof, You may choose to offer,
168 | and charge a fee for, acceptance of support, warranty, indemnity,
169 | or other liability obligations and/or rights consistent with this
170 | License. However, in accepting such obligations, You may act only
171 | on Your own behalf and on Your sole responsibility, not on behalf
172 | of any other Contributor, and only if You agree to indemnify,
173 | defend, and hold each Contributor harmless for any liability
174 | incurred by, or claims asserted against, such Contributor by reason
175 | of your accepting any such warranty or additional liability.
176 |
177 | END OF TERMS AND CONDITIONS
178 |
179 | APPENDIX: How to apply the Apache License to your work.
180 |
181 | To apply the Apache License to your work, attach the following
182 | boilerplate notice, with the fields enclosed by brackets "[]"
183 | replaced with your own identifying information. (Don't include
184 | the brackets!) The text should be enclosed in the appropriate
185 | comment syntax for the file format. We also recommend that a
186 | file or class name and description of purpose be included on the
187 | same "printed page" as the copyright notice for easier
188 | identification within third-party archives.
189 |
190 | Copyright [yyyy] [name of copyright owner]
191 |
192 | Licensed under the Apache License, Version 2.0 (the "License");
193 | you may not use this file except in compliance with the License.
194 | You may obtain a copy of the License at
195 |
196 | http://www.apache.org/licenses/LICENSE-2.0
197 |
198 | Unless required by applicable law or agreed to in writing, software
199 | distributed under the License is distributed on an "AS IS" BASIS,
200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201 | See the License for the specific language governing permissions and
202 | limitations under the License.
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # tcp_killer
2 |
3 | Shuts down a TCP connection on Linux or macOS. Local and remote endpoint arguments can be copied from the output of 'netstat -lanW'.
4 |
5 | The functionality offered by *tcp_killer* is intended to mimic [TCPView](https://technet.microsoft.com/en-us/sysinternals/tcpview.aspx)'s "Close Connection" functionality and [tcpdrop](http://man.openbsd.org/tcpdrop.8)'s functionality on Linux and macOS.
6 |
7 | ## Basic Usage
8 |
9 | `python tcp_killer.py [-verbose] `
10 |
11 | Arguments:
12 |
13 | -verbose Show verbose output
14 | Connection's local IP address and port
15 | Connection's remote IP address and port
16 |
17 | Examples:
18 |
19 | tcp_killer.py 10.31.33.7:50246 93.184.216.34:443
20 | tcp_killer.py 2001:db8:85a3::8a2e:370:7334.93 2606:2800:220:1:248:1893:25c8:1946.80
21 | tcp_killer.py -verbose [2001:4860:4860::8888]:46820 [2607:f8b0:4005:807::200e]:80
22 |
23 | ## Full Example
24 | ```
25 | geffner@ubuntu:~$ # Create a server to listen on TCP port 12345
26 | geffner@ubuntu:~$ nc -d -l -p 12345 &
27 | [1] 135578
28 |
29 | geffner@ubuntu:~$ # Connect to the local server on TCP port 12345
30 | geffner@ubuntu:~$ nc -v -d localhost 12345 &
31 | [2] 135579
32 | Connection to localhost 12345 port [tcp/*] succeeded!
33 |
34 | geffner@ubuntu:~$ # Find the connection endpoints
35 | geffner@ubuntu:~$ netstat -lanW | grep 12345.*ESTABLISHED
36 | tcp 0 0 127.0.0.1:33994 127.0.0.1:12345 ESTABLISHED
37 | tcp 0 0 127.0.0.1:12345 127.0.0.1:33994 ESTABLISHED
38 |
39 | geffner@ubuntu:~$ # Kill the connection by copying and pasting the output of netstat
40 | geffner@ubuntu:~$ python tcp_killer.py 127.0.0.1:33994 127.0.0.1:12345
41 | TCP connection was successfully shutdown.
42 | [1]- Done nc -d -l -p 12345
43 | [2]+ Done nc -v -d localhost 12345
44 | ```
45 |
46 | ## Dependencies
47 |
48 | ### lsof
49 |
50 | This program uses [lsof](https://en.wikipedia.org/wiki/Lsof) to find the process and socket file descriptor associated with a given TCP connection.
51 |
52 | lsof can be installed via your package management system (for example, `sudo apt-get install lsof`).
53 |
54 | ### frida
55 |
56 | This program uses the [frida](https://www.frida.re/) framework to perform code injection.
57 |
58 | Frida can be installed as follows: `sudo pip install frida`
59 |
60 | ## Disclaimer
61 |
62 | This is not an official Google product.
63 |
--------------------------------------------------------------------------------
/tcp_killer.py:
--------------------------------------------------------------------------------
1 | # Copyright 2017 Google Inc. All Rights Reserved.
2 |
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 |
15 | """Shuts down a TCP connection on Linux or macOS.
16 |
17 | Finds the process and socket file descriptor associated with a given TCP
18 | connection. Then injects into that process a call to shutdown()
19 | (http://man7.org/linux/man-pages/man2/shutdown.2.html) that file descriptor,
20 | thereby shutting down the TCP connection.
21 |
22 | Typical usage example:
23 |
24 | tcp_kill("10.31.33.7", 50246 "93.184.216.34", 443)
25 |
26 | Dependencies:
27 | lsof (https://en.wikipedia.org/wiki/Lsof)
28 | frida (https://www.frida.re/): sudo pip install frida
29 | """
30 |
31 | __author__ = "geffner@google.com (Jason Geffner)"
32 | __version__ = "1.0"
33 |
34 |
35 | import argparse
36 | import os
37 | import platform
38 | import re
39 | import socket
40 | import subprocess
41 | import threading
42 |
43 | import frida
44 |
45 |
46 | _FRIDA_SCRIPT = """
47 | var resolver = new ApiResolver("module");
48 | var lib = Process.platform == "darwin" ? "libsystem" : "libc";
49 | var matches = resolver.enumerateMatchesSync("exports:*" + lib + "*!shutdown");
50 | if (matches.length == 0)
51 | {
52 | throw new Error("Could not find *" + lib + "*!shutdown in target process.");
53 | }
54 | else if (matches.length != 1)
55 | {
56 | // Sometimes Frida returns duplicates.
57 | var address = 0;
58 | var s = "";
59 | var duplicates_only = true;
60 | for (var i = 0; i < matches.length; i++)
61 | {
62 | if (s.length != 0)
63 | {
64 | s += ", ";
65 | }
66 | s += matches[i].name + "@" + matches[i].address;
67 | if (address == 0)
68 | {
69 | address = matches[i].address;
70 | }
71 | else if (!address.equals(matches[i].address))
72 | {
73 | duplicates_only = false;
74 | }
75 | }
76 | if (!duplicates_only)
77 | {
78 | throw new Error("More than one match found for *libc*!shutdown: " + s);
79 | }
80 | }
81 | var shutdown = new NativeFunction(matches[0].address, "int", ["int", "int"]);
82 | if (shutdown(%d, 0) != 0)
83 | {
84 | throw new Error("Call to shutdown() returned an error.");
85 | }
86 | send("");
87 | """
88 |
89 |
90 | def canonicalize_ip_address(address):
91 | if ":" in address:
92 | family = socket.AF_INET6
93 | else:
94 | family = socket.AF_INET
95 | return socket.inet_ntop(family, socket.inet_pton(family, address))
96 |
97 |
98 | def tcp_kill(local_addr, local_port, remote_addr, remote_port, verbose=False):
99 | """Shuts down a TCP connection on Linux or macOS.
100 |
101 | Finds the process and socket file descriptor associated with a given TCP
102 | connection. Then injects into that process a call to shutdown()
103 | (http://man7.org/linux/man-pages/man2/shutdown.2.html) that file descriptor,
104 | thereby shutting down the TCP connection.
105 |
106 | Args:
107 | local_addr: The IP address (as a string) associated with the local endpoint
108 | of the connection.
109 | local_port: The port (as an int) associated with the local endpoint of the
110 | connection.
111 | remote_addr: The IP address (as a string) associated with the remote
112 | endpoint of the connection.
113 | remote_port: The port (as an int) associated with the remote endpoint of the
114 | connection.
115 | verbose: If True, print verbose output to the console.
116 |
117 | Returns:
118 | No return value if successful. If unsuccessful, raises an exception.
119 |
120 | Raises:
121 | KeyError: Unexpected output from lsof command.
122 | NotImplementedError: Not running on a Linux or macOS system.
123 | OSError: TCP connection not found or socket file descriptor not found.
124 | RuntimeError: Error during execution of JavaScript injected into process.
125 | """
126 |
127 | if platform.system() not in ("Darwin", "Linux"):
128 | raise NotImplementedError("This function is only implemented for Linux and "
129 | "macOS systems.")
130 |
131 | local_addr = canonicalize_ip_address(local_addr)
132 | remote_addr = canonicalize_ip_address(remote_addr)
133 |
134 | name_pattern = re.compile(
135 | r"^\[?(.+?)]?:([0-9]{1,5})->\[?(.+?)]?:([0-9]{1,5})$")
136 | fd_pattern = re.compile(r"^(\d)+")
137 |
138 | field_names = ("PID", "FD", "NAME")
139 | fields = {}
140 | pid = None
141 | sockfd = None
142 | for line in subprocess.check_output("lsof -bnlPiTCP -sTCP:ESTABLISHED "
143 | "2>/dev/null", shell=True).splitlines():
144 | words = line.split()
145 |
146 | if len(fields) != len(field_names):
147 | for i in xrange(len(words)):
148 | for field in field_names:
149 | if words[i] == field:
150 | fields[field] = i
151 | break
152 | if len(fields) != len(field_names):
153 | raise KeyError("Unexpected field headers in output of lsof command.")
154 | continue
155 |
156 | name = name_pattern.match(words[fields["NAME"]])
157 | if not name:
158 | raise KeyError("Unexpected NAME in output of lsof command.")
159 | if (int(name.group(2)) == local_port and int(name.group(4)) == remote_port
160 | and canonicalize_ip_address(name.group(1)) == local_addr and
161 | canonicalize_ip_address(name.group(3)) == remote_addr):
162 | pid = int(words[fields["PID"]])
163 | sockfd = int(fd_pattern.match(words[fields["FD"]]).group(1))
164 | if verbose:
165 | print "Process ID of socket's process: %d" % pid
166 | print "Socket file descriptor: %d" % sockfd
167 | break
168 |
169 | if not sockfd:
170 | s = " Try running as root." if os.geteuid() != 0 else ""
171 | raise OSError("Socket not found for connection." + s)
172 |
173 | _shutdown_sockfd(pid, sockfd)
174 |
175 |
176 | def _shutdown_sockfd(pid, sockfd):
177 | """Injects into a process a call to shutdown() a socket file descriptor.
178 |
179 | Injects into a process a call to shutdown()
180 | (http://man7.org/linux/man-pages/man2/shutdown.2.html) a socket file
181 | descriptor, thereby shutting down its associated TCP connection.
182 |
183 | Args:
184 | pid: The process ID (as an int) of the target process.
185 | sockfd: The socket file descriptor (as an int) in the context of the target
186 | process to be shutdown.
187 |
188 | Raises:
189 | RuntimeError: Error during execution of JavaScript injected into process.
190 | """
191 |
192 | js_error = {} # Using dictionary since Python 2.7 doesn't support "nonlocal".
193 | event = threading.Event()
194 |
195 | def on_message(message, data): # pylint: disable=unused-argument
196 | if message["type"] == "error":
197 | js_error["error"] = message["description"]
198 | event.set()
199 |
200 | session = frida.attach(pid)
201 | script = session.create_script(_FRIDA_SCRIPT % sockfd)
202 | script.on("message", on_message)
203 | closed = False
204 |
205 | try:
206 | script.load()
207 | except frida.TransportError as e:
208 | if str(e) != "the connection is closed":
209 | raise
210 | closed = True
211 |
212 | if not closed:
213 | event.wait()
214 | session.detach()
215 | if "error" in js_error:
216 | raise RuntimeError(js_error["error"])
217 |
218 |
219 | if __name__ == "__main__":
220 |
221 | class ArgParser(argparse.ArgumentParser):
222 |
223 | def error(self, message):
224 | print "tcp_killer v" + __version__
225 | print "by " + __author__
226 | print
227 | print "Error: " + message
228 | print
229 | print self.format_help().replace("usage:", "Usage:")
230 | self.exit(0)
231 |
232 | parser = ArgParser(
233 | add_help=False,
234 | description="Shuts down a TCP connection on Linux or macOS. Local and "
235 | "remote endpoint arguments can be copied from the output of 'netstat "
236 | "-lanW'.",
237 | formatter_class=argparse.RawDescriptionHelpFormatter,
238 | epilog=r"""
239 | Examples:
240 | %(prog)s 10.31.33.7:50246 93.184.216.34:443
241 | %(prog)s 2001:db8:85a3::8a2e:370:7334.93 2606:2800:220:1:248:1893:25c8:1946.80
242 | %(prog)s -verbose [2001:4860:4860::8888]:46820 [2607:f8b0:4005:807::200e]:80
243 | """)
244 |
245 | args = parser.add_argument_group("Arguments")
246 | args.add_argument("-verbose", required=False, action="store_const",
247 | const=True, help="Show verbose output")
248 | args.add_argument("local", metavar="",
249 | help="Connection's local IP address and port")
250 | args.add_argument("remote", metavar="",
251 | help="Connection's remote IP address and port")
252 | parsed = parser.parse_args()
253 |
254 | ep_format = re.compile(r"^(.+)[:\.]([0-9]{1,5})$")
255 | local = ep_format.match(parsed.local)
256 | remote = ep_format.match(parsed.remote)
257 | if not local or not remote:
258 | parser.error("Invalid command-line argument.")
259 |
260 | local_address = local.group(1)
261 | if local_address.startswith("[") and local_address.endswith("]"):
262 | local_address = local_address[1:-1]
263 |
264 | remote_address = remote.group(1)
265 | if remote_address.startswith("[") and remote_address.endswith("]"):
266 | remote_address = remote_address[1:-1]
267 |
268 | tcp_kill(local_address, int(local.group(2)), remote_address,
269 | int(remote.group(2)), parsed.verbose)
270 |
271 | print "TCP connection was successfully shutdown."
272 |
--------------------------------------------------------------------------------