├── .github
├── dependabot.yml
└── workflows
│ ├── docker-hub-description.yml
│ ├── on-pull-request.yml
│ ├── on-push.yml
│ └── on-release.yml
├── .gitignore
├── Dockerfile
├── LICENSE
├── README.md
├── client
└── client.go
├── dashboard
├── endlessh.json
└── screenshot.png
├── examples
├── README.md
├── docker-maxmind
│ ├── README.md
│ └── docker-compose.yml
└── docker-simple
│ ├── README.md
│ ├── docker-compose.yml
│ ├── grafana-datasource.yml
│ └── prometheus.yml
├── geoip
├── country.go
└── geoip.go
├── go.mod
├── go.sum
├── main.go
└── metrics
├── metrics.go
└── priority_queue.go
/.github/dependabot.yml:
--------------------------------------------------------------------------------
1 | # To get started with Dependabot version updates, you'll need to specify which
2 | # package ecosystems to update and where the package manifests are located.
3 | # Please see the documentation for all configuration options:
4 | # https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates
5 |
6 | version: 2
7 | updates:
8 | - package-ecosystem: "gomod"
9 | directory: "/" # Location of package manifests
10 | schedule:
11 | interval: "weekly"
12 | - package-ecosystem: "github-actions"
13 | directory: "/" # Location of package manifests
14 | schedule:
15 | interval: "weekly"
16 | - package-ecosystem: "docker"
17 | directory: "/" # Location of package manifests
18 | schedule:
19 | interval: "weekly"
20 |
--------------------------------------------------------------------------------
/.github/workflows/docker-hub-description.yml:
--------------------------------------------------------------------------------
1 | name: Update Docker Hub description
2 |
3 | on:
4 | release:
5 | types:
6 | - created
7 | workflow_dispatch:
8 |
9 | jobs:
10 | publish:
11 | name: Update Docker Hub description
12 | runs-on: ubuntu-latest
13 | steps:
14 | - name: Checkout Code
15 | uses: actions/checkout@v4
16 | - name: Update Docker Hub description
17 | uses: peter-evans/dockerhub-description@v4
18 | with:
19 | username: ${{ secrets.DOCKERHUB_USERNAME }}
20 | password: ${{ secrets.DOCKERHUB_PASSWORD }}
21 | repository: ${{ github.repository }}
22 | short-description: ${{ github.event.repository.description }}
--------------------------------------------------------------------------------
/.github/workflows/on-pull-request.yml:
--------------------------------------------------------------------------------
1 | name: On pull request
2 |
3 | on:
4 | pull_request:
5 | branches:
6 | - 'main'
7 | paths-ignore:
8 | - 'dashboard/*'
9 | - 'examples/*'
10 | - 'README.md'
11 | - 'LICENSE'
12 | workflow_dispatch:
13 |
14 | env:
15 | PLATFORMS: "linux/amd64,linux/arm64,linux/arm/v7"
16 |
17 | jobs:
18 | build_container_image:
19 | name: Build Docker image
20 | runs-on: ubuntu-latest
21 | steps:
22 | - name: Checkout code
23 | uses: actions/checkout@v4
24 | - name: Set up QEMU
25 | uses: docker/setup-qemu-action@v3
26 | - name: Set up Docker Buildx
27 | uses: docker/setup-buildx-action@v3.10.0
28 | - name: Docker meta
29 | id: meta
30 | uses: docker/metadata-action@v5
31 | with:
32 | images: |
33 | ghcr.io/${{ github.repository }}-development
34 | tags: |
35 | type=raw,value=dev-{{date 'X'}}
36 | type=raw,value=latest
37 | type=ref,event=branch
38 | type=edge,branch=main
39 | - name: Build
40 | uses: docker/build-push-action@v6.15.0
41 | with:
42 | platforms: ${{ env.PLATFORMS }}
43 | push: false
44 | tags: ${{ steps.meta.outputs.tags }}
45 | labels: ${{ steps.meta.outputs.labels }}
46 | provenance: false
47 |
48 |
49 |
--------------------------------------------------------------------------------
/.github/workflows/on-push.yml:
--------------------------------------------------------------------------------
1 | name: On push
2 |
3 | on:
4 | push:
5 | branches-ignore:
6 | - 'release'
7 | - 'dependabot/**'
8 | paths-ignore:
9 | - 'dashboard/*'
10 | - 'examples/*'
11 | - 'README.md'
12 | - 'LICENSE'
13 | workflow_dispatch:
14 |
15 | env:
16 | PLATFORMS: "linux/amd64,linux/arm64,linux/arm/v7"
17 |
18 | jobs:
19 | build_and_push:
20 | name: Build and push Docker image
21 | runs-on: ubuntu-latest
22 | if: ${{ github.actor != 'dependabot[bot]' }}
23 | steps:
24 | - name: Checkout code
25 | uses: actions/checkout@v4
26 | - name: Set up QEMU
27 | uses: docker/setup-qemu-action@v3
28 | - name: Set up Docker Buildx
29 | uses: docker/setup-buildx-action@v3.10.0
30 | - name: Login to Docker Hub
31 | uses: docker/login-action@v3.4.0
32 | with:
33 | username: ${{ secrets.DOCKERHUB_USERNAME }}
34 | password: ${{ secrets.DOCKERHUB_PASSWORD }}
35 | - name: Login to GitHub Container Registry
36 | uses: docker/login-action@v3.4.0
37 | with:
38 | registry: ghcr.io
39 | username: ${{ github.repository_owner }}
40 | password: ${{ github.token }}
41 | - name: Docker meta
42 | id: meta
43 | uses: docker/metadata-action@v5
44 | with:
45 | images: |
46 | ${{ github.repository }}-development
47 | ghcr.io/${{ github.repository }}-development
48 | tags: |
49 | type=raw,value=dev-{{date 'X'}}
50 | type=raw,value=latest
51 | type=ref,event=branch
52 | type=edge,branch=main
53 | - name: Build and push ${{ github.repository }}:${{ steps.git.outputs.image_tag }}
54 | uses: docker/build-push-action@v6.15.0
55 | with:
56 | platforms: ${{ env.PLATFORMS }}
57 | push: true
58 | tags: ${{ steps.meta.outputs.tags }}
59 | labels: ${{ steps.meta.outputs.labels }}
60 | provenance: false
61 |
62 |
63 |
--------------------------------------------------------------------------------
/.github/workflows/on-release.yml:
--------------------------------------------------------------------------------
1 | name: On release
2 |
3 | on:
4 | release:
5 | types: # This configuration does not affect the page_build event above
6 | - created
7 | env:
8 | PLATFORMS: "linux/amd64,linux/arm64,linux/arm/v7"
9 |
10 | jobs:
11 | build_and_push:
12 | name: Build and push Docker image
13 | runs-on: ubuntu-latest
14 | steps:
15 | - name: Checkout code
16 | uses: actions/checkout@v4
17 | - name: Set up QEMU
18 | uses: docker/setup-qemu-action@v3
19 | - name: Set up Docker Buildx
20 | uses: docker/setup-buildx-action@v3.10.0
21 | - name: Login to docker hub
22 | uses: docker/login-action@v3.4.0
23 | with:
24 | username: ${{ secrets.DOCKERHUB_USERNAME }}
25 | password: ${{ secrets.DOCKERHUB_PASSWORD }}
26 | - name: Login to GitHub Container Registry
27 | uses: docker/login-action@v3.4.0
28 | with:
29 | registry: ghcr.io
30 | username: ${{ github.repository_owner }}
31 | password: ${{ github.token }}
32 | - name: Docker meta
33 | id: meta
34 | uses: docker/metadata-action@v5
35 | with:
36 | images: |
37 | ${{ github.repository }}
38 | ghcr.io/${{ github.repository }}
39 | tags: |
40 | type=ref,event=branch
41 | type=ref,event=tag
42 | - name: Build and push
43 | uses: docker/build-push-action@v6.15.0
44 | with:
45 | platforms: ${{ env.PLATFORMS }}
46 | push: true
47 | tags: ${{ steps.meta.outputs.tags }}
48 | labels: ${{ steps.meta.outputs.labels }}
49 | provenance: false
50 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | endlessh-go
2 |
--------------------------------------------------------------------------------
/Dockerfile:
--------------------------------------------------------------------------------
1 | FROM golang AS build
2 |
3 | RUN mkdir /endlessh
4 | ADD . /endlessh
5 | WORKDIR /endlessh
6 | RUN go mod tidy
7 | RUN CGO_ENABLED=0 go build -o endlessh .
8 |
9 | FROM gcr.io/distroless/base
10 |
11 | LABEL org.opencontainers.image.title=endlessh-go
12 | LABEL org.opencontainers.image.description="Endlessh: an SSH tarpit"
13 | LABEL org.opencontainers.image.vendor="Shizun Ge"
14 | LABEL org.opencontainers.image.licenses=GPLv3
15 |
16 | COPY --from=build /endlessh/endlessh /endlessh
17 | EXPOSE 2222 2112
18 | USER nobody
19 | ENTRYPOINT ["/endlessh"]
20 | CMD ["-logtostderr", "-v=1"]
21 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # endlessh-go
2 |
3 | A golang implementation of [endlessh](https://nullprogram.com/blog/2019/03/22/) exporting Prometheus metrics, visualized by a Grafana dashboard.
4 |
5 | 
6 |
7 | ## Introduction
8 |
9 | [Endlessh](https://nullprogram.com/blog/2019/03/22/) is a great idea that not only blocks the brute force SSH attacks, but also wastes attackers time as a kind of counter-attack. Besides trapping the attackers, I also want to visualize the Geolocations and other statistics of the sources of attacks. Unfortunately the wonderful original [C implementation of endlessh](https://github.com/skeeto/endlessh) only provides text based log, but I do not like the solution that writes extra scripts to parse the log outputs, then exports the results to a dashboard, because it would introduce extra layers in my current setup and it would depend on the format of the text log file rather than some structured data. Thus I create this golang implementation of endlessh to export [Prometheus](https://prometheus.io/) metrics and a [Grafana](https://grafana.com/) dashboard to visualize them.
10 |
11 | If you want a dashboard of sources of attacks and do not mind the endlessh server, besides trapping the attackers, does extra things including: translating IP to Geohash, exporting Prometheus metrics, and using more memory (about 10MB), this is the solution for you.
12 |
13 | ## Getting Started
14 |
15 | Clone the repo then build from source:
16 |
17 | ```
18 | go build .
19 | ./endlessh-go &
20 | ```
21 |
22 | Alternatively, you can use the [docker image](https://hub.docker.com/r/shizunge/endlessh-go):
23 |
24 | ```
25 | docker run -d -p 2222:2222 shizunge/endlessh-go -logtostderr -v=1
26 | ```
27 |
28 | It listens to port `2222` by default.
29 |
30 | Then you can try to connect to the endlessh server. Your SSH client should hang there.
31 |
32 | ```
33 | ssh -p 2222 localhost
34 | ```
35 |
36 | If you want log like the [C implementation](https://github.com/skeeto/endlessh), you need to set both CLI arguments `-logtostderr` and `-v=1`, then the log will go to stderr. You can set different log destinations via CLI arguments.
37 |
38 | Also check out [examples](./examples/README.md) for the setup of the full stack.
39 |
40 | ## Usage
41 |
42 | `./endlessh-go --help`
43 |
44 | ```
45 | Usage of ./endlessh-go
46 | -alsologtostderr
47 | log to standard error as well as files
48 | -conn_type string
49 | Connection type. Possible values are tcp, tcp4, tcp6 (default "tcp")
50 | -enable_prometheus
51 | Enable prometheus
52 | -geoip_supplier string
53 | Supplier to obtain Geohash of IPs. Possible values are "off", "ip-api", "max-mind-db" (default "off")
54 | -host string
55 | SSH listening address (default "0.0.0.0")
56 | -interval_ms int
57 | Message millisecond delay (default 1000)
58 | -line_length int
59 | Maximum banner line length (default 32)
60 | -log_backtrace_at value
61 | when logging hits line file:N, emit a stack trace
62 | -log_dir string
63 | If non-empty, write log files in this directory
64 | -log_link string
65 | If non-empty, add symbolic links in this directory to the log files
66 | -logbuflevel int
67 | Buffer log messages logged at this level or lower (-1 means don't buffer; 0 means buffer INFO only; ...). Has limited applicability on non-prod platforms.
68 | -logtostderr
69 | log to standard error instead of files
70 | -max_clients int
71 | Maximum number of clients (default 4096)
72 | -max_mind_db string
73 | Path to the MaxMind DB file.
74 | -port value
75 | SSH listening port. You may provide multiple -port flags to listen to multiple ports. (default "2222")
76 | -prometheus_clean_unseen_seconds int
77 | Remove series if the IP is not seen for the given time. Set to 0 to disable. (default 0)
78 | -prometheus_entry string
79 | Entry point for prometheus (default "metrics")
80 | -prometheus_host string
81 | The address for prometheus (default "0.0.0.0")
82 | -prometheus_port string
83 | The port for prometheus (default "2112")
84 | -stderrthreshold value
85 | logs at or above this threshold go to stderr (default 2)
86 | -v value
87 | log level for V logs
88 | -vmodule value
89 | comma-separated list of pattern=N settings for file-filtered logging
90 | ```
91 |
92 | ## Metrics
93 |
94 | Endlessh-go exports the following Prometheus metrics.
95 |
96 | | Metric | Type | Description |
97 | |--------------------------------------|-------|--------------|
98 | | endlessh_client_open_count_total | count | Total number of clients that tried to connect to this host. |
99 | | endlessh_client_closed_count_total | count | Total number of clients that stopped connecting to this host. |
100 | | endlessh_sent_bytes_total | count | Total bytes sent to clients that tried to connect to this host. |
101 | | endlessh_trapped_time_seconds_total | count | Total seconds clients spent on endlessh. |
102 | | endlessh_client_open_count | count | Number of connections of clients.
Labels:
- `ip`: Remote IP of the client
- `local_port`: Local port the program listens to
- `country`: Country of the IP
- `location`: Country, Region, and City
- `geohash`: Geohash of the location
|
103 | | endlessh_client_trapped_time_seconds | count | Seconds a client spends on endlessh.
Labels:
- `ip`: Remote IP of the client
- `local_port`: Local port the program listens to
|
104 |
105 | The metrics is off by default, you can turn it via the CLI argument `-enable_prometheus`.
106 |
107 | It listens to port `2112` and entry point is `/metrics` by default. The port and entry point can be changed via CLI arguments.
108 |
109 | The endlessh-go server stores the geohash of attackers as a label on `endlessh_client_open_count`, which is also off by default. You can turn it on via the CLI argument `-geoip_supplier`. The endlessh-go uses service from [ip-api](https://ip-api.com/), which may enforce a query rate and limit commercial use. Visit their website for their terms and policies.
110 |
111 | You could also use an offline GeoIP database from [MaxMind](https://www.maxmind.com) by setting `-geoip_supplier` to _max-mind-db_ and `-max_mind_db` to the path of the database file.
112 |
113 | ## Dashboard
114 |
115 | The dashboard requires Grafana 8.2.
116 |
117 | You can import the dashboard from Grafana.com using ID [15156](https://grafana.com/grafana/dashboards/15156)
118 |
119 | The dashboard visualizes data for the selected time range.
120 |
121 | The IP addresses are clickable and link you to the [ARIN](https://www.arin.net/) database.
122 |
123 | ## Contacts
124 |
125 | If you have any problems or questions, please contact me through a [GitHub issue](https://github.com/shizunge/endlessh-go/issues)
126 |
--------------------------------------------------------------------------------
/client/client.go:
--------------------------------------------------------------------------------
1 | // Copyright (C) 2021-2024 Shizun Ge
2 | //
3 | // This program is free software: you can redistribute it and/or modify
4 | // it under the terms of the GNU General Public License as published by
5 | // the Free Software Foundation, either version 3 of the License, or
6 | // (at your option) any later version.
7 | //
8 | // This program is distributed in the hope that it will be useful,
9 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 | // GNU General Public License for more details.
12 | //
13 | // You should have received a copy of the GNU General Public License
14 | // along with this program. If not, see .
15 | //
16 |
17 | package client
18 |
19 | import (
20 | "math/rand"
21 | "net"
22 | "strconv"
23 | "sync/atomic"
24 | "time"
25 |
26 | "github.com/golang/glog"
27 | )
28 |
29 | var (
30 | numCurrentClients int64
31 | letterBytes = []byte(" abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890!@#$%^&*()-=_+[]{}|;:',./<>?")
32 | )
33 |
34 | func randStringBytes(n int64) []byte {
35 | b := make([]byte, n+1)
36 | for i := range b {
37 | b[i] = letterBytes[rand.Intn(len(letterBytes))]
38 | }
39 | b[n] = '\n'
40 | return b
41 | }
42 |
43 | type Client struct {
44 | conn net.Conn
45 | next time.Time
46 | start time.Time
47 | last time.Time
48 | interval time.Duration
49 | bytesSent int
50 | }
51 |
52 | func NewClient(conn net.Conn, interval time.Duration, maxClients int64) *Client {
53 | for numCurrentClients >= maxClients {
54 | time.Sleep(interval)
55 | }
56 | atomic.AddInt64(&numCurrentClients, 1)
57 | addr := conn.RemoteAddr().(*net.TCPAddr)
58 | glog.V(1).Infof("ACCEPT host=%v port=%v n=%v/%v\n", addr.IP, addr.Port, numCurrentClients, maxClients)
59 | return &Client{
60 | conn: conn,
61 | next: time.Now().Add(interval),
62 | start: time.Now(),
63 | last: time.Now(),
64 | interval: interval,
65 | bytesSent: 0,
66 | }
67 | }
68 |
69 | func (c *Client) RemoteIpAddr() string {
70 | return c.conn.RemoteAddr().(*net.TCPAddr).IP.String()
71 | }
72 |
73 | func (c *Client) LocalPort() string {
74 | return strconv.Itoa(c.conn.LocalAddr().(*net.TCPAddr).Port)
75 | }
76 |
77 | func (c *Client) Send(bannerMaxLength int64) (int, error) {
78 | if time.Now().Before(c.next) {
79 | time.Sleep(c.next.Sub(time.Now()))
80 | }
81 | c.next = time.Now().Add(c.interval)
82 | length := rand.Int63n(bannerMaxLength)
83 | bytesSent, err := c.conn.Write(randStringBytes(length))
84 | if err != nil {
85 | return 0, err
86 | }
87 | c.bytesSent += bytesSent
88 | return bytesSent, nil
89 | }
90 |
91 | func (c *Client) MillisecondsSinceLast() int64 {
92 | millisecondsSpent := time.Now().Sub(c.last).Milliseconds()
93 | c.last = time.Now()
94 | return millisecondsSpent
95 | }
96 |
97 | func (c *Client) Close() {
98 | addr := c.conn.RemoteAddr().(*net.TCPAddr)
99 | glog.V(1).Infof("CLOSE host=%v port=%v time=%v bytes=%v\n", addr.IP, addr.Port, time.Now().Sub(c.start).Seconds(), c.bytesSent)
100 | c.conn.Close()
101 | atomic.AddInt64(&numCurrentClients, -1)
102 | }
103 |
--------------------------------------------------------------------------------
/dashboard/endlessh.json:
--------------------------------------------------------------------------------
1 | {
2 | "__inputs": [
3 | {
4 | "name": "DS_PROMETHEUS",
5 | "label": "Prometheus",
6 | "description": "",
7 | "type": "datasource",
8 | "pluginId": "prometheus",
9 | "pluginName": "Prometheus"
10 | }
11 | ],
12 | "__elements": {},
13 | "__requires": [
14 | {
15 | "type": "panel",
16 | "id": "geomap",
17 | "name": "Geomap",
18 | "version": ""
19 | },
20 | {
21 | "type": "grafana",
22 | "id": "grafana",
23 | "name": "Grafana",
24 | "version": "10.3.0-64399"
25 | },
26 | {
27 | "type": "panel",
28 | "id": "piechart",
29 | "name": "Pie chart",
30 | "version": ""
31 | },
32 | {
33 | "type": "datasource",
34 | "id": "prometheus",
35 | "name": "Prometheus",
36 | "version": "1.0.0"
37 | },
38 | {
39 | "type": "panel",
40 | "id": "stat",
41 | "name": "Stat",
42 | "version": ""
43 | },
44 | {
45 | "type": "panel",
46 | "id": "table",
47 | "name": "Table",
48 | "version": ""
49 | },
50 | {
51 | "type": "panel",
52 | "id": "timeseries",
53 | "name": "Time series",
54 | "version": ""
55 | }
56 | ],
57 | "annotations": {
58 | "list": [
59 | {
60 | "builtIn": 1,
61 | "datasource": {
62 | "type": "datasource",
63 | "uid": "grafana"
64 | },
65 | "enable": true,
66 | "hide": true,
67 | "iconColor": "rgba(0, 211, 255, 1)",
68 | "name": "Annotations & Alerts",
69 | "target": {
70 | "limit": 100,
71 | "matchAny": false,
72 | "tags": [],
73 | "type": "dashboard"
74 | },
75 | "type": "dashboard"
76 | }
77 | ]
78 | },
79 | "description": "Dashboard for endlessh (Fix current connections)",
80 | "editable": false,
81 | "fiscalYearStartMonth": 0,
82 | "gnetId": 15156,
83 | "graphTooltip": 0,
84 | "id": null,
85 | "links": [
86 | {
87 | "asDropdown": false,
88 | "icon": "external link",
89 | "includeVars": false,
90 | "keepTime": false,
91 | "tags": [],
92 | "targetBlank": true,
93 | "title": "GitHub",
94 | "tooltip": "GitHub",
95 | "type": "link",
96 | "url": "https://github.com/shizunge/endlessh-go"
97 | },
98 | {
99 | "asDropdown": false,
100 | "icon": "external link",
101 | "includeVars": false,
102 | "keepTime": false,
103 | "tags": [],
104 | "targetBlank": true,
105 | "title": "Grafana",
106 | "tooltip": "Grafana Dashboard",
107 | "type": "link",
108 | "url": "https://grafana.com/grafana/dashboards/15156"
109 | }
110 | ],
111 | "liveNow": false,
112 | "panels": [
113 | {
114 | "datasource": {
115 | "type": "prometheus",
116 | "uid": "${DS_PROMETHEUS}"
117 | },
118 | "fieldConfig": {
119 | "defaults": {
120 | "color": {
121 | "mode": "thresholds"
122 | },
123 | "mappings": [],
124 | "thresholds": {
125 | "mode": "absolute",
126 | "steps": [
127 | {
128 | "color": "green",
129 | "value": null
130 | }
131 | ]
132 | }
133 | },
134 | "overrides": []
135 | },
136 | "gridPos": {
137 | "h": 3,
138 | "w": 4,
139 | "x": 0,
140 | "y": 0
141 | },
142 | "id": 36,
143 | "interval": "1m",
144 | "maxDataPoints": 1440,
145 | "options": {
146 | "colorMode": "value",
147 | "graphMode": "none",
148 | "justifyMode": "auto",
149 | "orientation": "auto",
150 | "reduceOptions": {
151 | "calcs": [
152 | "lastNotNull"
153 | ],
154 | "fields": "/^Total number connections that endlessh trapped$/",
155 | "values": false
156 | },
157 | "text": {},
158 | "textMode": "auto",
159 | "wideLayout": true
160 | },
161 | "pluginVersion": "10.3.0-64399",
162 | "targets": [
163 | {
164 | "datasource": {
165 | "type": "prometheus",
166 | "uid": "${DS_PROMETHEUS}"
167 | },
168 | "editorMode": "code",
169 | "expr": "(endlessh_client_open_count{instance=~\"$host\",job=~\"$job\"} - endlessh_client_open_count{instance=~\"$host\",job=~\"$job\"} offset $__interval) > 0 or (endlessh_client_open_count{instance=~\"$host\",job=~\"$job\"}!=0 unless endlessh_client_open_count{instance=~\"$host\",job=~\"$job\"} offset $__interval)",
170 | "format": "table",
171 | "instant": false,
172 | "legendFormat": "Seen {{ip}}",
173 | "range": true,
174 | "refId": "Seen"
175 | },
176 | {
177 | "datasource": {
178 | "type": "prometheus",
179 | "uid": "${DS_PROMETHEUS}"
180 | },
181 | "editorMode": "code",
182 | "expr": "(endlessh_client_trapped_time_seconds{instance=~\"$host\",job=~\"$job\"} - endlessh_client_trapped_time_seconds{instance=~\"$host\",job=~\"$job\"} offset $__interval) > 0 or (endlessh_client_trapped_time_seconds{instance=~\"$host\",job=~\"$job\"}!=0 unless endlessh_client_trapped_time_seconds{instance=~\"$host\",job=~\"$job\"} offset $__interval)",
183 | "format": "table",
184 | "hide": false,
185 | "instant": false,
186 | "legendFormat": "Trapped {{ip}}",
187 | "range": true,
188 | "refId": "Trapped"
189 | }
190 | ],
191 | "title": "Connections",
192 | "transformations": [
193 | {
194 | "id": "filterByRefId",
195 | "options": {
196 | "include": "Seen"
197 | }
198 | },
199 | {
200 | "id": "filterByValue",
201 | "options": {
202 | "filters": [
203 | {
204 | "config": {
205 | "id": "greaterOrEqual",
206 | "options": {
207 | "value": 0
208 | }
209 | },
210 | "fieldName": "Value #Seen"
211 | }
212 | ],
213 | "match": "any",
214 | "type": "include"
215 | }
216 | },
217 | {
218 | "id": "groupBy",
219 | "options": {
220 | "fields": {
221 | "Value #Seen": {
222 | "aggregations": [
223 | "sum"
224 | ],
225 | "operation": "aggregate"
226 | },
227 | "ip": {
228 | "aggregations": [],
229 | "operation": "groupby"
230 | }
231 | }
232 | }
233 | },
234 | {
235 | "id": "reduce",
236 | "options": {
237 | "includeTimeField": false,
238 | "labelsToFields": false,
239 | "mode": "reduceFields",
240 | "reducers": [
241 | "sum"
242 | ]
243 | }
244 | },
245 | {
246 | "id": "organize",
247 | "options": {
248 | "excludeByName": {},
249 | "indexByName": {},
250 | "renameByName": {
251 | "Value #Seen (sum)": "Total number connections that endlessh trapped"
252 | }
253 | }
254 | }
255 | ],
256 | "type": "stat"
257 | },
258 | {
259 | "datasource": {
260 | "type": "datasource",
261 | "uid": "-- Dashboard --"
262 | },
263 | "fieldConfig": {
264 | "defaults": {
265 | "color": {
266 | "mode": "thresholds"
267 | },
268 | "mappings": [],
269 | "thresholds": {
270 | "mode": "absolute",
271 | "steps": [
272 | {
273 | "color": "green",
274 | "value": null
275 | }
276 | ]
277 | },
278 | "unit": "s"
279 | },
280 | "overrides": []
281 | },
282 | "gridPos": {
283 | "h": 3,
284 | "w": 4,
285 | "x": 4,
286 | "y": 0
287 | },
288 | "id": 42,
289 | "options": {
290 | "colorMode": "value",
291 | "graphMode": "none",
292 | "justifyMode": "auto",
293 | "orientation": "auto",
294 | "reduceOptions": {
295 | "calcs": [
296 | "lastNotNull"
297 | ],
298 | "fields": "/^Time spent on endlessh$/",
299 | "values": false
300 | },
301 | "text": {},
302 | "textMode": "auto",
303 | "wideLayout": true
304 | },
305 | "pluginVersion": "10.3.0-64399",
306 | "targets": [
307 | {
308 | "datasource": {
309 | "type": "datasource",
310 | "uid": "-- Dashboard --"
311 | },
312 | "panelId": 36,
313 | "refId": "A"
314 | }
315 | ],
316 | "title": "Trapped Time",
317 | "transformations": [
318 | {
319 | "id": "filterByRefId",
320 | "options": {
321 | "include": "Trapped"
322 | }
323 | },
324 | {
325 | "id": "filterByValue",
326 | "options": {
327 | "filters": [
328 | {
329 | "config": {
330 | "id": "greaterOrEqual",
331 | "options": {
332 | "value": 0
333 | }
334 | },
335 | "fieldName": "Value #Trapped"
336 | }
337 | ],
338 | "match": "all",
339 | "type": "include"
340 | }
341 | },
342 | {
343 | "id": "groupBy",
344 | "options": {
345 | "fields": {
346 | "Value #Trapped": {
347 | "aggregations": [
348 | "sum"
349 | ],
350 | "operation": "aggregate"
351 | },
352 | "ip": {
353 | "aggregations": [],
354 | "operation": "groupby"
355 | }
356 | }
357 | }
358 | },
359 | {
360 | "id": "reduce",
361 | "options": {
362 | "includeTimeField": false,
363 | "labelsToFields": false,
364 | "mode": "reduceFields",
365 | "reducers": [
366 | "sum"
367 | ]
368 | }
369 | },
370 | {
371 | "id": "organize",
372 | "options": {
373 | "excludeByName": {},
374 | "indexByName": {},
375 | "renameByName": {
376 | "Total": "Seconds spent on endlessh",
377 | "Value #Trapped (sum)": "Time spent on endlessh"
378 | }
379 | }
380 | }
381 | ],
382 | "type": "stat"
383 | },
384 | {
385 | "datasource": {
386 | "type": "prometheus",
387 | "uid": "${DS_PROMETHEUS}"
388 | },
389 | "fieldConfig": {
390 | "defaults": {
391 | "color": {
392 | "mode": "thresholds"
393 | },
394 | "mappings": [],
395 | "thresholds": {
396 | "mode": "absolute",
397 | "steps": [
398 | {
399 | "color": "green",
400 | "value": null
401 | }
402 | ]
403 | },
404 | "unit": "bytes"
405 | },
406 | "overrides": []
407 | },
408 | "gridPos": {
409 | "h": 3,
410 | "w": 4,
411 | "x": 8,
412 | "y": 0
413 | },
414 | "id": 18,
415 | "options": {
416 | "colorMode": "value",
417 | "graphMode": "none",
418 | "justifyMode": "auto",
419 | "orientation": "auto",
420 | "reduceOptions": {
421 | "calcs": [
422 | "lastNotNull"
423 | ],
424 | "fields": "",
425 | "values": false
426 | },
427 | "text": {},
428 | "textMode": "auto",
429 | "wideLayout": true
430 | },
431 | "pluginVersion": "10.3.0-64399",
432 | "targets": [
433 | {
434 | "datasource": {
435 | "type": "prometheus",
436 | "uid": "${DS_PROMETHEUS}"
437 | },
438 | "exemplar": true,
439 | "expr": "sum(increase(endlessh_sent_bytes_total{instance=~\"$host\",job=~\"$job\"}[$__range]))",
440 | "hide": false,
441 | "interval": "",
442 | "legendFormat": "Bytes sent by endlessh",
443 | "refId": "sent_bytes"
444 | }
445 | ],
446 | "title": "Sent Bytes",
447 | "type": "stat"
448 | },
449 | {
450 | "datasource": {
451 | "type": "datasource",
452 | "uid": "-- Dashboard --"
453 | },
454 | "fieldConfig": {
455 | "defaults": {
456 | "color": {
457 | "mode": "thresholds"
458 | },
459 | "mappings": [],
460 | "thresholds": {
461 | "mode": "absolute",
462 | "steps": [
463 | {
464 | "color": "green",
465 | "value": null
466 | }
467 | ]
468 | }
469 | },
470 | "overrides": []
471 | },
472 | "gridPos": {
473 | "h": 3,
474 | "w": 4,
475 | "x": 12,
476 | "y": 0
477 | },
478 | "id": 38,
479 | "options": {
480 | "colorMode": "value",
481 | "graphMode": "none",
482 | "justifyMode": "auto",
483 | "orientation": "auto",
484 | "reduceOptions": {
485 | "calcs": [
486 | "lastNotNull"
487 | ],
488 | "fields": "/^Unique IPs connected$/",
489 | "values": false
490 | },
491 | "text": {},
492 | "textMode": "auto",
493 | "wideLayout": true
494 | },
495 | "pluginVersion": "10.3.0-64399",
496 | "targets": [
497 | {
498 | "datasource": {
499 | "type": "datasource",
500 | "uid": "-- Dashboard --"
501 | },
502 | "panelId": 36,
503 | "refId": "A"
504 | }
505 | ],
506 | "title": "Unique IPs",
507 | "transformations": [
508 | {
509 | "id": "filterByRefId",
510 | "options": {
511 | "include": "Seen"
512 | }
513 | },
514 | {
515 | "id": "groupBy",
516 | "options": {
517 | "fields": {
518 | "Value #Seen": {
519 | "aggregations": [
520 | "sum"
521 | ],
522 | "operation": "aggregate"
523 | },
524 | "ip": {
525 | "aggregations": [],
526 | "operation": "groupby"
527 | }
528 | }
529 | }
530 | },
531 | {
532 | "id": "reduce",
533 | "options": {
534 | "includeTimeField": false,
535 | "labelsToFields": false,
536 | "mode": "reduceFields",
537 | "reducers": [
538 | "count"
539 | ]
540 | }
541 | },
542 | {
543 | "id": "organize",
544 | "options": {
545 | "excludeByName": {},
546 | "indexByName": {},
547 | "renameByName": {
548 | "Value #Seen (sum)": "Unique IPs connected",
549 | "ip": ""
550 | }
551 | }
552 | }
553 | ],
554 | "type": "stat"
555 | },
556 | {
557 | "datasource": {
558 | "type": "datasource",
559 | "uid": "-- Dashboard --"
560 | },
561 | "fieldConfig": {
562 | "defaults": {
563 | "color": {
564 | "mode": "thresholds"
565 | },
566 | "links": [
567 | {
568 | "targetBlank": true,
569 | "title": "whois",
570 | "url": "https://search.arin.net/rdap/?query=${__value.text}"
571 | }
572 | ],
573 | "mappings": [],
574 | "thresholds": {
575 | "mode": "absolute",
576 | "steps": [
577 | {
578 | "color": "green",
579 | "value": null
580 | }
581 | ]
582 | }
583 | },
584 | "overrides": []
585 | },
586 | "gridPos": {
587 | "h": 3,
588 | "w": 4,
589 | "x": 16,
590 | "y": 0
591 | },
592 | "id": 45,
593 | "options": {
594 | "colorMode": "value",
595 | "graphMode": "none",
596 | "justifyMode": "auto",
597 | "orientation": "auto",
598 | "reduceOptions": {
599 | "calcs": [
600 | "lastNotNull"
601 | ],
602 | "fields": "/^Client IP of the latest connection$/",
603 | "values": false
604 | },
605 | "text": {},
606 | "textMode": "value",
607 | "wideLayout": true
608 | },
609 | "pluginVersion": "10.3.0-64399",
610 | "targets": [
611 | {
612 | "datasource": {
613 | "type": "datasource",
614 | "uid": "-- Dashboard --"
615 | },
616 | "panelId": 36,
617 | "refId": "A"
618 | }
619 | ],
620 | "title": "Latest Connection",
621 | "transformations": [
622 | {
623 | "id": "filterByRefId",
624 | "options": {
625 | "include": "Seen"
626 | }
627 | },
628 | {
629 | "id": "filterByValue",
630 | "options": {
631 | "filters": [
632 | {
633 | "config": {
634 | "id": "greaterOrEqual",
635 | "options": {
636 | "value": 0
637 | }
638 | },
639 | "fieldName": "Value #Seen"
640 | }
641 | ],
642 | "match": "any",
643 | "type": "include"
644 | }
645 | },
646 | {
647 | "id": "groupBy",
648 | "options": {
649 | "fields": {
650 | "Time": {
651 | "aggregations": [
652 | "lastNotNull"
653 | ],
654 | "operation": "aggregate"
655 | },
656 | "Value #Seen": {
657 | "aggregations": [
658 | "sum"
659 | ],
660 | "operation": "aggregate"
661 | },
662 | "ip": {
663 | "aggregations": [],
664 | "operation": "groupby"
665 | }
666 | }
667 | }
668 | },
669 | {
670 | "id": "sortBy",
671 | "options": {
672 | "fields": {},
673 | "sort": [
674 | {
675 | "field": "Time (lastNotNull)"
676 | }
677 | ]
678 | }
679 | },
680 | {
681 | "id": "organize",
682 | "options": {
683 | "excludeByName": {
684 | "instance": true,
685 | "job": true
686 | },
687 | "indexByName": {},
688 | "renameByName": {
689 | "Time (lastNotNull)": "Time",
690 | "Value #Seen (sum)": "Count",
691 | "ip": "Client IP of the latest connection"
692 | }
693 | }
694 | }
695 | ],
696 | "type": "stat"
697 | },
698 | {
699 | "datasource": {
700 | "type": "prometheus",
701 | "uid": "${DS_PROMETHEUS}"
702 | },
703 | "fieldConfig": {
704 | "defaults": {
705 | "color": {
706 | "mode": "thresholds"
707 | },
708 | "mappings": [],
709 | "min": 0,
710 | "thresholds": {
711 | "mode": "absolute",
712 | "steps": [
713 | {
714 | "color": "green",
715 | "value": null
716 | },
717 | {
718 | "color": "#EAB839",
719 | "value": 10
720 | },
721 | {
722 | "color": "red",
723 | "value": 20
724 | }
725 | ]
726 | },
727 | "unit": "short"
728 | },
729 | "overrides": []
730 | },
731 | "gridPos": {
732 | "h": 3,
733 | "w": 4,
734 | "x": 20,
735 | "y": 0
736 | },
737 | "id": 20,
738 | "options": {
739 | "colorMode": "value",
740 | "graphMode": "none",
741 | "justifyMode": "auto",
742 | "orientation": "auto",
743 | "reduceOptions": {
744 | "calcs": [
745 | "lastNotNull"
746 | ],
747 | "fields": "",
748 | "values": false
749 | },
750 | "text": {},
751 | "textMode": "auto",
752 | "wideLayout": true
753 | },
754 | "pluginVersion": "10.3.0-64399",
755 | "targets": [
756 | {
757 | "datasource": {
758 | "type": "prometheus",
759 | "uid": "${DS_PROMETHEUS}"
760 | },
761 | "exemplar": true,
762 | "expr": "sum((endlessh_client_open_count_total{instance=~\"$host\",job=~\"$job\"}) - (endlessh_client_closed_count_total{instance=~\"$host\",job=~\"$job\"} or endlessh_client_open_count_total{instance=~\"$host\",job=~\"$job\"} * 0))",
763 | "instant": false,
764 | "interval": "",
765 | "legendFormat": "Open Connections",
766 | "refId": "current_open"
767 | }
768 | ],
769 | "title": "Current Connections",
770 | "type": "stat"
771 | },
772 | {
773 | "datasource": {
774 | "type": "datasource",
775 | "uid": "-- Dashboard --"
776 | },
777 | "fieldConfig": {
778 | "defaults": {
779 | "color": {
780 | "mode": "palette-classic"
781 | },
782 | "custom": {
783 | "axisBorderShow": false,
784 | "axisCenteredZero": false,
785 | "axisColorMode": "text",
786 | "axisLabel": "",
787 | "axisPlacement": "auto",
788 | "barAlignment": 0,
789 | "drawStyle": "line",
790 | "fillOpacity": 0,
791 | "gradientMode": "none",
792 | "hideFrom": {
793 | "legend": false,
794 | "tooltip": false,
795 | "viz": false
796 | },
797 | "insertNulls": false,
798 | "lineInterpolation": "stepAfter",
799 | "lineWidth": 1,
800 | "pointSize": 5,
801 | "scaleDistribution": {
802 | "type": "linear"
803 | },
804 | "showPoints": "auto",
805 | "spanNulls": false,
806 | "stacking": {
807 | "group": "A",
808 | "mode": "none"
809 | },
810 | "thresholdsStyle": {
811 | "mode": "off"
812 | }
813 | },
814 | "mappings": [],
815 | "min": -0.01,
816 | "thresholds": {
817 | "mode": "absolute",
818 | "steps": [
819 | {
820 | "color": "green",
821 | "value": null
822 | }
823 | ]
824 | }
825 | },
826 | "overrides": []
827 | },
828 | "gridPos": {
829 | "h": 4,
830 | "w": 12,
831 | "x": 0,
832 | "y": 3
833 | },
834 | "id": 30,
835 | "options": {
836 | "legend": {
837 | "calcs": [],
838 | "displayMode": "list",
839 | "placement": "bottom",
840 | "showLegend": false
841 | },
842 | "tooltip": {
843 | "mode": "single",
844 | "sort": "none"
845 | }
846 | },
847 | "targets": [
848 | {
849 | "datasource": {
850 | "type": "datasource",
851 | "uid": "-- Dashboard --"
852 | },
853 | "panelId": 20,
854 | "refId": "A"
855 | }
856 | ],
857 | "title": "Concurrent Connections",
858 | "type": "timeseries"
859 | },
860 | {
861 | "datasource": {
862 | "type": "datasource",
863 | "uid": "-- Dashboard --"
864 | },
865 | "fieldConfig": {
866 | "defaults": {
867 | "color": {
868 | "mode": "palette-classic"
869 | },
870 | "custom": {
871 | "hideFrom": {
872 | "legend": false,
873 | "tooltip": false,
874 | "viz": false
875 | }
876 | },
877 | "mappings": []
878 | },
879 | "overrides": []
880 | },
881 | "gridPos": {
882 | "h": 8,
883 | "w": 12,
884 | "x": 12,
885 | "y": 3
886 | },
887 | "id": 32,
888 | "options": {
889 | "displayLabels": [],
890 | "legend": {
891 | "displayMode": "table",
892 | "placement": "right",
893 | "showLegend": true,
894 | "values": [
895 | "value",
896 | "percent"
897 | ]
898 | },
899 | "pieType": "pie",
900 | "reduceOptions": {
901 | "calcs": [
902 | "lastNotNull"
903 | ],
904 | "fields": "",
905 | "values": false
906 | },
907 | "tooltip": {
908 | "mode": "single",
909 | "sort": "none"
910 | }
911 | },
912 | "targets": [
913 | {
914 | "datasource": {
915 | "type": "datasource",
916 | "uid": "-- Dashboard --"
917 | },
918 | "panelId": 36,
919 | "refId": "A"
920 | }
921 | ],
922 | "title": "Connections by country",
923 | "transformations": [
924 | {
925 | "id": "filterByRefId",
926 | "options": {
927 | "include": "Seen"
928 | }
929 | },
930 | {
931 | "id": "filterByValue",
932 | "options": {
933 | "filters": [
934 | {
935 | "config": {
936 | "id": "greaterOrEqual",
937 | "options": {
938 | "value": 0
939 | }
940 | },
941 | "fieldName": "Value #Seen"
942 | }
943 | ],
944 | "match": "any",
945 | "type": "include"
946 | }
947 | },
948 | {
949 | "id": "groupBy",
950 | "options": {
951 | "fields": {
952 | "Value #Seen": {
953 | "aggregations": [
954 | "sum"
955 | ],
956 | "operation": "aggregate"
957 | },
958 | "country": {
959 | "aggregations": [
960 | "last"
961 | ],
962 | "operation": "aggregate"
963 | },
964 | "ip": {
965 | "aggregations": [],
966 | "operation": "groupby"
967 | }
968 | }
969 | }
970 | },
971 | {
972 | "id": "groupBy",
973 | "options": {
974 | "fields": {
975 | "Value #Seen (sum)": {
976 | "aggregations": [
977 | "sum"
978 | ],
979 | "operation": "aggregate"
980 | },
981 | "country (last)": {
982 | "aggregations": [],
983 | "operation": "groupby"
984 | }
985 | }
986 | }
987 | },
988 | {
989 | "id": "rowsToFields",
990 | "options": {}
991 | }
992 | ],
993 | "type": "piechart"
994 | },
995 | {
996 | "datasource": {
997 | "type": "datasource",
998 | "uid": "-- Dashboard --"
999 | },
1000 | "fieldConfig": {
1001 | "defaults": {
1002 | "color": {
1003 | "mode": "continuous-GrYlRd"
1004 | },
1005 | "custom": {
1006 | "hideFrom": {
1007 | "legend": false,
1008 | "tooltip": false,
1009 | "viz": false
1010 | }
1011 | },
1012 | "mappings": [],
1013 | "thresholds": {
1014 | "mode": "absolute",
1015 | "steps": [
1016 | {
1017 | "color": "#96D98D",
1018 | "value": null
1019 | }
1020 | ]
1021 | }
1022 | },
1023 | "overrides": []
1024 | },
1025 | "gridPos": {
1026 | "h": 12,
1027 | "w": 12,
1028 | "x": 0,
1029 | "y": 7
1030 | },
1031 | "id": 48,
1032 | "links": [],
1033 | "options": {
1034 | "basemap": {
1035 | "config": {},
1036 | "name": "Layer 0",
1037 | "type": "default"
1038 | },
1039 | "controls": {
1040 | "mouseWheelZoom": false,
1041 | "showAttribution": false,
1042 | "showDebug": false,
1043 | "showMeasure": false,
1044 | "showScale": false,
1045 | "showZoom": true
1046 | },
1047 | "layers": [
1048 | {
1049 | "config": {
1050 | "color": {
1051 | "field": "Connections",
1052 | "fixed": "dark-green"
1053 | },
1054 | "fillOpacity": 0.4,
1055 | "shape": "circle",
1056 | "showLegend": false,
1057 | "size": {
1058 | "field": "Connections",
1059 | "fixed": 5,
1060 | "max": 10,
1061 | "min": 2
1062 | },
1063 | "style": {
1064 | "color": {
1065 | "field": "Connections",
1066 | "fixed": "dark-green"
1067 | },
1068 | "size": {
1069 | "field": "Connections",
1070 | "fixed": 5,
1071 | "max": 9,
1072 | "min": 2
1073 | },
1074 | "text": {
1075 | "field": "location (lastNotNull) (lastNotNull)",
1076 | "fixed": "",
1077 | "mode": "fixed"
1078 | }
1079 | }
1080 | },
1081 | "location": {
1082 | "geohash": "Geohash",
1083 | "mode": "geohash"
1084 | },
1085 | "name": "Layer 1",
1086 | "type": "markers"
1087 | }
1088 | ],
1089 | "tooltip": {
1090 | "mode": "details"
1091 | },
1092 | "view": {
1093 | "allLayers": true,
1094 | "id": "zero",
1095 | "lat": 0,
1096 | "lon": 0,
1097 | "zoom": 1
1098 | }
1099 | },
1100 | "pluginVersion": "10.3.0-64399",
1101 | "targets": [
1102 | {
1103 | "datasource": {
1104 | "type": "datasource",
1105 | "uid": "-- Dashboard --"
1106 | },
1107 | "panelId": 36,
1108 | "refId": "A"
1109 | }
1110 | ],
1111 | "title": "Locations",
1112 | "transformations": [
1113 | {
1114 | "id": "filterByRefId",
1115 | "options": {
1116 | "include": "Seen"
1117 | }
1118 | },
1119 | {
1120 | "id": "filterByValue",
1121 | "options": {
1122 | "filters": [
1123 | {
1124 | "config": {
1125 | "id": "greaterOrEqual",
1126 | "options": {
1127 | "value": 0
1128 | }
1129 | },
1130 | "fieldName": "Value #Seen"
1131 | }
1132 | ],
1133 | "match": "any",
1134 | "type": "include"
1135 | }
1136 | },
1137 | {
1138 | "id": "groupBy",
1139 | "options": {
1140 | "fields": {
1141 | "Value #Seen": {
1142 | "aggregations": [
1143 | "sum"
1144 | ],
1145 | "operation": "aggregate"
1146 | },
1147 | "geohash": {
1148 | "aggregations": [
1149 | "lastNotNull"
1150 | ],
1151 | "operation": "groupby"
1152 | },
1153 | "location": {
1154 | "aggregations": [
1155 | "lastNotNull"
1156 | ],
1157 | "operation": "aggregate"
1158 | }
1159 | }
1160 | }
1161 | },
1162 | {
1163 | "id": "organize",
1164 | "options": {
1165 | "excludeByName": {},
1166 | "indexByName": {
1167 | "Value #geo (lastNotNull) (sum)": 2,
1168 | "geohash (lastNotNull)": 0,
1169 | "location (lastNotNull) (lastNotNull)": 1
1170 | },
1171 | "renameByName": {
1172 | "Value #Seen (sum)": "Connections",
1173 | "geohash": "Geohash",
1174 | "location (lastNotNull)": "Location"
1175 | }
1176 | }
1177 | }
1178 | ],
1179 | "type": "geomap"
1180 | },
1181 | {
1182 | "datasource": {
1183 | "type": "datasource",
1184 | "uid": "-- Dashboard --"
1185 | },
1186 | "fieldConfig": {
1187 | "defaults": {
1188 | "color": {
1189 | "mode": "thresholds"
1190 | },
1191 | "custom": {
1192 | "align": "auto",
1193 | "cellOptions": {
1194 | "type": "auto"
1195 | },
1196 | "filterable": true,
1197 | "inspect": false,
1198 | "minWidth": 50
1199 | },
1200 | "links": [],
1201 | "mappings": [],
1202 | "thresholds": {
1203 | "mode": "absolute",
1204 | "steps": [
1205 | {
1206 | "color": "green",
1207 | "value": null
1208 | }
1209 | ]
1210 | }
1211 | },
1212 | "overrides": [
1213 | {
1214 | "matcher": {
1215 | "id": "byName",
1216 | "options": "Last Connection"
1217 | },
1218 | "properties": [
1219 | {
1220 | "id": "custom.minWidth",
1221 | "value": 150
1222 | },
1223 | {
1224 | "id": "unit",
1225 | "value": "dateTimeAsIso"
1226 | },
1227 | {
1228 | "id": "custom.align",
1229 | "value": "left"
1230 | }
1231 | ]
1232 | },
1233 | {
1234 | "matcher": {
1235 | "id": "byName",
1236 | "options": "IP"
1237 | },
1238 | "properties": [
1239 | {
1240 | "id": "links",
1241 | "value": [
1242 | {
1243 | "targetBlank": true,
1244 | "title": "search ARIN",
1245 | "url": "https://search.arin.net/rdap/?query=${__data.fields.IP}"
1246 | }
1247 | ]
1248 | }
1249 | ]
1250 | },
1251 | {
1252 | "matcher": {
1253 | "id": "byName",
1254 | "options": "Trapped Time"
1255 | },
1256 | "properties": [
1257 | {
1258 | "id": "unit",
1259 | "value": "s"
1260 | }
1261 | ]
1262 | }
1263 | ]
1264 | },
1265 | "gridPos": {
1266 | "h": 8,
1267 | "w": 12,
1268 | "x": 12,
1269 | "y": 11
1270 | },
1271 | "id": 49,
1272 | "options": {
1273 | "cellHeight": "sm",
1274 | "footer": {
1275 | "countRows": false,
1276 | "fields": "",
1277 | "reducer": [
1278 | "sum"
1279 | ],
1280 | "show": false
1281 | },
1282 | "frameIndex": 0,
1283 | "showHeader": true,
1284 | "sortBy": [
1285 | {
1286 | "desc": true,
1287 | "displayName": "Last Connection"
1288 | }
1289 | ]
1290 | },
1291 | "pluginVersion": "10.3.0-64399",
1292 | "targets": [
1293 | {
1294 | "datasource": {
1295 | "type": "datasource",
1296 | "uid": "-- Dashboard --"
1297 | },
1298 | "panelId": 36,
1299 | "refId": "A"
1300 | }
1301 | ],
1302 | "title": "Clients",
1303 | "transformations": [
1304 | {
1305 | "id": "filterByValue",
1306 | "options": {
1307 | "filters": [
1308 | {
1309 | "config": {
1310 | "id": "greaterOrEqual",
1311 | "options": {
1312 | "value": 0
1313 | }
1314 | },
1315 | "fieldName": "Value #Seen"
1316 | },
1317 | {
1318 | "config": {
1319 | "id": "greaterOrEqual",
1320 | "options": {
1321 | "value": 0
1322 | }
1323 | },
1324 | "fieldName": "Value #Trapped"
1325 | }
1326 | ],
1327 | "match": "any",
1328 | "type": "include"
1329 | }
1330 | },
1331 | {
1332 | "id": "merge",
1333 | "options": {}
1334 | },
1335 | {
1336 | "id": "calculateField",
1337 | "options": {
1338 | "alias": "Seen",
1339 | "mode": "reduceRow",
1340 | "reduce": {
1341 | "include": [
1342 | "Value #Seen"
1343 | ],
1344 | "reducer": "sum"
1345 | }
1346 | }
1347 | },
1348 | {
1349 | "id": "calculateField",
1350 | "options": {
1351 | "alias": "Trapped",
1352 | "mode": "reduceRow",
1353 | "reduce": {
1354 | "include": [
1355 | "Value #Trapped"
1356 | ],
1357 | "reducer": "sum"
1358 | }
1359 | }
1360 | },
1361 | {
1362 | "id": "filterByValue",
1363 | "options": {
1364 | "filters": [
1365 | {
1366 | "config": {
1367 | "id": "greaterOrEqual",
1368 | "options": {
1369 | "value": 0
1370 | }
1371 | },
1372 | "fieldName": "Seen"
1373 | },
1374 | {
1375 | "config": {
1376 | "id": "greaterOrEqual",
1377 | "options": {
1378 | "value": 0
1379 | }
1380 | },
1381 | "fieldName": "Trapped"
1382 | }
1383 | ],
1384 | "match": "all",
1385 | "type": "include"
1386 | }
1387 | },
1388 | {
1389 | "id": "groupBy",
1390 | "options": {
1391 | "fields": {
1392 | "Seen": {
1393 | "aggregations": [
1394 | "sum"
1395 | ],
1396 | "operation": "aggregate"
1397 | },
1398 | "Time": {
1399 | "aggregations": [
1400 | "max"
1401 | ],
1402 | "operation": "aggregate"
1403 | },
1404 | "Trapped": {
1405 | "aggregations": [
1406 | "sum"
1407 | ],
1408 | "operation": "aggregate"
1409 | },
1410 | "country": {
1411 | "aggregations": [
1412 | "lastNotNull"
1413 | ],
1414 | "operation": "aggregate"
1415 | },
1416 | "ip": {
1417 | "aggregations": [],
1418 | "operation": "groupby"
1419 | }
1420 | }
1421 | }
1422 | },
1423 | {
1424 | "id": "filterByValue",
1425 | "options": {
1426 | "filters": [
1427 | {
1428 | "config": {
1429 | "id": "isNull",
1430 | "options": {}
1431 | },
1432 | "fieldName": "ip"
1433 | }
1434 | ],
1435 | "match": "any",
1436 | "type": "exclude"
1437 | }
1438 | },
1439 | {
1440 | "id": "organize",
1441 | "options": {
1442 | "excludeByName": {},
1443 | "indexByName": {
1444 | "Seen (sum)": 3,
1445 | "Time (max)": 0,
1446 | "Trapped (sum)": 4,
1447 | "country (lastNotNull)": 2,
1448 | "ip": 1
1449 | },
1450 | "renameByName": {
1451 | "Seen (sum)": "Connections",
1452 | "Time (max)": "Last Connection",
1453 | "Trapped (sum)": "Trapped Time",
1454 | "country (lastNotNull)": "Country",
1455 | "ip": "IP"
1456 | }
1457 | }
1458 | }
1459 | ],
1460 | "type": "table"
1461 | }
1462 | ],
1463 | "refresh": "",
1464 | "schemaVersion": 39,
1465 | "tags": [
1466 | "prometheus"
1467 | ],
1468 | "templating": {
1469 | "list": [
1470 | {
1471 | "allValue": ".*",
1472 | "current": {},
1473 | "datasource": {
1474 | "type": "prometheus",
1475 | "uid": "${DS_PROMETHEUS}"
1476 | },
1477 | "definition": "label_values(endlessh_client_open_count_total, job)",
1478 | "hide": 0,
1479 | "includeAll": true,
1480 | "label": "Job",
1481 | "multi": true,
1482 | "name": "job",
1483 | "options": [],
1484 | "query": {
1485 | "query": "label_values(endlessh_client_open_count_total, job)",
1486 | "refId": "StandardVariableQuery"
1487 | },
1488 | "refresh": 2,
1489 | "regex": "",
1490 | "skipUrlSync": false,
1491 | "sort": 1,
1492 | "type": "query"
1493 | },
1494 | {
1495 | "allValue": ".*",
1496 | "current": {},
1497 | "datasource": {
1498 | "type": "prometheus",
1499 | "uid": "${DS_PROMETHEUS}"
1500 | },
1501 | "definition": "label_values(endlessh_client_open_count_total{job=~\"$job\"}, instance)",
1502 | "hide": 0,
1503 | "includeAll": true,
1504 | "label": "Host",
1505 | "multi": true,
1506 | "name": "host",
1507 | "options": [],
1508 | "query": {
1509 | "query": "label_values(endlessh_client_open_count_total{job=~\"$job\"}, instance)",
1510 | "refId": "StandardVariableQuery"
1511 | },
1512 | "refresh": 2,
1513 | "regex": "",
1514 | "skipUrlSync": false,
1515 | "sort": 1,
1516 | "type": "query"
1517 | }
1518 | ]
1519 | },
1520 | "time": {
1521 | "from": "now-24h",
1522 | "to": "now"
1523 | },
1524 | "timepicker": {},
1525 | "timezone": "",
1526 | "title": "Endlessh",
1527 | "uid": "ATIxYkO7k",
1528 | "version": 12,
1529 | "weekStart": ""
1530 | }
1531 |
--------------------------------------------------------------------------------
/dashboard/screenshot.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/shizunge/endlessh-go/93181ac5b3bd7eff523956ab11f3283fa14a4e4b/dashboard/screenshot.png
--------------------------------------------------------------------------------
/examples/README.md:
--------------------------------------------------------------------------------
1 | # Examples
2 |
3 | > The default container user has uid 65534.
4 |
5 | ## [docker-simple](./docker-simple)
6 |
7 | An example how to setup endlessh-go, Prometheus, and Grafana using [docker compose](https://docs.docker.com/compose/).
8 |
9 | ## [docker-maxmind](./docker-maxmind)
10 |
11 | An example how to setup endlessh-go with the Maxmind GeoIP Database.
12 |
13 | ## FAQ
14 | ### Bind to privileged ports (<1024) in a container
15 |
16 | You need to add capability `NET_BIND_SERVICE` to the program.
17 |
18 | If you are using docker, this can be done via cli argument [`--cap-add`](https://docs.docker.com/engine/reference/run/#runtime-privilege-and-linux-capabilities) or [`cap_add`](https://docs.docker.com/compose/compose-file/compose-file-v3/#cap_add-cap_drop) in the docker compose file.
19 |
--------------------------------------------------------------------------------
/examples/docker-maxmind/README.md:
--------------------------------------------------------------------------------
1 | ## docker compose
2 |
3 | This is an example how to setup endlessh-go with the Maxmind GeoIP Database using [docker compose](https://docs.docker.com/compose/). The reference of the compose file can be found [here](https://docs.docker.com/compose/compose-file/).
4 |
5 | To start the stack, in the _examples_ folder, run:
6 |
7 | ```
8 | docker-compose up -d
9 | ```
10 |
11 | The GeoIP Database will be saved in a mounted volume in: `./geo-data`. And the endlessh-go container will use this database to do the location lookups.
12 |
13 | This example exposes the following ports. Except the SSH port, you should not expose other ports to public without protections (not included in this example) in production.
14 |
15 | - **2222**: The SSH port. You may test endlessh-go by running `ssh -p 2222 localhost`. Your SSH client should hang. View the log of endlessh-go by running `docker logs endlessh`.
16 | - **2112**: The Prometheus metrics exported by endlessh-go. Go to [http://localhost:2112/metrics](http://localhost:2112/metrics) in your web browser to view the metrics.
17 |
--------------------------------------------------------------------------------
/examples/docker-maxmind/docker-compose.yml:
--------------------------------------------------------------------------------
1 | version: "3"
2 | services:
3 |
4 | endlessh:
5 | container_name: endlessh
6 | image: shizunge/endlessh-go:latest
7 | restart: unless-stopped
8 | #user: root
9 | command:
10 | - "-logtostderr"
11 | - "-v=1"
12 | - "-geoip_supplier=max-mind-db"
13 | - "-max_mind_db=/geo-data/GeoLite2-City.mmdb"
14 | networks:
15 | - example_network
16 | ports:
17 | - 2222:2222 # SSH port
18 | - 127.0.0.1:2112:2112 # Prometheus metrics port
19 | volumes:
20 | - ./geo-data/:/geo-data/:ro # geoip data
21 |
22 | geoipupdate:
23 | image: ghcr.io/maxmind/geoipupdate:v5
24 | container_name: geoipupdate
25 | restart: unless-stopped
26 | security_opt: [ "no-new-privileges:true" ]
27 | volumes:
28 | - ./geo-data/:/usr/share/GeoIP/
29 | environment:
30 | - GEOIPUPDATE_EDITION_IDS=GeoLite2-City
31 | - GEOIPUPDATE_FREQUENCY=72
32 | - GEOIPUPDATE_ACCOUNT_ID=xxxxxx
33 | - GEOIPUPDATE_LICENSE_KEY=xxxxxx
34 |
35 | networks:
36 | example_network:
37 |
--------------------------------------------------------------------------------
/examples/docker-simple/README.md:
--------------------------------------------------------------------------------
1 | ## docker compose
2 |
3 | This is an example how to setup endlessh-go, Prometheus, and Grafana using [docker compose](https://docs.docker.com/compose/). The reference of the compose file can be found [here](https://docs.docker.com/compose/compose-file/).
4 |
5 | *prometheus.yml* is used as a [Prometheus configuration](https://prometheus.io/docs/prometheus/latest/configuration/configuration/).
6 |
7 | *grafana-datasource.yml* is used to provision a data source for Grafana to ease the setup, though Grafana data source can also be setup manually.
8 |
9 | To start the stack, in the *examples* folder, run:
10 |
11 | ```
12 | docker-compose up -d
13 | ```
14 |
15 | This example exposes the following ports. Except the SSH port, you should not expose other ports to public without protections (not included in this example) in production.
16 |
17 | * **2222**: The SSH port. You may test endlessh-go by running `ssh -p 2222 localhost`. Your SSH client should hang. View the log of endlessh-go by running `docker logs endlessh`.
18 | * **2112**: The Prometheus metrics exported by endlessh-go. Go to [http://localhost:2112/metrics](http://localhost:2112/metrics) in your web browser to view the metrics.
19 | * **9090**: Prometheus web interface. Go to [http://localhost:9090](http://localhost:9090) in your web browser for Prometheus. You can check whether the target of endlessh-go is up (Click Status, then Targets).
20 | * **3000**: Grafana. Go to [http://localhost:3000](http://localhost:3000) in your web browser for Grafana. Use username *examples* and password *examples* to login.
21 |
22 | In this example, we do not provision a dashboard for Grafana. You need to manually load the endlessh-go dashboard, by either importing it from the Grafana.com using ID [15156](https://grafana.com/grafana/dashboards/15156), or pasting the dashboard JSON text to the text area. See the [Grafana documentation](https://grafana.com/docs/grafana/latest/dashboards/export-import/) about import. Then select *Prometheus* as the data source.
23 |
--------------------------------------------------------------------------------
/examples/docker-simple/docker-compose.yml:
--------------------------------------------------------------------------------
1 | version: '3.5'
2 | services:
3 |
4 | endlessh:
5 | container_name: endlessh
6 | image: shizunge/endlessh-go:latest
7 | restart: always
8 | command:
9 | - -interval_ms=1000
10 | - -logtostderr
11 | - -v=1
12 | - -enable_prometheus
13 | - -geoip_supplier=ip-api
14 | networks:
15 | - example_network
16 | ports:
17 | - 2222:2222 # SSH port
18 | - 127.0.0.1:2112:2112 # Prometheus metrics port
19 |
20 | prometheus:
21 | image: prom/prometheus:latest
22 | container_name: prometheus
23 | restart: always
24 | command:
25 | - --config.file=/etc/prometheus/prometheus.yml
26 | - --storage.tsdb.path=/prometheus
27 | - --storage.tsdb.retention.time=45d
28 | - --web.console.libraries=/usr/share/prometheus/console_libraries
29 | - --web.console.templates=/usr/share/prometheus/consoles
30 | - --web.enable-admin-api
31 | networks:
32 | - example_network
33 | ports:
34 | - 127.0.0.1:9090:9090
35 | volumes:
36 | - ./prometheus.yml:/etc/prometheus/prometheus.yml
37 | - prometheus:/prometheus
38 |
39 | grafana:
40 | image: grafana/grafana:latest
41 | container_name: grafana
42 | restart: always
43 | networks:
44 | - example_network
45 | ports:
46 | - 127.0.0.1:3000:3000
47 | environment:
48 | - GF_SECURITY_ADMIN_USER=examples
49 | - GF_SECURITY_ADMIN_PASSWORD=examples
50 | volumes:
51 | - grafana_var:/var/lib/grafana/
52 | - ./grafana-datasource.yml:/etc/grafana/provisioning/datasources/prometheus.yml
53 |
54 | networks:
55 | example_network:
56 |
57 |
58 | volumes:
59 | prometheus:
60 | grafana_var:
61 |
--------------------------------------------------------------------------------
/examples/docker-simple/grafana-datasource.yml:
--------------------------------------------------------------------------------
1 | apiVersion: 1
2 |
3 | datasources:
4 | - name: Prometheus
5 | type: prometheus
6 | url: http://prometheus:9090
7 |
--------------------------------------------------------------------------------
/examples/docker-simple/prometheus.yml:
--------------------------------------------------------------------------------
1 | scrape_configs:
2 | - job_name: 'endlessh'
3 | scrape_interval: 60s
4 | static_configs:
5 | - targets: ['endlessh:2112']
--------------------------------------------------------------------------------
/geoip/country.go:
--------------------------------------------------------------------------------
1 | // Copyright (C) 2023-2024 Shizun Ge
2 | //
3 | // This program is free software: you can redistribute it and/or modify
4 | // it under the terms of the GNU General Public License as published by
5 | // the Free Software Foundation, either version 3 of the License, or
6 | // (at your option) any later version.
7 | //
8 | // This program is distributed in the hope that it will be useful,
9 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 | // GNU General Public License for more details.
12 | //
13 | // You should have received a copy of the GNU General Public License
14 | // along with this program. If not, see .
15 | //
16 |
17 | package geoip
18 |
19 | // Map country's ISO to their capital's latitude and longitude.
20 | // Country's ISO see https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2
21 | type location struct {
22 | Latitude float64
23 | Longitude float64
24 | }
25 |
26 | var countryToLocation = map[string]location{
27 | "AD": {42.5, 1.5},
28 | "AE": {24.4511, 54.3969},
29 | "AF": {34.5328, 69.1658},
30 | "AG": {17.1211, -61.8447},
31 | "AI": {18.2167, -63.05},
32 | "AL": {41.33, 19.82},
33 | "AM": {40.1814, 44.5144},
34 | "AO": {-8.8383, 13.2344},
35 | "AR": {-34.5997, -58.3819},
36 | "AS": {-14.274, -170.7046},
37 | "AT": {48.2083, 16.3725},
38 | "AU": {-35.2931, 149.1269},
39 | "AW": {12.5186, -70.0358},
40 | "AZ": {40.3667, 49.8352},
41 | "BA": {43.8563, 18.4132},
42 | "BB": {13.0975, -59.6167},
43 | "BD": {23.7289, 90.3944},
44 | "BE": {50.8353, 4.3314},
45 | "BF": {12.3686, -1.5275},
46 | "BG": {42.6979, 23.3217},
47 | "BH": {26.225, 50.5775},
48 | "BI": {-3.3825, 29.3611},
49 | "BJ": {6.402, 2.518},
50 | "BL": {17.8958, -62.8508},
51 | "BM": {32.2942, -64.7839},
52 | "BN": {4.9167, 114.9167},
53 | "BO": {-16.4942, -68.1475},
54 | "BR": {-15.7939, -47.8828},
55 | "BS": {25.0667, -77.3333},
56 | "BT": {27.4833, 89.6333},
57 | "BW": {-24.6569, 25.9086},
58 | "BY": {53.9022, 27.5618},
59 | "BZ": {17.25, -88.7675},
60 | "CA": {45.4247, -75.695},
61 | "CD": {-4.3317, 15.3139},
62 | "CF": {4.3732, 18.5628},
63 | "CG": {-4.2667, 15.2833},
64 | "CH": {46.948, 7.4474},
65 | "CI": {5.3364, -4.0267},
66 | "CK": {-21.207, -159.771},
67 | "CL": {-33.45, -70.6667},
68 | "CM": {3.8578, 11.5181},
69 | "CN": {39.904, 116.4075},
70 | "CO": {4.6126, -74.0705},
71 | "CR": {9.9333, -84.0833},
72 | "CU": {23.1367, -82.3589},
73 | "CV": {14.9177, -23.5092},
74 | "CW": {12.108, -68.935},
75 | "CX": {-10.4167, 105.7167},
76 | "CY": {35.1725, 33.365},
77 | "CZ": {50.0833, 14.4167},
78 | "DE": {52.5167, 13.3833},
79 | "DJ": {11.595, 43.1481},
80 | "DK": {55.6805, 12.5615},
81 | "DM": {15.3, -61.3833},
82 | "DO": {18.4764, -69.8933},
83 | "DZ": {36.7764, 3.0586},
84 | "EC": {-0.22, -78.5125},
85 | "EE": {59.4372, 24.745},
86 | "EG": {30.0444, 31.2358},
87 | "ER": {15.3333, 38.9167},
88 | "ES": {40.4167, -3.7167},
89 | "ET": {9.0272, 38.7369},
90 | "FI": {60.1756, 24.9342},
91 | "FJ": {-18.1333, 178.4333},
92 | "FK": {-51.7, -57.85},
93 | "FM": {6.9178, 158.185},
94 | "FO": {62, -6.7833},
95 | "FR": {48.8566, 2.3522},
96 | "GA": {0.3901, 9.4544},
97 | "GB": {51.5072, -0.1275},
98 | "GD": {12.0444, -61.7417},
99 | "GE": {41.7225, 44.7925},
100 | "GF": {4.933, -52.33},
101 | "GH": {5.6037, -0.187},
102 | "GI": {36.1324, -5.3781},
103 | "GL": {64.175, -51.7333},
104 | "GM": {13.4531, -16.5775},
105 | "GN": {9.538, -13.6773},
106 | "GP": {16.0104, -61.7055},
107 | "GQ": {3.7521, 8.7737},
108 | "GR": {37.9842, 23.7281},
109 | "GS": {-54.2833, -36.5},
110 | "GT": {14.6099, -90.5252},
111 | "GU": {13.4745, 144.7504},
112 | "GW": {11.8592, -15.5956},
113 | "GY": {6.7833, -58.1667},
114 | "HK": {22.3069, 114.1831},
115 | "HN": {14.0942, -87.2067},
116 | "HR": {45.8131, 15.9772},
117 | "HT": {18.5425, -72.3386},
118 | "HU": {47.4983, 19.0408},
119 | "ID": {-6.2146, 106.8451},
120 | "IE": {53.3497, -6.2603},
121 | "IL": {31.7833, 35.2167},
122 | "IM": {54.15, -4.4819},
123 | "IN": {28.6139, 77.209},
124 | "IQ": {33.35, 44.4167},
125 | "IR": {35.7, 51.4167},
126 | "IS": {64.1475, -21.935},
127 | "IT": {41.8931, 12.4828},
128 | "JE": {49.1858, -2.11},
129 | "JM": {17.9714, -76.7931},
130 | "JO": {31.95, 35.9333},
131 | "JP": {35.6839, 139.7744},
132 | "KE": {-1.2864, 36.8172},
133 | "KG": {42.8667, 74.5667},
134 | "KH": {11.5696, 104.921},
135 | "KI": {1.3382, 173.0176},
136 | "KM": {-11.7036, 43.2536},
137 | "KN": {17.2983, -62.7342},
138 | "KP": {39.03, 125.73},
139 | "KR": {37.56, 126.99},
140 | "KW": {29.375, 47.98},
141 | "KY": {19.2866, -81.3744},
142 | "KZ": {51.1333, 71.4333},
143 | "LA": {17.9667, 102.6},
144 | "LB": {33.8869, 35.5131},
145 | "LC": {14.0167, -60.9833},
146 | "LI": {47.1397, 9.5219},
147 | "LK": {6.9, 79.9164},
148 | "LR": {6.3106, -10.8047},
149 | "LS": {-29.31, 27.48},
150 | "LT": {54.6833, 25.2833},
151 | "LU": {49.6106, 6.1328},
152 | "LV": {56.9475, 24.1069},
153 | "LY": {32.8752, 13.1875},
154 | "MA": {26.0928, -10.6089},
155 | "MC": {43.7396, 7.4069},
156 | "MD": {47.0228, 28.8353},
157 | "ME": {42.4397, 19.2661},
158 | "MF": {18.0706, -63.0847},
159 | "MG": {-18.9386, 47.5214},
160 | "MH": {7.0918, 171.3802},
161 | "MK": {41.9833, 21.4333},
162 | "ML": {12.6458, -7.9922},
163 | "MM": {16.795, 96.16},
164 | "MN": {47.9214, 106.9055},
165 | "MP": {15.2137, 145.7546},
166 | "MQ": {14.6104, -61.08},
167 | "MR": {18.0858, -15.9785},
168 | "MS": {16.7928, -62.2106},
169 | "MT": {35.8978, 14.5125},
170 | "MU": {-20.1667, 57.5},
171 | "MV": {4.175, 73.5083},
172 | "MW": {-13.9833, 33.7833},
173 | "MX": {19.4333, -99.1333},
174 | "MY": {3.1478, 101.6953},
175 | "MZ": {-25.9153, 32.5764},
176 | "NA": {-22.57, 17.0836},
177 | "NC": {-22.2625, 166.4443},
178 | "NE": {13.5086, 2.1111},
179 | "NF": {-29.0569, 167.9617},
180 | "NG": {9.0556, 7.4914},
181 | "NI": {12.15, -86.2667},
182 | "NL": {52.08, 4.31},
183 | "NO": {59.9111, 10.7528},
184 | "NP": {27.7167, 85.3667},
185 | "NR": {-0.5477, 166.9209},
186 | "NU": {-19.056, -169.921},
187 | "NZ": {-41.2889, 174.7772},
188 | "OM": {23.6139, 58.5922},
189 | "PA": {9, -79.5},
190 | "PE": {-12.06, -77.0375},
191 | "PF": {-17.5334, -149.5667},
192 | "PG": {-9.4789, 147.1494},
193 | "PH": {14.6, 120.9833},
194 | "PK": {33.6989, 73.0369},
195 | "PL": {52.23, 21.0111},
196 | "PM": {46.7811, -56.1764},
197 | "PN": {-25.0667, -130.0833},
198 | "PR": {18.4037, -66.0636},
199 | "PT": {38.708, -9.139},
200 | "PW": {7.5006, 134.6242},
201 | "PY": {-25.3, -57.6333},
202 | "QA": {25.3, 51.5333},
203 | "RE": {-20.8789, 55.4481},
204 | "RO": {44.4, 26.0833},
205 | "RS": {44.8167, 20.4667},
206 | "RU": {55.7558, 37.6178},
207 | "RW": {-1.9536, 30.0606},
208 | "SA": {24.65, 46.71},
209 | "SB": {-9.4333, 159.95},
210 | "SC": {-4.6236, 55.4544},
211 | "SD": {15.6031, 32.5265},
212 | "SE": {59.3294, 18.0686},
213 | "SG": {1.3, 103.8},
214 | "SH": {-15.9251, -5.7179},
215 | "SI": {46.05, 14.5167},
216 | "SK": {48.1447, 17.1128},
217 | "SL": {8.4833, -13.2331},
218 | "SM": {43.932, 12.4484},
219 | "SN": {14.7319, -17.4572},
220 | "SO": {2.0408, 45.3425},
221 | "SR": {5.8667, -55.1667},
222 | "SS": {4.85, 31.6},
223 | "ST": {0.3333, 6.7333},
224 | "SV": {13.6989, -89.1914},
225 | "SX": {18.0256, -63.0492},
226 | "SY": {33.5131, 36.2919},
227 | "SZ": {-26.3208, 31.1617},
228 | "TC": {21.4664, -71.136},
229 | "TD": {12.11, 15.05},
230 | "TG": {6.1319, 1.2228},
231 | "TH": {13.75, 100.5167},
232 | "TJ": {38.5731, 68.7864},
233 | "TL": {-8.5536, 125.5783},
234 | "TM": {37.95, 58.3833},
235 | "TN": {36.8008, 10.18},
236 | "TO": {-21.1347, -175.2083},
237 | "TR": {39.93, 32.85},
238 | "TT": {10.6667, -61.5167},
239 | "TV": {-8.5243, 179.1942},
240 | "TZ": {-6.8, 39.2833},
241 | "UA": {50.45, 30.5236},
242 | "UG": {0.3136, 32.5811},
243 | "US": {38.9047, -77.0163},
244 | "UY": {-34.8667, -56.1667},
245 | "UZ": {41.3, 69.2667},
246 | "VA": {41.9033, 12.4534},
247 | "VC": {13.1667, -61.2333},
248 | "VE": {10.5, -66.9333},
249 | "VG": {18.4167, -64.6167},
250 | "VI": {18.3419, -64.9332},
251 | "VN": {21.0245, 105.8412},
252 | "VU": {-17.7333, 168.3167},
253 | "WF": {-13.2825, -176.1736},
254 | "WS": {-13.8333, -171.8333},
255 | "XG": {31.5069, 34.456},
256 | "XK": {42.6633, 21.1622},
257 | "XR": {78.2167, 15.6333},
258 | "XW": {31.7764, 35.2269},
259 | "YE": {15.35, 44.2},
260 | "YT": {-12.7871, 45.275},
261 | "ZA": {-25.7464, 28.1881},
262 | "ZM": {-15.4167, 28.2833},
263 | "ZW": {-17.8292, 31.0522},
264 | }
265 |
--------------------------------------------------------------------------------
/geoip/geoip.go:
--------------------------------------------------------------------------------
1 | // Copyright (C) 2021-2024 Shizun Ge
2 | //
3 | // This program is free software: you can redistribute it and/or modify
4 | // it under the terms of the GNU General Public License as published by
5 | // the Free Software Foundation, either version 3 of the License, or
6 | // (at your option) any later version.
7 | //
8 | // This program is distributed in the hope that it will be useful,
9 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 | // GNU General Public License for more details.
12 | //
13 | // You should have received a copy of the GNU General Public License
14 | // along with this program. If not, see .
15 | //
16 |
17 | package geoip
18 |
19 | import (
20 | "encoding/json"
21 | "fmt"
22 | "io/ioutil"
23 | "net"
24 | "net/http"
25 | "strings"
26 |
27 | "github.com/oschwald/geoip2-golang"
28 | "github.com/pierrre/geohash"
29 | )
30 |
31 | type GeoOption struct {
32 | GeoipSupplier string
33 | MaxMindDbFileName string
34 | }
35 |
36 | func composeLocation(country string, region string, city string) string {
37 | var locations []string
38 | for _, s := range []string{country, region, city} {
39 | if strings.TrimSpace(s) != "" {
40 | locations = append(locations, s)
41 | }
42 | }
43 | location := strings.Join(locations, ", ")
44 | if location == "" {
45 | return "Unknown"
46 | }
47 | return location
48 | }
49 |
50 | func composeCountry(country string) string {
51 | if country == "" {
52 | return "Unknown"
53 | }
54 | return country
55 | }
56 |
57 | type ipapi struct {
58 | Status string `json:"status"`
59 | Message string `json:"message"`
60 | Ip string `json:"query"`
61 | CountryCode string `json:"countryCode"`
62 | CountryName string `json:"country"`
63 | RegionCode string `json:"region"`
64 | RegionName string `json:"regionName"`
65 | City string `json:"city"`
66 | Zipcode string `json:"zip"`
67 | Latitude float64 `json:"lat"`
68 | Longitude float64 `json:"lon"`
69 | }
70 |
71 | func geohashAndLocationFromIpapi(ipAddr string) (string, string, string, error) {
72 | var geo ipapi
73 | response, err := http.Get("http://ip-api.com/json/" + ipAddr)
74 | if err != nil {
75 | return "s000", "Unknown", "Unknown", err
76 | }
77 | defer response.Body.Close()
78 |
79 | body, err := ioutil.ReadAll(response.Body)
80 | if err != nil {
81 | return "s000", "Unknown", "Unknown", err
82 | }
83 |
84 | err = json.Unmarshal(body, &geo)
85 | if err != nil {
86 | return "s000", "Unknown", "Unknown", err
87 | }
88 |
89 | if geo.Status != "success" {
90 | return "s000", "Unknown", "Unknown", fmt.Errorf("failed to query %v via ip-api: status: %v, message: %v", ipAddr, geo.Status, geo.Message)
91 | }
92 |
93 | gh := geohash.EncodeAuto(geo.Latitude, geo.Longitude)
94 | country := composeCountry(geo.CountryName)
95 | location := composeLocation(geo.CountryName, geo.RegionName, geo.City)
96 |
97 | return gh, country, location, nil
98 | }
99 |
100 | func geohashAndLocationFromMaxMindDb(ipAddr, maxMindDbFileName string) (string, string, string, error) {
101 | db, err := geoip2.Open(maxMindDbFileName)
102 | if err != nil {
103 | return "s000", "Unknown", "Unknown", err
104 | }
105 | defer db.Close()
106 | // If you are using strings that may be invalid, check that ip is not nil
107 | ip := net.ParseIP(ipAddr)
108 | cityRecord, err := db.City(ip)
109 | if err != nil {
110 | return "s000", "Unknown", "Unknown", err
111 | }
112 | countryName := cityRecord.Country.Names["en"]
113 | cityName := cityRecord.City.Names["en"]
114 | latitude := cityRecord.Location.Latitude
115 | longitude := cityRecord.Location.Longitude
116 | iso := cityRecord.Country.IsoCode
117 | if latitude == 0 && longitude == 0 {
118 | // In case of using Country DB, city is not available.
119 | loc, ok := countryToLocation[iso]
120 | if ok {
121 | latitude = loc.Latitude
122 | longitude = loc.Longitude
123 | } else {
124 | if iso != "" {
125 | // For debugging, adding the iso to the country name.
126 | countryName = countryName + " (" + iso + ")"
127 | }
128 | }
129 | }
130 | gh := geohash.EncodeAuto(latitude, longitude)
131 | country := composeCountry(countryName)
132 | location := composeLocation(countryName, "", cityName)
133 |
134 | return gh, country, location, nil
135 | }
136 |
137 | func GeohashAndLocation(ipAddr string, option GeoOption) (string, string, string, error) {
138 | switch option.GeoipSupplier {
139 | case "off":
140 | return "s000", "Geohash off", "Geohash off", nil
141 | case "ip-api":
142 | return geohashAndLocationFromIpapi(ipAddr)
143 | case "max-mind-db":
144 | return geohashAndLocationFromMaxMindDb(ipAddr, option.MaxMindDbFileName)
145 | default:
146 | return "s000", "Unknown", "Unknown", fmt.Errorf("unknown geoipSupplier %v.", option.GeoipSupplier)
147 | }
148 | }
149 |
--------------------------------------------------------------------------------
/go.mod:
--------------------------------------------------------------------------------
1 | module endlessh-go
2 |
3 | go 1.24.2
4 |
5 | require (
6 | github.com/golang/glog v1.2.4
7 | github.com/oschwald/geoip2-golang v1.11.0
8 | github.com/pierrre/geohash v1.1.2
9 | github.com/prometheus/client_golang v1.22.0
10 | )
11 |
12 | require (
13 | github.com/beorn7/perks v1.0.1 // indirect
14 | github.com/cespare/xxhash/v2 v2.3.0 // indirect
15 | github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
16 | github.com/oschwald/maxminddb-golang v1.13.0 // indirect
17 | github.com/prometheus/client_model v0.6.1 // indirect
18 | github.com/prometheus/common v0.62.0 // indirect
19 | github.com/prometheus/procfs v0.15.1 // indirect
20 | golang.org/x/sys v0.30.0 // indirect
21 | google.golang.org/protobuf v1.36.5 // indirect
22 | )
23 |
--------------------------------------------------------------------------------
/go.sum:
--------------------------------------------------------------------------------
1 | github.com/Codefor/geohash v0.0.0-20140723084247-1b41c28e3a9d h1:iG9B49Q218F/XxXNRM7k/vWf7MKmLIS8AcJV9cGN4nA=
2 | github.com/Codefor/geohash v0.0.0-20140723084247-1b41c28e3a9d/go.mod h1:RVnhzAX71far8Kc3TQeA0k/dcaEKUnTDSOyet/JCmGI=
3 | github.com/TomiHiltunen/geohash-golang v0.0.0-20150112065804-b3e4e625abfb h1:wumPkzt4zaxO4rHPBrjDK8iZMR41C1qs7njNqlacwQg=
4 | github.com/TomiHiltunen/geohash-golang v0.0.0-20150112065804-b3e4e625abfb/go.mod h1:QiYsIBRQEO+Z4Rz7GoI+dsHVneZNONvhczuA+llOZNM=
5 | github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
6 | github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=
7 | github.com/broady/gogeohash v0.0.0-20120525094510-7b2c40d64042 h1:iEdmkrNMLXbM7ecffOAtZJQOQUTE4iMonxrb5opUgE4=
8 | github.com/broady/gogeohash v0.0.0-20120525094510-7b2c40d64042/go.mod h1:f1L9YvXvlt9JTa+A17trQjSMM6bV40f+tHjB+Pi+Fqk=
9 | github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
10 | github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
11 | github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
12 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
13 | github.com/fanixk/geohash v0.0.0-20150324002647-c1f9b5fa157a h1:Fyfh/dsHFrC6nkX7H7+nFdTd1wROlX/FxEIWVpKYf1U=
14 | github.com/fanixk/geohash v0.0.0-20150324002647-c1f9b5fa157a/go.mod h1:UgNw+PTmmGN8rV7RvjvnBMsoTU8ZXXnaT3hYsDTBlgQ=
15 | github.com/golang/glog v1.2.4 h1:CNNw5U8lSiiBk7druxtSHHTsRWcxKoac6kZKm2peBBc=
16 | github.com/golang/glog v1.2.4/go.mod h1:6AhwSGph0fcJtXVM/PEHPqZlFeoLxhs7/t5UDAwmO+w=
17 | github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
18 | github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
19 | github.com/klauspost/compress v1.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo=
20 | github.com/klauspost/compress v1.18.0/go.mod h1:2Pp+KzxcywXVXMr50+X0Q/Lsb43OQHYWRCY2AiWywWQ=
21 | github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc=
22 | github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw=
23 | github.com/mmcloughlin/geohash v0.10.0 h1:9w1HchfDfdeLc+jFEf/04D27KP7E2QmpDu52wPbJWRE=
24 | github.com/mmcloughlin/geohash v0.10.0/go.mod h1:oNZxQo5yWJh0eMQEP/8hwQuVx9Z9tjwFUqcTB1SmG0c=
25 | github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA=
26 | github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ=
27 | github.com/oschwald/geoip2-golang v1.11.0 h1:hNENhCn1Uyzhf9PTmquXENiWS6AlxAEnBII6r8krA3w=
28 | github.com/oschwald/geoip2-golang v1.11.0/go.mod h1:P9zG+54KPEFOliZ29i7SeYZ/GM6tfEL+rgSn03hYuUo=
29 | github.com/oschwald/maxminddb-golang v1.13.0 h1:R8xBorY71s84yO06NgTmQvqvTvlS/bnYZrrWX1MElnU=
30 | github.com/oschwald/maxminddb-golang v1.13.0/go.mod h1:BU0z8BfFVhi1LQaonTwwGQlsHUEu9pWNdMfmq4ztm0o=
31 | github.com/pierrre/assert v0.5.0 h1:l5XuybndelAlp+FfH5Uy6wVJybcCpbU3GnwYcur+4Mo=
32 | github.com/pierrre/assert v0.5.0/go.mod h1:a2kNx38ErwdJHGEi8a9aFDTImkoO5W/mfix2Es/Zcp0=
33 | github.com/pierrre/compare v1.4.7 h1:wa8vWJXUj39Uzw4C+VFXseZ9u3ZD5k1jgt3iJLmvWsI=
34 | github.com/pierrre/compare v1.4.7/go.mod h1:EfhQgoxtZiKi4e2NiCjasv6am7xqVDrVgiyUFcoorLI=
35 | github.com/pierrre/geohash v1.1.2 h1:UvIJTJHOhtBxn0QZhqeKRln6lirxxznAff1S06BZx3w=
36 | github.com/pierrre/geohash v1.1.2/go.mod h1:ACW6wOs9Ha9laaU33CGel2y46hJkRjZY7uFGXeVnwDo=
37 | github.com/pierrre/go-libs v0.7.0 h1:uaHiD66VBLb0jF1PaWGVLKBHdRhkw0KsM5pmlUK+CO8=
38 | github.com/pierrre/go-libs v0.7.0/go.mod h1:0g8JPnx0MUreex2DGohGhUGrmLu8u87bD5drSMfEOP0=
39 | github.com/pierrre/pretty v0.3.4 h1:Pxu9M/+Tfx9l03ceehyd+3LUfmIIjdr4YbYGLtAVOwc=
40 | github.com/pierrre/pretty v0.3.4/go.mod h1:FbroWIpyd5L8P5sehyQ9sxX4YYY51oZbUN+ggNdMIuY=
41 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
42 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
43 | github.com/prometheus/client_golang v1.22.0 h1:rb93p9lokFEsctTys46VnV1kLCDpVZ0a/Y92Vm0Zc6Q=
44 | github.com/prometheus/client_golang v1.22.0/go.mod h1:R7ljNsLXhuQXYZYtw6GAE9AZg8Y7vEW5scdCXrWRXC0=
45 | github.com/prometheus/client_model v0.6.1 h1:ZKSh/rekM+n3CeS952MLRAdFwIKqeY8b62p8ais2e9E=
46 | github.com/prometheus/client_model v0.6.1/go.mod h1:OrxVMOVHjw3lKMa8+x6HeMGkHMQyHDk9E3jmP2AmGiY=
47 | github.com/prometheus/common v0.62.0 h1:xasJaQlnWAeyHdUBeGjXmutelfJHWMRr+Fg4QszZ2Io=
48 | github.com/prometheus/common v0.62.0/go.mod h1:vyBcEuLSvWos9B1+CyL7JZ2up+uFzXhkqml0W5zIY1I=
49 | github.com/prometheus/procfs v0.15.1 h1:YagwOFzUgYfKKHX6Dr+sHT7km/hxC76UB0learggepc=
50 | github.com/prometheus/procfs v0.15.1/go.mod h1:fB45yRUv8NstnjriLhBQLuOUt+WW4BsoGhij/e3PBqk=
51 | github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA=
52 | github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
53 | github.com/the42/cartconvert v1.0.0 h1:g8kt6ic2GEhdcZ61ZP9GsWwhosVo5nCnH1n2/oAQXUU=
54 | github.com/the42/cartconvert v1.0.0/go.mod h1:fWO/msnJVhHqN1yX6OBoxSyfj7TEj1hHiL8bJSQsK30=
55 | golang.org/x/sys v0.30.0 h1:QjkSwP/36a20jFYWkSue1YwXzLmsV5Gfq7Eiy72C1uc=
56 | golang.org/x/sys v0.30.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
57 | google.golang.org/protobuf v1.36.5 h1:tPhr+woSbjfYvY6/GPufUoYizxw1cF/yFoxJ2fmpwlM=
58 | google.golang.org/protobuf v1.36.5/go.mod h1:9fA7Ob0pmnwhb644+1+CVWFRbNajQ6iRojtC/QF5bRE=
59 | gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
60 | gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
61 |
--------------------------------------------------------------------------------
/main.go:
--------------------------------------------------------------------------------
1 | // Copyright (C) 2021-2024 Shizun Ge
2 | //
3 | // This program is free software: you can redistribute it and/or modify
4 | // it under the terms of the GNU General Public License as published by
5 | // the Free Software Foundation, either version 3 of the License, or
6 | // (at your option) any later version.
7 | //
8 | // This program is distributed in the hope that it will be useful,
9 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 | // GNU General Public License for more details.
12 | //
13 | // You should have received a copy of the GNU General Public License
14 | // along with this program. If not, see .
15 | //
16 |
17 | package main
18 |
19 | import (
20 | "endlessh-go/client"
21 | "endlessh-go/geoip"
22 | "endlessh-go/metrics"
23 | "flag"
24 | "fmt"
25 | "net"
26 | "os"
27 | "strings"
28 | "time"
29 |
30 | "github.com/golang/glog"
31 | )
32 |
33 | func startSending(maxClients int64, bannerMaxLength int64, records chan<- metrics.RecordEntry) chan *client.Client {
34 | clients := make(chan *client.Client, maxClients)
35 | go func() {
36 | for {
37 | c, more := <-clients
38 | if !more {
39 | return
40 | }
41 | go func() {
42 | bytesSent, err := c.Send(bannerMaxLength)
43 | remoteIpAddr := c.RemoteIpAddr()
44 | localPort := c.LocalPort()
45 | millisecondsSpent := c.MillisecondsSinceLast()
46 | if err != nil {
47 | c.Close()
48 | records <- metrics.RecordEntry{
49 | RecordType: metrics.RecordEntryTypeStop,
50 | IpAddr: remoteIpAddr,
51 | LocalPort: localPort,
52 | MillisecondsSpent: millisecondsSpent,
53 | }
54 | return
55 | }
56 | clients <- c
57 | records <- metrics.RecordEntry{
58 | RecordType: metrics.RecordEntryTypeSend,
59 | IpAddr: remoteIpAddr,
60 | LocalPort: localPort,
61 | MillisecondsSpent: millisecondsSpent,
62 | BytesSent: bytesSent,
63 | }
64 | }()
65 | }
66 | }()
67 | return clients
68 | }
69 |
70 | func startAccepting(maxClients int64, connType, connHost, connPort string, interval time.Duration, clients chan<- *client.Client, records chan<- metrics.RecordEntry) {
71 | go func() {
72 | l, err := net.Listen(connType, connHost+":"+connPort)
73 | if err != nil {
74 | glog.Errorf("Error listening: %v", err)
75 | os.Exit(1)
76 | }
77 | // Close the listener when the application closes.
78 | defer l.Close()
79 | glog.Infof("Listening on %v:%v", connHost, connPort)
80 | for {
81 | // Listen for an incoming connection.
82 | conn, err := l.Accept()
83 | if err != nil {
84 | glog.Errorf("Error accepting connection from port %v: %v", connPort, err)
85 | os.Exit(1)
86 | }
87 | c := client.NewClient(conn, interval, maxClients)
88 | remoteIpAddr := c.RemoteIpAddr()
89 | records <- metrics.RecordEntry{
90 | RecordType: metrics.RecordEntryTypeStart,
91 | IpAddr: remoteIpAddr,
92 | LocalPort: connPort,
93 | }
94 | clients <- c
95 | }
96 | }()
97 | }
98 |
99 | type arrayStrings []string
100 |
101 | func (a *arrayStrings) String() string {
102 | return strings.Join(*a, ", ")
103 | }
104 |
105 | func (a *arrayStrings) Set(value string) error {
106 | *a = append(*a, value)
107 | return nil
108 | }
109 |
110 | const defaultPort = "2222"
111 |
112 | var connPorts arrayStrings
113 |
114 | func main() {
115 | intervalMs := flag.Int("interval_ms", 1000, "Message millisecond delay")
116 | bannerMaxLength := flag.Int64("line_length", 32, "Maximum banner line length")
117 | maxClients := flag.Int64("max_clients", 4096, "Maximum number of clients")
118 | connType := flag.String("conn_type", "tcp", "Connection type. Possible values are tcp, tcp4, tcp6")
119 | connHost := flag.String("host", "0.0.0.0", "SSH listening address")
120 | flag.Var(&connPorts, "port", fmt.Sprintf("SSH listening port. You may provide multiple -port flags to listen to multiple ports. (default %q)", defaultPort))
121 | prometheusEnabled := flag.Bool("enable_prometheus", false, "Enable prometheus")
122 | prometheusHost := flag.String("prometheus_host", "0.0.0.0", "The address for prometheus")
123 | prometheusPort := flag.String("prometheus_port", "2112", "The port for prometheus")
124 | prometheusEntry := flag.String("prometheus_entry", "metrics", "Entry point for prometheus")
125 | prometheusCleanUnseenSeconds := flag.Int("prometheus_clean_unseen_seconds", 0, "Remove series if the IP is not seen for the given time. Set to 0 to disable. (default 0)")
126 | geoipSupplier := flag.String("geoip_supplier", "off", "Supplier to obtain Geohash of IPs. Possible values are \"off\", \"ip-api\", \"max-mind-db\"")
127 | maxMindDbFileName := flag.String("max_mind_db", "", "Path to the MaxMind DB file.")
128 |
129 | flag.Usage = func() {
130 | fmt.Fprintf(flag.CommandLine.Output(), "Usage of %v \n", os.Args[0])
131 | flag.PrintDefaults()
132 | }
133 | flag.Parse()
134 |
135 | if *prometheusEnabled {
136 | if *connType == "tcp6" && *prometheusHost == "0.0.0.0" {
137 | *prometheusHost = "[::]"
138 | }
139 | metrics.InitPrometheus(*prometheusHost, *prometheusPort, *prometheusEntry)
140 | }
141 |
142 | records := metrics.StartRecording(*maxClients, *prometheusEnabled, *prometheusCleanUnseenSeconds,
143 | geoip.GeoOption{
144 | GeoipSupplier: *geoipSupplier,
145 | MaxMindDbFileName: *maxMindDbFileName,
146 | })
147 | clients := startSending(*maxClients, *bannerMaxLength, records)
148 |
149 | interval := time.Duration(*intervalMs) * time.Millisecond
150 | // Listen for incoming connections.
151 | if *connType == "tcp6" && *connHost == "0.0.0.0" {
152 | *connHost = "[::]"
153 | }
154 | if len(connPorts) == 0 {
155 | connPorts = append(connPorts, defaultPort)
156 | }
157 | for _, connPort := range connPorts {
158 | startAccepting(*maxClients, *connType, *connHost, connPort, interval, clients, records)
159 | }
160 | for {
161 | if *prometheusCleanUnseenSeconds <= 0 {
162 | time.Sleep(time.Duration(1<<63 - 1))
163 | } else {
164 | time.Sleep(time.Second * time.Duration(60))
165 | records <- metrics.RecordEntry{
166 | RecordType: metrics.RecordEntryTypeClean,
167 | }
168 | }
169 | }
170 | }
171 |
--------------------------------------------------------------------------------
/metrics/metrics.go:
--------------------------------------------------------------------------------
1 | // Copyright (C) 2024 Shizun Ge
2 | //
3 | // This program is free software: you can redistribute it and/or modify
4 | // it under the terms of the GNU General Public License as published by
5 | // the Free Software Foundation, either version 3 of the License, or
6 | // (at your option) any later version.
7 | //
8 | // This program is distributed in the hope that it will be useful,
9 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 | // GNU General Public License for more details.
12 | //
13 | // You should have received a copy of the GNU General Public License
14 | // along with this program. If not, see .
15 | //
16 |
17 | package metrics
18 |
19 | import (
20 | "endlessh-go/geoip"
21 | "net/http"
22 | "os"
23 | "time"
24 | "strings"
25 | "net"
26 |
27 | "github.com/golang/glog"
28 | "github.com/prometheus/client_golang/prometheus"
29 | "github.com/prometheus/client_golang/prometheus/promhttp"
30 | )
31 |
32 | var (
33 | pq *UpdatablePriorityQueue
34 | totalClients *prometheus.CounterVec
35 | totalClientsClosed *prometheus.CounterVec
36 | totalBytes *prometheus.CounterVec
37 | totalSeconds *prometheus.CounterVec
38 | clientIP *prometheus.CounterVec
39 | clientSeconds *prometheus.CounterVec
40 | )
41 |
42 | func InitPrometheus(prometheusHost, prometheusPort, prometheusEntry string) {
43 | pq = NewUpdatablePriorityQueue()
44 | totalClients = prometheus.NewCounterVec(
45 | prometheus.CounterOpts{
46 | Name: "endlessh_client_open_count_total",
47 | Help: "Total number of clients that tried to connect to this host.",
48 | }, []string{"local_port"},
49 | )
50 | totalClientsClosed = prometheus.NewCounterVec(
51 | prometheus.CounterOpts{
52 | Name: "endlessh_client_closed_count_total",
53 | Help: "Total number of clients that stopped connecting to this host.",
54 | }, []string{"local_port"},
55 | )
56 | totalBytes = prometheus.NewCounterVec(
57 | prometheus.CounterOpts{
58 | Name: "endlessh_sent_bytes_total",
59 | Help: "Total bytes sent to clients that tried to connect to this host.",
60 | }, []string{"local_port"},
61 | )
62 | totalSeconds = prometheus.NewCounterVec(
63 | prometheus.CounterOpts{
64 | Name: "endlessh_trapped_time_seconds_total",
65 | Help: "Total seconds clients spent on endlessh.",
66 | }, []string{"local_port"},
67 | )
68 | clientIP = prometheus.NewCounterVec(
69 | prometheus.CounterOpts{
70 | Name: "endlessh_client_open_count",
71 | Help: "Number of connections of clients.",
72 | },
73 | []string{"ip", "local_port", "geohash", "country", "location"},
74 | )
75 | clientSeconds = prometheus.NewCounterVec(
76 | prometheus.CounterOpts{
77 | Name: "endlessh_client_trapped_time_seconds",
78 | Help: "Seconds a client spends on endlessh.",
79 | },
80 | []string{"ip", "local_port"},
81 | )
82 | promReg := prometheus.NewRegistry()
83 | promReg.MustRegister(totalClients)
84 | promReg.MustRegister(totalClientsClosed)
85 | promReg.MustRegister(totalBytes)
86 | promReg.MustRegister(totalSeconds)
87 | promReg.MustRegister(clientIP)
88 | promReg.MustRegister(clientSeconds)
89 | handler := promhttp.HandlerFor(promReg, promhttp.HandlerOpts{EnableOpenMetrics: true})
90 | http.Handle("/"+prometheusEntry, handler)
91 | go func() {
92 |
93 | if strings.HasPrefix(prometheusHost, "unix:") {
94 | socketPath := prometheusHost[5:] // trim the "unix:" prefix
95 | glog.Infof("Starting Prometheus on Unix socket %v, entry point is /%v", socketPath, prometheusEntry)
96 | serveOnUnixSocket(socketPath)
97 | } else {
98 | ipPort := prometheusHost+":"+prometheusPort
99 | glog.Infof("Starting Prometheus on IP port %v, entry point is /%v", ipPort, prometheusEntry)
100 | serveOnIpPort(ipPort)
101 | }
102 |
103 | }()
104 | }
105 |
106 | func serveOnUnixSocket(socketPath string) {
107 | _ = os.Remove(socketPath) // allow failure
108 | unixListener, err := net.Listen("unix", socketPath)
109 | if err != nil {
110 | glog.Errorf("Error starting Prometheus on socket %v: %v", socketPath, err)
111 | os.Exit(1)
112 | }
113 | if err := http.Serve(unixListener, nil); err != nil {
114 | glog.Errorf("Error starting Prometheus at socket %v: %v", socketPath, err)
115 | os.Exit(1)
116 | }
117 | }
118 |
119 | func serveOnIpPort(ipPort string) {
120 | if err := http.ListenAndServe(ipPort, nil); err != nil {
121 | glog.Errorf("Error starting Prometheus at IP port %v: %v", ipPort, err)
122 | os.Exit(1)
123 | }
124 | }
125 |
126 | const (
127 | RecordEntryTypeStart = iota
128 | RecordEntryTypeSend = iota
129 | RecordEntryTypeStop = iota
130 | RecordEntryTypeClean = iota
131 | )
132 |
133 | type RecordEntry struct {
134 | RecordType int
135 | IpAddr string
136 | LocalPort string
137 | MillisecondsSpent int64
138 | BytesSent int
139 | }
140 |
141 | func StartRecording(maxClients int64, prometheusEnabled bool, prometheusCleanUnseenSeconds int, geoOption geoip.GeoOption) chan RecordEntry {
142 | records := make(chan RecordEntry, maxClients)
143 | go func() {
144 | for {
145 | r, more := <-records
146 | if !more {
147 | return
148 | }
149 | if !prometheusEnabled {
150 | continue
151 | }
152 | switch r.RecordType {
153 | case RecordEntryTypeStart:
154 | geohash, country, location, err := geoip.GeohashAndLocation(r.IpAddr, geoOption)
155 | if err != nil {
156 | glog.Warningf("Failed to obatin the geohash of %v: %v.", r.IpAddr, err)
157 | }
158 | clientIP.With(prometheus.Labels{
159 | "ip": r.IpAddr,
160 | "local_port": r.LocalPort,
161 | "geohash": geohash,
162 | "country": country,
163 | "location": location}).Inc()
164 | totalClients.With(prometheus.Labels{"local_port": r.LocalPort}).Inc()
165 | pq.Update(r.IpAddr, time.Now())
166 | case RecordEntryTypeSend:
167 | secondsSpent := float64(r.MillisecondsSpent) / 1000
168 | clientSeconds.With(prometheus.Labels{
169 | "ip": r.IpAddr,
170 | "local_port": r.LocalPort}).Add(secondsSpent)
171 | totalSeconds.With(prometheus.Labels{"local_port": r.LocalPort}).Add(secondsSpent)
172 | totalBytes.With(prometheus.Labels{"local_port": r.LocalPort}).Add(float64(r.BytesSent))
173 | pq.Update(r.IpAddr, time.Now())
174 | case RecordEntryTypeStop:
175 | secondsSpent := float64(r.MillisecondsSpent) / 1000
176 | clientSeconds.With(prometheus.Labels{
177 | "ip": r.IpAddr,
178 | "local_port": r.LocalPort}).Add(secondsSpent)
179 | totalSeconds.With(prometheus.Labels{"local_port": r.LocalPort}).Add(secondsSpent)
180 | totalClientsClosed.With(prometheus.Labels{"local_port": r.LocalPort}).Inc()
181 | pq.Update(r.IpAddr, time.Now())
182 | case RecordEntryTypeClean:
183 | top := pq.Peek()
184 | deadline := time.Now().Add(-time.Second * time.Duration(prometheusCleanUnseenSeconds))
185 | for top != nil && top.Value.Before(deadline) {
186 | clientIP.DeletePartialMatch(prometheus.Labels{"ip": top.Key})
187 | clientSeconds.DeletePartialMatch(prometheus.Labels{"ip": top.Key})
188 | pq.Pop()
189 | top = pq.Peek()
190 | }
191 | }
192 | }
193 | }()
194 | return records
195 | }
196 |
--------------------------------------------------------------------------------
/metrics/priority_queue.go:
--------------------------------------------------------------------------------
1 | package metrics
2 |
3 | import (
4 | "container/heap"
5 | "time"
6 | )
7 |
8 | // Pair represents a key-value pair with a timestamp
9 | type Pair struct {
10 | Key string
11 | Value time.Time
12 | HeapIdx int // Index in the heap for efficient updates
13 | }
14 |
15 | // PriorityQueue is a min-heap implementation for Pairs
16 | type PriorityQueue []*Pair
17 |
18 | // Len returns the length of the priority queue
19 | func (pq PriorityQueue) Len() int { return len(pq) }
20 |
21 | // Less compares two pairs based on their values (timestamps)
22 | func (pq PriorityQueue) Less(i, j int) bool {
23 | return pq[i].Value.Before(pq[j].Value)
24 | }
25 |
26 | // Swap swaps two pairs in the priority queue
27 | func (pq PriorityQueue) Swap(i, j int) {
28 | pq[i], pq[j] = pq[j], pq[i]
29 | pq[i].HeapIdx = i
30 | pq[j].HeapIdx = j
31 | }
32 |
33 | // Push adds a pair to the priority queue
34 | func (pq *PriorityQueue) Push(x interface{}) {
35 | pair := x.(*Pair)
36 | pair.HeapIdx = len(*pq)
37 | *pq = append(*pq, pair)
38 | }
39 |
40 | // Pop removes the pair with the minimum value (timestamp) from the priority queue
41 | func (pq *PriorityQueue) Pop() interface{} {
42 | old := *pq
43 | n := len(old)
44 | pair := old[n-1]
45 | pair.HeapIdx = -1 // for safety
46 | *pq = old[0 : n-1]
47 | return pair
48 | }
49 |
50 | // UpdatablePriorityQueue represents the data structure with the priority queue
51 | type UpdatablePriorityQueue struct {
52 | pq PriorityQueue
53 | keyMap map[string]*Pair
54 | }
55 |
56 | // NewUpdatablePriorityQueue initializes a new UpdatablePriorityQueue
57 | func NewUpdatablePriorityQueue() *UpdatablePriorityQueue {
58 | return &UpdatablePriorityQueue{
59 | pq: make(PriorityQueue, 0),
60 | keyMap: make(map[string]*Pair),
61 | }
62 | }
63 |
64 | // Update adds or updates a key-value pair in the data structure
65 | func (ds *UpdatablePriorityQueue) Update(key string, value time.Time) {
66 | if pair, ok := ds.keyMap[key]; ok {
67 | // Key exists, update the time
68 | pair.Value = value
69 | heap.Fix(&ds.pq, pair.HeapIdx)
70 | } else {
71 | // Key does not exist, create a new entry
72 | pair := &Pair{Key: key, Value: value}
73 | heap.Push(&ds.pq, pair)
74 | ds.keyMap[key] = pair
75 | }
76 | }
77 |
78 | // Peek returns the entry with the minimal time
79 | func (ds *UpdatablePriorityQueue) Peek() *Pair {
80 | if ds.pq.Len() == 0 {
81 | return nil
82 | }
83 | return ds.pq[0]
84 | }
85 |
86 | // Pop removes the entry with the minimal time
87 | func (ds *UpdatablePriorityQueue) Pop() *Pair {
88 | if ds.pq.Len() == 0 {
89 | return nil
90 | }
91 | pair := heap.Pop(&ds.pq).(*Pair)
92 | delete(ds.keyMap, pair.Key)
93 | return pair
94 | }
95 |
--------------------------------------------------------------------------------