From cfbe11cefa144e60a157cbd85c68fa040049d520 Mon Sep 17 00:00:00 2001 From: John Jawed Date: Sat, 20 May 2023 02:54:25 +0000 Subject: [PATCH] Initial commit --- .github/ISSUE_TEMPLATE | 7 ++ .github/PULL_REQUEST_TEMPLATE | 9 ++ .gitignore | 3 + CHANGELOG | 4 + LICENSE.txt | 29 +++++ Makefile | 10 ++ README.md | 63 +++++++++++ SECURITY.md | 18 ++++ SUPPORT.md | 7 ++ docs/CODE-OF-CONDUCT.md | 128 ++++++++++++++++++++++ docs/CONTRIBUTING.md | 50 +++++++++ tcphup.c | 196 ++++++++++++++++++++++++++++++++++ test/.gitkeep | 0 13 files changed, 524 insertions(+) create mode 100644 .github/ISSUE_TEMPLATE create mode 100644 .github/PULL_REQUEST_TEMPLATE create mode 100644 .gitignore create mode 100644 CHANGELOG create mode 100644 LICENSE.txt create mode 100644 Makefile create mode 100644 README.md create mode 100644 SECURITY.md create mode 100644 SUPPORT.md create mode 100644 docs/CODE-OF-CONDUCT.md create mode 100644 docs/CONTRIBUTING.md create mode 100644 tcphup.c create mode 100644 test/.gitkeep diff --git a/.github/ISSUE_TEMPLATE b/.github/ISSUE_TEMPLATE new file mode 100644 index 0000000..037557b --- /dev/null +++ b/.github/ISSUE_TEMPLATE @@ -0,0 +1,7 @@ +--- +name: Tracking issue +about: Use this template for tracking new features. +title: "[DATE]: [FEATURE NAME]" +labels: tracking issue, needs triage +assignees: octocat +--- diff --git a/.github/PULL_REQUEST_TEMPLATE b/.github/PULL_REQUEST_TEMPLATE new file mode 100644 index 0000000..a6618b7 --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE @@ -0,0 +1,9 @@ +## Describe your changes + +## Issue ticket number and link + +## Checklist before requesting a review +- [ ] I have performed a self-review of my code +- [ ] If it is a core feature, I have added thorough tests. +- [ ] Do we need to implement analytics? +- [ ] Will this be part of a product update? If yes, please write one phrase about this update. diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ff50489 --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +*.o +*.swp +.gdb_history diff --git a/CHANGELOG b/CHANGELOG new file mode 100644 index 0000000..dbbd321 --- /dev/null +++ b/CHANGELOG @@ -0,0 +1,4 @@ +# Changelog + +## main +- initial commit diff --git a/LICENSE.txt b/LICENSE.txt new file mode 100644 index 0000000..1e8a868 --- /dev/null +++ b/LICENSE.txt @@ -0,0 +1,29 @@ +Copyright (c) 2023 eBay Inc. + +The MIT License (MIT) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +USE OF SOME COMPONENTS REQUIRES A SEPARATE, NON-OPEN-SOURCE LICENSE FROM THIRD PARTIES + +The data visualization components and the charting components of the eBayUI library are designed to use one or more HighCharts® software products. HighCharts® is a registered trademark of HighSoft AS. HighSoft AS is not affiliated with Ebay. Ebay provides no warranties of any kind (e.g., of merchantability, fitness for a particular purpose, and noninfringement), whether express or implied, with respect to the HighCharts® software products that the data visualization components and the charting components are designed to use. + +COMMERCIAL USE OF HIGHCHARTS® SOFTWARE PRODUCTS REQUIRES A PAID LICENSE PROVIDED BY HIGHSOFT AS. While many components of the eBayUI library are licensed under the MIT License, the HighCharts® software products which the data visualization components and charting components of the EbayUI library are designed to use are NOT licensed under the MIT License or any other open source license. Rights pertaining to HighCharts® software products (e.g., including, but not limited to, rights to use, install, distribute, publish, merge, duplicate, and modify) are governed by the terms of one or more proprietary license agreements that are available online at http://www.highcharts.com or by the terms of custom license agreements that HighSoft AS may negotiate with its customers at its own discretion. While HighSoft AS may choose to license HighCharts® software products for non-commercial use at no cost, IT IS THE RESPONSIBILITY OF ANY PARTY THAT WISHES TO USE HIGHCHARTS® SOFTWARE PRODUCTS TO VERIFY THE TERMS OF SUCH A LICENSE WITH HIGHSOFT AS. NOTWITHSTANDING ANY PROVISION OF THIS LICENSE, PARTIES WHO ARE NOT LICENSED BY HIGHSOFT AS (OR ITS SUCCESSORS OR ASSIGNS) TO USE HIGHCHARTS® SOFTWARE PRODUCTS ARE NOT LICENSED TO USE THE DATA VISUALIZATION COMPONENTS AND THE CHARTING COMPONENTS OF THE EBAYUI LIBRARY. + +This notice shall be included in all copies or substantial portions of the Software. diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..68bb4f1 --- /dev/null +++ b/Makefile @@ -0,0 +1,10 @@ +CC = gcc +CFLAGS = -Wall -Wextra +LIBS = +TARGET = tcphup +SRCS = tcphup.c +all: $(TARGET) +$(TARGET): $(SRCS) + $(CC) $(CFLAGS) -o $@ $^ $(LIBS) +clean: + rm -f $(TARGET) diff --git a/README.md b/README.md new file mode 100644 index 0000000..0fecb15 --- /dev/null +++ b/README.md @@ -0,0 +1,63 @@ +# tcphup + +Hang up on TCP connections. + +tcphup is particularily useful for dropping stale TCP keep alive connections. + +# Why tcphup + +tcphup is an alternative to existing approaches which attempt to +man-in-the-middle TCP RST packets on existing flows. + +The primary disadvantages of existing approaches are: + +1. The next sequence number has to be guessed and front run in order to insert +the RST packet. +2. For keep alive connections, idleness causes delays in trying to insert the +RST packet. + +# tcphup is different + +tcphup sends a proper shutdown to the socket, a proper FIN, as if the client had +called close(2) on the socket without any modifications to running applications. + +tcphup is more efficient and provides better reliability in closing the connection. + +## Example use case + +An application opens keep alive connections to a service, however due to large +keep alive intervals or counts, the application cannot fail over to a new +service IP in the event of fail over(s) in a timely fashion. + +tcphup issuing a close(2) on behalf of the application hangs up the keep alive +connection, which would allow the application to handle service fail overs more +gracefully. + +# Dependencies +- linux > 5.10.0 + +# Build +```bash +$ make +``` + +# Usage + +Kill all port 80/tcp connections to httpstat.us: + +```bash +$ curl -v httpstat.us/200?sleep=500000 +# in another tty +$ tcphup $(getent hosts httpstat.us | awk '{ print $1 }') 80 +``` + +Kill all connections to httpstat.us (set port to 0): + +```bash +$ curl -v httpstat.us/200?sleep=500000 +# in another tty +$ tcphup $(getent hosts httpstat.us | awk '{ print $1 }') 0 +``` + +# License +[MIT License](./LICENSE.txt) diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..eea647a --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,18 @@ +# Security Policy + +## Supported Versions + +We release patches for security vulnerabilities. Which versions are eligible for +receiving such patches depends on the CVSS v3.0 Rating: + +| CVSS v3.0 | Supported Versions | +| --------- | ----------------------------------------- | +| 9.0-10.0 | Releases within the previous three months | +| 4.0-8.9 | Most recent release | + +## Reporting a Vulnerability + +Please report (suspected) security vulnerabilities to +**[jawed@php.net](mailto:jawed@php.net)**. You will receive a response from +us within 48 hours. If the issue is confirmed, we will release a patch as soon +as possible depending on complexity but historically within a few days. diff --git a/SUPPORT.md b/SUPPORT.md new file mode 100644 index 0000000..c80e40a --- /dev/null +++ b/SUPPORT.md @@ -0,0 +1,7 @@ +# Support + +## How to file issues and get help + +This project uses GitHub Issues to track bugs and feature requests. Please search the existing +issues before filing new issues to avoid duplicates. For new issues, file your bug or +feature request as a new Issue. diff --git a/docs/CODE-OF-CONDUCT.md b/docs/CODE-OF-CONDUCT.md new file mode 100644 index 0000000..59bed5d --- /dev/null +++ b/docs/CODE-OF-CONDUCT.md @@ -0,0 +1,128 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +We as members, contributors, and leaders pledge to make participation in our +community a harassment-free experience for everyone, regardless of age, body +size, visible or invisible disability, ethnicity, sex characteristics, gender +identity and expression, level of experience, education, socio-economic status, +nationality, personal appearance, race, religion, or sexual identity +and orientation. + +We pledge to act and interact in ways that contribute to an open, welcoming, +diverse, inclusive, and healthy community. + +## Our Standards + +Examples of behavior that contributes to a positive environment for our +community include: + +* Demonstrating empathy and kindness toward other people +* Being respectful of differing opinions, viewpoints, and experiences +* Giving and gracefully accepting constructive feedback +* Accepting responsibility and apologizing to those affected by our mistakes, + and learning from the experience +* Focusing on what is best not just for us as individuals, but for the + overall community + +Examples of unacceptable behavior include: + +* The use of sexualized language or imagery, and sexual attention or + advances of any kind +* Trolling, insulting or derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or email + address, without their explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Enforcement Responsibilities + +Community leaders are responsible for clarifying and enforcing our standards of +acceptable behavior and will take appropriate and fair corrective action in +response to any behavior that they deem inappropriate, threatening, offensive, +or harmful. + +Community leaders have the right and responsibility to remove, edit, or reject +comments, commits, code, wiki edits, issues, and other contributions that are +not aligned to this Code of Conduct, and will communicate reasons for moderation +decisions when appropriate. + +## Scope + +This Code of Conduct applies within all community spaces, and also applies when +an individual is officially representing the community in public spaces. +Examples of representing our community include using an official e-mail address, +posting via an official social media account, or acting as an appointed +representative at an online or offline event. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported to the community leaders responsible for enforcement at +jawed@php.net. +All complaints will be reviewed and investigated promptly and fairly. + +All community leaders are obligated to respect the privacy and security of the +reporter of any incident. + +## Enforcement Guidelines + +Community leaders will follow these Community Impact Guidelines in determining +the consequences for any action they deem in violation of this Code of Conduct: + +### 1. Correction + +**Community Impact**: Use of inappropriate language or other behavior deemed +unprofessional or unwelcome in the community. + +**Consequence**: A private, written warning from community leaders, providing +clarity around the nature of the violation and an explanation of why the +behavior was inappropriate. A public apology may be requested. + +### 2. Warning + +**Community Impact**: A violation through a single incident or series +of actions. + +**Consequence**: A warning with consequences for continued behavior. No +interaction with the people involved, including unsolicited interaction with +those enforcing the Code of Conduct, for a specified period of time. This +includes avoiding interactions in community spaces as well as external channels +like social media. Violating these terms may lead to a temporary or +permanent ban. + +### 3. Temporary Ban + +**Community Impact**: A serious violation of community standards, including +sustained inappropriate behavior. + +**Consequence**: A temporary ban from any sort of interaction or public +communication with the community for a specified period of time. No public or +private interaction with the people involved, including unsolicited interaction +with those enforcing the Code of Conduct, is allowed during this period. +Violating these terms may lead to a permanent ban. + +### 4. Permanent Ban + +**Community Impact**: Demonstrating a pattern of violation of community +standards, including sustained inappropriate behavior, harassment of an +individual, or aggression toward or disparagement of classes of individuals. + +**Consequence**: A permanent ban from any sort of public interaction within +the community. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], +version 2.0, available at +https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. + +Community Impact Guidelines were inspired by [Mozilla's code of conduct +enforcement ladder](https://github.com/mozilla/diversity). + +[homepage]: https://www.contributor-covenant.org + +For answers to common questions about this code of conduct, see the FAQ at +https://www.contributor-covenant.org/faq. Translations are available at +https://www.contributor-covenant.org/translations. diff --git a/docs/CONTRIBUTING.md b/docs/CONTRIBUTING.md new file mode 100644 index 0000000..c2bb721 --- /dev/null +++ b/docs/CONTRIBUTING.md @@ -0,0 +1,50 @@ +# Welcome to the tcphup contributing guide + +Thank you for investing your time in contributing to our project :sparkles:. + +Read our [Code of Conduct](./CODE_OF_CONDUCT.md) to keep our community approachable and respectable. + +In this guide you will get an overview of the contribution workflow from opening an issue, creating a PR, reviewing, and merging the PR. + +## New contributor guide + +To get an overview of the project, read the [README](../README.md). Here are some resources to help you get started with open source contributions: + +- [Finding ways to contribute to open source on GitHub](https://docs.github.com/en/get-started/exploring-projects-on-github/finding-ways-to-contribute-to-open-source-on-github) +- [Set up Git](https://docs.github.com/en/get-started/quickstart/set-up-git) +- [GitHub flow](https://docs.github.com/en/get-started/quickstart/github-flow) +- [Collaborating with pull requests](https://docs.github.com/en/github/collaborating-with-pull-requests) + +### Issues + +#### Create a new issue + +If you spot a problem with the docs, [search if an issue already exists](https://docs.github.com/en/github/searching-for-information-on-github/searching-on-github/searching-issues-and-pull-requests#search-by-the-title-body-or-comments). If a related issue doesn't exist, you can open a new issue. + +#### Solve an issue + +Scan through our existing issues to find one that interests you. You can narrow down the search using `labels` as filters. As a general rule, we don’t assign issues to anyone. If you find an issue to work on, you are welcome to open a PR with a fix. + +### Make Changes + +#### Make changes locally + +1. Fork the repository. +- Using GitHub Desktop: + - [Getting started with GitHub Desktop](https://docs.github.com/en/desktop/installing-and-configuring-github-desktop/getting-started-with-github-desktop) will guide you through setting up Desktop. + - Once Desktop is set up, you can use it to [fork the repo](https://docs.github.com/en/desktop/contributing-and-collaborating-using-github-desktop/cloning-and-forking-repositories-from-github-desktop)! + +- Using the command line: + - [Fork the repo](https://docs.github.com/en/github/getting-started-with-github/fork-a-repo#fork-an-example-repository) so that you can make your changes without affecting the original project until you're ready to merge them. + +2. Create a working branch and start with your changes! + +### Commit your update + +Commit the changes once you are happy with them. + +### Pull Request + +When you're finished with the changes, create a pull request, also known as a PR. +- Fill the "Ready for review" template so that we can review your PR. This template helps reviewers understand your changes as well as the purpose of your pull request. +- Don't forget to [link PR to issue](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue) if you are solving one. diff --git a/tcphup.c b/tcphup.c new file mode 100644 index 0000000..1d7db71 --- /dev/null +++ b/tcphup.c @@ -0,0 +1,196 @@ +/* SPDX-License-Identifier: MIT */ +/* + * tcphup.c "tcphup.c", close tcp connections + * + * Authors: John Jawed, + */ + +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define thup_exit(msg) perror(msg); exit(EXIT_FAILURE); + +/* this is how iproute2/misc/ss.c largely does it too */ +bool thup_find_pid_and_fd_by_inode(int inode, int *pid, int *fd) { + DIR *proc_dir = opendir("/proc"); + + if (!proc_dir) { + thup_exit("opendir"); + } + + struct dirent *entry; + + while ((entry = readdir(proc_dir))) { + int current_pid; + char fd_dir_path[64]; + struct dirent *fd_entry; + DIR *fd_dir; + + if (sscanf(entry->d_name, "%d", ¤t_pid) != 1) { + continue; + } + + snprintf(fd_dir_path, sizeof(fd_dir_path), "/proc/%d/fd", current_pid); + + fd_dir = opendir(fd_dir_path); + + if (!fd_dir) { + continue; + } + + while ((fd_entry = readdir(fd_dir))) { + char target[256]; + char fd_link[512]; + ssize_t len; + int current_inode; + + snprintf(fd_link, sizeof(fd_link), "%s/%s", fd_dir_path, fd_entry->d_name); + + len = readlink(fd_link, target, sizeof(target) - 1); + + if (len == -1) { + continue; + } + + target[len] = '\0'; + + if (sscanf(target, "socket:[%d]", ¤t_inode) == 1 && current_inode == inode) { + sscanf(fd_entry->d_name, "%d", fd); + *pid = current_pid; + closedir(fd_dir); + closedir(proc_dir); + return true; + } + } + closedir(fd_dir); + } + + closedir(proc_dir); + + return false; +} + +static int pidfd_open(pid_t pid, unsigned int flags) { + return syscall(__NR_pidfd_open, pid, flags); +} + +static int pidfd_getfd(int pidfd, int targetfd, unsigned int flags) { + return syscall(__NR_pidfd_getfd, pidfd, targetfd, flags); +} + +void thup_parse_tcp_info(struct nlmsghdr *nlh, const char *search_ip, int search_port) { + struct inet_diag_msg *diag_msg = NLMSG_DATA(nlh); + struct rtattr *attr; + int len = nlh->nlmsg_len - NLMSG_LENGTH(sizeof(*diag_msg)); + + for (attr = (struct rtattr *)(diag_msg + 1); RTA_OK(attr, len); attr = RTA_NEXT(attr, len)) { + char src_ip[INET_ADDRSTRLEN]; + + inet_ntop(AF_INET, &(diag_msg->id.idiag_dst), src_ip, INET_ADDRSTRLEN); + + if (strcmp(src_ip, search_ip) == 0 && (search_port==0 || ntohs(diag_msg->id.idiag_dport) == search_port)) { + int pid, fd; + + thup_find_pid_and_fd_by_inode(diag_msg->idiag_inode, &pid, &fd); + + if (pid==0 || fd==0) { + continue; + } + + int pidfd = pidfd_open(pid, 0); + + if (pidfd == -1) { + continue; + } + + int sfd = pidfd_getfd(pidfd, fd, 0); + + if (sfd == -1) { + continue; + } + + shutdown(sfd, SHUT_RDWR); + + close(sfd); + close(pidfd); + } + } +} + +int main(int argc, char *argv[]) { + if (argc != 3) { + fprintf(stderr, "Usage: %s \n", argv[0]); + exit(EXIT_FAILURE); + } + + const char *search_ip = argv[1]; + + int search_port = atoi(argv[2]); + + int sock = socket(AF_NETLINK, SOCK_RAW, NETLINK_INET_DIAG); + + if (sock == -1) { + thup_exit("socket"); + } + + struct { + struct nlmsghdr nlh; + struct inet_diag_req r; + } req; + + memset(&req, 0, sizeof(req)); + req.nlh.nlmsg_len = NLMSG_LENGTH(sizeof(req.r)); + req.nlh.nlmsg_type = TCPDIAG_GETSOCK; + req.nlh.nlmsg_flags = NLM_F_REQUEST | NLM_F_DUMP; + req.r.idiag_family = AF_INET; + req.r.idiag_states = -1; + + if (send(sock, &req, sizeof(req), 0) == -1) { + thup_exit("send"); + } + + bool done = false; + + while (!done) { + char buf[8192]; + int len = recv(sock, buf, sizeof(buf), 0); + + if (len == -1) { + thup_exit("recv"); + } + + for (struct nlmsghdr *nlh = (struct nlmsghdr *)buf; NLMSG_OK(nlh, len); nlh = NLMSG_NEXT(nlh, len)) { + switch (nlh->nlmsg_type) { + case NLMSG_DONE: + done = true; + break; + case NLMSG_ERROR: + fprintf(stderr, "Error in netlink response\n"); + close(sock); + exit(EXIT_FAILURE); + case TCPDIAG_GETSOCK: + thup_parse_tcp_info(nlh, search_ip, search_port); + break; + default: + break; + } + } + } + close(sock); + return 0; +} diff --git a/test/.gitkeep b/test/.gitkeep new file mode 100644 index 0000000..e69de29