├── .github ├── CODEOWNERS ├── ISSUE_TEMPLATE │ ├── bug_report.md │ └── feature-request.md ├── PULL_REQUEST_TEMPLATE.md └── workflows │ ├── go.yml │ ├── golangci-lint.yml │ └── release.yml ├── .gitignore ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── SECURITY.md ├── assets ├── info_1.gif ├── logo.png ├── machine_1.gif ├── sherlocks_1.gif ├── sherlocks_2.gif └── sherlocks_3.gif ├── cmd ├── completion.go ├── getflag.go ├── hosts.go ├── info.go ├── machines.go ├── pwnbox.go ├── reset.go ├── root.go ├── sherlocks.go ├── shoutbox.go ├── start.go ├── stop.go ├── submit.go ├── update.go ├── version.go └── vpn.go ├── config └── config.go ├── go.mod ├── go.sum ├── golangci.yml ├── lib ├── hosts │ └── hosts.go ├── sherlocks │ ├── models.go │ ├── sherlocks.go │ └── tui.go ├── shoutbox │ ├── models.go │ └── shoutbox.go ├── ssh │ └── ssh.go ├── submit │ └── submit.go ├── update │ ├── models.go │ └── update.go ├── utils │ ├── api.go │ ├── models.go │ ├── tui.go │ └── utils.go ├── vpn │ ├── models.go │ └── vpn.go └── webhooks │ ├── models.go │ └── webhooks.go └── main.go /.github/CODEOWNERS: -------------------------------------------------------------------------------- 1 | QU35T-code 2 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | title: "[BUG] " 5 | labels: bug 6 | assignees: QU35T-code 7 | 8 | --- 9 | 10 | **Describe the bug** 11 | A clear and concise description of what the bug is. 12 | 13 | **To Reproduce** 14 | Steps to reproduce the behavior: 15 | 1. Go to '...' 16 | 2. Click on '....' 17 | 3. Scroll down to '....' 18 | 4. See error 19 | 20 | **Expected behavior** 21 | A clear and concise description of what you expected to happen. 22 | 23 | **Screenshots** 24 | If applicable, add screenshots to help explain your problem. 25 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature-request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature Request 3 | about: "For feature requests. Please search for existing issues first." 4 | title: "[FEAT] <title>" 5 | labels: feat 6 | assignees: QU35T-code 7 | 8 | --- 9 | 10 | **Is your feature request related to a problem? Please describe.** 11 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] 12 | 13 | **Describe the solution you'd like** 14 | A clear and concise description of what you want to happen. 15 | 16 | **Describe alternatives you've considered** 17 | A clear and concise description of any alternative solutions or features you've considered. 18 | 19 | **Additional context** 20 | Add any other context or screenshots about the feature request here. 21 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | # Description 2 | 3 | Please include a summary of the changes and the related issue. Please also include relevant motivation and context. List any dependencies that are required for this change. 4 | 5 | Fixes # (issue) 6 | 7 | ## Type of change 8 | 9 | Please delete options that are not relevant. 10 | 11 | - [ ] Bug fix 12 | - [ ] New feature 13 | - [ ] This change requires a documentation update 14 | 15 | # How Has This Been Tested? 16 | 17 | Please describe the tests that you ran to verify your changes. Provide instructions so we can reproduce. Please also list any relevant details for your test configuration 18 | 19 | - [ ] Test A 20 | - [ ] Test B 21 | 22 | # Checklist: 23 | 24 | - [ ] My code follows the style guidelines of this project 25 | - [ ] I have performed a self-review of my code 26 | - [ ] I have commented my code, particularly in hard-to-understand areas 27 | - [ ] My changes generate no new warnings -------------------------------------------------------------------------------- /.github/workflows/go.yml: -------------------------------------------------------------------------------- 1 | name: Go 2 | 3 | on: 4 | push: 5 | branches: [ "main", "dev" ] 6 | pull_request: 7 | branches: [ "main", "dev" ] 8 | types: [opened, synchronize, reopened, ready_for_review] 9 | 10 | permissions: 11 | contents: write 12 | 13 | jobs: 14 | 15 | build: 16 | if: github.event_name != 'pull_request' || (github.event_name == 'pull_request' && !github.event.pull_request.draft) 17 | runs-on: ubuntu-latest 18 | strategy: 19 | matrix: 20 | go: ['1.20', '1.22', '1.23', '1.24'] 21 | os: [ 'linux', 'windows', 'darwin' ] 22 | arch: [ 'amd64', 'arm64' ] 23 | outputs: 24 | commit-hash: ${{ steps.get_commit.outputs.commit }} 25 | 26 | steps: 27 | - uses: actions/checkout@v4 28 | 29 | - name: Set up Go 30 | uses: actions/setup-go@v5 31 | with: 32 | go-version: ${{ matrix.go }} 33 | 34 | - name: Build 35 | env: 36 | GOOS: ${{ matrix.os }} 37 | GOARCH: ${{ matrix.arch }} 38 | run: go build -v ./... 39 | -------------------------------------------------------------------------------- /.github/workflows/golangci-lint.yml: -------------------------------------------------------------------------------- 1 | name: golangci-lint 2 | 3 | on: 4 | push: 5 | branches: [ "main", "dev" ] 6 | pull_request: 7 | branches: [ "main", "dev" ] 8 | types: [opened, synchronize, reopened, ready_for_review] 9 | 10 | jobs: 11 | golangci: 12 | name: lint 13 | runs-on: ubuntu-latest 14 | 15 | steps: 16 | - name: Checkout code 17 | uses: actions/checkout@v4 18 | 19 | - name: Set up Go 20 | uses: actions/setup-go@v5 21 | with: 22 | go-version: 1.24 23 | 24 | - name: Run golangci-lint 25 | uses: golangci/golangci-lint-action@v6.3.2 26 | with: 27 | version: latest 28 | skip-cache: true 29 | skip-save-cache: true 30 | 31 | - name: Upload lint results 32 | uses: actions/upload-artifact@v4 33 | if: failure() 34 | with: 35 | name: golangci-lint-results 36 | path: golangci-lint-report.txt 37 | -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: Release 2 | 3 | on: 4 | push: 5 | tags: 6 | - 'v*.*.*' 7 | 8 | permissions: 9 | contents: write 10 | 11 | jobs: 12 | 13 | release: 14 | runs-on: ubuntu-latest 15 | steps: 16 | - uses: actions/checkout@v4 17 | with: 18 | fetch-depth: 0 19 | 20 | - name: Set up Go 21 | uses: actions/setup-go@v5 22 | with: 23 | go-version: '1.20' 24 | 25 | - name: Release 26 | uses: goreleaser/goreleaser-action@v6 27 | with: 28 | distribution: goreleaser 29 | version: latest 30 | args: release --clean 31 | env: 32 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 33 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # If you prefer the allow list template instead of the deny list, see community template: 2 | # https://github.com/github/gitignore/blob/main/community/Golang/Go.AllowList.gitignore 3 | # 4 | # Binaries for programs and plugins 5 | *.exe 6 | *.exe~ 7 | *.dll 8 | *.so 9 | *.dylib 10 | .idea 11 | 12 | # Test binary, built with `go test -c` 13 | *.test 14 | 15 | # Output of the go coverage tool, specifically when used with LiteIDE 16 | *.out 17 | 18 | # Dependency directories (remove the comment below to include it) 19 | # vendor/ 20 | 21 | # Go workspace file 22 | go.work 23 | coverage.out 24 | htb-cli -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | We as members, contributors, and leaders pledge to make participation in our 6 | community a harassment-free experience for everyone, regardless of age, body 7 | size, visible or invisible disability, ethnicity, sex characteristics, gender 8 | identity and expression, level of experience, education, socio-economic status, 9 | nationality, personal appearance, race, religion, or sexual identity 10 | and orientation. 11 | 12 | We pledge to act and interact in ways that contribute to an open, welcoming, 13 | diverse, inclusive, and healthy community. 14 | 15 | ## Our Standards 16 | 17 | Examples of behavior that contributes to a positive environment for our 18 | community include: 19 | 20 | * Demonstrating empathy and kindness toward other people 21 | * Being respectful of differing opinions, viewpoints, and experiences 22 | * Giving and gracefully accepting constructive feedback 23 | * Accepting responsibility and apologizing to those affected by our mistakes, 24 | and learning from the experience 25 | * Focusing on what is best not just for us as individuals, but for the 26 | overall community 27 | 28 | Examples of unacceptable behavior include: 29 | 30 | * The use of sexualized language or imagery, and sexual attention or 31 | advances of any kind 32 | * Trolling, insulting or derogatory comments, and personal or political attacks 33 | * Public or private harassment 34 | * Publishing others' private information, such as a physical or email 35 | address, without their explicit permission 36 | * Other conduct which could reasonably be considered inappropriate in a 37 | professional setting 38 | 39 | ## Enforcement Responsibilities 40 | 41 | Community leaders are responsible for clarifying and enforcing our standards of 42 | acceptable behavior and will take appropriate and fair corrective action in 43 | response to any behavior that they deem inappropriate, threatening, offensive, 44 | or harmful. 45 | 46 | Community leaders have the right and responsibility to remove, edit, or reject 47 | comments, commits, code, wiki edits, issues, and other contributions that are 48 | not aligned to this Code of Conduct, and will communicate reasons for moderation 49 | decisions when appropriate. 50 | 51 | ## Scope 52 | 53 | This Code of Conduct applies within all community spaces, and also applies when 54 | an individual is officially representing the community in public spaces. 55 | Examples of representing our community include using an official e-mail address, 56 | posting via an official social media account, or acting as an appointed 57 | representative at an online or offline event. 58 | 59 | ## Enforcement 60 | 61 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 62 | reported to the community leaders responsible for enforcement at 63 | github@qu35t-mail.simplelogin.com. 64 | All complaints will be reviewed and investigated promptly and fairly. 65 | 66 | All community leaders are obligated to respect the privacy and security of the 67 | reporter of any incident. 68 | 69 | ## Enforcement Guidelines 70 | 71 | Community leaders will follow these Community Impact Guidelines in determining 72 | the consequences for any action they deem in violation of this Code of Conduct: 73 | 74 | ### 1. Correction 75 | 76 | **Community Impact**: Use of inappropriate language or other behavior deemed 77 | unprofessional or unwelcome in the community. 78 | 79 | **Consequence**: A private, written warning from community leaders, providing 80 | clarity around the nature of the violation and an explanation of why the 81 | behavior was inappropriate. A public apology may be requested. 82 | 83 | ### 2. Warning 84 | 85 | **Community Impact**: A violation through a single incident or series 86 | of actions. 87 | 88 | **Consequence**: A warning with consequences for continued behavior. No 89 | interaction with the people involved, including unsolicited interaction with 90 | those enforcing the Code of Conduct, for a specified period of time. This 91 | includes avoiding interactions in community spaces as well as external channels 92 | like social media. Violating these terms may lead to a temporary or 93 | permanent ban. 94 | 95 | ### 3. Temporary Ban 96 | 97 | **Community Impact**: A serious violation of community standards, including 98 | sustained inappropriate behavior. 99 | 100 | **Consequence**: A temporary ban from any sort of interaction or public 101 | communication with the community for a specified period of time. No public or 102 | private interaction with the people involved, including unsolicited interaction 103 | with those enforcing the Code of Conduct, is allowed during this period. 104 | Violating these terms may lead to a permanent ban. 105 | 106 | ### 4. Permanent Ban 107 | 108 | **Community Impact**: Demonstrating a pattern of violation of community 109 | standards, including sustained inappropriate behavior, harassment of an 110 | individual, or aggression toward or disparagement of classes of individuals. 111 | 112 | **Consequence**: A permanent ban from any sort of public interaction within 113 | the community. 114 | 115 | ## Attribution 116 | 117 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], 118 | version 2.0, available at 119 | https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. 120 | 121 | Community Impact Guidelines were inspired by [Mozilla's code of conduct 122 | enforcement ladder](https://github.com/mozilla/diversity). 123 | 124 | [homepage]: https://www.contributor-covenant.org 125 | 126 | For answers to common questions about this code of conduct, see the FAQ at 127 | https://www.contributor-covenant.org/faq. Translations are available at 128 | https://www.contributor-covenant.org/translations. -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | Don't hesitate to contribute to the project with a pull request. All ideas are welcome to improve the project ! -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/> 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 | <one line to give the program's name and a brief idea of what it does.> 635 | Copyright (C) <year> <name of author> 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 <https://www.gnu.org/licenses/>. 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 | <program> Copyright (C) <year> <name of author> 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 | <https://www.gnu.org/licenses/>. 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 | <https://www.gnu.org/licenses/why-not-lgpl.html>. 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # htb-cli 2 | 3 | ![Workflows (main)](https://github.com/GoToolSharing/htb-cli/actions/workflows/go.yml/badge.svg?branch=main) 4 | ![Workflows (dev)](https://github.com/GoToolSharing/htb-cli/actions/workflows/go.yml/badge.svg?branch=dev) 5 | ![GitHub go.mod Go version (main)](https://img.shields.io/github/go-mod/go-version/GoToolSharing/htb-cli/main) 6 | ![GitHub go.mod Go version (dev)](https://img.shields.io/github/go-mod/go-version/GoToolSharing/htb-cli/dev) 7 | ![GitHub release](https://img.shields.io/github/v/release/GoToolSharing/htb-cli) 8 | ![GitHub Repo stars](https://img.shields.io/github/stars/GoToolSharing/htb-cli) 9 | 10 | <a target="_blank" rel="noopener noreferrer" href="https://twitter.com/QU35T_TV" title="Follow"><img src="https://img.shields.io/twitter/follow/QU35T_TV?label=QU35T_TV&style=social" alt="Twitter QU35T_TV"></a> 11 | 12 | <div> 13 | <img alt="current version" src="https://img.shields.io/badge/linux-supported-success"> 14 | <img alt="current version" src="https://img.shields.io/badge/WSL-supported-success"> 15 | <img alt="current version" src="https://img.shields.io/badge/mac-supported-success"> 16 | <br> 17 | <img alt="amd64" src="https://img.shields.io/badge/amd64%20(x86__64)-supported-success"> 18 | <img alt="arm64" src="https://img.shields.io/badge/arm64%20(aarch64)-supported-success"> 19 | </div> 20 | 21 | <div align="center"> 22 | <img src="./assets/logo.png" alt="Alt text" width="400"> 23 | </div></br> 24 | 25 | # Official Documentation 26 | 27 | The official documentation for htb-cli is hosted on Github Pages and can be accessed via the following link: <a href="https://htb-cli-documentation.qu35t.pw/" target="_blank">https://htb-cli-documentation.qu35t.pw/</a> 28 | -------------------------------------------------------------------------------- /SECURITY.md: -------------------------------------------------------------------------------- 1 | # Security Policy 2 | 3 | ## Reporting a Vulnerability 4 | 5 | Please report (suspected) security vulnerabilities to github@qu35t-mail.simplelogin.com. You will receive a response from us within 48 hours. If the issue is confirmed, we will release a patch as soon as possible depending on complexity. 6 | 7 | -------------------------------------------------------------------------------- /assets/info_1.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GoToolSharing/htb-cli/35a970d405f721f7ca2aa4d3d1244b6bdae7bb38/assets/info_1.gif -------------------------------------------------------------------------------- /assets/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GoToolSharing/htb-cli/35a970d405f721f7ca2aa4d3d1244b6bdae7bb38/assets/logo.png -------------------------------------------------------------------------------- /assets/machine_1.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GoToolSharing/htb-cli/35a970d405f721f7ca2aa4d3d1244b6bdae7bb38/assets/machine_1.gif -------------------------------------------------------------------------------- /assets/sherlocks_1.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GoToolSharing/htb-cli/35a970d405f721f7ca2aa4d3d1244b6bdae7bb38/assets/sherlocks_1.gif -------------------------------------------------------------------------------- /assets/sherlocks_2.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GoToolSharing/htb-cli/35a970d405f721f7ca2aa4d3d1244b6bdae7bb38/assets/sherlocks_2.gif -------------------------------------------------------------------------------- /assets/sherlocks_3.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GoToolSharing/htb-cli/35a970d405f721f7ca2aa4d3d1244b6bdae7bb38/assets/sherlocks_3.gif -------------------------------------------------------------------------------- /cmd/completion.go: -------------------------------------------------------------------------------- 1 | package cmd 2 | 3 | import ( 4 | "fmt" 5 | "os" 6 | 7 | "github.com/spf13/cobra" 8 | ) 9 | 10 | // Generates shell autocompletion file 11 | var completionCmd = &cobra.Command{ 12 | Use: "completion [bash|zsh|fish|powershell]", 13 | Short: "Generate completion script", 14 | ValidArgs: []string{"bash", "zsh", "fish", "powershell"}, 15 | Args: cobra.MatchAll(cobra.ExactArgs(1), cobra.OnlyValidArgs), 16 | Run: func(cmd *cobra.Command, args []string) { 17 | switch args[0] { 18 | case "bash": 19 | err := cmd.Root().GenBashCompletion(os.Stdout) 20 | if err != nil { 21 | fmt.Println(err) 22 | return 23 | } 24 | case "zsh": 25 | err := cmd.Root().GenZshCompletion(os.Stdout) 26 | if err != nil { 27 | fmt.Println(err) 28 | return 29 | } 30 | case "fish": 31 | err := cmd.Root().GenFishCompletion(os.Stdout, true) 32 | if err != nil { 33 | fmt.Println(err) 34 | return 35 | } 36 | case "powershell": 37 | err := cmd.Root().GenPowerShellCompletionWithDesc(os.Stdout) 38 | if err != nil { 39 | fmt.Println(err) 40 | return 41 | } 42 | } 43 | }, 44 | } 45 | 46 | func init() { 47 | rootCmd.AddCommand(completionCmd) 48 | } 49 | -------------------------------------------------------------------------------- /cmd/getflag.go: -------------------------------------------------------------------------------- 1 | package cmd 2 | 3 | import ( 4 | "fmt" 5 | "os" 6 | "strings" 7 | 8 | "github.com/GoToolSharing/htb-cli/config" 9 | "github.com/GoToolSharing/htb-cli/lib/ssh" 10 | "github.com/GoToolSharing/htb-cli/lib/submit" 11 | "github.com/spf13/cobra" 12 | "go.uber.org/zap" 13 | ) 14 | 15 | var getflagCmd = &cobra.Command{ 16 | Use: "getflag", 17 | Short: "Retrieves and submits flags from an SSH connection (linux only)", 18 | Run: func(cmd *cobra.Command, args []string) { 19 | config.GlobalConfig.Logger.Info("Getflag command executed") 20 | username, err := cmd.Flags().GetString("username") 21 | if err != nil { 22 | config.GlobalConfig.Logger.Error("", zap.Error(err)) 23 | os.Exit(1) 24 | } 25 | password, err := cmd.Flags().GetString("password") 26 | if err != nil { 27 | config.GlobalConfig.Logger.Error("", zap.Error(err)) 28 | os.Exit(1) 29 | } 30 | host, err := cmd.Flags().GetString("host") 31 | if err != nil { 32 | config.GlobalConfig.Logger.Error("", zap.Error(err)) 33 | os.Exit(1) 34 | } 35 | port, err := cmd.Flags().GetInt("port") 36 | if err != nil { 37 | config.GlobalConfig.Logger.Error("", zap.Error(err)) 38 | os.Exit(1) 39 | } 40 | connection, err := ssh.Connect(username, password, host, port) 41 | if err != nil { 42 | config.GlobalConfig.Logger.Error("", zap.Error(err)) 43 | os.Exit(1) 44 | } 45 | userFlag, err := ssh.GetUserFlag(connection) 46 | if err != nil { 47 | config.GlobalConfig.Logger.Error("", zap.Error(err)) 48 | os.Exit(1) 49 | } 50 | userFlag = strings.ReplaceAll(userFlag, "\n", "") 51 | hostname, err := ssh.GetHostname(connection) 52 | if err != nil { 53 | config.GlobalConfig.Logger.Error("", zap.Error(err)) 54 | os.Exit(1) 55 | } 56 | connection.Close() 57 | url, payload, err := ssh.BuildSubmitStuff(hostname, userFlag) 58 | if err != nil { 59 | config.GlobalConfig.Logger.Error("", zap.Error(err)) 60 | os.Exit(1) 61 | } 62 | 63 | message, err := submit.SubmitFlag(url, payload) 64 | if err != nil { 65 | config.GlobalConfig.Logger.Error("", zap.Error(err)) 66 | os.Exit(1) 67 | } 68 | fmt.Println(message) 69 | 70 | config.GlobalConfig.Logger.Info("Exit getflag command correctly") 71 | }, 72 | } 73 | 74 | func init() { 75 | rootCmd.AddCommand(getflagCmd) 76 | getflagCmd.Flags().StringP("username", "u", "", "SSH username") 77 | getflagCmd.Flags().StringP("password", "p", "", "SSH password") 78 | getflagCmd.Flags().IntP("port", "P", 22, "(Optional) SSH Port (Default 22)") 79 | getflagCmd.Flags().StringP("host", "", "", "(Optional) SSH host") 80 | } 81 | -------------------------------------------------------------------------------- /cmd/hosts.go: -------------------------------------------------------------------------------- 1 | package cmd 2 | 3 | import ( 4 | "os" 5 | 6 | "github.com/GoToolSharing/htb-cli/config" 7 | "github.com/GoToolSharing/htb-cli/lib/hosts" 8 | "github.com/spf13/cobra" 9 | "go.uber.org/zap" 10 | ) 11 | 12 | var hostsCmd = &cobra.Command{ 13 | Use: "hosts", 14 | Short: "Interact with hosts file", 15 | Run: func(cmd *cobra.Command, args []string) { 16 | config.GlobalConfig.Logger.Info("Hosts command executed") 17 | addParam, err := cmd.Flags().GetString("add") 18 | if err != nil { 19 | config.GlobalConfig.Logger.Error("", zap.Error(err)) 20 | os.Exit(1) 21 | } 22 | 23 | deleteParam, err := cmd.Flags().GetString("delete") 24 | if err != nil { 25 | config.GlobalConfig.Logger.Error("", zap.Error(err)) 26 | os.Exit(1) 27 | } 28 | 29 | ipParam, err := cmd.Flags().GetString("ip") 30 | if err != nil { 31 | config.GlobalConfig.Logger.Error("", zap.Error(err)) 32 | os.Exit(1) 33 | } 34 | 35 | if addParam != "" && deleteParam != "" { 36 | config.GlobalConfig.Logger.Error("Only one parameter is allowed") 37 | os.Exit(1) 38 | } 39 | 40 | if addParam != "" { 41 | err = hosts.AddEntryToHosts(ipParam, addParam) 42 | if err != nil { 43 | config.GlobalConfig.Logger.Error("", zap.Error(err)) 44 | os.Exit(1) 45 | } 46 | } 47 | 48 | if deleteParam != "" { 49 | err = hosts.RemoveEntryFromHosts(ipParam, deleteParam) 50 | if err != nil { 51 | config.GlobalConfig.Logger.Error("", zap.Error(err)) 52 | os.Exit(1) 53 | } 54 | } 55 | 56 | config.GlobalConfig.Logger.Info("Exit hosts command correctly") 57 | }, 58 | } 59 | 60 | func init() { 61 | rootCmd.AddCommand(hostsCmd) 62 | hostsCmd.Flags().StringP("add", "a", "", "Add a new entry") 63 | hostsCmd.Flags().StringP("ip", "i", "", "IP Address") 64 | hostsCmd.Flags().StringP("delete", "d", "", "Delete an entry") 65 | } 66 | -------------------------------------------------------------------------------- /cmd/info.go: -------------------------------------------------------------------------------- 1 | package cmd 2 | 3 | import ( 4 | "encoding/json" 5 | "errors" 6 | "fmt" 7 | "net/http" 8 | "os" 9 | "strings" 10 | "text/tabwriter" 11 | "time" 12 | 13 | "github.com/GoToolSharing/htb-cli/config" 14 | "github.com/GoToolSharing/htb-cli/lib/utils" 15 | "github.com/spf13/cobra" 16 | "go.uber.org/zap" 17 | ) 18 | 19 | type Response struct { 20 | Message string `json:"message"` 21 | ExpiresAt string `json:"expires_at"` 22 | } 23 | 24 | // Retrieves data for user profile 25 | func fetchData(itemID int, endpoint string, infoKey string) (map[string]interface{}, error) { 26 | url := fmt.Sprintf("%s%s%d", config.BaseHackTheBoxAPIURL, endpoint, itemID) 27 | config.GlobalConfig.Logger.Debug(fmt.Sprintf("URL: %s", url)) 28 | 29 | resp, err := utils.HtbRequest(http.MethodGet, url, nil) 30 | if err != nil { 31 | return nil, err 32 | } 33 | 34 | parsedInfo := utils.ParseJsonMessage(resp, infoKey) 35 | dataMap, ok := parsedInfo.(map[string]interface{}) 36 | if !ok { 37 | return nil, errors.New("Could not convert parsedInfo to map[string]interface{}") 38 | } 39 | return dataMap, nil 40 | } 41 | 42 | // fetchAndDisplayInfo fetches and displays information based on the specified parameters. 43 | func fetchAndDisplayInfo(url, header string, params []string, elementType string) error { 44 | w := utils.SetTabWriterHeader(header) 45 | 46 | // Iteration on all machines / challenges / users argument 47 | var itemID int 48 | for _, param := range params { 49 | if elementType == "Challenge" { 50 | config.GlobalConfig.Logger.Info("Challenge search...") 51 | challenges, err := utils.SearchChallengeByName(param) 52 | if err != nil { 53 | return err 54 | } 55 | config.GlobalConfig.Logger.Debug(fmt.Sprintf("Challenge found: %v", challenges)) 56 | 57 | itemID = challenges.ID 58 | } else { 59 | itemID, _ = utils.SearchItemIDByName(param, elementType) 60 | } 61 | 62 | resp, err := utils.HtbRequest(http.MethodGet, fmt.Sprintf("%s%d", url, itemID), nil) 63 | if err != nil { 64 | return err 65 | } 66 | 67 | var infoKey string 68 | if strings.Contains(url, "machine") { 69 | infoKey = "info" 70 | } else if strings.Contains(url, "challenge") { 71 | infoKey = "challenge" 72 | } else if strings.Contains(url, "user/profile") { 73 | infoKey = "profile" 74 | } else { 75 | return fmt.Errorf("infoKey not defined") 76 | } 77 | 78 | config.GlobalConfig.Logger.Debug(fmt.Sprintf("URL: %s", url)) 79 | config.GlobalConfig.Logger.Debug(fmt.Sprintf("InfoKey: %s", infoKey)) 80 | 81 | info := utils.ParseJsonMessage(resp, infoKey) 82 | data := info.(map[string]interface{}) 83 | 84 | endpoints := []struct { 85 | name string 86 | url string 87 | }{ 88 | {"Fortresses", "/user/profile/progress/fortress/"}, 89 | {"Prolabs", "/user/profile/progress/prolab/"}, 90 | {"Activity", "/user/profile/activity/"}, 91 | } 92 | 93 | dataMaps := make(map[string]map[string]interface{}) 94 | 95 | for _, ep := range endpoints { 96 | data, err := fetchData(itemID, ep.url, "profile") 97 | if err != nil { 98 | fmt.Printf("Error fetching data for %s: %v\n", ep.name, err) 99 | continue 100 | } 101 | dataMaps[ep.name] = data 102 | } 103 | 104 | var bodyData string 105 | if elementType == "Machine" { 106 | status := utils.SetStatus(data) 107 | retiredStatus := getMachineStatus(data) 108 | release_key := "release" 109 | datetime, err := utils.ParseAndFormatDate(data[release_key].(string)) 110 | if err != nil { 111 | return err 112 | } 113 | ip := getIPStatus(data) 114 | bodyData = fmt.Sprintf("%v\t%v\t%v\t%v\t%v\t%v\t%v\t%v\t%v\n", data["name"], data["os"], retiredStatus, data["difficultyText"], data["stars"], ip, status, data["last_reset_time"], datetime) 115 | } else if elementType == "Challenge" { 116 | status := utils.SetStatus(data) 117 | retiredStatus := getMachineStatus(data) 118 | release_key := "release_date" 119 | datetime, err := utils.ParseAndFormatDate(data[release_key].(string)) 120 | if err != nil { 121 | return err 122 | } 123 | bodyData = fmt.Sprintf("%v\t%v\t%v\t%v\t%v\t%v\t%v\t%v\n", data["name"], data["category_name"], retiredStatus, data["difficulty"], data["stars"], data["solves"], status, datetime) 124 | } else if elementType == "Username" { 125 | utils.DisplayInformationsGUI(data, dataMaps) 126 | return nil 127 | } 128 | 129 | utils.SetTabWriterData(w, bodyData) 130 | w.Flush() 131 | } 132 | return nil 133 | } 134 | 135 | // coreInfoCmd is the core of the info command; it checks the parameters and displays corresponding information. 136 | func coreInfoCmd(machineName []string, challengeName []string, usernameName []string) error { 137 | machineHeader := "Name\tOS\tRetired\tDifficulty\tStars\tIP\tStatus\tLast Reset\tRelease" 138 | challengeHeader := "Name\tCategory\tRetired\tDifficulty\tStars\tSolves\tStatus\tRelease" 139 | usernameHeader := "Name\tUser Owns\tSystem Owns\tUser Bloods\tSystem Bloods\tTeam\tUniversity\tRank\tGlobal Rank\tPoints" 140 | 141 | type infoType struct { 142 | APIURL string 143 | Header string 144 | Params []string 145 | Name string 146 | } 147 | 148 | infos := []infoType{ 149 | {config.BaseHackTheBoxAPIURL + "/machine/profile/", machineHeader, machineName, "Machine"}, 150 | {config.BaseHackTheBoxAPIURL + "/challenge/info/", challengeHeader, challengeName, "Challenge"}, 151 | {config.BaseHackTheBoxAPIURL + "/user/profile/basic/", usernameHeader, usernameName, "Username"}, 152 | } 153 | 154 | // No arguments provided 155 | if len(machineName) == 0 && len(usernameName) == 0 && len(challengeName) == 0 { 156 | isConfirmed := utils.AskConfirmation("Do you want to check for active machine ?") 157 | if isConfirmed { 158 | err := displayActiveMachine(machineHeader) 159 | if err != nil { 160 | return err 161 | } 162 | } 163 | // Get current account 164 | resp, err := utils.HtbRequest(http.MethodGet, config.BaseHackTheBoxAPIURL+"/user/info", nil) 165 | if err != nil { 166 | return err 167 | } 168 | info := utils.ParseJsonMessage(resp, "info") 169 | infoMap, _ := info.(map[string]interface{}) 170 | newInfo := infoType{ 171 | APIURL: config.BaseHackTheBoxAPIURL + "/user/profile/basic/", 172 | Header: "", 173 | Params: []string{infoMap["name"].(string)}, 174 | Name: "Username", 175 | } 176 | infos = append(infos, newInfo) 177 | } 178 | 179 | for _, info := range infos { 180 | if len(info.Params) > 0 { 181 | if info.Name == "Machine" { 182 | isConfirmed := utils.AskConfirmation("Do you want to check for active " + strings.ToLower(info.Name) + "?") 183 | if isConfirmed { 184 | err := displayActiveMachine(info.Header) 185 | if err != nil { 186 | return err 187 | } 188 | } 189 | } 190 | for _, param := range info.Params { 191 | err := fetchAndDisplayInfo(info.APIURL, info.Header, []string{param}, info.Name) 192 | if err != nil { 193 | return err 194 | } 195 | } 196 | } 197 | } 198 | return nil 199 | } 200 | 201 | // getMachineStatus returns machine status 202 | func getMachineStatus(data map[string]interface{}) string { 203 | if data["retired"] == false { 204 | return "No" 205 | } 206 | return "Yes" 207 | } 208 | 209 | // getIPStatus returns ip status 210 | func getIPStatus(data map[string]interface{}) interface{} { 211 | if data["ip"] == nil { 212 | return "Undefined" 213 | } 214 | return data["ip"] 215 | } 216 | 217 | // displayActiveMachine displays information about the active machine if one is found. 218 | func displayActiveMachine(header string) error { 219 | machineID, err := utils.GetActiveMachineID() 220 | if err != nil { 221 | return err 222 | } 223 | if machineID == 0 { 224 | fmt.Println("No machine is running") 225 | return nil 226 | } 227 | machineType, err := utils.GetMachineType(machineID) 228 | if err != nil { 229 | return err 230 | } 231 | config.GlobalConfig.Logger.Debug(fmt.Sprintf("Machine Type: %s", machineType)) 232 | 233 | expiresTime, err := utils.GetExpiredTime(machineType) 234 | if err != nil { 235 | return err 236 | } 237 | config.GlobalConfig.Logger.Debug(fmt.Sprintf("Expires Time: %s", expiresTime)) 238 | 239 | config.GlobalConfig.Logger.Info("Active machine found !") 240 | config.GlobalConfig.Logger.Debug(fmt.Sprintf("Machine ID: %d", machineID)) 241 | 242 | if expiresTime != "Undefined" { 243 | err = checkIfExpiringSoon(expiresTime, machineID) 244 | if err != nil { 245 | return err 246 | } 247 | } 248 | 249 | tabwriter.NewWriter(os.Stdout, 0, 0, 3, ' ', tabwriter.Debug) 250 | w := utils.SetTabWriterHeader(header) 251 | 252 | url := fmt.Sprintf("%s/machine/profile/%d", config.BaseHackTheBoxAPIURL, machineID) 253 | resp, err := utils.HtbRequest(http.MethodGet, url, nil) 254 | if err != nil { 255 | return err 256 | } 257 | info := utils.ParseJsonMessage(resp, "info") 258 | // info := utils.ParseJsonMessage(resp, "data") 259 | 260 | data := info.(map[string]interface{}) 261 | status := utils.SetStatus(data) 262 | retiredStatus := getMachineStatus(data) 263 | 264 | datetime, err := utils.ParseAndFormatDate(data["release"].(string)) 265 | if err != nil { 266 | return err 267 | } 268 | config.GlobalConfig.Logger.Debug(fmt.Sprintf("Machine Type: %s", machineType)) 269 | 270 | userSubscription, err := utils.GetUserSubscription() 271 | if err != nil { 272 | return err 273 | } 274 | config.GlobalConfig.Logger.Debug(fmt.Sprintf("User subscription: %s", userSubscription)) 275 | 276 | ip := "Undefined" 277 | _ = ip 278 | switch { 279 | case machineType == "release": 280 | ip, err = utils.GetActiveReleaseArenaMachineIP() 281 | if err != nil { 282 | return err 283 | } 284 | case userSubscription == "vip+": 285 | ip, err = utils.GetActiveMachineIP() 286 | if err != nil { 287 | return err 288 | } 289 | default: 290 | ip = getIPStatus(data).(string) 291 | } 292 | 293 | bodyData := fmt.Sprintf("%v\t%v\t%v\t%v\t%v\t%v\t%v\t%v\t%v\n", 294 | data["name"], data["os"], retiredStatus, 295 | data["difficultyText"], data["stars"], 296 | ip, status, data["last_reset_time"], datetime) 297 | 298 | utils.SetTabWriterData(w, bodyData) 299 | w.Flush() 300 | return nil 301 | } 302 | 303 | func checkIfExpiringSoon(expiresTime string, machineID int) error { 304 | layout := "2006-01-02 15:04:05" 305 | 306 | date, err := time.Parse(layout, expiresTime) 307 | if err != nil { 308 | return fmt.Errorf("date conversion error: %v", err) 309 | } 310 | 311 | now := time.Now() 312 | config.GlobalConfig.Logger.Debug(fmt.Sprintf("Actual date: %v", now)) 313 | 314 | timeLeft := date.Sub(now) 315 | limit := 2 * time.Hour 316 | if timeLeft > 0 && timeLeft <= limit { 317 | var remainingTime string 318 | if date.After(now) { 319 | duration := date.Sub(now) 320 | hours := int(duration.Hours()) 321 | minutes := int(duration.Minutes()) % 60 322 | seconds := int(duration.Seconds()) % 60 323 | 324 | remainingTime = fmt.Sprintf("%dh %dm %ds", hours, minutes, seconds) 325 | 326 | } 327 | // Extend time 328 | isConfirmed := utils.AskConfirmation(fmt.Sprintf("Would you like to extend the active machine time ? Remaining: %s", remainingTime)) 329 | if isConfirmed { 330 | jsonData := []byte(fmt.Sprintf(`{"machine_id":%d}`, machineID)) 331 | resp, err := utils.HtbRequest(http.MethodPost, config.BaseHackTheBoxAPIURL+"/vm/extend", jsonData) 332 | if err != nil { 333 | return err 334 | } 335 | var response Response 336 | if err := json.NewDecoder(resp.Body).Decode(&response); err != nil { 337 | return fmt.Errorf("error decoding JSON response: %v", err) 338 | } 339 | 340 | inputLayout := "2006-01-02 15:04:05" 341 | 342 | date, err := time.Parse(inputLayout, response.ExpiresAt) 343 | if err != nil { 344 | return fmt.Errorf("error decoding JSON response: %v", err) 345 | } 346 | 347 | outputLayout := "2006-01-02 - 15h 04m 05s" 348 | 349 | formattedDate := date.Format(outputLayout) 350 | 351 | fmt.Println(response.Message) 352 | fmt.Printf("Expires Date: %s\n", formattedDate) 353 | 354 | } 355 | } 356 | return nil 357 | } 358 | 359 | // infoCmd is a Cobra command that serves as an entry point to display detailed information about machines. 360 | var infoCmd = &cobra.Command{ 361 | Use: "info", 362 | Short: "Detailed information on challenges and machines", 363 | Long: "Displays detailed information on machines and challenges in a structured table", 364 | Run: func(cmd *cobra.Command, args []string) { 365 | machineParam, err := cmd.Flags().GetStringSlice("machine") 366 | if err != nil { 367 | fmt.Println(err) 368 | return 369 | } 370 | 371 | challengeParam, err := cmd.Flags().GetStringSlice("challenge") 372 | if err != nil { 373 | fmt.Println(err) 374 | return 375 | } 376 | 377 | usernameParam, err := cmd.Flags().GetStringSlice("username") 378 | if err != nil { 379 | fmt.Println(err) 380 | return 381 | } 382 | err = coreInfoCmd(machineParam, challengeParam, usernameParam) 383 | if err != nil { 384 | config.GlobalConfig.Logger.Error("", zap.Error(err)) 385 | os.Exit(1) 386 | } 387 | }, 388 | } 389 | 390 | // init adds the info command to the root command and sets flags specific to this command. 391 | func init() { 392 | rootCmd.AddCommand(infoCmd) 393 | infoCmd.Flags().StringSliceP("machine", "m", []string{}, "Machine name") 394 | infoCmd.Flags().StringSliceP("challenge", "c", []string{}, "Challenge name") 395 | infoCmd.Flags().StringSliceP("username", "u", []string{}, "Username") 396 | } 397 | -------------------------------------------------------------------------------- /cmd/machines.go: -------------------------------------------------------------------------------- 1 | package cmd 2 | 3 | import ( 4 | "fmt" 5 | "net/http" 6 | "os" 7 | "time" 8 | 9 | "github.com/GoToolSharing/htb-cli/config" 10 | "github.com/GoToolSharing/htb-cli/lib/utils" 11 | "github.com/rivo/tview" 12 | "github.com/spf13/cobra" 13 | "go.uber.org/zap" 14 | ) 15 | 16 | const ( 17 | machineURL = config.BaseHackTheBoxAPIURL + "/machine/paginated/?per_page=20" 18 | retiredURL = config.BaseHackTheBoxAPIURL + "/machine/list/retired/paginated/?per_page=20&sort_by=release-date" 19 | scheduledURL = config.BaseHackTheBoxAPIURL + "/machine/unreleased/" 20 | activeTitle = "Active" 21 | retiredTitle = "Retired" 22 | scheduledTitle = "Scheduled" 23 | CheckMark = "\U00002705" 24 | CrossMark = "\U0000274C" 25 | Penguin = "\U0001F427" 26 | Computer = "\U0001F5A5 " 27 | ) 28 | 29 | // getColorFromDifficultyText returns the color corresponding to the given difficulty. 30 | func getColorFromDifficultyText(difficultyText string) string { 31 | switch difficultyText { 32 | case "Medium": 33 | return "[orange]" 34 | case "Easy": 35 | return "[green]" 36 | case "Hard": 37 | return "[red]" 38 | case "Insane": 39 | return "[purple]" 40 | default: 41 | return "[-]" 42 | } 43 | } 44 | 45 | // getOSEmoji returns an emoji corresponding to the given operating system 46 | func getOSEmoji(os string) string { 47 | switch os { 48 | case "Linux": 49 | return Penguin 50 | case "Windows": 51 | return Computer 52 | default: 53 | return "" 54 | } 55 | } 56 | 57 | // createFlex creates and returns a Flex view with machine information 58 | func createFlex(info interface{}, title string, isScheduled bool) (*tview.Flex, error) { 59 | flex := tview.NewFlex().SetDirection(tview.FlexRow) 60 | flex.SetBorder(true).SetTitle(title).SetTitleAlign(tview.AlignLeft) 61 | 62 | for _, value := range info.([]interface{}) { 63 | data := value.(map[string]interface{}) 64 | 65 | // Determining the color according to difficulty 66 | 67 | key := "Undefined" 68 | _ = key 69 | if title == "Scheduled" { 70 | key = data["difficulty_text"].(string) 71 | } else { 72 | key = data["difficultyText"].(string) 73 | } 74 | color := getColorFromDifficultyText(key) 75 | osEmoji := getOSEmoji(data["os"].(string)) 76 | 77 | var formatString string 78 | 79 | // Choice of display format depending on the nature of the information 80 | if isScheduled { 81 | formatString = fmt.Sprintf("%-10s %s%-10s %s%-10s[-]", 82 | data["name"], osEmoji, data["os"], color, data["difficulty_text"]) 83 | } else { 84 | // Convert and format date 85 | parsedDate, err := time.Parse(time.RFC3339Nano, data["release"].(string)) 86 | if err != nil { 87 | return nil, fmt.Errorf("error parsing date: %v", err) 88 | } 89 | formattedDate := parsedDate.Format("02 January 2006") 90 | 91 | userEmoji := CrossMark + "User" 92 | if value, ok := data["authUserInUserOwns"]; ok && value != nil { 93 | if value.(bool) { 94 | userEmoji = CheckMark + "User" 95 | } 96 | } 97 | 98 | rootEmoji := CrossMark + "Root" 99 | if value, ok := data["authUserInRootOwns"]; ok && value != nil { 100 | if value.(bool) { 101 | rootEmoji = CheckMark + "Root" 102 | } 103 | } 104 | 105 | formatString = fmt.Sprintf("%-15s %s%-10s %s%-10s[-] %-5v %-5v %-7v %-30s", 106 | data["name"], osEmoji, data["os"], color, data["difficultyText"], 107 | data["star"], userEmoji, rootEmoji, formattedDate) 108 | } 109 | 110 | flex.AddItem(tview.NewTextView().SetText(formatString).SetDynamicColors(true), 1, 0, false) 111 | } 112 | 113 | return flex, nil 114 | } 115 | 116 | var machinesCmd = &cobra.Command{ 117 | Use: "machines", 118 | Short: "Displays active / retired machines and next machines to be released", 119 | Run: func(cmd *cobra.Command, args []string) { 120 | app := tview.NewApplication() 121 | 122 | getAndDisplayFlex := func(url, title string, isScheduled bool, flex *tview.Flex) error { 123 | resp, err := utils.HtbRequest(http.MethodGet, url, nil) 124 | if err != nil { 125 | return fmt.Errorf("failed to get data from %s: %w", url, err) 126 | } 127 | 128 | info := utils.ParseJsonMessage(resp, "data") 129 | 130 | machineFlex, err := createFlex(info, title, isScheduled) 131 | if err != nil { 132 | return fmt.Errorf("failed to create flex for %s: %w", title, err) 133 | } 134 | 135 | flex.AddItem(machineFlex, 0, 1, false) 136 | return nil 137 | } 138 | 139 | leftFlex := tview.NewFlex().SetDirection(tview.FlexRow) 140 | rightFlex := tview.NewFlex().SetDirection(tview.FlexRow) 141 | 142 | if err := getAndDisplayFlex(machineURL, activeTitle, false, leftFlex); err != nil { 143 | config.GlobalConfig.Logger.Error("", zap.Error(err)) 144 | os.Exit(1) 145 | } 146 | 147 | if err := getAndDisplayFlex(retiredURL, retiredTitle, false, leftFlex); err != nil { 148 | config.GlobalConfig.Logger.Error("", zap.Error(err)) 149 | os.Exit(1) 150 | } 151 | 152 | if err := getAndDisplayFlex(scheduledURL, scheduledTitle, true, rightFlex); err != nil { 153 | config.GlobalConfig.Logger.Error("", zap.Error(err)) 154 | os.Exit(1) 155 | } 156 | 157 | rightFlex.AddItem(tview.NewTextView().SetText("").SetDynamicColors(true), 0, 0, false) 158 | 159 | mainFlex := tview.NewFlex().SetDirection(tview.FlexColumn). 160 | AddItem(leftFlex, 0, 3, false). 161 | AddItem(rightFlex, 0, 1, false) 162 | 163 | if err := app.SetRoot(mainFlex, true).Run(); err != nil { 164 | config.GlobalConfig.Logger.Error("", zap.Error(err)) 165 | os.Exit(1) 166 | } 167 | }, 168 | } 169 | 170 | func init() { 171 | rootCmd.AddCommand(machinesCmd) 172 | } 173 | -------------------------------------------------------------------------------- /cmd/pwnbox.go: -------------------------------------------------------------------------------- 1 | package cmd 2 | 3 | import ( 4 | "fmt" 5 | "net/http" 6 | "os" 7 | 8 | "github.com/GoToolSharing/htb-cli/config" 9 | "github.com/GoToolSharing/htb-cli/lib/utils" 10 | "github.com/GoToolSharing/htb-cli/lib/webhooks" 11 | "github.com/spf13/cobra" 12 | "go.uber.org/zap" 13 | ) 14 | 15 | func doAction(mode string) { 16 | } 17 | 18 | var pwnboxCmd = &cobra.Command{ 19 | Use: "pwnbox", 20 | Short: "Interact with the pwnbox", 21 | Run: func(cmd *cobra.Command, args []string) { 22 | modeFlag, err := cmd.Flags().GetString("mode") 23 | if err != nil { 24 | fmt.Println(err) 25 | return 26 | } 27 | 28 | if modeFlag == "" { 29 | fmt.Println("You have to choose a mode to use the pwnbox (-m)") 30 | return 31 | } 32 | 33 | locationFlag, err := cmd.Flags().GetString("location") 34 | if err != nil { 35 | fmt.Println(err) 36 | return 37 | } 38 | 39 | _ = locationFlag 40 | 41 | startFlag, err := cmd.Flags().GetBool("start") 42 | if err != nil { 43 | fmt.Println(err) 44 | return 45 | } 46 | 47 | // _ = startFlag 48 | 49 | stopFlag, err := cmd.Flags().GetBool("stop") 50 | if err != nil { 51 | fmt.Println(err) 52 | return 53 | } 54 | 55 | if !startFlag && !stopFlag { 56 | fmt.Println("Wrong action supplied : --start / --stop") 57 | return 58 | } 59 | 60 | // Check subscription 61 | config.GlobalConfig.Logger.Debug(fmt.Sprintf("Mode: %s", modeFlag)) 62 | 63 | if startFlag { 64 | fmt.Println("Sorry, but HackTheBox currently uses a v3 recaptcha to start a pwnbox.") 65 | return 66 | } 67 | // Start and stop 68 | if stopFlag { 69 | resp, err := utils.HtbRequest(http.MethodPost, config.BaseHackTheBoxAPIURL+"/pwnbox/terminate", nil) 70 | if err != nil { 71 | fmt.Println(resp) 72 | return 73 | } 74 | message, ok := utils.ParseJsonMessage(resp, "message").(string) 75 | if !ok { 76 | fmt.Println("unexpected response format") 77 | return 78 | } 79 | fmt.Println(message) 80 | 81 | err = webhooks.SendToDiscord("pwnbox", message) 82 | if err != nil { 83 | config.GlobalConfig.Logger.Error("", zap.Error(err)) 84 | os.Exit(1) 85 | } 86 | return 87 | } 88 | 89 | switch modeFlag { 90 | case "machines": 91 | fmt.Println("Machines") 92 | doAction("machines") 93 | return 94 | case "sp": 95 | fmt.Println("Starting Points") 96 | doAction("sp") 97 | return 98 | case "fortresses": 99 | fmt.Println("Fortresses") 100 | doAction("fortresses") 101 | return 102 | case "prolabs": 103 | fmt.Println("Prolabs") 104 | doAction("prolabs") 105 | return 106 | case "seasonals": 107 | fmt.Println("Seasonals") 108 | doAction("seasonals") 109 | return 110 | default: 111 | fmt.Println("Available modes : machines - sp - fortresses - prolabs - seasonals") 112 | return 113 | } 114 | }, 115 | } 116 | 117 | func init() { 118 | rootCmd.AddCommand(pwnboxCmd) 119 | pwnboxCmd.Flags().StringP("location", "l", "", "Pwnbox Location") 120 | pwnboxCmd.Flags().BoolP("start", "", false, "Start pwnbox") 121 | pwnboxCmd.Flags().BoolP("stop", "", false, "Stop active pwnbox") 122 | pwnboxCmd.Flags().StringP("mode", "m", "", "Select mode") // TODO: Choice list 123 | } 124 | -------------------------------------------------------------------------------- /cmd/reset.go: -------------------------------------------------------------------------------- 1 | package cmd 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | "net/http" 7 | "os" 8 | 9 | "github.com/GoToolSharing/htb-cli/config" 10 | "github.com/GoToolSharing/htb-cli/lib/utils" 11 | "github.com/GoToolSharing/htb-cli/lib/webhooks" 12 | "github.com/spf13/cobra" 13 | "go.uber.org/zap" 14 | ) 15 | 16 | // coreResetCmd sends a reset request for an active machine. 17 | func coreResetCmd() (string, error) { 18 | // Retrieve the ID of the active machine. 19 | machineID, err := utils.GetActiveMachineID() 20 | if err != nil { 21 | return "", err 22 | } 23 | if machineID == 0 { 24 | return "No active machine found", nil 25 | } 26 | config.GlobalConfig.Logger.Debug(fmt.Sprintf("Machine ID: %d", machineID)) 27 | 28 | // Retrieve the type of the machine. 29 | machineType, err := utils.GetMachineType(machineID) 30 | if err != nil { 31 | return "", err 32 | } 33 | config.GlobalConfig.Logger.Debug(fmt.Sprintf("Machine Type: %s", machineType)) 34 | 35 | // Determine the API endpoint and construct JSON data based on the machine type. 36 | var endpoint string 37 | switch machineType { 38 | case "active": 39 | endpoint = "/vm/reset" 40 | default: 41 | endpoint = "/arena/reset" 42 | } 43 | url := config.BaseHackTheBoxAPIURL + endpoint 44 | 45 | // Construct JSON data. 46 | jsonData, err := json.Marshal(map[string]interface{}{"machine_id": machineID}) 47 | if err != nil { 48 | return "", fmt.Errorf("failed to create JSON data: %w", err) 49 | } 50 | 51 | // Send an HTTP request to reset the machine. 52 | resp, err := utils.HtbRequest(http.MethodPost, url, jsonData) 53 | if err != nil { 54 | return "", err 55 | } 56 | 57 | // Parse and return the message from the response. 58 | message, ok := utils.ParseJsonMessage(resp, "message").(string) 59 | if !ok { 60 | return "", fmt.Errorf("unexpected response format") 61 | } 62 | return message, nil 63 | } 64 | 65 | // resetCmd defines the "reset" command, which allows the user to reset a machine. 66 | var resetCmd = &cobra.Command{ 67 | Use: "reset", 68 | Short: "Reset a machine", 69 | Long: "Initiates a reset request for the selected machine.", 70 | Run: func(cmd *cobra.Command, args []string) { 71 | // Execute the core reset function and handle the results. 72 | output, err := coreResetCmd() 73 | if err != nil { 74 | config.GlobalConfig.Logger.Error("", zap.Error(err)) 75 | os.Exit(1) 76 | } 77 | fmt.Println(output) 78 | err = webhooks.SendToDiscord("reset", output) 79 | if err != nil { 80 | config.GlobalConfig.Logger.Error("", zap.Error(err)) 81 | os.Exit(1) 82 | } 83 | }, 84 | } 85 | 86 | // init adds the resetCmd to rootCmd, making it callable. 87 | func init() { 88 | rootCmd.AddCommand(resetCmd) 89 | } 90 | -------------------------------------------------------------------------------- /cmd/root.go: -------------------------------------------------------------------------------- 1 | package cmd 2 | 3 | import ( 4 | "fmt" 5 | "os" 6 | "strings" 7 | 8 | "github.com/GoToolSharing/htb-cli/config" 9 | "github.com/GoToolSharing/htb-cli/lib/update" 10 | "github.com/spf13/cobra" 11 | "go.uber.org/zap" 12 | ) 13 | 14 | var rootCmd = &cobra.Command{ 15 | Use: "htb-cli", 16 | Short: "CLI enhancing the HackTheBox user experience.", 17 | Long: `This software, engineered using the Go programming language, serves to streamline and automate various tasks for the HackTheBox platform, enhancing user efficiency and productivity.`, 18 | PersistentPreRun: func(cmd *cobra.Command, args []string) { 19 | err := config.ConfigureLogger() 20 | if err != nil { 21 | config.GlobalConfig.Logger.Error("", zap.Error(err)) 22 | os.Exit(1) 23 | } 24 | config.GlobalConfig.Logger.Debug(fmt.Sprintf("Verbosity level : %v", config.GlobalConfig.Verbose)) 25 | err = config.Init() 26 | if err != nil { 27 | config.GlobalConfig.Logger.Error("", zap.Error(err)) 28 | os.Exit(1) 29 | } 30 | config.GlobalConfig.Logger.Debug(fmt.Sprintf("Check for updates : %v", config.GlobalConfig.NoCheck)) 31 | if !config.GlobalConfig.NoCheck { 32 | message, err := update.Check(config.Version) 33 | if err != nil { 34 | config.GlobalConfig.Logger.Error("", zap.Error(err)) 35 | os.Exit(1) 36 | } 37 | config.GlobalConfig.Logger.Debug(fmt.Sprintf("Message : %s", message)) 38 | if strings.Contains(message, "A new update") { 39 | fmt.Printf("%s\n\n", message) 40 | } 41 | } 42 | }, 43 | } 44 | 45 | func Execute() { 46 | err := rootCmd.Execute() 47 | if err != nil { 48 | fmt.Println(err) 49 | os.Exit(1) 50 | } 51 | } 52 | 53 | func init() { 54 | rootCmd.CompletionOptions.DisableDefaultCmd = true 55 | rootCmd.PersistentFlags().CountVarP(&config.GlobalConfig.Verbose, "verbose", "v", "Verbose level") 56 | rootCmd.PersistentFlags().StringVarP(&config.GlobalConfig.ProxyParam, "proxy", "", "", "Configure a URL for an HTTP proxy") 57 | rootCmd.PersistentFlags().BoolVarP(&config.GlobalConfig.BatchParam, "batch", "b", false, "Don't ask questions") 58 | rootCmd.PersistentFlags().BoolVarP(&config.GlobalConfig.NoCheck, "no-check", "n", false, "Don't check for new updates") 59 | } 60 | -------------------------------------------------------------------------------- /cmd/sherlocks.go: -------------------------------------------------------------------------------- 1 | package cmd 2 | 3 | import ( 4 | "fmt" 5 | "net/http" 6 | "os" 7 | 8 | "github.com/GoToolSharing/htb-cli/config" 9 | "github.com/GoToolSharing/htb-cli/lib/sherlocks" 10 | "github.com/GoToolSharing/htb-cli/lib/utils" 11 | "github.com/rivo/tview" 12 | "github.com/spf13/cobra" 13 | "go.uber.org/zap" 14 | ) 15 | 16 | var sherlocksCmd = &cobra.Command{ 17 | Use: "sherlocks", 18 | Short: "Play Sherlocks mode (blue team)", 19 | Run: func(cmd *cobra.Command, args []string) { 20 | sherlockNameParam, err := cmd.Flags().GetString("sherlock_name") 21 | if err != nil { 22 | fmt.Println(err) 23 | return 24 | } 25 | 26 | sherlockDownloadPath, err := cmd.Flags().GetString("download") 27 | if err != nil { 28 | fmt.Println(err) 29 | return 30 | } 31 | 32 | sherlockTaskID, err := cmd.Flags().GetInt("task") 33 | if err != nil { 34 | fmt.Println(err) 35 | return 36 | } 37 | 38 | sherlockHint, err := cmd.Flags().GetBool("hint") 39 | if err != nil { 40 | fmt.Println(err) 41 | return 42 | } 43 | 44 | if sherlockNameParam != "" { 45 | sherlockID, err := sherlocks.SearchIDByName(sherlockNameParam) 46 | if err != nil { 47 | fmt.Println(err) 48 | return 49 | } 50 | config.GlobalConfig.Logger.Debug(fmt.Sprintf("SherlockID: %s", sherlockID)) 51 | 52 | if sherlockTaskID != 0 { 53 | err := sherlocks.GetTaskByID(sherlockID, sherlockTaskID, sherlockHint) 54 | if err != nil { 55 | fmt.Println(err) 56 | return 57 | } 58 | return 59 | } 60 | 61 | err = sherlocks.GetGeneralInformations(sherlockID, sherlockDownloadPath) 62 | 63 | if err != nil { 64 | fmt.Println(err) 65 | return 66 | } 67 | 68 | data, err := sherlocks.GetTasks(sherlockID) 69 | if err != nil { 70 | fmt.Println(err) 71 | return 72 | } 73 | for _, task := range data.Tasks { 74 | if task.Completed { 75 | fmt.Printf("\n%s (DONE) :\n%s\n\n", task.Title, task.Description) 76 | } else { 77 | fmt.Printf("\n%s :\n%s\n\n", task.Title, task.Description) 78 | } 79 | } 80 | return 81 | } 82 | app := tview.NewApplication() 83 | 84 | getAndDisplayFlex := func(url, title string, isScheduled bool, flex *tview.Flex) error { 85 | resp, err := utils.HtbRequest(http.MethodGet, url, nil) 86 | if err != nil { 87 | return fmt.Errorf("failed to get data from %s: %w", url, err) 88 | } 89 | 90 | info := utils.ParseJsonMessage(resp, "data") 91 | 92 | machineFlex, err := sherlocks.CreateFlex(info, title, isScheduled) 93 | if err != nil { 94 | return fmt.Errorf("failed to create flex for %s: %w", title, err) 95 | } 96 | 97 | flex.AddItem(machineFlex, 0, 1, false) 98 | return nil 99 | } 100 | 101 | leftFlex := tview.NewFlex().SetDirection(tview.FlexRow) 102 | rightFlex := tview.NewFlex().SetDirection(tview.FlexRow) 103 | 104 | if err := getAndDisplayFlex(sherlocks.SherlocksURL, sherlocks.ActiveSherlocksTitle, false, leftFlex); err != nil { 105 | config.GlobalConfig.Logger.Error("", zap.Error(err)) 106 | os.Exit(1) 107 | } 108 | 109 | if err := getAndDisplayFlex(sherlocks.RetiredSherlocksURL, sherlocks.RetiredSherlocksTitle, false, leftFlex); err != nil { 110 | config.GlobalConfig.Logger.Error("", zap.Error(err)) 111 | os.Exit(1) 112 | } 113 | 114 | if err := getAndDisplayFlex(sherlocks.ScheduledSherlocksURL, sherlocks.ScheduledSherlocksTitle, true, rightFlex); err != nil { 115 | config.GlobalConfig.Logger.Error("", zap.Error(err)) 116 | os.Exit(1) 117 | } 118 | 119 | rightFlex.AddItem(tview.NewTextView().SetText("").SetDynamicColors(true), 0, 0, false) 120 | 121 | mainFlex := tview.NewFlex().SetDirection(tview.FlexColumn). 122 | AddItem(leftFlex, 0, 3, false). 123 | AddItem(rightFlex, 0, 1, false) 124 | 125 | if err := app.SetRoot(mainFlex, true).Run(); err != nil { 126 | config.GlobalConfig.Logger.Error("", zap.Error(err)) 127 | os.Exit(1) 128 | } 129 | 130 | }, 131 | } 132 | 133 | func init() { 134 | rootCmd.AddCommand(sherlocksCmd) 135 | sherlocksCmd.Flags().StringP("sherlock_name", "s", "", "Sherlock Name") 136 | sherlocksCmd.Flags().StringP("download", "d", "", "Download Sherlock Resources") 137 | sherlocksCmd.Flags().IntP("task", "t", 0, "Task ID") 138 | sherlocksCmd.Flags().BoolP("hint", "", false, "Hint") 139 | } 140 | -------------------------------------------------------------------------------- /cmd/shoutbox.go: -------------------------------------------------------------------------------- 1 | package cmd 2 | 3 | import ( 4 | "fmt" 5 | 6 | "github.com/GoToolSharing/htb-cli/config" 7 | "github.com/spf13/cobra" 8 | ) 9 | 10 | var shoutboxCmd = &cobra.Command{ 11 | Use: "shoutbox", 12 | Short: "Displays shoutbox information in real time", 13 | Run: func(cmd *cobra.Command, args []string) { 14 | config.GlobalConfig.Logger.Info("Shoutbox command executed") 15 | fmt.Println("DEPRECATED: HackTheBox no longer uses the shoutbox. A similar alternative is coming soon !") 16 | /*err := shoutbox.ConnectToWebSocket() 17 | if err != nil { 18 | config.GlobalConfig.Logger.Error("", zap.Error(err)) 19 | os.Exit(1) 20 | }*/ 21 | config.GlobalConfig.Logger.Info("Exit shoutbox command correctly") 22 | }, 23 | } 24 | 25 | func init() { 26 | rootCmd.AddCommand(shoutboxCmd) 27 | } 28 | -------------------------------------------------------------------------------- /cmd/start.go: -------------------------------------------------------------------------------- 1 | package cmd 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | "net/http" 7 | "os" 8 | "os/signal" 9 | "strings" 10 | "syscall" 11 | "time" 12 | 13 | "github.com/GoToolSharing/htb-cli/config" 14 | "github.com/GoToolSharing/htb-cli/lib/utils" 15 | "github.com/GoToolSharing/htb-cli/lib/webhooks" 16 | "github.com/briandowns/spinner" 17 | "github.com/spf13/cobra" 18 | "go.uber.org/zap" 19 | ) 20 | 21 | // setupSignalHandler configures a signal handler to stop the spinner and gracefully exit upon receiving specific signals. 22 | func setupSignalHandler(s *spinner.Spinner) { 23 | sigs := make(chan os.Signal, 1) 24 | signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM) 25 | go func() { 26 | <-sigs 27 | s.Stop() 28 | os.Exit(0) 29 | }() 30 | } 31 | 32 | // coreStartCmd starts a specified machine and returns a status message and any error encountered. 33 | func coreStartCmd(machineChoosen string, machineID int) (string, error) { 34 | var err error 35 | if machineID == 0 { 36 | machineID, err = utils.SearchItemIDByName(machineChoosen, "Machine") 37 | if err != nil { 38 | return "", err 39 | } 40 | 41 | } 42 | config.GlobalConfig.Logger.Info(fmt.Sprintf("Machine ID: %d", machineID)) 43 | 44 | machineTypeChan := make(chan string) 45 | machineErrChan := make(chan error) 46 | userSubChan := make(chan string) 47 | userSubErrChan := make(chan error) 48 | 49 | go func() { 50 | machineType, err := utils.GetMachineType(machineID) 51 | machineTypeChan <- machineType 52 | machineErrChan <- err 53 | }() 54 | 55 | go func() { 56 | userSubscription, err := utils.GetUserSubscription() 57 | userSubChan <- userSubscription 58 | userSubErrChan <- err 59 | }() 60 | 61 | machineType := <-machineTypeChan 62 | err = <-machineErrChan 63 | if err != nil { 64 | return "", err 65 | } 66 | config.GlobalConfig.Logger.Info(fmt.Sprintf("Machine Type: %s", machineType)) 67 | 68 | userSubscription := <-userSubChan 69 | err = <-userSubErrChan 70 | if err != nil { 71 | return "", err 72 | } 73 | 74 | config.GlobalConfig.Logger.Info(fmt.Sprintf("User subscription: %s", userSubscription)) 75 | 76 | // isActive := utils.CheckVPN() 77 | // if !isActive { 78 | // isConfirmed := utils.AskConfirmation("No active VPN has been detected. Would you like to start it ?", batchParam) 79 | // if isConfirmed { 80 | // utils.StartVPN(config.BaseDirectory + "/lab_QU35T3190.ovpn") 81 | // } 82 | // } 83 | 84 | var url string 85 | var jsonData []byte 86 | 87 | switch { 88 | case machineType == "release": 89 | url = config.BaseHackTheBoxAPIURL + "/arena/start" 90 | jsonData = []byte("{}") 91 | case userSubscription == "vip" || userSubscription == "vip+": 92 | url = config.BaseHackTheBoxAPIURL + "/vm/spawn" 93 | jsonData, err = json.Marshal(map[string]interface{}{"machine_id": machineID}) 94 | if err != nil { 95 | return "", fmt.Errorf("failed to create JSON data: %w", err) 96 | } 97 | default: 98 | url = config.BaseHackTheBoxAPIURL + fmt.Sprintf("%s%d", "/machine/play/", machineID) 99 | jsonData = []byte("{}") 100 | } 101 | 102 | resp, err := utils.HtbRequest(http.MethodPost, url, jsonData) 103 | if err != nil { 104 | return "", err 105 | } 106 | 107 | message, ok := utils.ParseJsonMessage(resp, "message").(string) 108 | if !ok { 109 | return "", fmt.Errorf("unexpected response format") 110 | } 111 | 112 | if strings.Contains(message, "You must stop") { 113 | return message, nil 114 | } 115 | 116 | ip := "Undefined" 117 | startTime := time.Now() 118 | switch { 119 | case machineType == "release": 120 | s := spinner.New(spinner.CharSets[14], 100*time.Millisecond) 121 | setupSignalHandler(s) 122 | s.Suffix = " Waiting for the machine to start in order to fetch the IP address (this might take a while)." 123 | s.Start() 124 | defer s.Stop() 125 | timeout := time.After(10 * time.Minute) 126 | LoopRelease: 127 | for { 128 | select { 129 | case <-timeout: 130 | fmt.Println("Timeout (10 min) ! Exiting") 131 | s.Stop() 132 | return "", nil 133 | default: 134 | ip, err = utils.GetActiveReleaseArenaMachineIP() 135 | if err != nil { 136 | return "", err 137 | } 138 | if ip != "Undefined" { 139 | s.Stop() 140 | break LoopRelease 141 | } 142 | time.Sleep(3 * time.Second) 143 | } 144 | } 145 | case userSubscription == "vip+": 146 | s := spinner.New(spinner.CharSets[14], 100*time.Millisecond) 147 | setupSignalHandler(s) 148 | s.Suffix = " Waiting for the machine to start in order to fetch the IP address (this might take a while)." 149 | s.Start() 150 | defer s.Stop() 151 | timeout := time.After(10 * time.Minute) 152 | Loop: 153 | for { 154 | select { 155 | case <-timeout: 156 | fmt.Println("Timeout (10 min) ! Exiting") 157 | s.Stop() 158 | return "", nil 159 | default: 160 | ip, err = utils.GetActiveMachineIP() 161 | if err != nil { 162 | return "", err 163 | } 164 | if ip != "Undefined" { 165 | s.Stop() 166 | break Loop 167 | } 168 | time.Sleep(3 * time.Second) 169 | } 170 | } 171 | default: 172 | // Get IP address from active machine 173 | activeMachineData, err := utils.GetInformationsFromActiveMachine() 174 | if err != nil { 175 | return "", err 176 | } 177 | ip = activeMachineData["ip"].(string) 178 | } 179 | tts := time.Since(startTime) 180 | formattedTts := fmt.Sprintf("%.2f", tts.Seconds()) 181 | message = fmt.Sprintf("%s\nTarget: %s\nTime to spawn was %s seconds !", message, ip, formattedTts) 182 | return message, nil 183 | } 184 | 185 | // startCmd defines the "start" command which initiates the starting of a specified machine. 186 | var startCmd = &cobra.Command{ 187 | Use: "start", 188 | Short: "Start a machine", 189 | Long: `Starts a Hackthebox machine specified in argument`, 190 | Run: func(cmd *cobra.Command, args []string) { 191 | config.GlobalConfig.Logger.Info("Start command executed") 192 | machineChoosen, err := cmd.Flags().GetString("machine") 193 | if err != nil { 194 | config.GlobalConfig.Logger.Error("", zap.Error(err)) 195 | os.Exit(1) 196 | } 197 | var machineID int 198 | if machineChoosen == "" { 199 | config.GlobalConfig.Logger.Info("Launching the machine in release arena") 200 | machineID, err = utils.SearchLastReleaseArenaMachine() 201 | 202 | if err != nil { 203 | config.GlobalConfig.Logger.Error("", zap.Error(err)) 204 | os.Exit(1) 205 | } 206 | config.GlobalConfig.Logger.Debug(fmt.Sprintf("Machine ID : %d", machineID)) 207 | 208 | } 209 | output, err := coreStartCmd(machineChoosen, machineID) 210 | if err != nil { 211 | config.GlobalConfig.Logger.Error("", zap.Error(err)) 212 | os.Exit(1) 213 | } 214 | fmt.Println(output) 215 | err = webhooks.SendToDiscord("start", output) 216 | if err != nil { 217 | config.GlobalConfig.Logger.Error("", zap.Error(err)) 218 | os.Exit(1) 219 | } 220 | config.GlobalConfig.Logger.Info("Exit start command correctly") 221 | }, 222 | } 223 | 224 | // init adds the startCmd to rootCmd and sets flags for the "start" command. 225 | func init() { 226 | rootCmd.AddCommand(startCmd) 227 | startCmd.Flags().StringP("machine", "m", "", "Machine name") 228 | } 229 | -------------------------------------------------------------------------------- /cmd/stop.go: -------------------------------------------------------------------------------- 1 | package cmd 2 | 3 | import ( 4 | "fmt" 5 | "net/http" 6 | "os" 7 | 8 | "github.com/GoToolSharing/htb-cli/config" 9 | "github.com/GoToolSharing/htb-cli/lib/utils" 10 | "github.com/GoToolSharing/htb-cli/lib/webhooks" 11 | "github.com/spf13/cobra" 12 | "go.uber.org/zap" 13 | ) 14 | 15 | var ( 16 | releaseAPI = fmt.Sprintf("%s/arena/stop", config.BaseHackTheBoxAPIURL) 17 | vipAPI = fmt.Sprintf("%s/vm/terminate", config.BaseHackTheBoxAPIURL) 18 | defaultAPI = fmt.Sprintf("%s/machine/stop", config.BaseHackTheBoxAPIURL) 19 | ) 20 | 21 | // buildMachineStopRequest constructs the URL endpoint and JSON data payload for stopping a machine based on its type and user's subscription. 22 | func buildMachineStopRequest(machineType string, userSubscription string, machineID int) (string, []byte) { 23 | var apiEndpoint string 24 | var jsonData []byte 25 | 26 | if machineType == "release" { 27 | return releaseAPI, []byte(`{}`) 28 | } 29 | 30 | switch userSubscription { 31 | case "vip", "vip+": 32 | apiEndpoint = vipAPI 33 | default: 34 | apiEndpoint = defaultAPI 35 | } 36 | 37 | jsonData = []byte(fmt.Sprintf(`{"machine_id": "%d"}`, machineID)) 38 | return apiEndpoint, jsonData 39 | } 40 | 41 | // coreStopCmd stops the currently active machine. 42 | // It fetches machine's ID, its type, and user's subscription to determine how to stop the machine. 43 | func coreStopCmd() (string, error) { 44 | // err := utils.StopVPN() 45 | // if err != nil { 46 | // return "", err 47 | // } 48 | machineID, err := utils.GetActiveMachineID() 49 | if err != nil { 50 | return "", err 51 | } 52 | if machineID == 0 { 53 | return "No machine is running", nil 54 | } 55 | config.GlobalConfig.Logger.Debug(fmt.Sprintf("Machine ID: %d", machineID)) 56 | 57 | machineTypeChan := make(chan string) 58 | machineErrChan := make(chan error) 59 | userSubChan := make(chan string) 60 | userSubErrChan := make(chan error) 61 | 62 | go func() { 63 | machineType, err := utils.GetMachineType(machineID) 64 | machineTypeChan <- machineType 65 | machineErrChan <- err 66 | }() 67 | 68 | go func() { 69 | userSubscription, err := utils.GetUserSubscription() 70 | userSubChan <- userSubscription 71 | userSubErrChan <- err 72 | }() 73 | 74 | machineType := <-machineTypeChan 75 | err = <-machineErrChan 76 | if err != nil { 77 | return "", err 78 | } 79 | config.GlobalConfig.Logger.Info(fmt.Sprintf("Machine Type: %s", machineType)) 80 | 81 | userSubscription := <-userSubChan 82 | err = <-userSubErrChan 83 | if err != nil { 84 | return "", err 85 | } 86 | 87 | config.GlobalConfig.Logger.Info(fmt.Sprintf("User subscription: %s", userSubscription)) 88 | 89 | apiEndpoint, jsonData := buildMachineStopRequest(machineType, userSubscription, machineID) 90 | resp, err := utils.HtbRequest(http.MethodPost, apiEndpoint, jsonData) 91 | if err != nil { 92 | return "", err 93 | } 94 | 95 | message, ok := utils.ParseJsonMessage(resp, "message").(string) 96 | if !ok { 97 | return "", fmt.Errorf("error parsing message from response") 98 | } 99 | 100 | // err = utils.StopVPN() 101 | // if err != nil { 102 | // return "", err 103 | // } 104 | 105 | return message, nil 106 | } 107 | 108 | var stopCmd = &cobra.Command{ 109 | Use: "stop", 110 | Short: "Stop the current machine", 111 | Run: func(cmd *cobra.Command, args []string) { 112 | config.GlobalConfig.Logger.Info("Stop command executed") 113 | output, err := coreStopCmd() 114 | if err != nil { 115 | config.GlobalConfig.Logger.Error("", zap.Error(err)) 116 | os.Exit(1) 117 | } 118 | 119 | fmt.Println(output) 120 | 121 | err = webhooks.SendToDiscord("stop", output) 122 | if err != nil { 123 | config.GlobalConfig.Logger.Error("", zap.Error(err)) 124 | os.Exit(1) 125 | } 126 | config.GlobalConfig.Logger.Info("Exit stop command correctly") 127 | }, 128 | } 129 | 130 | func init() { 131 | rootCmd.AddCommand(stopCmd) 132 | } 133 | -------------------------------------------------------------------------------- /cmd/submit.go: -------------------------------------------------------------------------------- 1 | package cmd 2 | 3 | import ( 4 | "fmt" 5 | "os" 6 | 7 | "github.com/GoToolSharing/htb-cli/config" 8 | "github.com/GoToolSharing/htb-cli/lib/submit" 9 | "github.com/GoToolSharing/htb-cli/lib/webhooks" 10 | "github.com/spf13/cobra" 11 | "go.uber.org/zap" 12 | ) 13 | 14 | var submitCmd = &cobra.Command{ 15 | Use: "submit", 16 | Short: "Submit credentials (machines / challenges / release arena)", 17 | Long: "This command allows for the submission of user and root flags discovered on vulnerable machines / challenges", 18 | Run: func(cmd *cobra.Command, args []string) { 19 | config.GlobalConfig.Logger.Info("Submit command executed") 20 | difficultyParam, err := cmd.Flags().GetInt("difficulty") 21 | if err != nil { 22 | config.GlobalConfig.Logger.Error("", zap.Error(err)) 23 | os.Exit(1) 24 | } 25 | 26 | machineNameParam, err := cmd.Flags().GetString("machine") 27 | if err != nil { 28 | config.GlobalConfig.Logger.Error("", zap.Error(err)) 29 | os.Exit(1) 30 | } 31 | 32 | challengeNameParam, err := cmd.Flags().GetString("challenge") 33 | if err != nil { 34 | config.GlobalConfig.Logger.Error("", zap.Error(err)) 35 | os.Exit(1) 36 | } 37 | 38 | fortressNameParam, err := cmd.Flags().GetString("fortress") 39 | if err != nil { 40 | config.GlobalConfig.Logger.Error("", zap.Error(err)) 41 | os.Exit(1) 42 | } 43 | 44 | prolabNameParam, err := cmd.Flags().GetString("prolab") 45 | if err != nil { 46 | config.GlobalConfig.Logger.Error("", zap.Error(err)) 47 | os.Exit(1) 48 | } 49 | 50 | if challengeNameParam != "" { 51 | if difficultyParam == 0 { 52 | fmt.Println("required flag(s) 'difficulty' not set") 53 | os.Exit(1) 54 | } 55 | } 56 | 57 | var modeType string 58 | var modeValue string 59 | 60 | if fortressNameParam != "" { 61 | modeType = "fortress" 62 | modeValue = fortressNameParam 63 | } else if machineNameParam != "" { 64 | modeType = "machine" 65 | modeValue = machineNameParam 66 | } else if challengeNameParam != "" { 67 | modeType = "challenge" 68 | modeValue = challengeNameParam 69 | } else if prolabNameParam != "" { 70 | modeType = "prolab" 71 | modeValue = prolabNameParam 72 | } else { 73 | modeType = "release-arena" 74 | modeValue = "" 75 | } 76 | 77 | config.GlobalConfig.Logger.Debug(fmt.Sprintf("Mode type: %s", modeType)) 78 | config.GlobalConfig.Logger.Debug(fmt.Sprintf("Mode value: %s", modeValue)) 79 | 80 | output, machineID, err := submit.CoreSubmitCmd(difficultyParam, modeType, modeValue) 81 | if err != nil { 82 | config.GlobalConfig.Logger.Error("", zap.Error(err)) 83 | os.Exit(1) 84 | } 85 | 86 | fmt.Println(output) 87 | 88 | link, err := submit.GetAchievementLink(machineID) 89 | if err != nil { 90 | config.GlobalConfig.Logger.Error("", zap.Error(err)) 91 | os.Exit(1) 92 | } 93 | 94 | fmt.Println(link) 95 | 96 | err = webhooks.SendToDiscord("submit", output) 97 | if err != nil { 98 | config.GlobalConfig.Logger.Error("", zap.Error(err)) 99 | os.Exit(1) 100 | } 101 | config.GlobalConfig.Logger.Info("Exit submit command correctly") 102 | }, 103 | } 104 | 105 | func init() { 106 | rootCmd.AddCommand(submitCmd) 107 | submitCmd.Flags().StringP("machine", "m", "", "Machine Name") 108 | submitCmd.Flags().StringP("challenge", "c", "", "Challenge Name") 109 | submitCmd.Flags().StringP("fortress", "f", "", "Fortress Name") 110 | submitCmd.Flags().StringP("prolab", "p", "", "Prolab Name") 111 | submitCmd.Flags().IntP("difficulty", "d", 0, "Difficulty") 112 | } 113 | -------------------------------------------------------------------------------- /cmd/update.go: -------------------------------------------------------------------------------- 1 | package cmd 2 | 3 | import ( 4 | "fmt" 5 | "os" 6 | 7 | "github.com/GoToolSharing/htb-cli/config" 8 | "github.com/GoToolSharing/htb-cli/lib/update" 9 | "github.com/GoToolSharing/htb-cli/lib/webhooks" 10 | "github.com/spf13/cobra" 11 | "go.uber.org/zap" 12 | ) 13 | 14 | // Check if an update is available for htb-cli 15 | var updateCmd = &cobra.Command{ 16 | Use: "update", 17 | Short: "Check if updates are available", 18 | Run: func(cmd *cobra.Command, args []string) { 19 | config.GlobalConfig.Logger.Info("Update command executed") 20 | message, err := update.Check(config.Version) 21 | if err != nil { 22 | config.GlobalConfig.Logger.Error("", zap.Error(err)) 23 | os.Exit(1) 24 | } 25 | fmt.Println(message) 26 | 27 | err = webhooks.SendToDiscord("update", message) 28 | if err != nil { 29 | config.GlobalConfig.Logger.Error("", zap.Error(err)) 30 | os.Exit(1) 31 | } 32 | 33 | config.GlobalConfig.Logger.Info("Exit update command correctly") 34 | }, 35 | } 36 | 37 | func init() { 38 | rootCmd.AddCommand(updateCmd) 39 | } 40 | -------------------------------------------------------------------------------- /cmd/version.go: -------------------------------------------------------------------------------- 1 | package cmd 2 | 3 | import ( 4 | "fmt" 5 | "os" 6 | 7 | "github.com/GoToolSharing/htb-cli/config" 8 | "github.com/GoToolSharing/htb-cli/lib/webhooks" 9 | "github.com/spf13/cobra" 10 | "go.uber.org/zap" 11 | ) 12 | 13 | // Displays the current version of htb-cli 14 | var versionCmd = &cobra.Command{ 15 | Use: "version", 16 | Short: "Displays the current version of htb-cli", 17 | Run: func(cmd *cobra.Command, args []string) { 18 | config.GlobalConfig.Logger.Info("Version command executed") 19 | config.GlobalConfig.Logger.Debug(fmt.Sprintf("config.Version: %s", config.Version)) 20 | var message string 21 | if config.Version == "dev" { 22 | message = "Development version (dev branch)" 23 | } else { 24 | message = fmt.Sprintf("Stable version (main branch): %s", config.Version) 25 | } 26 | 27 | fmt.Println(message) 28 | err := webhooks.SendToDiscord("version", message) 29 | if err != nil { 30 | config.GlobalConfig.Logger.Error("", zap.Error(err)) 31 | os.Exit(1) 32 | } 33 | 34 | config.GlobalConfig.Logger.Info("Exit version command correctly") 35 | }, 36 | } 37 | 38 | func init() { 39 | rootCmd.AddCommand(versionCmd) 40 | } 41 | -------------------------------------------------------------------------------- /cmd/vpn.go: -------------------------------------------------------------------------------- 1 | package cmd 2 | 3 | import ( 4 | "fmt" 5 | "os" 6 | 7 | "github.com/GoToolSharing/htb-cli/config" 8 | "github.com/GoToolSharing/htb-cli/lib/vpn" 9 | "github.com/GoToolSharing/htb-cli/lib/webhooks" 10 | "github.com/spf13/cobra" 11 | "go.uber.org/zap" 12 | ) 13 | 14 | var vpnCmd = &cobra.Command{ 15 | Use: "vpn", 16 | Short: "Interact with HackTheBox VPNs", 17 | Run: func(cmd *cobra.Command, args []string) { 18 | config.GlobalConfig.Logger.Info("VPN command executed") 19 | downloadVPNParam, err := cmd.Flags().GetBool("download") 20 | if err != nil { 21 | config.GlobalConfig.Logger.Error("", zap.Error(err)) 22 | os.Exit(1) 23 | } 24 | listVPNParam, err := cmd.Flags().GetBool("list") 25 | if err != nil { 26 | config.GlobalConfig.Logger.Error("", zap.Error(err)) 27 | os.Exit(1) 28 | } 29 | 30 | if listVPNParam { 31 | err := vpn.List() 32 | if err != nil { 33 | config.GlobalConfig.Logger.Error("", zap.Error(err)) 34 | os.Exit(1) 35 | } 36 | return 37 | } 38 | 39 | startVPNParam, err := cmd.Flags().GetBool("start") 40 | if err != nil { 41 | config.GlobalConfig.Logger.Error("", zap.Error(err)) 42 | os.Exit(1) 43 | } 44 | stopVPNParam, err := cmd.Flags().GetBool("stop") 45 | if err != nil { 46 | config.GlobalConfig.Logger.Error("", zap.Error(err)) 47 | os.Exit(1) 48 | } 49 | modeVPNParam, err := cmd.Flags().GetString("mode") 50 | if err != nil { 51 | config.GlobalConfig.Logger.Error("", zap.Error(err)) 52 | os.Exit(1) 53 | } 54 | 55 | config.GlobalConfig.Logger.Debug(fmt.Sprintf("Mode: %s", modeVPNParam)) 56 | 57 | if downloadVPNParam { 58 | config.GlobalConfig.Logger.Info("--download flag detected") 59 | err := vpn.DownloadAll() 60 | if err != nil { 61 | config.GlobalConfig.Logger.Error("", zap.Error(err)) 62 | os.Exit(1) 63 | } 64 | } 65 | if startVPNParam && stopVPNParam { 66 | fmt.Println("--start and --stop cannot be used at the same time") 67 | os.Exit(1) 68 | } 69 | 70 | // config.BaseDirectory 71 | 72 | var filename string 73 | var pattern string 74 | if startVPNParam { 75 | switch modeVPNParam { 76 | case "labs": 77 | pattern = "Labs" 78 | filename = config.BaseDirectory + "/*" + pattern + "*" 79 | case "sp": 80 | pattern = "StartingPoint" 81 | filename = config.BaseDirectory + "/*" + pattern + "*" 82 | case "fortresses": 83 | pattern = "Fortress" 84 | filename = config.BaseDirectory + "/*" + pattern + "*" 85 | case "prolabs": 86 | // TODO : Get VPN name 87 | pattern = "Pro" 88 | filename = config.BaseDirectory + "/*" + pattern + "*" 89 | case "competitive": 90 | pattern = "Release_Arena" 91 | filename = config.BaseDirectory + "/*" + pattern + "*" 92 | default: 93 | fmt.Println("Available modes (-m) : labs - sp - fortresses - prolabs - competitive") 94 | return 95 | } 96 | 97 | _, err = vpn.Start(filename) 98 | if err != nil { 99 | config.GlobalConfig.Logger.Error("", zap.Error(err)) 100 | os.Exit(1) 101 | } 102 | } else if stopVPNParam { 103 | message, err := vpn.Stop() 104 | if err != nil { 105 | config.GlobalConfig.Logger.Error("", zap.Error(err)) 106 | os.Exit(1) 107 | } 108 | fmt.Println(message) 109 | err = webhooks.SendToDiscord("vpn", message) 110 | if err != nil { 111 | config.GlobalConfig.Logger.Error("", zap.Error(err)) 112 | os.Exit(1) 113 | } 114 | } 115 | 116 | config.GlobalConfig.Logger.Info("Exit vpn command correctly") 117 | }, 118 | } 119 | 120 | func init() { 121 | rootCmd.AddCommand(vpnCmd) 122 | vpnCmd.Flags().BoolP("download", "d", false, "Download All VPNs from HackTheBox") 123 | vpnCmd.Flags().BoolP("start", "", false, "Start a VPN") 124 | vpnCmd.Flags().BoolP("stop", "", false, "Stop a VPN") 125 | vpnCmd.Flags().BoolP("list", "", false, "List VPNs") 126 | vpnCmd.Flags().StringP("mode", "m", "", "Mode") 127 | } 128 | -------------------------------------------------------------------------------- /config/config.go: -------------------------------------------------------------------------------- 1 | package config 2 | 3 | import ( 4 | "bufio" 5 | "fmt" 6 | "net/url" 7 | "os" 8 | "strings" 9 | 10 | "go.uber.org/zap" 11 | "go.uber.org/zap/zapcore" 12 | ) 13 | 14 | type Settings struct { 15 | Verbose int 16 | Logger *zap.Logger 17 | ProxyParam string 18 | BatchParam bool 19 | NoCheck bool 20 | } 21 | 22 | var GlobalConfig Settings 23 | 24 | var ConfigFile map[string]string 25 | 26 | var homeDir = os.Getenv("HOME") 27 | 28 | var BaseDirectory = homeDir + "/.local/htb-cli" 29 | 30 | const HostHackTheBox = "labs.hackthebox.com" 31 | 32 | const BaseHackTheBoxAPIURL = "https://" + HostHackTheBox + "/api/v4" 33 | 34 | const Version = "v1.7.0" 35 | 36 | func ConfigureLogger() error { 37 | var logLevel zapcore.Level 38 | 39 | switch GlobalConfig.Verbose { 40 | case 0: 41 | logLevel = zap.ErrorLevel 42 | case 1: 43 | logLevel = zap.InfoLevel 44 | case 2: 45 | logLevel = zap.DebugLevel 46 | default: 47 | logLevel = zap.DebugLevel 48 | } 49 | 50 | encoderConfig := zap.NewDevelopmentEncoderConfig() 51 | encoderConfig.EncodeLevel = zapcore.CapitalColorLevelEncoder // Ajoute des couleurs pour les niveaux de log 52 | 53 | cfg := zap.Config{ 54 | Level: zap.NewAtomicLevelAt(logLevel), 55 | Development: true, 56 | Encoding: "console", 57 | EncoderConfig: encoderConfig, 58 | OutputPaths: []string{"stdout"}, 59 | ErrorOutputPaths: []string{"stderr"}, 60 | } 61 | 62 | var err error 63 | GlobalConfig.Logger, err = cfg.Build() 64 | if err != nil { 65 | return fmt.Errorf("logger configuration error: %v", err) 66 | } 67 | zap.ReplaceGlobals(GlobalConfig.Logger) 68 | return nil 69 | } 70 | 71 | // LoadConfig reads a configuration file from a specified filepath and returns a map of key-value pairs. 72 | func LoadConfig(filepath string) (map[string]string, error) { 73 | config := make(map[string]string) 74 | 75 | file, err := os.Open(filepath) 76 | if err != nil { 77 | return nil, err 78 | } 79 | defer file.Close() 80 | 81 | scanner := bufio.NewScanner(file) 82 | for scanner.Scan() { 83 | line := scanner.Text() 84 | if line == "" || strings.HasPrefix(line, "#") { 85 | continue 86 | } 87 | 88 | parts := strings.SplitN(line, "=", 2) 89 | if len(parts) != 2 { 90 | return nil, fmt.Errorf("incorrectly formatted line in configuration file: %s", line) 91 | } 92 | 93 | key := strings.TrimSpace(parts[0]) 94 | value := strings.TrimSpace(parts[1]) 95 | if err := validateConfig(key, value); err != nil { 96 | return nil, err 97 | } 98 | 99 | config[key] = value 100 | } 101 | 102 | if err := scanner.Err(); err != nil { 103 | return nil, err 104 | } 105 | 106 | return config, nil 107 | } 108 | 109 | // validateConfig checks if the provided key-value pairs in the configuration are valid. 110 | func validateConfig(key, value string) error { 111 | switch key { 112 | case "Logging", "Batch": 113 | if value != "True" && value != "False" { 114 | return fmt.Errorf("the value for '%s' must be 'True' or 'False', got : %s", key, value) 115 | } 116 | case "Proxy": 117 | if value != "False" && !isValidHTTPorHTTPSURL(value) { 118 | return fmt.Errorf("the URL for '%s' must be a valid URL starting with http or https, got : %s", key, value) 119 | } 120 | case "Discord": 121 | if value != "False" && !isValidDiscordWebhook(value) { 122 | return fmt.Errorf("the Discord webhook URL is invalid : %s", value) 123 | } 124 | } 125 | 126 | return nil 127 | } 128 | 129 | // isValidDiscordWebhook checks if a given URL is a valid Discord webhook. 130 | func isValidDiscordWebhook(u string) bool { 131 | parsedURL, err := url.Parse(u) 132 | return err == nil && parsedURL.Scheme == "https" && strings.Contains(parsedURL.Host, "discord.com") && strings.Contains(parsedURL.Path, "/api/webhooks/") 133 | } 134 | 135 | // isValidHTTPorHTTPSURL checks if a given URL is valid and uses either the HTTP or HTTPS protocol. 136 | func isValidHTTPorHTTPSURL(u string) bool { 137 | parsedURL, err := url.Parse(u) 138 | return err == nil && (parsedURL.Scheme == "http" || parsedURL.Scheme == "https") 139 | } 140 | 141 | // Init initializes the application by setting up necessary directories, creating a default configuration file if it doesn't exist, and loading the configuration. 142 | func Init() error { 143 | if _, err := os.Stat(BaseDirectory); os.IsNotExist(err) { 144 | GlobalConfig.Logger.Info(fmt.Sprintf("The \"%s\" folder does not exist, creation in progress...\n", BaseDirectory)) 145 | err := os.MkdirAll(BaseDirectory, os.ModePerm) 146 | if err != nil { 147 | return fmt.Errorf("error folder creation: %s", err) 148 | } 149 | 150 | GlobalConfig.Logger.Info(fmt.Sprintf("\"%s\" folder created successfully\n\n", BaseDirectory)) 151 | } 152 | 153 | confFilePath := BaseDirectory + "/default.conf" 154 | if _, err := os.Stat(confFilePath); os.IsNotExist(err) { 155 | file, err := os.Create(confFilePath) 156 | if err != nil { 157 | return fmt.Errorf("error creating file: %v", err) 158 | } 159 | defer file.Close() 160 | 161 | configContent := `Discord = False 162 | Update = False` 163 | 164 | writer := bufio.NewWriter(file) 165 | _, err = writer.WriteString(configContent) 166 | if err != nil { 167 | return fmt.Errorf("error when writing to file: %v", err) 168 | } 169 | 170 | err = writer.Flush() 171 | if err != nil { 172 | return fmt.Errorf("error clearing buffer: %v", err) 173 | } 174 | 175 | GlobalConfig.Logger.Info("Configuration file created successfully.") 176 | } 177 | 178 | GlobalConfig.Logger.Info("Loading configuration file...") 179 | config, err := LoadConfig(BaseDirectory + "/default.conf") 180 | if err != nil { 181 | return fmt.Errorf("error loading configuration file: %v", err) 182 | } 183 | 184 | GlobalConfig.Logger.Info("Configuration successfully loaded") 185 | GlobalConfig.Logger.Debug(fmt.Sprintf("%v", config)) 186 | ConfigFile = config 187 | return nil 188 | } 189 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/GoToolSharing/htb-cli 2 | 3 | go 1.20 4 | 5 | require ( 6 | github.com/AlecAivazis/survey/v2 v2.3.7 7 | github.com/briandowns/spinner v1.23.2 8 | github.com/chzyer/readline v1.5.1 9 | github.com/gorilla/websocket v1.5.3 10 | github.com/rivo/tview v0.0.0-20241227133733-17b7edb88c57 11 | github.com/sahilm/fuzzy v0.1.1 12 | github.com/spf13/cobra v1.8.1 13 | go.uber.org/zap v1.27.0 14 | golang.org/x/crypto v0.33.0 15 | golang.org/x/term v0.29.0 16 | ) 17 | 18 | require ( 19 | github.com/fatih/color v1.18.0 // indirect 20 | github.com/gdamore/encoding v1.0.1 // indirect 21 | github.com/gdamore/tcell/v2 v2.8.1 // indirect 22 | github.com/inconshreveable/mousetrap v1.1.0 // indirect 23 | github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51 // indirect 24 | github.com/kylelemons/godebug v1.1.0 // indirect 25 | github.com/lucasb-eyer/go-colorful v1.2.0 // indirect 26 | github.com/mattn/go-colorable v0.1.14 // indirect 27 | github.com/mattn/go-isatty v0.0.20 // indirect 28 | github.com/mattn/go-runewidth v0.0.16 // indirect 29 | github.com/mgutz/ansi v0.0.0-20200706080929-d51e80ef957d // indirect 30 | github.com/rivo/uniseg v0.4.7 // indirect 31 | github.com/spf13/pflag v1.0.6 // indirect 32 | go.uber.org/multierr v1.11.0 // indirect 33 | golang.org/x/sys v0.30.0 // indirect 34 | golang.org/x/text v0.22.0 // indirect 35 | ) 36 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/AlecAivazis/survey/v2 v2.3.7 h1:6I/u8FvytdGsgonrYsVn2t8t4QiRnh6QSTqkkhIiSjQ= 2 | github.com/AlecAivazis/survey/v2 v2.3.7/go.mod h1:xUTIdE4KCOIjsBAE1JYsUPoCqYdZ1reCfTwbto0Fduo= 3 | github.com/Netflix/go-expect v0.0.0-20220104043353-73e0943537d2 h1:+vx7roKuyA63nhn5WAunQHLTznkw5W8b1Xc0dNjp83s= 4 | github.com/Netflix/go-expect v0.0.0-20220104043353-73e0943537d2/go.mod h1:HBCaDeC1lPdgDeDbhX8XFpy1jqjK0IBG8W5K+xYqA0w= 5 | github.com/briandowns/spinner v1.23.2 h1:Zc6ecUnI+YzLmJniCfDNaMbW0Wid1d5+qcTq4L2FW8w= 6 | github.com/briandowns/spinner v1.23.2/go.mod h1:LaZeM4wm2Ywy6vO571mvhQNRcWfRUnXOs0RcKV0wYKM= 7 | github.com/chzyer/logex v1.2.1 h1:XHDu3E6q+gdHgsdTPH6ImJMIp436vR6MPtH8gP05QzM= 8 | github.com/chzyer/logex v1.2.1/go.mod h1:JLbx6lG2kDbNRFnfkgvh4eRJRPX1QCoOIWomwysCBrQ= 9 | github.com/chzyer/readline v1.5.1 h1:upd/6fQk4src78LMRzh5vItIt361/o4uq553V8B5sGI= 10 | github.com/chzyer/readline v1.5.1/go.mod h1:Eh+b79XXUwfKfcPLepksvw2tcLE/Ct21YObkaSkeBlk= 11 | github.com/chzyer/test v1.0.0 h1:p3BQDXSxOhOG0P9z6/hGnII4LGiEPOYBhs8asl/fC04= 12 | github.com/chzyer/test v1.0.0/go.mod h1:2JlltgoNkt4TW/z9V/IzDdFaMTM2JPIi26O1pF38GC8= 13 | github.com/cpuguy83/go-md2man/v2 v2.0.4/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= 14 | github.com/creack/pty v1.1.17 h1:QeVUsEDNrLBW4tMgZHvxy18sKtr6VI492kBhUfhDJNI= 15 | github.com/creack/pty v1.1.17/go.mod h1:MOBLtS5ELjhRRrroQr9kyvTxUAFNvYEK993ew/Vr4O4= 16 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 17 | github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= 18 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 19 | github.com/fatih/color v1.18.0 h1:S8gINlzdQ840/4pfAwic/ZE0djQEH3wM94VfqLTZcOM= 20 | github.com/fatih/color v1.18.0/go.mod h1:4FelSpRwEGDpQ12mAdzqdOukCy4u8WUtOY6lkT/6HfU= 21 | github.com/gdamore/encoding v1.0.1 h1:YzKZckdBL6jVt2Gc+5p82qhrGiqMdG/eNs6Wy0u3Uhw= 22 | github.com/gdamore/encoding v1.0.1/go.mod h1:0Z0cMFinngz9kS1QfMjCP8TY7em3bZYeeklsSDPivEo= 23 | github.com/gdamore/tcell/v2 v2.8.1 h1:KPNxyqclpWpWQlPLx6Xui1pMk8S+7+R37h3g07997NU= 24 | github.com/gdamore/tcell/v2 v2.8.1/go.mod h1:bj8ori1BG3OYMjmb3IklZVWfZUJ1UBQt9JXrOCOhGWw= 25 | github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= 26 | github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg= 27 | github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= 28 | github.com/hinshun/vt10x v0.0.0-20220119200601-820417d04eec h1:qv2VnGeEQHchGaZ/u7lxST/RaJw+cv273q79D81Xbog= 29 | github.com/hinshun/vt10x v0.0.0-20220119200601-820417d04eec/go.mod h1:Q48J4R4DvxnHolD5P8pOtXigYlRuPLGl6moFx3ulM68= 30 | github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= 31 | github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= 32 | github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51 h1:Z9n2FFNUXsshfwJMBgNA0RU6/i7WVaAegv3PtuIHPMs= 33 | github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51/go.mod h1:CzGEWj7cYgsdH8dAjBGEr58BoE7ScuLd+fwFZ44+/x8= 34 | github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc= 35 | github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw= 36 | github.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69Aj6K7nkY= 37 | github.com/lucasb-eyer/go-colorful v1.2.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0= 38 | github.com/mattn/go-colorable v0.1.2/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE= 39 | github.com/mattn/go-colorable v0.1.14 h1:9A9LHSqF/7dyVVX6g0U9cwm9pG3kP9gSzcuIPHPsaIE= 40 | github.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8= 41 | github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s= 42 | github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= 43 | github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= 44 | github.com/mattn/go-runewidth v0.0.16 h1:E5ScNMtiwvlvB5paMFdw9p4kSQzbXFikJ5SQO6TULQc= 45 | github.com/mattn/go-runewidth v0.0.16/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w= 46 | github.com/mgutz/ansi v0.0.0-20170206155736-9520e82c474b/go.mod h1:01TrycV0kFyexm33Z7vhZRXopbI8J3TDReVlkTgMUxE= 47 | github.com/mgutz/ansi v0.0.0-20200706080929-d51e80ef957d h1:5PJl274Y63IEHC+7izoQE9x6ikvDFZS2mDVS3drnohI= 48 | github.com/mgutz/ansi v0.0.0-20200706080929-d51e80ef957d/go.mod h1:01TrycV0kFyexm33Z7vhZRXopbI8J3TDReVlkTgMUxE= 49 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= 50 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 51 | github.com/rivo/tview v0.0.0-20241227133733-17b7edb88c57 h1:LmsF7Fk5jyEDhJk0fYIqdWNuTxSyid2W42A0L2YWjGE= 52 | github.com/rivo/tview v0.0.0-20241227133733-17b7edb88c57/go.mod h1:02iFIz7K/A9jGCvrizLPvoqr4cEIx7q54RH5Qudkrss= 53 | github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= 54 | github.com/rivo/uniseg v0.4.3/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88= 55 | github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ= 56 | github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88= 57 | github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= 58 | github.com/sahilm/fuzzy v0.1.1 h1:ceu5RHF8DGgoi+/dR5PsECjCDH1BE3Fnmpo7aVXOdRA= 59 | github.com/sahilm/fuzzy v0.1.1/go.mod h1:VFvziUEIMCrT6A6tw2RFIXPXXmzXbOsSHF0DOI8ZK9Y= 60 | github.com/spf13/cobra v1.8.1 h1:e5/vxKd/rZsfSJMUX1agtjeTDf+qv1/JdBF8gg5k9ZM= 61 | github.com/spf13/cobra v1.8.1/go.mod h1:wHxEcudfqmLYa8iTfL+OuZPbBZkmvliBWKIezN3kD9Y= 62 | github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= 63 | github.com/spf13/pflag v1.0.6 h1:jFzHGLGAlb3ruxLB8MhbI6A8+AQX/2eW4qeyNZXNp2o= 64 | github.com/spf13/pflag v1.0.6/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= 65 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= 66 | github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= 67 | github.com/stretchr/testify v1.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk= 68 | github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= 69 | go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= 70 | go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0= 71 | go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y= 72 | go.uber.org/zap v1.27.0 h1:aJMhYGrd5QSmlpLMr2MftRKl7t8J8PTZPA732ud/XR8= 73 | go.uber.org/zap v1.27.0/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E= 74 | golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= 75 | golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= 76 | golang.org/x/crypto v0.13.0/go.mod h1:y6Z2r+Rw4iayiXXAIxJIDAJ1zMW4yaTpebo8fPOliYc= 77 | golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU= 78 | golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v8= 79 | golang.org/x/crypto v0.33.0 h1:IOBPskki6Lysi0lo9qQvbxiQ+FvsCC/YWOecCHAixus= 80 | golang.org/x/crypto v0.33.0/go.mod h1:bVdXmD7IV/4GdElGPozy6U7lWdRXA4qyRVGJV57uQ5M= 81 | golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= 82 | golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= 83 | golang.org/x/mod v0.12.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= 84 | golang.org/x/mod v0.15.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= 85 | golang.org/x/mod v0.17.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= 86 | golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= 87 | golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= 88 | golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= 89 | golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= 90 | golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg= 91 | golang.org/x/net v0.15.0/go.mod h1:idbUs1IY1+zTqbi8yxTbhexhEEk5ur9LInksu6HrEpk= 92 | golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44= 93 | golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM= 94 | golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 95 | golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 96 | golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 97 | golang.org/x/sync v0.3.0/go.mod h1:FU7BRWz2tNW+3quACPkgCx/L+uEAv1htQ0V83Z9Rj+Y= 98 | golang.org/x/sync v0.6.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= 99 | golang.org/x/sync v0.7.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= 100 | golang.org/x/sync v0.10.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= 101 | golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 102 | golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 103 | golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 104 | golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 105 | golang.org/x/sys v0.0.0-20220310020820-b874c991c1a5/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 106 | golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 107 | golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 108 | golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 109 | golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 110 | golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 111 | golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 112 | golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= 113 | golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= 114 | golang.org/x/sys v0.29.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= 115 | golang.org/x/sys v0.30.0 h1:QjkSwP/36a20jFYWkSue1YwXzLmsV5Gfq7Eiy72C1uc= 116 | golang.org/x/sys v0.30.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= 117 | golang.org/x/telemetry v0.0.0-20240228155512-f48c80bd79b2/go.mod h1:TeRTkGYfJXctD9OcfyVLyj2J3IxLnKwHJR8f4D8a3YE= 118 | golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= 119 | golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= 120 | golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= 121 | golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo= 122 | golang.org/x/term v0.12.0/go.mod h1:owVbMEjm3cBLCHdkQu9b1opXd4ETQWc3BhuQGKgXgvU= 123 | golang.org/x/term v0.17.0/go.mod h1:lLRBjIVuehSbZlaOtGMbcMncT+aqLLLmKrsjNrUguwk= 124 | golang.org/x/term v0.20.0/go.mod h1:8UkIAJTvZgivsXaD6/pH6U9ecQzZ45awqEOzuCvwpFY= 125 | golang.org/x/term v0.28.0/go.mod h1:Sw/lC2IAUZ92udQNf3WodGtn4k/XoLyZoh8v/8uiwek= 126 | golang.org/x/term v0.29.0 h1:L6pJp37ocefwRRtYPKSWOWzOtWSxVajvz2ldH/xi3iU= 127 | golang.org/x/term v0.29.0/go.mod h1:6bl4lRlvVuDgSf3179VpIxBF0o10JUpXWOnI7nErv7s= 128 | golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= 129 | golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= 130 | golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= 131 | golang.org/x/text v0.4.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= 132 | golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= 133 | golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= 134 | golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE= 135 | golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= 136 | golang.org/x/text v0.15.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= 137 | golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ= 138 | golang.org/x/text v0.22.0 h1:bofq7m3/HAFvbF51jz3Q9wLg3jkvSPuiZu/pD1XwgtM= 139 | golang.org/x/text v0.22.0/go.mod h1:YRoo4H8PVmsu+E3Ou7cqLVH8oXWIHVoX0jqUWALQhfY= 140 | golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= 141 | golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= 142 | golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= 143 | golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= 144 | golang.org/x/tools v0.13.0/go.mod h1:HvlwmtVNQAhOuCjW7xxvovg8wbNq7LwfXh/k7wXUl58= 145 | golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d/go.mod h1:aiJjzUbINMkxbQROHiO6hDPo2LHcIPhhQsa9DLh0yGk= 146 | golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= 147 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 148 | gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 149 | gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= 150 | gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 151 | -------------------------------------------------------------------------------- /golangci.yml: -------------------------------------------------------------------------------- 1 | run: 2 | timeout: "5m" 3 | issue-exit-code: 1 4 | tests: false 5 | skip-dirs-use-default: true 6 | allow-parallel-runners: false 7 | go: "1.19" 8 | output: 9 | print-issued-lines: true 10 | print-linter-name: true 11 | unique-by-line: true 12 | path-prefix: "" 13 | linters: 14 | enable-all: false 15 | disable-all: true 16 | enable: 17 | # Defaults linters 18 | - errcheck 19 | - gosimple 20 | - govet 21 | - ineffassign 22 | - staticcheck 23 | - typecheck 24 | # - unused 25 | # Non Default linters 26 | - asciicheck 27 | - bodyclose 28 | - cyclop 29 | - decorder 30 | - dupl 31 | - dupword 32 | - errchkjson 33 | - goconst 34 | - gocritic 35 | - goerr113 36 | - gofmt 37 | - gosec 38 | - loggercheck 39 | - paralleltest 40 | - prealloc 41 | - revive 42 | linters-settings: 43 | cyclop: 44 | skip-tests: true 45 | max-complexity: 15 46 | package-average: 0 -------------------------------------------------------------------------------- /lib/hosts/hosts.go: -------------------------------------------------------------------------------- 1 | package hosts 2 | 3 | import ( 4 | "bufio" 5 | "bytes" 6 | "fmt" 7 | "os" 8 | "os/exec" 9 | "strings" 10 | ) 11 | 12 | const hostsFile = "/etc/hosts" 13 | 14 | func readHostsFile(processLine func(string) (string, bool)) (string, bool, error) { 15 | file, err := os.Open(hostsFile) 16 | if err != nil { 17 | return "", false, err 18 | } 19 | defer file.Close() 20 | 21 | var buffer bytes.Buffer 22 | changeMade := false 23 | 24 | scanner := bufio.NewScanner(file) 25 | for scanner.Scan() { 26 | line := scanner.Text() 27 | if strings.TrimSpace(line) == "" { 28 | buffer.WriteString("\n") 29 | continue 30 | } 31 | 32 | processedLine, changed := processLine(line) 33 | if changed { 34 | changeMade = true 35 | } 36 | buffer.WriteString(processedLine + "\n") 37 | } 38 | 39 | return buffer.String(), changeMade, scanner.Err() 40 | } 41 | 42 | func updateHostsFile(newContent string) error { 43 | cmd := exec.Command("sh", "-c", fmt.Sprintf("echo '%s' | sudo tee /etc/hosts > /dev/null", newContent)) 44 | cmd.Stdin = os.Stdin 45 | cmd.Stdout = os.Stdout 46 | cmd.Stderr = os.Stderr 47 | return cmd.Run() 48 | } 49 | 50 | func AddEntryToHosts(ip string, host string) error { 51 | ipFound := false 52 | hostAdded := false 53 | 54 | processLine := func(line string) (string, bool) { 55 | trimmedLine := strings.TrimSpace(line) 56 | if trimmedLine == "" { 57 | return line, false 58 | } 59 | 60 | fields := strings.Fields(trimmedLine) 61 | if fields[0] == ip { 62 | ipFound = true 63 | for _, field := range fields[1:] { 64 | if field == host { 65 | return line, false 66 | } 67 | } 68 | return line + " " + host, true 69 | } 70 | return line, false 71 | } 72 | 73 | newContent, changeMade, err := readHostsFile(processLine) 74 | if err != nil { 75 | return err 76 | } 77 | 78 | if !ipFound { 79 | newContent = strings.TrimSpace(newContent) + "\n" + ip + " " + host 80 | hostAdded = true 81 | } else { 82 | hostAdded = changeMade 83 | } 84 | 85 | if hostAdded { 86 | if err := updateHostsFile(strings.TrimSpace(newContent)); err != nil { 87 | return err 88 | } 89 | fmt.Println("Entry successfully updated or added.") 90 | return nil 91 | } 92 | 93 | fmt.Println("Entry already exists.") 94 | return nil 95 | } 96 | 97 | func RemoveEntryFromHosts(ip string, host string) error { 98 | hostRemoved := false 99 | 100 | processLine := func(line string) (string, bool) { 101 | trimmedLine := strings.TrimSpace(line) 102 | if trimmedLine == "" { 103 | return line, false 104 | } 105 | 106 | fields := strings.Fields(trimmedLine) 107 | if fields[0] == ip { 108 | var newFields []string 109 | newFields = append(newFields, ip) 110 | 111 | for _, field := range fields[1:] { 112 | if field != host { 113 | newFields = append(newFields, field) 114 | } 115 | } 116 | 117 | if len(newFields) > 1 { 118 | return strings.Join(newFields, " "), true 119 | } 120 | return "", true 121 | } 122 | return line, false 123 | } 124 | 125 | newContent, changeMade, err := readHostsFile(processLine) 126 | if err != nil { 127 | return err 128 | } 129 | 130 | if changeMade { 131 | newContent = strings.TrimSpace(newContent) 132 | if err := updateHostsFile(newContent); err != nil { 133 | return err 134 | } 135 | fmt.Println("Entry successfully deleted.") 136 | return nil 137 | } 138 | 139 | if !hostRemoved { 140 | fmt.Println("Entry not found.") 141 | } 142 | return nil 143 | } 144 | -------------------------------------------------------------------------------- /lib/sherlocks/models.go: -------------------------------------------------------------------------------- 1 | package sherlocks 2 | 3 | type SherlockTask struct { 4 | ID int `json:"id"` 5 | Title string `json:"title"` 6 | Description string `json:"description"` 7 | MaskedFlag string `json:"masked_flag"` 8 | Hint string `json:"hint"` 9 | Completed bool `json:"completed"` 10 | } 11 | 12 | type SherlockDataTasks struct { 13 | Tasks []SherlockTask `json:"data"` 14 | } 15 | 16 | type SherlockElement struct { 17 | ID int `json:"id"` 18 | Name string `json:"name"` 19 | } 20 | 21 | type SherlockData struct { 22 | Data []SherlockElement `json:"data"` 23 | } 24 | 25 | type SherlockNameID struct { 26 | Name string 27 | ID int 28 | } 29 | 30 | type DownloadFile struct { 31 | URL string `json:"url"` 32 | ExpiresIn int `json:"expires_in"` 33 | } 34 | -------------------------------------------------------------------------------- /lib/sherlocks/sherlocks.go: -------------------------------------------------------------------------------- 1 | package sherlocks 2 | 3 | import ( 4 | "encoding/json" 5 | "errors" 6 | "fmt" 7 | "io" 8 | "net/http" 9 | "os" 10 | "strconv" 11 | "strings" 12 | 13 | "github.com/GoToolSharing/htb-cli/config" 14 | "github.com/GoToolSharing/htb-cli/lib/utils" 15 | "github.com/chzyer/readline" 16 | "github.com/sahilm/fuzzy" 17 | ) 18 | 19 | // getSherlockDownloadLink constructs and returns the download link for a specific Sherlock challenge. 20 | func getDownloadLink(sherlockID string) (string, error) { 21 | url := fmt.Sprintf("%s/sherlocks/%s/download_link", config.BaseHackTheBoxAPIURL, sherlockID) 22 | 23 | // url := "https://www.hackthebox.com/api/v4/challenge/download/196" 24 | 25 | // return url, nil 26 | 27 | resp, err := utils.HtbRequest(http.MethodGet, url, nil) 28 | if err != nil { 29 | return "", err 30 | } 31 | defer resp.Body.Close() 32 | 33 | if resp.StatusCode != http.StatusOK { 34 | return "", fmt.Errorf("error: Sherlock is not available for now") 35 | } 36 | 37 | body, err := io.ReadAll(resp.Body) 38 | if err != nil { 39 | return "", err 40 | } 41 | 42 | var data DownloadFile 43 | err = json.Unmarshal(body, &data) 44 | if err != nil { 45 | return "", err 46 | } 47 | 48 | config.GlobalConfig.Logger.Debug(fmt.Sprintf("Download URL: %s", data.URL)) 49 | return data.URL, nil 50 | } 51 | 52 | // downloadFile downloads the Sherlock file from a given URL to a specified download path. 53 | func downloadFile(url string, downloadPath string) error { 54 | resp, err := utils.HtbRequest(http.MethodGet, url, nil) 55 | if err != nil { 56 | return err 57 | } 58 | defer resp.Body.Close() 59 | 60 | if resp.StatusCode != http.StatusOK { 61 | fmt.Println("error: Status code:", resp.StatusCode) 62 | return nil 63 | } 64 | 65 | outFile, err := os.Create(downloadPath) 66 | if err != nil { 67 | return err 68 | } 69 | defer outFile.Close() 70 | 71 | _, err = io.Copy(outFile, resp.Body) 72 | if err != nil { 73 | return err 74 | } 75 | 76 | fmt.Println("Archive downloaded successfully. The password for unlock is: hacktheblue") 77 | fmt.Println("") 78 | return nil 79 | } 80 | 81 | // submitTask sends a flag for a specific task of a Sherlock challenge and returns the server's response. 82 | func submitTask(sherlockID string, taskID string, flag string) (string, error) { 83 | url := fmt.Sprintf("%s/sherlocks/%s/tasks/%s/flag", config.BaseHackTheBoxAPIURL, sherlockID, taskID) 84 | 85 | body := map[string]string{ 86 | "flag": flag, 87 | } 88 | jsonBody, err := json.Marshal(body) 89 | if err != nil { 90 | return "", fmt.Errorf("failed to create JSON data: %w", err) 91 | } 92 | resp, err := utils.HtbRequest(http.MethodPost, url, jsonBody) 93 | if err != nil { 94 | return "", err 95 | } 96 | defer resp.Body.Close() 97 | 98 | message, ok := utils.ParseJsonMessage(resp, "message").(string) 99 | if !ok { 100 | return "", errors.New("unexpected response format") 101 | } 102 | return message, nil 103 | } 104 | 105 | // GetTaskByID retrieves and prints the description of a specific task of a Sherlock challenge. 106 | func GetTaskByID(sherlockID string, sherlockTaskID int, sherlockHint bool) error { 107 | // TODO: Add hint 108 | url := fmt.Sprintf("%s/sherlocks/%s/tasks", config.BaseHackTheBoxAPIURL, sherlockID) 109 | resp, err := utils.HtbRequest(http.MethodGet, url, nil) 110 | if err != nil { 111 | return err 112 | } 113 | defer resp.Body.Close() 114 | 115 | jsonData, _ := io.ReadAll(resp.Body) 116 | 117 | var sherlockData SherlockDataTasks 118 | err = json.Unmarshal([]byte(jsonData), &sherlockData) 119 | if err != nil { 120 | return fmt.Errorf("error parsing JSON: %w", err) 121 | } 122 | 123 | if sherlockTaskID >= 1 && sherlockTaskID <= len(sherlockData.Tasks) { 124 | if sherlockHint && sherlockData.Tasks[sherlockTaskID-1].Hint != "" { 125 | fmt.Printf("\n%s :\n%s\n\nHint : %s\nMasked Flag : %s\n", sherlockData.Tasks[sherlockTaskID-1].Title, sherlockData.Tasks[sherlockTaskID-1].Description, sherlockData.Tasks[sherlockTaskID-1].Hint, sherlockData.Tasks[sherlockTaskID-1].MaskedFlag) 126 | } else { 127 | fmt.Printf("\n%s :\n%s\n\nMasked Flag : %s\n", sherlockData.Tasks[sherlockTaskID-1].Title, sherlockData.Tasks[sherlockTaskID-1].Description, sherlockData.Tasks[sherlockTaskID-1].MaskedFlag) 128 | } 129 | rl, err := readline.New("Answer: ") 130 | if err != nil { 131 | panic(err) 132 | } 133 | defer rl.Close() 134 | 135 | flag, err := rl.Readline() 136 | if err != nil { 137 | return err 138 | } 139 | flag = strings.TrimSpace(flag) 140 | config.GlobalConfig.Logger.Debug(fmt.Sprintf("Flag: %s", flag)) 141 | taskID := strconv.Itoa(sherlockData.Tasks[sherlockTaskID-1].ID) 142 | 143 | message, err := submitTask(sherlockID, taskID, flag) 144 | 145 | if err != nil { 146 | return err 147 | } 148 | 149 | fmt.Println(message) 150 | } else { 151 | fmt.Println("Invalid task ID :", sherlockTaskID) 152 | } 153 | return nil 154 | } 155 | 156 | // GetTasks retrieves all tasks for a specific Sherlock challenge. 157 | func GetTasks(sherlockID string) (*SherlockDataTasks, error) { 158 | url := fmt.Sprintf("%s/sherlocks/%s/tasks", config.BaseHackTheBoxAPIURL, sherlockID) 159 | resp, err := utils.HtbRequest(http.MethodGet, url, nil) 160 | if err != nil { 161 | return nil, err 162 | } 163 | defer resp.Body.Close() 164 | 165 | jsonData, _ := io.ReadAll(resp.Body) 166 | 167 | var parsedData SherlockDataTasks 168 | err = json.Unmarshal([]byte(jsonData), &parsedData) 169 | if err != nil { 170 | return nil, fmt.Errorf("error parsing JSON: %w", err) 171 | } 172 | 173 | return &parsedData, nil 174 | } 175 | 176 | // GetGeneralInformations retrieves and prints general information about a Sherlock challenge. 177 | func GetGeneralInformations(sherlockID string, sherlockDownloadPath string) error { 178 | url := fmt.Sprintf("%s/sherlocks/%s/play", config.BaseHackTheBoxAPIURL, sherlockID) 179 | resp, err := utils.HtbRequest(http.MethodGet, url, nil) 180 | if err != nil { 181 | return err 182 | } 183 | defer resp.Body.Close() 184 | 185 | info := utils.ParseJsonMessage(resp, "data").(map[string]interface{}) 186 | 187 | if sherlockDownloadPath != "" { 188 | url, err := getDownloadLink(sherlockID) 189 | if err != nil { 190 | return err 191 | } 192 | err = downloadFile(url, sherlockDownloadPath) 193 | if err != nil { 194 | return err 195 | } 196 | } 197 | 198 | config.GlobalConfig.Logger.Debug(fmt.Sprintf("Informations: %v", info)) 199 | fmt.Println("Scenario :", info["scenario"]) 200 | fmt.Println("\nFile :", info["file_name"]) 201 | fmt.Println("File Size :", info["file_size"]) 202 | return nil 203 | } 204 | 205 | // SearchIDByName searches for a Sherlock challenge by name and returns its ID. 206 | func SearchIDByName(sherlockSearch string) (string, error) { 207 | url := fmt.Sprintf("%s/sherlocks", config.BaseHackTheBoxAPIURL) 208 | resp, err := utils.HtbRequest(http.MethodGet, url, nil) 209 | if err != nil { 210 | return "", err 211 | } 212 | defer resp.Body.Close() 213 | 214 | jsonData, _ := io.ReadAll(resp.Body) 215 | 216 | var parsedData SherlockData 217 | err = json.Unmarshal([]byte(jsonData), &parsedData) 218 | if err != nil { 219 | return "", fmt.Errorf("error parsing JSON: %s", err) 220 | } 221 | 222 | var nameIDs []SherlockNameID 223 | for _, challenge := range parsedData.Data { 224 | nameIDs = append(nameIDs, SherlockNameID{challenge.Name, challenge.ID}) 225 | } 226 | 227 | var names []string 228 | for _, ni := range nameIDs { 229 | names = append(names, ni.Name) 230 | } 231 | 232 | matches := fuzzy.Find(sherlockSearch, names) 233 | 234 | for _, match := range matches { 235 | matchedNameID := nameIDs[match.Index] 236 | isConfirmed := utils.AskConfirmation("The following sherlock was found : " + matchedNameID.Name) 237 | if isConfirmed { 238 | return strconv.Itoa(matchedNameID.ID), nil 239 | } 240 | } 241 | 242 | return "", fmt.Errorf("error: Nothing was found") 243 | } 244 | -------------------------------------------------------------------------------- /lib/sherlocks/tui.go: -------------------------------------------------------------------------------- 1 | package sherlocks 2 | 3 | import ( 4 | "fmt" 5 | 6 | "github.com/GoToolSharing/htb-cli/config" 7 | "github.com/rivo/tview" 8 | ) 9 | 10 | const ( 11 | SherlocksURL = config.BaseHackTheBoxAPIURL + "/sherlocks?state=active" 12 | RetiredSherlocksURL = config.BaseHackTheBoxAPIURL + "/sherlocks?state=retired" 13 | ScheduledSherlocksURL = config.BaseHackTheBoxAPIURL + "/sherlocks?state=unreleased" 14 | ActiveSherlocksTitle = "Active" 15 | RetiredSherlocksTitle = "Retired" 16 | ScheduledSherlocksTitle = "Scheduled" 17 | SherlocksCheckMark = "\U00002705" 18 | SherlocksCrossMark = "\U0000274C" 19 | SPenguin = "\U0001F427" 20 | SComputer = "\U0001F5A5 " 21 | ) 22 | 23 | // GetColorFromDifficultyText returns the color corresponding to the given difficulty. 24 | func GetColorFromDifficultyText(difficultyText string) string { 25 | switch difficultyText { 26 | case "Medium": 27 | return "[orange]" 28 | case "Easy": 29 | return "[green]" 30 | case "Hard": 31 | return "[red]" 32 | case "Insane": 33 | return "[purple]" 34 | default: 35 | return "[-]" 36 | } 37 | } 38 | 39 | // CreateFlex creates and returns a Flex view with machine information 40 | func CreateFlex(info interface{}, title string, isScheduled bool) (*tview.Flex, error) { 41 | config.GlobalConfig.Logger.Debug(fmt.Sprintf("Info: %v", info)) 42 | flex := tview.NewFlex().SetDirection(tview.FlexRow) 43 | flex.SetBorder(true).SetTitle(title).SetTitleAlign(tview.AlignLeft) 44 | 45 | for _, value := range info.([]interface{}) { 46 | data := value.(map[string]interface{}) 47 | 48 | // Determining the color according to difficulty 49 | 50 | key := "Undefined" 51 | if title == "Scheduled" { 52 | key = data["difficulty"].(string) 53 | } 54 | color := GetColorFromDifficultyText(key) 55 | 56 | // var formatString string 57 | 58 | // Choice of display format depending on the nature of the information 59 | // if isScheduled { 60 | formatString := fmt.Sprintf("%-15s %s%-10s[-]", 61 | data["name"], color, data["difficulty"]) 62 | //} 63 | // else { 64 | 65 | // Convert and format date 66 | // parsedDate, err := time.Parse(time.RFC3339Nano, data["release"].(string)) 67 | // if err != nil { 68 | // return nil, fmt.Errorf("error parsing date: %v", err) 69 | // } 70 | // formattedDate := parsedDate.Format("02 January 2006") 71 | 72 | // userEmoji := SherlocksCrossMark + "User" 73 | // if value, ok := data["authUserInUserOwns"]; ok && value != nil { 74 | // if value.(bool) { 75 | // userEmoji = SherlocksCheckMark + "User" 76 | // } 77 | // } 78 | 79 | // rootEmoji := SherlocksCrossMark + "Root" 80 | // if value, ok := data["authUserInRootOwns"]; ok && value != nil { 81 | // if value.(bool) { 82 | // rootEmoji = SherlocksCheckMark + "Root" 83 | // } 84 | // } 85 | 86 | // formatString = fmt.Sprintf("%-15s %s%-10s[-] %-5v %-5v %-7v %-30s", 87 | // data["name"], color, data["difficultyText"], 88 | // data["star"], userEmoji, rootEmoji, formattedDate) 89 | // } 90 | 91 | flex.AddItem(tview.NewTextView().SetText(formatString).SetDynamicColors(true), 1, 0, false) 92 | } 93 | 94 | return flex, nil 95 | } 96 | -------------------------------------------------------------------------------- /lib/shoutbox/models.go: -------------------------------------------------------------------------------- 1 | package shoutbox 2 | -------------------------------------------------------------------------------- /lib/shoutbox/shoutbox.go: -------------------------------------------------------------------------------- 1 | package shoutbox 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | "net/url" 7 | "regexp" 8 | 9 | "github.com/GoToolSharing/htb-cli/config" 10 | "github.com/gorilla/websocket" 11 | ) 12 | 13 | func ConnectToWebSocket() error { 14 | config.GlobalConfig.Logger.Info("Starting the websocket connection") 15 | u := url.URL{Scheme: "wss", Host: "ws-eu.pusher.com", Path: "/app/97608bf7532e6f0fe898", RawQuery: "protocol=7&client=js&version=5.1.1&flash=false"} 16 | 17 | c, _, err := websocket.DefaultDialer.Dial(u.String(), nil) 18 | if err != nil { 19 | return fmt.Errorf("Websocket connection error: %v", err) 20 | } 21 | defer c.Close() 22 | 23 | for { 24 | _, message, err := c.ReadMessage() 25 | if err != nil { 26 | return fmt.Errorf("Error reading websocket message: %v", err) 27 | } 28 | config.GlobalConfig.Logger.Debug(fmt.Sprintf("Message received: %s", message)) 29 | var msgData map[string]interface{} 30 | if err := json.Unmarshal(message, &msgData); err != nil { 31 | return fmt.Errorf("Error when analyzing internal data: %v", err) 32 | } 33 | 34 | if msgData["event"] == "display-info" { 35 | if data, ok := msgData["data"].(string); ok { 36 | var dataContent map[string]string 37 | if err := json.Unmarshal([]byte(data), &dataContent); err != nil { 38 | return fmt.Errorf("Error when analyzing internal data: %v", err) 39 | } 40 | 41 | config.GlobalConfig.Logger.Debug(fmt.Sprintf("Data: %s", dataContent)) 42 | extractedMessage, _ := parseOwnsMessages(dataContent) 43 | fmt.Println(extractedMessage) 44 | } 45 | } 46 | 47 | var received map[string]interface{} 48 | if err := json.Unmarshal(message, &received); err != nil { 49 | return fmt.Errorf("Message parsing error: %v", err) 50 | } 51 | 52 | if received["event"] == "pusher:connection_established" { 53 | subscribeMessage := map[string]interface{}{ 54 | "event": "pusher:subscribe", 55 | "data": map[string]interface{}{ 56 | "auth": "", 57 | "channel": "owns-channel", 58 | }, 59 | } 60 | 61 | subscribeMessageBytes, err := json.Marshal(subscribeMessage) 62 | if err != nil { 63 | return fmt.Errorf("Error creating subscription message: %v", err) 64 | } 65 | 66 | config.GlobalConfig.Logger.Info("Channel owns subscription") 67 | if err := c.WriteMessage(websocket.TextMessage, subscribeMessageBytes); err != nil { 68 | return fmt.Errorf("Error sending subscription message: %v", err) 69 | } 70 | 71 | _, message, err := c.ReadMessage() 72 | if err != nil { 73 | return fmt.Errorf("Error reading websocket message: %v", err) 74 | } 75 | config.GlobalConfig.Logger.Debug(fmt.Sprintf("Messagess received: %s", message)) 76 | } 77 | } 78 | } 79 | 80 | func parseOwnsMessages(message map[string]string) (string, error) { 81 | re := regexp.MustCompile(`<span class="text-info">(.*?)</span>`) 82 | matches := re.FindStringSubmatch(message["prepend"]) 83 | 84 | var messageFormated string 85 | 86 | if len(matches) >= 2 { 87 | config.GlobalConfig.Logger.Debug(fmt.Sprintf("Matches: %s", matches)) 88 | messageFormated = fmt.Sprintf("%s - ", matches[1]) 89 | } 90 | 91 | re = regexp.MustCompile(`<[^>]+>`) 92 | output := re.ReplaceAllString(message["text"], "") 93 | 94 | re = regexp.MustCompile(`\s*\[.*?\]\s*`) 95 | output = re.ReplaceAllString(output, "") 96 | 97 | reSpaces := regexp.MustCompile(`\s{2,}`) 98 | output = reSpaces.ReplaceAllString(output, " ") 99 | 100 | messageFormated += output 101 | return messageFormated, nil 102 | } 103 | -------------------------------------------------------------------------------- /lib/ssh/ssh.go: -------------------------------------------------------------------------------- 1 | package ssh 2 | 3 | import ( 4 | "fmt" 5 | "path/filepath" 6 | "strings" 7 | 8 | "github.com/GoToolSharing/htb-cli/config" 9 | "github.com/GoToolSharing/htb-cli/lib/utils" 10 | "golang.org/x/crypto/ssh" 11 | ) 12 | 13 | func Connect(username, password, host string, port int) (*ssh.Client, error) { 14 | config := &ssh.ClientConfig{ 15 | User: username, 16 | Auth: []ssh.AuthMethod{ 17 | ssh.Password(password), 18 | }, 19 | HostKeyCallback: ssh.InsecureIgnoreHostKey(), 20 | } 21 | connection, err := ssh.Dial("tcp", fmt.Sprintf("%s:%d", host, port), config) 22 | if err != nil { 23 | return nil, fmt.Errorf("Connection error: %s\n", err) 24 | } 25 | fmt.Println("SSH connection established") 26 | 27 | return connection, nil 28 | } 29 | 30 | func GetUserFlag(connection *ssh.Client) (string, error) { 31 | session, err := connection.NewSession() 32 | if err != nil { 33 | return "", fmt.Errorf("Session creation error: %s\n", err) 34 | } 35 | defer session.Close() 36 | 37 | cmd := "cat /etc/passwd | grep -E '/home|/users' | cut -d: -f6" 38 | output, err := session.CombinedOutput(cmd) 39 | if err != nil { 40 | return "", fmt.Errorf("Error during command execution: %s\n", err) 41 | } 42 | homes := strings.Split(string(output), "\n") 43 | config.GlobalConfig.Logger.Debug(fmt.Sprintf("Users homes : %v", homes)) 44 | 45 | fileFound := false 46 | for _, home := range homes { 47 | if home == "" { 48 | continue 49 | } 50 | filePath := filepath.Join(home, "user.txt") 51 | fileSession, err := connection.NewSession() 52 | if err != nil { 53 | fmt.Printf("Error creating file session: %s\n", err) 54 | continue 55 | } 56 | cmd := fmt.Sprintf("if [ -f %s ]; then echo found; else echo not found; fi", filePath) 57 | fileOutput, err := fileSession.CombinedOutput(cmd) 58 | if err != nil { 59 | return "", err 60 | } 61 | fileSession.Close() 62 | 63 | if strings.TrimSpace(string(fileOutput)) == "found" { 64 | fileFound = true 65 | config.GlobalConfig.Logger.Debug(fmt.Sprintf("User flag found: %s\n", filePath)) 66 | 67 | contentSession, err := connection.NewSession() 68 | if err != nil { 69 | fmt.Printf("Error creating content session: %s\n", err) 70 | continue 71 | } 72 | contentCmd := fmt.Sprintf("cat %s", filePath) 73 | contentOutput, err := contentSession.CombinedOutput(contentCmd) 74 | if err != nil { 75 | fmt.Printf("File read error %s: %s\n", filePath, err) 76 | permSession, err := connection.NewSession() 77 | if err != nil { 78 | fmt.Printf("Error creating permissions session: %s\n", err) 79 | continue 80 | } 81 | permCmd := fmt.Sprintf("ls -la %s", filePath) 82 | permOutput, err := permSession.CombinedOutput(permCmd) 83 | if err != nil { 84 | fmt.Printf("Error obtaining permissions: %s\n", err) 85 | } else { 86 | fmt.Printf("Permissions required: %s\n", string(permOutput)) 87 | } 88 | permSession.Close() 89 | continue 90 | } 91 | fmt.Printf("%s: %s\n", filePath, string(contentOutput)) 92 | if len(contentOutput) == 32 || len(contentOutput) == 33 { 93 | config.GlobalConfig.Logger.Info("HTB flag detected") 94 | return (string(contentOutput)), nil 95 | } 96 | contentSession.Close() 97 | break 98 | } 99 | } 100 | 101 | if !fileFound { 102 | fmt.Println("user.txt file not found in home directories") 103 | } 104 | return "", nil 105 | } 106 | 107 | func GetHostname(connection *ssh.Client) (string, error) { 108 | hostnameSession, err := connection.NewSession() 109 | if err != nil { 110 | return "", fmt.Errorf("Error creating hostname session: %s\n", err) 111 | } 112 | cmd := "hostname" 113 | sessionOutput, err := hostnameSession.CombinedOutput(cmd) 114 | if err != nil { 115 | return "", err 116 | } 117 | hostnameSession.Close() 118 | hostname := strings.ReplaceAll(string(sessionOutput), "\n", "") 119 | config.GlobalConfig.Logger.Debug(fmt.Sprintf("Hotname: %s", hostname)) 120 | return hostname, nil 121 | } 122 | 123 | func BuildSubmitStuff(hostname string, userFlag string) (string, map[string]interface{}, error) { 124 | // Can be release arena or machine 125 | var payload map[string]interface{} 126 | var url string 127 | 128 | machineID, err := utils.SearchItemIDByName(hostname, "Machine") 129 | if err != nil { 130 | return "", nil, err 131 | } 132 | machineType, err := utils.GetMachineType(machineID) 133 | if err != nil { 134 | return "", nil, err 135 | } 136 | config.GlobalConfig.Logger.Debug(fmt.Sprintf("Machine Type: %s", machineType)) 137 | 138 | if machineType == "release" { 139 | url = config.BaseHackTheBoxAPIURL + "/arena/own" 140 | payload = map[string]interface{}{ 141 | "flag": userFlag, 142 | } 143 | } else { 144 | url = config.BaseHackTheBoxAPIURL + "/machine/own" 145 | payload = map[string]interface{}{ 146 | "id": machineID, 147 | "flag": userFlag, 148 | } 149 | } 150 | 151 | return url, payload, nil 152 | } 153 | -------------------------------------------------------------------------------- /lib/submit/submit.go: -------------------------------------------------------------------------------- 1 | package submit 2 | 3 | import ( 4 | "encoding/json" 5 | "errors" 6 | "fmt" 7 | "net/http" 8 | "os" 9 | "strconv" 10 | "strings" 11 | 12 | "github.com/GoToolSharing/htb-cli/config" 13 | "github.com/GoToolSharing/htb-cli/lib/utils" 14 | "golang.org/x/term" 15 | ) 16 | 17 | func SubmitFlag(url string, payload map[string]interface{}) (string, error) { 18 | jsonData, err := json.Marshal(payload) 19 | if err != nil { 20 | return "", fmt.Errorf("failed to create JSON data: %w", err) 21 | } 22 | resp, err := utils.HtbRequest(http.MethodPost, url, jsonData) 23 | if err != nil { 24 | return "", err 25 | } 26 | 27 | message, ok := utils.ParseJsonMessage(resp, "message").(string) 28 | if !ok { 29 | return "", errors.New("unexpected response format") 30 | } 31 | return message, nil 32 | } 33 | 34 | // coreSubmitCmd handles the submission of flags for machines or challenges, returning a status message or error. 35 | func CoreSubmitCmd(difficultyParam int, modeType string, modeValue string) (string, int, error) { 36 | var payload map[string]interface{} 37 | var difficultyString string 38 | var url string 39 | var challengeID string 40 | var mID int 41 | 42 | if modeType == "challenge" { 43 | config.GlobalConfig.Logger.Info("Challenge submit requested") 44 | if difficultyParam != 0 { 45 | if difficultyParam < 1 || difficultyParam > 10 { 46 | return "", 0, errors.New("difficulty must be set between 1 and 10") 47 | } 48 | difficultyString = strconv.Itoa(difficultyParam * 10) 49 | } 50 | challenges, err := utils.SearchChallengeByName(modeValue) 51 | if err != nil { 52 | return "", 0, err 53 | } 54 | config.GlobalConfig.Logger.Debug(fmt.Sprintf("Challenge found: %v", challenges)) 55 | 56 | // TODO: get this int 57 | challengeID = strconv.Itoa(challenges.ID) 58 | 59 | url = config.BaseHackTheBoxAPIURL + "/challenge/own" 60 | payload = map[string]interface{}{ 61 | "difficulty": difficultyString, 62 | "challenge_id": challengeID, 63 | } 64 | } else if modeType == "machine" { 65 | config.GlobalConfig.Logger.Info("Machine submit requested") 66 | machineID, err := utils.SearchItemIDByName(modeValue, "Machine") 67 | if err != nil { 68 | return "", 0, err 69 | } 70 | machineType, err := utils.GetMachineType(machineID) 71 | if err != nil { 72 | return "", 0, err 73 | } 74 | config.GlobalConfig.Logger.Debug(fmt.Sprintf("Machine Type: %s", machineType)) 75 | 76 | if machineType == "release" { 77 | url = config.BaseHackTheBoxAPIURL + "/arena/own" 78 | } else { 79 | url = config.BaseHackTheBoxAPIURL + "/machine/own" 80 | 81 | } 82 | payload = map[string]interface{}{ 83 | "id": machineID, 84 | } 85 | mID = machineID 86 | } else if modeType == "fortress" { 87 | config.GlobalConfig.Logger.Info("Fortress submit requested") 88 | fortressID, err := utils.SearchFortressID(modeValue) 89 | if err != nil { 90 | return "", 0, err 91 | } 92 | config.GlobalConfig.Logger.Debug(fmt.Sprintf("Fortress ID : %d", fortressID)) 93 | url = fmt.Sprintf("%s/fortress/%d/flag", config.BaseHackTheBoxAPIURL, fortressID) 94 | payload = map[string]interface{}{} 95 | } else if modeType == "prolab" { 96 | config.GlobalConfig.Logger.Info("Prolab submit requested") 97 | prolabID, err := utils.SearchProlabID(modeValue) 98 | if err != nil { 99 | return "", 0, err 100 | } 101 | config.GlobalConfig.Logger.Debug(fmt.Sprintf("Prolab ID : %d", prolabID)) 102 | url = fmt.Sprintf("%s/prolab/%d/flag", config.BaseHackTheBoxAPIURL, prolabID) 103 | payload = map[string]interface{}{} 104 | } else if modeType == "release-arena" { 105 | config.GlobalConfig.Logger.Info("Release Arena submit requested") 106 | isConfirmed := utils.AskConfirmation("Would you like to submit a flag for the release arena ?") 107 | if !isConfirmed { 108 | return "", 0, nil 109 | } 110 | releaseID, err := utils.SearchLastReleaseArenaMachine() 111 | if err != nil { 112 | return "", 0, err 113 | } 114 | config.GlobalConfig.Logger.Debug(fmt.Sprintf("Release Arena ID : %d", releaseID)) 115 | url = fmt.Sprintf("%s/arena/own", config.BaseHackTheBoxAPIURL) 116 | payload = map[string]interface{}{ 117 | "id": releaseID, 118 | } 119 | mID = releaseID 120 | } 121 | 122 | fmt.Print("Flag : ") 123 | flagByte, err := term.ReadPassword(int(os.Stdin.Fd())) 124 | if err != nil { 125 | fmt.Println("Error reading flag") 126 | return "", 0, fmt.Errorf("error reading flag") 127 | } 128 | flagOriginal := string(flagByte) 129 | flag := strings.ReplaceAll(flagOriginal, " ", "") 130 | 131 | config.GlobalConfig.Logger.Debug(fmt.Sprintf("Flag: %s", flag)) 132 | 133 | payload["flag"] = flag 134 | 135 | message, err := SubmitFlag(url, payload) 136 | if err != nil { 137 | return "", 0, err 138 | } 139 | return message, mID, nil 140 | } 141 | 142 | func GetAchievementLink(machineID int) (string, error) { 143 | resp, err := utils.HtbRequest(http.MethodGet, fmt.Sprintf("%s/user/info", config.BaseHackTheBoxAPIURL), nil) 144 | if err != nil { 145 | return "", err 146 | } 147 | info := utils.ParseJsonMessage(resp, "info") 148 | infoMap, _ := info.(map[string]interface{}) 149 | config.GlobalConfig.Logger.Debug(fmt.Sprintf("User ID: %v", infoMap["id"])) 150 | config.GlobalConfig.Logger.Debug(fmt.Sprintf("Machine ID: %d", machineID)) 151 | 152 | resp, err = utils.HtbRequest(http.MethodGet, fmt.Sprintf("%s/user/achievement/machine/%v/%d", config.BaseHackTheBoxAPIURL, infoMap["id"], machineID), nil) 153 | if err != nil { 154 | return "", err 155 | } 156 | _, ok := utils.ParseJsonMessage(resp, "message").(string) 157 | if !ok { 158 | return fmt.Sprintf("\nAchievement link: https://labs.hackthebox.com/achievement/machine/%v/%d", infoMap["id"], machineID), nil 159 | } 160 | return "", nil 161 | 162 | } 163 | -------------------------------------------------------------------------------- /lib/update/models.go: -------------------------------------------------------------------------------- 1 | package update 2 | 3 | type GitHubRelease struct { 4 | TagName string `json:"tag_name"` 5 | } 6 | 7 | type Commit struct { 8 | SHA string `json:"sha"` 9 | Commit struct { 10 | Author struct { 11 | Name string `json:"name"` 12 | } `json:"author"` 13 | } `json:"commit"` 14 | } 15 | -------------------------------------------------------------------------------- /lib/update/update.go: -------------------------------------------------------------------------------- 1 | package update 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | "net/http" 7 | 8 | "github.com/GoToolSharing/htb-cli/config" 9 | "github.com/GoToolSharing/htb-cli/lib/utils" 10 | ) 11 | 12 | func Check(newVersion string) (string, error) { 13 | // Dev version 14 | config.GlobalConfig.Logger.Debug(fmt.Sprintf("config.Version: %s", config.Version)) 15 | if config.Version == "dev" { 16 | config.GlobalConfig.Logger.Info("Development version detected") 17 | return "Development version", nil 18 | } 19 | 20 | // Main version 21 | githubVersion := "https://api.github.com/repos/GoToolSharing/htb-cli/releases/latest" 22 | 23 | resp, err := utils.HTTPRequest(http.MethodGet, githubVersion, nil) 24 | if err != nil { 25 | return "", err 26 | } 27 | var release GitHubRelease 28 | if err := json.NewDecoder(resp.Body).Decode(&release); err != nil { 29 | return "", fmt.Errorf("error when decoding JSON: %v", err) 30 | } 31 | config.GlobalConfig.Logger.Debug(fmt.Sprintf("release.TagName : %s", release.TagName)) 32 | config.GlobalConfig.Logger.Debug(fmt.Sprintf("config.Version : %s", config.Version)) 33 | var message string 34 | if release.TagName != config.Version { 35 | message = fmt.Sprintf("A new update is now available ! (%s)\nUpdate with : go install github.com/GoToolSharing/htb-cli@latest", release.TagName) 36 | } else { 37 | message = fmt.Sprintf("You're up to date ! (%s)", config.Version) 38 | } 39 | 40 | return message, nil 41 | } 42 | -------------------------------------------------------------------------------- /lib/utils/api.go: -------------------------------------------------------------------------------- 1 | package utils 2 | 3 | import ( 4 | "fmt" 5 | "time" 6 | ) 7 | 8 | const dateFormat = "2006-01-02" 9 | 10 | // ParseAndFormatDate takes an input date string, parses it into a time.Time object, and formats it to the "2006-01-02" format. 11 | func ParseAndFormatDate(input string) (string, error) { 12 | t, err := time.Parse(time.RFC3339Nano, input) 13 | if err != nil { 14 | return "", fmt.Errorf("error parsing date [%s]: %v", input, err) 15 | } 16 | return t.Format(dateFormat), nil 17 | } 18 | 19 | // SetStatus determines the status based on user and root flags. 20 | func SetStatus(data map[string]interface{}) string { 21 | userFlag, userFlagExists := data["authUserInUserOwns"].(bool) 22 | rootFlag, rootFlagExists := data["authUserInRootOwns"].(bool) 23 | 24 | switch { 25 | case !userFlagExists && !rootFlagExists: 26 | return "No flags" 27 | case userFlag && !rootFlag: 28 | return "User flag" 29 | case !userFlag && rootFlag: 30 | return "Root flag" 31 | case userFlag && rootFlag: 32 | return "User & Root" 33 | default: 34 | return "No flags" 35 | } 36 | } 37 | 38 | // SetRetiredStatus determines whether an item is retired or not. 39 | func SetRetiredStatus(data map[string]interface{}) string { 40 | if retired, exists := data["retired"].(bool); exists && !retired { 41 | return "Yes" 42 | } 43 | return "No" 44 | } 45 | -------------------------------------------------------------------------------- /lib/utils/models.go: -------------------------------------------------------------------------------- 1 | package utils 2 | 3 | type Machine struct { 4 | ID int `json:"id"` 5 | Value string `json:"value"` 6 | } 7 | 8 | type Challenge struct { 9 | ID int `json:"id"` 10 | Value string `json:"value"` 11 | } 12 | 13 | type Username struct { 14 | ID int `json:"id"` 15 | Value string `json:"value"` 16 | } 17 | 18 | type Root struct { 19 | Machines interface{} `json:"machines"` 20 | Challenges interface{} `json:"challenges"` 21 | Usernames interface{} `json:"users"` 22 | } 23 | 24 | // Fortreses 25 | 26 | type Item struct { 27 | ID int `json:"id"` 28 | Name string `json:"name"` 29 | } 30 | 31 | // Structure pour représenter le JSON entier 32 | type JsonResponse struct { 33 | Status bool `json:"status"` 34 | Data map[string]Item `json:"data"` 35 | } 36 | 37 | // Prolabs 38 | 39 | type Lab struct { 40 | ID int `json:"id"` 41 | Name string `json:"name"` 42 | } 43 | 44 | // Structure pour représenter la section 'data' du JSON 45 | type Data struct { 46 | Labs []Lab `json:"labs"` 47 | } 48 | 49 | // Structure pour représenter le JSON entier 50 | type ProlabJsonResponse struct { 51 | Status bool `json:"status"` 52 | Data Data `json:"data"` 53 | } 54 | 55 | // Challenges 56 | 57 | type ChallengeFinder struct { 58 | ID int `json:"id"` 59 | Name string `json:"name"` 60 | } 61 | 62 | type ChallengeResponseFinder struct { 63 | ChallengesFinder []ChallengeFinder `json:"challenges"` 64 | } 65 | 66 | // Activity 67 | 68 | type Activity struct { 69 | CreatedAt string `json:"created_at"` 70 | Date string `json:"date"` 71 | DateDiff string `json:"date_diff"` 72 | UserID int `json:"user_id"` 73 | UserName string `json:"user_name"` 74 | UserAvatar string `json:"user_avatar"` 75 | Type string `json:"type"` 76 | } 77 | 78 | type InfoActivity struct { 79 | Activities []Activity `json:"activity"` 80 | } 81 | 82 | type DataActivity struct { 83 | Info InfoActivity `json:"info"` 84 | } 85 | -------------------------------------------------------------------------------- /lib/utils/tui.go: -------------------------------------------------------------------------------- 1 | package utils 2 | 3 | import ( 4 | "fmt" 5 | "strings" 6 | 7 | "github.com/rivo/tview" 8 | ) 9 | 10 | const ( 11 | maxFortressNameLength = 9 12 | maxProlabNameLength = 11 13 | maxActivityNameLength = 11 14 | ) 15 | 16 | // Calculates the spacing between keys and values to ensure alignment 17 | func calculateSpacing(baseName string, maxNameLength int) string { 18 | return fmt.Sprintf("%-*s", maxNameLength-len(baseName)+1, "") 19 | } 20 | 21 | // Parse and return the user's subscription level 22 | func parseUserSubscription(profile map[string]interface{}) string { 23 | isVip := profile["isVip"].(bool) 24 | isDedicatedVIP := profile["isDedicatedVip"].(bool) 25 | 26 | if isDedicatedVIP { 27 | return "VIP+" 28 | } else if isVip { 29 | return "VIP" 30 | } 31 | 32 | return "Free" 33 | } 34 | 35 | // Format output for display in tview 36 | func formatFlagInfo(name string, ownedFlags, totalFlags float64, flagSymbol string, maxNameLength int) string { 37 | var color string 38 | if ownedFlags == totalFlags { 39 | color = "[green]" 40 | } else if ownedFlags == 0 { 41 | color = "[red]" 42 | } else { 43 | color = "[orange]" 44 | } 45 | 46 | spacing := calculateSpacing(name, maxNameLength) 47 | 48 | return fmt.Sprintf("[::b]%s %s%s: %s%.0f/%.0f[-]", flagSymbol, name, spacing, color, ownedFlags, totalFlags) 49 | } 50 | 51 | // Add items and display in tview 52 | func displayInfoPanel(title string, items []interface{}, formatterFunc func(map[string]interface{}) string, paddingBottom int) *tview.Flex { 53 | panel := tview.NewFlex().SetDirection(tview.FlexRow) 54 | panel.SetBorder(true).SetTitle(title).SetTitleAlign(tview.AlignLeft) 55 | 56 | isScrollable := title == "Activity" 57 | textView := tview.NewTextView().SetDynamicColors(true).SetScrollable(isScrollable) 58 | 59 | for _, itemInterface := range items { 60 | item, ok := itemInterface.(map[string]interface{}) 61 | if !ok { 62 | fmt.Fprintln(textView, "Error: couldn't convert item to a map[string]interface{}") 63 | continue 64 | } 65 | 66 | text := formatterFunc(item) 67 | fmt.Fprintln(textView, text) 68 | } 69 | 70 | panel.AddItem(textView, 0, 1, false) 71 | 72 | return panel 73 | } 74 | 75 | // Get the right keys for display 76 | func displayInfo(dataMaps map[string]map[string]interface{}, dataMapKey string, title string, flagSymbol string, maxNameLength int, paddingBottom int) *tview.Flex { 77 | items, ok := dataMaps[strings.ToUpper(string(dataMapKey[0]))+dataMapKey[1:]][dataMapKey].([]interface{}) 78 | if !ok { 79 | fmt.Println("Error: couldn't convert data") 80 | return nil 81 | } 82 | 83 | var formatterFunc func(item map[string]interface{}) string 84 | if dataMapKey == "activity" { 85 | formatterFunc = func(item map[string]interface{}) string { 86 | var object_type interface{} 87 | switch item["object_type"].(string) { 88 | case "fortress": 89 | object_type = item["flag_title"] 90 | case "challenge": 91 | object_type = item["challenge_category"] 92 | case "machine": 93 | switch item["type"].(string) { 94 | case "root": 95 | object_type = "System" 96 | case "user": 97 | object_type = "User" 98 | default: 99 | object_type = item["type"].(string) 100 | } 101 | } 102 | return fmt.Sprintf("[::b]Owned %v - %s %s - %s - [green]+[%vpts][-]", object_type, item["name"], item["object_type"], item["date_diff"], item["points"]) 103 | } 104 | } else { 105 | formatterFunc = func(item map[string]interface{}) string { 106 | return formatFlagInfo(item["name"].(string), item["owned_flags"].(float64), item["total_flags"].(float64), flagSymbol, maxNameLength) 107 | } 108 | } 109 | 110 | return displayInfoPanel(title, items, formatterFunc, paddingBottom) 111 | } 112 | 113 | // Initializes and displays user information in tview 114 | func DisplayInformationsGUI(profile map[string]interface{}, advancedLabsMap map[string]map[string]interface{}) { 115 | 116 | teamName, teamRank := "N/A", "N/A" 117 | universityName, universityRank := "N/A", "N/A" 118 | 119 | if teamMap, ok := profile["team"].(map[string]interface{}); ok && teamMap != nil { 120 | teamName = teamMap["name"].(string) 121 | teamRank = fmt.Sprintf("%v", teamMap["ranking"].(float64)) 122 | } 123 | 124 | if universityMap, ok := profile["university"].(map[string]interface{}); ok && universityMap != nil { 125 | universityName = universityMap["name"].(string) 126 | universityRank = fmt.Sprintf("%v", universityMap["rank"].(float64)) 127 | } 128 | 129 | subscription := parseUserSubscription(profile) 130 | rankRequirement := "100" 131 | if val, ok := profile["rank_requirement"].(float64); ok { 132 | rankRequirement = fmt.Sprintf("%.0f", val) 133 | } 134 | 135 | ranking := "N/A" 136 | if rank, ok := profile["ranking"].(float64); ok { 137 | ranking = fmt.Sprintf("%.0f", rank) 138 | } 139 | 140 | app := tview.NewApplication() 141 | 142 | userInformationsFlex := tview.NewFlex().SetDirection(tview.FlexRow) 143 | userInformationsFlex.SetBorder(true).SetTitle("Profile").SetTitleAlign(tview.AlignLeft) 144 | userInformationsFlex.AddItem(tview.NewTextView().SetText(fmt.Sprintf("[::b]ID : %d[-]", int(profile["id"].(float64)))).SetDynamicColors(true), 1, 0, false) 145 | userInformationsFlex.AddItem(tview.NewTextView().SetText(fmt.Sprintf("[::b]Name : %v[-]", profile["name"])).SetDynamicColors(true), 1, 0, false) 146 | userInformationsFlex.AddItem(tview.NewTextView().SetText(fmt.Sprintf("[::b]Team : %v[-]", teamName)).SetDynamicColors(true), 1, 0, false) 147 | userInformationsFlex.AddItem(tview.NewTextView().SetText(fmt.Sprintf("[::b]University : %v[-]", universityName)).SetDynamicColors(true), 1, 0, false) 148 | userInformationsFlex.AddItem(tview.NewTextView().SetText(fmt.Sprintf("[::b]Country : %v[-]", profile["country_name"])).SetDynamicColors(true), 1, 0, false) 149 | userInformationsFlex.AddItem(tview.NewTextView().SetText(fmt.Sprintf("[::b]Subscription : %v[-]", subscription)).SetDynamicColors(true), 1, 0, false) 150 | 151 | userRankingInformationsFlex := tview.NewFlex().SetDirection(tview.FlexRow) 152 | userRankingInformationsFlex.SetBorder(true).SetTitle("Ranking Informations").SetTitleAlign(tview.AlignLeft) 153 | userRankingInformationsFlex.AddItem(tview.NewTextView().SetText(fmt.Sprintf("[::b]Global : %v[-]\U0001F3C6", ranking)).SetDynamicColors(true), 1, 0, false) 154 | userRankingInformationsFlex.AddItem(tview.NewTextView().SetText(fmt.Sprintf("[::b]Team : %v[-]\U0001F91D", teamRank)).SetDynamicColors(true), 1, 0, false) 155 | userRankingInformationsFlex.AddItem(tview.NewTextView().SetText(fmt.Sprintf("[::b]University : %v[-]\U0001F3EB", universityRank)).SetDynamicColors(true), 1, 0, false) 156 | userRankingInformationsFlex.AddItem(tview.NewTextView().SetText(fmt.Sprintf("[::b]Points : %v[-]\U0001F396", profile["points"])).SetDynamicColors(true), 1, 0, false) 157 | userRankingInformationsFlex.AddItem(tview.NewTextView().SetText(fmt.Sprintf("[::b]Rank : %v[-]", profile["rank"])).SetDynamicColors(true), 1, 0, false) 158 | userRankingInformationsFlex.AddItem(tview.NewTextView().SetText(fmt.Sprintf("[::b]Ownership : %v%% / %v%%[-]", profile["rank_ownership"], rankRequirement)).SetDynamicColors(true), 1, 0, false) 159 | 160 | userMiscInformationsFlex := tview.NewFlex().SetDirection(tview.FlexRow) 161 | userMiscInformationsFlex.SetBorder(true).SetTitle("Misc").SetTitleAlign(tview.AlignLeft) 162 | userMiscInformationsFlex.AddItem(tview.NewTextView().SetText(fmt.Sprintf("[::b]User Bloods : %v\U0001FA78[-]", profile["user_bloods"])).SetDynamicColors(true), 1, 0, false) 163 | userMiscInformationsFlex.AddItem(tview.NewTextView().SetText(fmt.Sprintf("[::b]System Bloods : %v\U0001FA78[-]", profile["system_bloods"])).SetDynamicColors(true), 1, 0, false) 164 | userMiscInformationsFlex.AddItem(tview.NewTextView().SetText(fmt.Sprintf("[::b]User Owns : %v[-]", profile["user_owns"])).SetDynamicColors(true), 1, 0, false) 165 | userMiscInformationsFlex.AddItem(tview.NewTextView().SetText(fmt.Sprintf("[::b]System Owns : %v[-]", profile["system_owns"])).SetDynamicColors(true), 1, 0, false) 166 | userMiscInformationsFlex.AddItem(tview.NewTextView().SetText(fmt.Sprintf("[::b]Respects : %v[-]", profile["respects"])).SetDynamicColors(true), 1, 0, false) 167 | userMiscInformationsFlex.AddItem(tview.NewTextView().SetText(fmt.Sprintf("[::b]Public : %v[-]", profile["public"])).SetDynamicColors(true), 1, 0, false) 168 | 169 | userInformationsContainer := tview.NewFlex(). 170 | SetDirection(tview.FlexRow). 171 | SetDirection(tview.FlexColumn). 172 | AddItem(userInformationsFlex, 0, 1, false). 173 | AddItem(userRankingInformationsFlex, 0, 1, false). 174 | AddItem(userMiscInformationsFlex, 0, 1, false) 175 | 176 | fortressesPanel := displayInfo(advancedLabsMap, "fortresses", "Fortresses", "\U0001F3F0", maxFortressNameLength, 4) 177 | prolabsPanel := displayInfo(advancedLabsMap, "prolabs", "Pro Labs", "\U0001F47D", maxProlabNameLength, 4) 178 | activityPanel := displayInfo(advancedLabsMap, "activity", "Activity", "", maxActivityNameLength, 3) 179 | 180 | advancedLabsFlex := tview.NewFlex(). 181 | SetDirection(tview.FlexRow). 182 | SetDirection(tview.FlexColumn). 183 | AddItem(fortressesPanel, 0, 1, false). 184 | AddItem(prolabsPanel, 0, 1, false) 185 | 186 | leftFlex := tview.NewFlex(). 187 | SetDirection(tview.FlexRow). 188 | AddItem(userInformationsContainer, 0, 1, false). 189 | AddItem(advancedLabsFlex, 0, 1, false). 190 | AddItem(activityPanel, 0, 2, false) 191 | 192 | mainFlex := tview.NewFlex(). 193 | AddItem(leftFlex, 0, 2, false) 194 | 195 | // Run the application 196 | if err := app.SetRoot(mainFlex, true).Run(); err != nil { 197 | panic(err) 198 | } 199 | } 200 | -------------------------------------------------------------------------------- /lib/utils/utils.go: -------------------------------------------------------------------------------- 1 | package utils 2 | 3 | import ( 4 | "bytes" 5 | "crypto/tls" 6 | "encoding/json" 7 | "errors" 8 | "fmt" 9 | "io" 10 | "net/http" 11 | "net/url" 12 | "os" 13 | "os/signal" 14 | "os/user" 15 | "strings" 16 | "sync" 17 | "syscall" 18 | "text/tabwriter" 19 | "time" 20 | 21 | "github.com/AlecAivazis/survey/v2" 22 | "github.com/GoToolSharing/htb-cli/config" 23 | "github.com/briandowns/spinner" 24 | "github.com/sahilm/fuzzy" 25 | ) 26 | 27 | // SetTabWriterHeader will display the information in an array 28 | func SetTabWriterHeader(header string) *tabwriter.Writer { 29 | w := tabwriter.NewWriter(os.Stdout, 0, 0, 3, ' ', tabwriter.Debug) 30 | fmt.Fprintln(w, header) 31 | return w 32 | } 33 | 34 | // SetTabWriterData will write the contents of each array cell 35 | func SetTabWriterData(w *tabwriter.Writer, data string) { 36 | fmt.Fprint(w, data) 37 | } 38 | 39 | // AskConfirmation will request confirmation from the user 40 | func AskConfirmation(message string) bool { 41 | if !config.GlobalConfig.BatchParam { 42 | var confirmation bool 43 | prompt := &survey.Confirm{ 44 | Message: message, 45 | } 46 | if err := survey.AskOne(prompt, &confirmation); err != nil { 47 | return false 48 | } 49 | return confirmation 50 | } 51 | return true 52 | } 53 | 54 | // GetHTBToken checks whether the HTB_TOKEN environment variable exists 55 | func GetHTBToken() (string, error) { 56 | var envName = "HTB_TOKEN" 57 | var htbToken = os.Getenv(envName) 58 | 59 | if htbToken == "" { 60 | return "", fmt.Errorf("environment variable is not set : %v\n", envName) 61 | } 62 | 63 | parts := strings.Split(htbToken, ".") 64 | if len(parts) != 3 { 65 | return "", fmt.Errorf("the %s variable must be an app token : https://app.hackthebox.com/profile/settings", envName) 66 | } 67 | 68 | return htbToken, nil 69 | } 70 | 71 | // SearchItemIDByName will return the id of an item (machine / challenge / user) based on its name 72 | func SearchItemIDByName(item string, element_type string) (int, error) { 73 | url := fmt.Sprintf("%s/search/fetch?query=%s", config.BaseHackTheBoxAPIURL, item) 74 | resp, err := HtbRequest(http.MethodGet, url, nil) 75 | if err != nil { 76 | return 0, err 77 | } 78 | defer resp.Body.Close() 79 | json_body, _ := io.ReadAll(resp.Body) 80 | 81 | var root Root 82 | err = json.Unmarshal([]byte(json_body), &root) 83 | if err != nil { 84 | fmt.Println("error:", err) 85 | } 86 | 87 | if element_type == "Machine" { 88 | switch root.Machines.(type) { 89 | case []interface{}: 90 | // Checking if machines array is empty 91 | if len(root.Machines.([]interface{})) == 0 { 92 | fmt.Println("No machine was found") 93 | os.Exit(0) 94 | } 95 | var machines []Machine 96 | machineData, _ := json.Marshal(root.Machines) 97 | err := json.Unmarshal(machineData, &machines) 98 | if err != nil { 99 | fmt.Println("error:", err) 100 | } 101 | config.GlobalConfig.Logger.Info("Machine found") 102 | config.GlobalConfig.Logger.Debug(fmt.Sprintf("Machine name: %s", machines[0].Value)) 103 | isConfirmed := AskConfirmation("The following machine was found : " + machines[0].Value) 104 | if isConfirmed { 105 | return machines[0].ID, nil 106 | } 107 | os.Exit(0) 108 | case map[string]interface{}: 109 | // Checking if machines array is empty 110 | if len(root.Machines.(map[string]interface{})) == 0 { 111 | fmt.Println("No machine was found") 112 | os.Exit(0) 113 | } 114 | var machines map[string]Machine 115 | machineData, _ := json.Marshal(root.Machines) 116 | err := json.Unmarshal(machineData, &machines) 117 | if err != nil { 118 | fmt.Println("error:", err) 119 | } 120 | config.GlobalConfig.Logger.Info("Machine found") 121 | config.GlobalConfig.Logger.Debug(fmt.Sprintf("Machine name: %s", machines["0"].Value)) 122 | isConfirmed := AskConfirmation("The following machine was found : " + machines["0"].Value) 123 | if isConfirmed { 124 | return machines["0"].ID, nil 125 | } 126 | os.Exit(0) 127 | default: 128 | fmt.Println("No machine was found") 129 | os.Exit(0) 130 | } 131 | } else if element_type == "Challenge" { 132 | switch root.Challenges.(type) { 133 | case []interface{}: 134 | // Checking if challenges array is empty 135 | if len(root.Challenges.([]interface{})) == 0 { 136 | fmt.Println("No challenge was found") 137 | os.Exit(0) 138 | } 139 | var challenges []Challenge 140 | challengeData, _ := json.Marshal(root.Challenges) 141 | err := json.Unmarshal(challengeData, &challenges) 142 | if err != nil { 143 | fmt.Println("error:", err) 144 | } 145 | config.GlobalConfig.Logger.Info("Challenge found") 146 | config.GlobalConfig.Logger.Debug(fmt.Sprintf("Challenge name: %s", challenges[0].Value)) 147 | isConfirmed := AskConfirmation("The following challenge was found : " + challenges[0].Value) 148 | if isConfirmed { 149 | return challenges[0].ID, nil 150 | } 151 | os.Exit(0) 152 | case map[string]interface{}: 153 | // Checking if challenges array is empty 154 | if len(root.Challenges.(map[string]interface{})) == 0 { 155 | fmt.Println("No challenge was found") 156 | os.Exit(0) 157 | } 158 | var challenges map[string]Challenge 159 | challengeData, _ := json.Marshal(root.Challenges) 160 | err := json.Unmarshal(challengeData, &challenges) 161 | if err != nil { 162 | fmt.Println("error:", err) 163 | } 164 | config.GlobalConfig.Logger.Info("Challenge found") 165 | config.GlobalConfig.Logger.Debug(fmt.Sprintf("Challenge name: %s", challenges["0"].Value)) 166 | isConfirmed := AskConfirmation("The following challenge was found : " + challenges["0"].Value) 167 | if isConfirmed { 168 | return challenges["0"].ID, nil 169 | } 170 | os.Exit(0) 171 | default: 172 | fmt.Println("No challenge was found") 173 | os.Exit(0) 174 | } 175 | } else if element_type == "Username" { 176 | switch root.Usernames.(type) { 177 | case []interface{}: 178 | // Checking if usernames array is empty 179 | if len(root.Usernames.([]interface{})) == 0 { 180 | fmt.Println("No username was found") 181 | return 0, fmt.Errorf("error: No username was found") 182 | } 183 | var usernames []Username 184 | usernameData, _ := json.Marshal(root.Usernames) 185 | err := json.Unmarshal(usernameData, &usernames) 186 | if err != nil { 187 | fmt.Println("error:", err) 188 | } 189 | config.GlobalConfig.Logger.Info("Username found") 190 | config.GlobalConfig.Logger.Debug(fmt.Sprintf("Username value: %s", usernames[0].Value)) 191 | isConfirmed := AskConfirmation("The following username was found : " + usernames[0].Value) 192 | if isConfirmed { 193 | return usernames[0].ID, nil 194 | } 195 | os.Exit(0) 196 | case map[string]interface{}: 197 | // Checking if usernames array is empty 198 | if len(root.Usernames.(map[string]interface{})) == 0 { 199 | fmt.Println("No username was found") 200 | return 0, fmt.Errorf("error: No username was found") 201 | } 202 | var usernames map[string]Username 203 | usernameData, _ := json.Marshal(root.Usernames) 204 | err := json.Unmarshal(usernameData, &usernames) 205 | if err != nil { 206 | fmt.Println("error:", err) 207 | } 208 | config.GlobalConfig.Logger.Info("Username found") 209 | config.GlobalConfig.Logger.Debug(fmt.Sprintf("Username value: %s", usernames["0"].Value)) 210 | isConfirmed := AskConfirmation("The following username was found : " + usernames["0"].Value) 211 | if isConfirmed { 212 | return usernames["0"].ID, nil 213 | } 214 | os.Exit(0) 215 | default: 216 | fmt.Println("No username found") 217 | } 218 | } else { 219 | return 0, errors.New("bad element_type") 220 | } 221 | 222 | // The HackTheBox API can return either a slice or a map 223 | return 0, nil 224 | } 225 | 226 | // ParseJsonMessage will parse the result of the API request into a JSON 227 | func ParseJsonMessage(resp *http.Response, key string) interface{} { 228 | json_body, _ := io.ReadAll(resp.Body) 229 | var result map[string]interface{} 230 | err := json.Unmarshal([]byte(json_body), &result) 231 | if err != nil { 232 | fmt.Println("error:", err) 233 | } 234 | return result[key] 235 | } 236 | 237 | // GetMachineType will return the machine type 238 | func GetMachineType(machine_id int) (string, error) { 239 | // Check if the machine is the latest release 240 | url := fmt.Sprintf("%s/machine/recommended/", config.BaseHackTheBoxAPIURL) 241 | resp, err := HtbRequest(http.MethodGet, url, nil) 242 | if err != nil { 243 | return "", err 244 | } 245 | card := ParseJsonMessage(resp, "card1").(map[string]interface{}) 246 | if card["id"] == machine_id { 247 | return "release", nil 248 | } 249 | 250 | // Check if the machine is active or retired 251 | url = fmt.Sprintf("%s/machine/profile/%d", config.BaseHackTheBoxAPIURL, machine_id) 252 | resp, err = HtbRequest(http.MethodGet, url, nil) 253 | if err != nil { 254 | return "", err 255 | } 256 | info := ParseJsonMessage(resp, "info").(map[string]interface{}) 257 | if info["active"] == true { 258 | return "active", nil 259 | } else if info["retired"] == true { 260 | return "retired", nil 261 | } 262 | return "", errors.New("error: machine type not found") 263 | } 264 | 265 | // GetUserSubscription returns the user's subscription level 266 | func GetUserSubscription() (string, error) { 267 | url := fmt.Sprintf("%s/user/info", config.BaseHackTheBoxAPIURL) 268 | resp, err := HtbRequest(http.MethodGet, url, nil) 269 | if err != nil { 270 | return "", err 271 | } 272 | info := ParseJsonMessage(resp, "info").(map[string]interface{}) 273 | canAccessVIP := info["canAccessVIP"].(bool) 274 | isDedicatedVIP := info["isDedicatedVip"].(bool) 275 | 276 | if canAccessVIP { 277 | if isDedicatedVIP { 278 | return "vip+", nil 279 | } 280 | return "vip", nil 281 | } 282 | 283 | return "free", nil 284 | } 285 | 286 | // GetActiveMachineID returns the id of the active machine 287 | func GetActiveMachineID() (int, error) { 288 | url := fmt.Sprintf("%s/machine/active", config.BaseHackTheBoxAPIURL) 289 | resp, err := HtbRequest(http.MethodGet, url, nil) 290 | if err != nil { 291 | return 0, err 292 | } 293 | info := ParseJsonMessage(resp, "info") 294 | if info == nil { 295 | return 0, err 296 | } 297 | idFloat, ok := info.(map[string]interface{})["id"].(float64) 298 | if !ok { 299 | return 0, fmt.Errorf("unable to parse machine ID") 300 | } 301 | 302 | return int(idFloat), nil 303 | } 304 | 305 | // GetExpiredTime returns the expired date of the machine 306 | func GetExpiredTime(machineType string) (string, error) { 307 | if machineType == "release" { 308 | return getReleaseArenaExpiredTime() 309 | } 310 | return getActiveExpiredTime() 311 | } 312 | 313 | // getActiveExpiredTime returns the expired date of the active machine 314 | func getActiveExpiredTime() (string, error) { 315 | url := fmt.Sprintf("%s/machine/active", config.BaseHackTheBoxAPIURL) 316 | resp, err := HtbRequest(http.MethodGet, url, nil) 317 | if err != nil { 318 | return "", err 319 | } 320 | info := ParseJsonMessage(resp, "info") 321 | if info == nil { 322 | return "Undefined", nil 323 | } 324 | data := info.(map[string]interface{}) 325 | expiresAt := data["expires_at"] 326 | if expiresAt == nil { 327 | return "Undefined", nil 328 | } 329 | return expiresAt.(string), nil 330 | } 331 | 332 | // getReleaseArenaExpiredTime returns the expired date of the release arena machine 333 | func getReleaseArenaExpiredTime() (string, error) { 334 | url := fmt.Sprintf("%s/season/machine/active", config.BaseHackTheBoxAPIURL) 335 | resp, err := HtbRequest(http.MethodGet, url, nil) 336 | if err != nil { 337 | return "", err 338 | } 339 | info := ParseJsonMessage(resp, "data") 340 | if info == nil { 341 | return "Undefined", nil 342 | } 343 | data := info.(map[string]interface{}) 344 | playInfo := data["play_info"].(map[string]interface{}) 345 | expiresAt := playInfo["expires_at"] 346 | if expiresAt == nil { 347 | return "Undefined", nil 348 | } 349 | return expiresAt.(string), nil 350 | } 351 | 352 | // GetActiveMachineIP returns the ip of the active machine 353 | func GetActiveMachineIP() (string, error) { 354 | url := fmt.Sprintf("%s/machine/active", config.BaseHackTheBoxAPIURL) 355 | resp, err := HtbRequest(http.MethodGet, url, nil) 356 | if err != nil { 357 | return "", err 358 | } 359 | info := ParseJsonMessage(resp, "info") 360 | if info == nil { 361 | return "", err 362 | } 363 | config.GlobalConfig.Logger.Debug(fmt.Sprintf("Active machine informations: %v", info)) 364 | if ipValue, ok := info.(map[string]interface{})["ip"].(string); ok { 365 | return ipValue, nil 366 | } 367 | return "Undefined", nil 368 | } 369 | 370 | // GetActiveReleaseArenaMachineIP returns the ip of the active release arena machine 371 | func GetActiveReleaseArenaMachineIP() (string, error) { 372 | url := fmt.Sprintf("%s/season/machine/active", config.BaseHackTheBoxAPIURL) 373 | resp, err := HtbRequest(http.MethodGet, url, nil) 374 | if err != nil { 375 | return "", err 376 | } 377 | data := ParseJsonMessage(resp, "data") 378 | if data == nil { 379 | return "", err 380 | } 381 | config.GlobalConfig.Logger.Debug(fmt.Sprintf("Relase arena active machine informations: %v", data)) 382 | 383 | return fmt.Sprintf("%v", data.(map[string]interface{})["ip"].(string)), nil 384 | } 385 | 386 | // HtbRequest makes an HTTP request to the Hackthebox API 387 | func HtbRequest(method string, urlParam string, jsonData []byte) (*http.Response, error) { 388 | s := spinner.New(spinner.CharSets[14], 100*time.Millisecond) 389 | sigs := make(chan os.Signal, 1) 390 | signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM) 391 | go func() { 392 | <-sigs 393 | s.Stop() 394 | os.Exit(0) 395 | }() 396 | 397 | s.Start() 398 | JWT_TOKEN, err := GetHTBToken() 399 | if err != nil { 400 | s.Stop() 401 | return nil, err 402 | } 403 | 404 | req, err := http.NewRequest(method, urlParam, bytes.NewBuffer(jsonData)) 405 | if err != nil { 406 | s.Stop() 407 | return nil, err 408 | } 409 | 410 | req.Header.Set("User-Agent", "htb-cli") 411 | req.Header.Set("Authorization", "Bearer "+JWT_TOKEN) 412 | 413 | if method == http.MethodPost { 414 | req.Header.Set("Content-Type", "application/json") 415 | req.Header.Set("Accept", "application/json, text/plain, */*") 416 | } else if method == http.MethodGet { 417 | req.Header.Set("Host", config.HostHackTheBox) 418 | } 419 | 420 | transport := &http.Transport{ 421 | TLSClientConfig: &tls.Config{ 422 | InsecureSkipVerify: true, 423 | }, 424 | } 425 | 426 | if config.GlobalConfig.ProxyParam != "" { 427 | config.GlobalConfig.Logger.Info("Proxy URL found") 428 | config.GlobalConfig.Logger.Debug(fmt.Sprintf("Proxy value : %s", config.GlobalConfig.ProxyParam)) 429 | proxyURLParsed, err := url.Parse(config.GlobalConfig.ProxyParam) 430 | if err != nil { 431 | s.Stop() 432 | return nil, fmt.Errorf("error parsing proxy url : %v", err) 433 | } 434 | transport.Proxy = http.ProxyURL(proxyURLParsed) 435 | } 436 | 437 | config.GlobalConfig.Logger.Info("Sending an HTTP HTB request") 438 | config.GlobalConfig.Logger.Debug(fmt.Sprintf("Request URL: %v", req.URL)) 439 | config.GlobalConfig.Logger.Debug(fmt.Sprintf("Request method: %v", req.Method)) 440 | config.GlobalConfig.Logger.Debug(fmt.Sprintf("Request body: %v", req.Body)) 441 | 442 | client := &http.Client{Transport: transport, CheckRedirect: func(req *http.Request, via []*http.Request) error { 443 | return http.ErrUseLastResponse 444 | }} 445 | 446 | resp, err := client.Do(req) 447 | if err != nil { 448 | return nil, err 449 | } 450 | defer resp.Body.Close() 451 | body, _ := io.ReadAll(resp.Body) 452 | resp.Body = io.NopCloser(bytes.NewReader(body)) 453 | 454 | // Check if token is invalid or expired 455 | if resp.StatusCode == 302 && strings.Contains(resp.Header.Get("Location"), "/login") { 456 | s.Stop() 457 | return nil, fmt.Errorf("HTB Token appears invalid or expired") 458 | } 459 | s.Stop() 460 | return resp, nil 461 | } 462 | 463 | func TruncateString(str string, maxLength int) string { 464 | if len(str) > maxLength { 465 | return str[:maxLength] 466 | } 467 | return str 468 | } 469 | 470 | func GetInformationsFromActiveMachine() (map[string]interface{}, error) { 471 | machineID, err := GetActiveMachineID() 472 | if err != nil { 473 | return nil, err 474 | } 475 | if machineID == 0 { 476 | fmt.Println("No machine is running") 477 | return nil, nil 478 | } 479 | config.GlobalConfig.Logger.Debug(fmt.Sprintf("Machine ID: %d", machineID)) 480 | 481 | url := fmt.Sprintf("%s/machine/profile/%d", config.BaseHackTheBoxAPIURL, machineID) 482 | resp, err := HtbRequest(http.MethodGet, url, nil) 483 | if err != nil { 484 | return nil, err 485 | } 486 | info := ParseJsonMessage(resp, "info") 487 | 488 | data := info.(map[string]interface{}) 489 | 490 | return data, nil 491 | } 492 | 493 | // HTTPRequest makes an HTTP request with the specified method, URL, proxy settings, and data. 494 | func HTTPRequest(method string, urlParam string, jsonData []byte) (*http.Response, error) { 495 | s := spinner.New(spinner.CharSets[14], 100*time.Millisecond) 496 | sigs := make(chan os.Signal, 1) 497 | signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM) 498 | go func() { 499 | <-sigs 500 | s.Stop() 501 | os.Exit(0) 502 | }() 503 | 504 | s.Start() 505 | 506 | req, err := http.NewRequest(method, urlParam, bytes.NewBuffer(jsonData)) 507 | if err != nil { 508 | s.Stop() 509 | return nil, err 510 | } 511 | 512 | req.Header.Set("User-Agent", "htb-cli") 513 | 514 | if method == http.MethodPost { 515 | req.Header.Set("Content-Type", "application/json") 516 | } 517 | 518 | transport := &http.Transport{ 519 | TLSClientConfig: &tls.Config{ 520 | InsecureSkipVerify: true, 521 | }, 522 | } 523 | 524 | if config.GlobalConfig.ProxyParam != "" { 525 | config.GlobalConfig.Logger.Info("Proxy URL found") 526 | config.GlobalConfig.Logger.Debug(fmt.Sprintf("Proxy value : %s", config.GlobalConfig.ProxyParam)) 527 | proxyURLParsed, err := url.Parse(config.GlobalConfig.ProxyParam) 528 | if err != nil { 529 | s.Stop() 530 | return nil, fmt.Errorf("error parsing proxy url : %v", err) 531 | } 532 | transport.Proxy = http.ProxyURL(proxyURLParsed) 533 | } 534 | 535 | config.GlobalConfig.Logger.Info("Sending an HTTP request") 536 | config.GlobalConfig.Logger.Debug(fmt.Sprintf("Request URL: %v", req.URL)) 537 | config.GlobalConfig.Logger.Debug(fmt.Sprintf("Request method: %v", req.Method)) 538 | config.GlobalConfig.Logger.Debug(fmt.Sprintf("Request body: %v", req.Body)) 539 | 540 | client := &http.Client{Transport: transport} 541 | 542 | resp, err := client.Do(req) 543 | if err != nil { 544 | return nil, err 545 | } 546 | defer resp.Body.Close() 547 | body, _ := io.ReadAll(resp.Body) 548 | resp.Body = io.NopCloser(bytes.NewReader(body)) 549 | s.Stop() 550 | return resp, nil 551 | } 552 | 553 | // GetCurrentUsername retrieves the current system user's name. 554 | func GetCurrentUsername() string { 555 | user, _ := user.Current() 556 | return user.Username 557 | } 558 | 559 | func SearchLastReleaseArenaMachine() (int, error) { 560 | url := fmt.Sprintf("%s/season/machine/active", config.BaseHackTheBoxAPIURL) 561 | resp, err := HtbRequest(http.MethodGet, url, nil) 562 | if err != nil { 563 | return 0, err 564 | } 565 | info := ParseJsonMessage(resp, "data") 566 | if info == nil { 567 | return 0, err 568 | } 569 | config.GlobalConfig.Logger.Debug(fmt.Sprintf("Information on the last active machine: %v", info)) 570 | machineID := int(info.(map[string]interface{})["id"].(float64)) 571 | return machineID, nil 572 | } 573 | 574 | func extractNamesAndIDs(jsonData string) (map[string]int, error) { 575 | var response JsonResponse 576 | err := json.Unmarshal([]byte(jsonData), &response) 577 | if err != nil { 578 | return nil, err 579 | } 580 | 581 | namesAndIDs := make(map[string]int) 582 | for _, item := range response.Data { 583 | namesAndIDs[item.Name] = item.ID 584 | } 585 | 586 | return namesAndIDs, nil 587 | } 588 | 589 | func SearchFortressID(partialName string) (int, error) { 590 | url := fmt.Sprintf("%s/fortresses", config.BaseHackTheBoxAPIURL) 591 | resp, err := HtbRequest(http.MethodGet, url, nil) 592 | if err != nil { 593 | return 0, err 594 | } 595 | jsonData, _ := io.ReadAll(resp.Body) 596 | namesAndIDs, err := extractNamesAndIDs(string(jsonData)) 597 | if err != nil { 598 | fmt.Println("Error parsing JSON:", err) 599 | return 0, nil 600 | } 601 | 602 | var names []string 603 | for name := range namesAndIDs { 604 | names = append(names, name) 605 | } 606 | 607 | matches := fuzzy.Find(partialName, names) 608 | 609 | for _, match := range matches { 610 | matchedName := names[match.Index] 611 | isConfirmed := AskConfirmation("The following fortress was found : " + matchedName) 612 | if isConfirmed { 613 | return namesAndIDs[matchedName], nil 614 | } 615 | os.Exit(0) 616 | } 617 | return 0, nil 618 | } 619 | 620 | func SearchProlabID(partialName string) (int, error) { 621 | url := fmt.Sprintf("%s/prolabs", config.BaseHackTheBoxAPIURL) 622 | resp, err := HtbRequest(http.MethodGet, url, nil) 623 | if err != nil { 624 | return 0, err 625 | } 626 | jsonData, _ := io.ReadAll(resp.Body) 627 | namesAndIDs, err := extractProlabsNamesAndIDs(string(jsonData)) 628 | if err != nil { 629 | fmt.Println("Error parsing JSON:", err) 630 | return 0, nil 631 | } 632 | 633 | var names []string 634 | for name := range namesAndIDs { 635 | names = append(names, name) 636 | } 637 | 638 | matches := fuzzy.Find(partialName, names) 639 | 640 | for _, match := range matches { 641 | matchedName := names[match.Index] 642 | isConfirmed := AskConfirmation("The following prolab was found : " + matchedName) 643 | if isConfirmed { 644 | return namesAndIDs[matchedName], nil 645 | } 646 | os.Exit(0) 647 | } 648 | return 0, nil 649 | } 650 | 651 | func extractProlabsNamesAndIDs(jsonData string) (map[string]int, error) { 652 | var response ProlabJsonResponse 653 | err := json.Unmarshal([]byte(jsonData), &response) 654 | if err != nil { 655 | return nil, err 656 | } 657 | 658 | namesAndIDs := make(map[string]int) 659 | for _, lab := range response.Data.Labs { 660 | namesAndIDs[lab.Name] = lab.ID 661 | } 662 | 663 | return namesAndIDs, nil 664 | } 665 | 666 | // Fuzzy finder for challenges 667 | 668 | func SearchChallengeByName(partialName string) (ChallengeFinder, error) { 669 | var wg sync.WaitGroup 670 | respChan := make(chan *http.Response, 2) 671 | var allChallenges []ChallengeFinder 672 | 673 | wg.Add(2) 674 | go sendRequest(fmt.Sprintf("%s/challenge/list", config.BaseHackTheBoxAPIURL), respChan, &wg) 675 | go sendRequest(fmt.Sprintf("%s/challenge/list/retired", config.BaseHackTheBoxAPIURL), respChan, &wg) 676 | 677 | go func() { 678 | wg.Wait() 679 | close(respChan) 680 | }() 681 | 682 | for resp := range respChan { 683 | challenges := processResponse(resp) 684 | allChallenges = append(allChallenges, challenges...) 685 | } 686 | 687 | challengeNames := make([]string, len(allChallenges)) 688 | for i, ch := range allChallenges { 689 | challengeNames[i] = ch.Name 690 | } 691 | 692 | matches := fuzzy.Find(partialName, challengeNames) 693 | 694 | config.GlobalConfig.Logger.Debug(fmt.Sprintf("Challenges matches: %v", matches)) 695 | 696 | for _, match := range matches { 697 | matchedName := challengeNames[match.Index] 698 | isConfirmed := AskConfirmation("The following challenge was found : " + matchedName) 699 | if isConfirmed { 700 | for _, ch := range allChallenges { 701 | if ch.Name == matchedName { 702 | return ch, nil 703 | } 704 | } 705 | } 706 | } 707 | 708 | return ChallengeFinder{}, fmt.Errorf("no matching challenge found") 709 | } 710 | 711 | func processResponse(resp *http.Response) []ChallengeFinder { 712 | defer resp.Body.Close() 713 | var cr ChallengeResponseFinder 714 | if err := json.NewDecoder(resp.Body).Decode(&cr); err != nil { 715 | fmt.Printf("JSON decoding error %v", err) 716 | os.Exit(1) 717 | } 718 | return cr.ChallengesFinder 719 | } 720 | 721 | func sendRequest(url string, respChan chan<- *http.Response, wg *sync.WaitGroup) { 722 | defer wg.Done() 723 | resp, err := HtbRequest(http.MethodGet, url, nil) 724 | if err != nil { 725 | fmt.Printf("error sending request : %v", err) 726 | os.Exit(1) 727 | } 728 | respChan <- resp 729 | } 730 | 731 | func GetChallengeBlooder(challengeID string) (string, error) { 732 | url := fmt.Sprintf("%s/challenge/activity/%s", config.BaseHackTheBoxAPIURL, challengeID) 733 | resp, err := HtbRequest(http.MethodGet, url, nil) 734 | if err != nil { 735 | return "", err 736 | } 737 | jsonData, _ := io.ReadAll(resp.Body) 738 | 739 | var data DataActivity 740 | err = json.Unmarshal([]byte(jsonData), &data) 741 | if err != nil { 742 | panic(err) 743 | } 744 | 745 | for _, activity := range data.Info.Activities { 746 | if activity.Type == "blood" { 747 | return activity.UserName, nil 748 | } 749 | } 750 | 751 | return "Not defined", nil 752 | } 753 | -------------------------------------------------------------------------------- /lib/vpn/models.go: -------------------------------------------------------------------------------- 1 | package vpn 2 | 3 | type Assigned struct { 4 | ID int `json:"id"` 5 | FriendlyName string `json:"friendly_name"` 6 | CurrentClients int `json:"current_clients"` 7 | Location string `json:"location"` 8 | LocationFriendly string `json:"location_type_friendly"` 9 | } 10 | 11 | type Data struct { 12 | Disabled bool `json:"disabled"` 13 | Assigned Assigned `json:"assigned"` 14 | } 15 | 16 | type Response struct { 17 | Status bool `json:"status"` 18 | Data Data `json:"data"` 19 | } 20 | -------------------------------------------------------------------------------- /lib/vpn/vpn.go: -------------------------------------------------------------------------------- 1 | package vpn 2 | 3 | import ( 4 | "bufio" 5 | "encoding/json" 6 | "errors" 7 | "fmt" 8 | "io" 9 | "net/http" 10 | "os" 11 | "os/exec" 12 | "path/filepath" 13 | "strings" 14 | "sync" 15 | "time" 16 | 17 | "github.com/GoToolSharing/htb-cli/config" 18 | "github.com/GoToolSharing/htb-cli/lib/utils" 19 | ) 20 | 21 | func downloadVPN(url string) error { 22 | resp, err := utils.HtbRequest(http.MethodGet, url, nil) 23 | if err != nil { 24 | return err 25 | } 26 | defer resp.Body.Close() 27 | 28 | parts := strings.Split(url, "=") 29 | productValue := parts[len(parts)-1] 30 | 31 | if resp.StatusCode == 401 { 32 | fmt.Println("You do not have permissions to download the following vpn:", productValue) 33 | return nil 34 | } 35 | 36 | if resp.StatusCode != http.StatusOK { 37 | return fmt.Errorf("error: Bad status code : %d", resp.StatusCode) 38 | } 39 | 40 | jsonData, err := io.ReadAll(resp.Body) 41 | if err != nil { 42 | return err 43 | } 44 | 45 | var response Response 46 | err = json.Unmarshal(jsonData, &response) 47 | if err != nil { 48 | return err 49 | } 50 | 51 | vpnURL := fmt.Sprintf("%s/access/ovpnfile/%d/0", config.BaseHackTheBoxAPIURL, response.Data.Assigned.ID) 52 | resp, err = utils.HtbRequest(http.MethodGet, vpnURL, nil) 53 | if err != nil { 54 | return err 55 | } 56 | defer resp.Body.Close() 57 | 58 | if resp.StatusCode == 429 { 59 | fmt.Printf("[%s] - You have reached the limit for the number of requests. New attempt in 1 minute\n", productValue) 60 | time.Sleep(60 * time.Second) 61 | err := downloadVPN(url) 62 | if err != nil { 63 | return err 64 | } 65 | } 66 | 67 | if resp.StatusCode == 500 || resp.StatusCode == 502 || resp.StatusCode == 400 { 68 | fmt.Println("The server returned an error. New attempt to download the VPN.") 69 | time.Sleep(2 * time.Second) 70 | err := downloadVPN(url) 71 | if err != nil { 72 | return err 73 | } 74 | } 75 | 76 | if resp.StatusCode != http.StatusOK { 77 | return fmt.Errorf("error: Bad status code : %d", resp.StatusCode) 78 | } 79 | 80 | vpnName := strings.ReplaceAll(response.Data.Assigned.FriendlyName, " ", "_") 81 | if strings.Contains(url, "product=labs") { 82 | parts := strings.Split(vpnName, "_") 83 | 84 | if len(parts) > 1 { 85 | parts[1] = "Labs" 86 | } 87 | 88 | vpnName = strings.Join(parts, "_") 89 | } else if strings.Contains(url, "product=competitive") { 90 | parts := strings.Split(vpnName, "_") 91 | 92 | if len(parts) > 1 && !strings.Contains(vpnName, "Release_Arena") { 93 | parts[1] = "Release_Arena" 94 | } 95 | 96 | vpnName = strings.Join(parts, "_") 97 | } 98 | downloadPath := fmt.Sprintf("%s/%s-vpn.ovpn", config.BaseDirectory, vpnName) 99 | outFile, err := os.Create(downloadPath) 100 | if err != nil { 101 | return err 102 | } 103 | defer outFile.Close() 104 | 105 | _, err = io.Copy(outFile, resp.Body) 106 | if err != nil { 107 | return err 108 | } 109 | 110 | fmt.Println("VPN :", vpnName, "downloaded successfully") 111 | return nil 112 | } 113 | 114 | // DownloadAll downloads VPN configurations from HackTheBox for different server types. 115 | func DownloadAll() error { 116 | baseURL := fmt.Sprintf("%s/connections/servers?product=", config.BaseHackTheBoxAPIURL) 117 | urls := []string{ 118 | baseURL + "labs", 119 | baseURL + "starting_point", 120 | baseURL + "fortresses", 121 | baseURL + "competitive", 122 | } 123 | 124 | var wg sync.WaitGroup 125 | errors := make(chan error, len(urls)) 126 | 127 | for _, url := range urls { 128 | wg.Add(1) 129 | go func(url string) { 130 | defer wg.Done() 131 | err := downloadVPN(url) 132 | if err != nil { 133 | errors <- err 134 | return 135 | } 136 | }(url) 137 | } 138 | 139 | wg.Wait() 140 | close(errors) 141 | 142 | fmt.Println("") 143 | 144 | message := fmt.Sprintf("VPNs are located at the following path : %s", config.BaseDirectory) 145 | 146 | fmt.Println(message) 147 | 148 | return nil 149 | } 150 | 151 | // Start starts the VPN connection using an OpenVPN configuration file. 152 | func Start(configPath string) (string, error) { 153 | files, err := filepath.Glob(configPath) 154 | if err != nil { 155 | return "", fmt.Errorf("search error : %v", err) 156 | } 157 | config.GlobalConfig.Logger.Debug(fmt.Sprintf("VPN config file : %s", files)) 158 | if len(files) == 0 { 159 | isConfirmed := utils.AskConfirmation("VPN was not found. Would you like to download it ?") 160 | if isConfirmed { 161 | err := DownloadAll() 162 | if err != nil { 163 | return "", err 164 | } 165 | } 166 | } 167 | config.GlobalConfig.Logger.Info("VPN is starting...") 168 | cmd := "ps aux | grep '[o]penvpn'" 169 | hacktheboxFound := false 170 | processes, err := exec.Command("sh", "-c", cmd).Output() 171 | if err != nil { 172 | hacktheboxFound = false 173 | } 174 | 175 | lines := strings.Split(string(processes), "\n") 176 | 177 | config.GlobalConfig.Logger.Debug(fmt.Sprintf("VPN processes: %v", lines)) 178 | 179 | uniquePaths := make(map[string]bool) 180 | 181 | for _, line := range lines { 182 | if strings.TrimSpace(line) == "" { 183 | continue 184 | } 185 | 186 | parts := strings.Fields(line) 187 | config.GlobalConfig.Logger.Debug(fmt.Sprintf("parts: %v", parts)) 188 | processPath := parts[len(parts)-1] 189 | config.GlobalConfig.Logger.Debug(fmt.Sprintf("processPath: %v", processPath)) 190 | 191 | if _, found := uniquePaths[processPath]; found { 192 | continue 193 | } 194 | 195 | uniquePaths[processPath] = true 196 | 197 | file, err := os.Open(processPath) 198 | if err != nil { 199 | return "", fmt.Errorf("error reading file %s: %v", processPath, err) 200 | } 201 | defer file.Close() 202 | 203 | scanner := bufio.NewScanner(file) 204 | for scanner.Scan() { 205 | if strings.HasPrefix(scanner.Text(), "remote") && strings.Contains(scanner.Text(), "hackthebox.eu") { 206 | hacktheboxFound = true 207 | break 208 | } 209 | } 210 | 211 | if err := scanner.Err(); err != nil { 212 | return "", fmt.Errorf("error reading file %s: %v", processPath, err) 213 | } 214 | } 215 | 216 | // If no HackTheBox VPN found, start the VPN. 217 | if !hacktheboxFound { 218 | cmd = fmt.Sprintf("sudo openvpn %s", configPath) 219 | vpnProcess := exec.Command("sh", "-c", cmd) 220 | stdout, _ := vpnProcess.StdoutPipe() 221 | err := vpnProcess.Start() 222 | if err != nil { 223 | return "", err 224 | } 225 | 226 | scanner := bufio.NewScanner(stdout) 227 | for scanner.Scan() { 228 | line := scanner.Text() 229 | if strings.Contains(line, "Initialization Sequence Completed") { 230 | fmt.Println("VPN Started Successfully!") 231 | return "VPN Started Successfully!", nil 232 | } 233 | } 234 | 235 | if err := scanner.Err(); err != nil { 236 | return "", fmt.Errorf("error reading output from VPN command: %v", err) 237 | } 238 | return "", fmt.Errorf("VPN did not start successfully. Initialization Sequence not completed.") 239 | } 240 | 241 | fmt.Println("VPN shutdown in progress...") 242 | _, err = Stop() 243 | if err != nil { 244 | return "", err 245 | } 246 | _, err = Start(configPath) 247 | if err != nil { 248 | return "", err 249 | } 250 | return "HackTheBox VPN is already running.", nil 251 | } 252 | 253 | // Status checks the current status of the VPN connection. 254 | func Status() (bool, error) { 255 | url := fmt.Sprintf("%s/connection/status", config.BaseHackTheBoxAPIURL) 256 | resp, err := utils.HtbRequest(http.MethodGet, url, nil) 257 | if err != nil { 258 | return false, err 259 | } 260 | defer resp.Body.Close() 261 | 262 | var result []map[string]interface{} 263 | jsonBody, err := io.ReadAll(resp.Body) 264 | if err != nil { 265 | return false, fmt.Errorf("error reading response body: %s", err) 266 | } 267 | 268 | err = json.Unmarshal(jsonBody, &result) 269 | if err != nil { 270 | return false, fmt.Errorf("error unmarshalling JSON: %s", err) 271 | } 272 | 273 | if len(result) == 0 { 274 | return false, nil 275 | } 276 | 277 | for _, item := range result { 278 | connectionData, ok := item["connection"].(map[string]interface{}) 279 | if !ok { 280 | return false, errors.New("error asserting connection data") 281 | } 282 | 283 | name := connectionData["name"] 284 | ip4 := connectionData["ip4"] 285 | 286 | fmt.Printf("Name: %s, IP4: %s\n", name, ip4) 287 | } 288 | return true, nil 289 | } 290 | 291 | // Stop terminates any active HackTheBox OpenVPN connections. 292 | func Stop() (string, error) { 293 | fmt.Println("Stopping VPN if any HackTheBox connection is found...") 294 | cmd := "pgrep -fa openvpn" 295 | processes, err := exec.Command("sh", "-c", cmd).Output() 296 | if err != nil { 297 | return "No vpn connection is active", nil 298 | } 299 | 300 | lines := strings.Split(string(processes), "\n") 301 | 302 | for _, line := range lines { 303 | if strings.TrimSpace(line) == "" { 304 | continue 305 | } 306 | 307 | parts := strings.Fields(line) 308 | processID := parts[0] 309 | configPath := parts[len(parts)-1] 310 | 311 | file, err := os.Open(configPath) 312 | if err != nil { 313 | continue 314 | } 315 | defer file.Close() 316 | 317 | scanner := bufio.NewScanner(file) 318 | for scanner.Scan() { 319 | if strings.HasPrefix(scanner.Text(), "remote") && strings.Contains(scanner.Text(), "hackthebox.eu") { 320 | killCmd := fmt.Sprintf("sudo kill %s", processID) 321 | if _, err := exec.Command("sh", "-c", killCmd).Output(); err != nil { 322 | return "", nil 323 | } 324 | fmt.Printf("Killed HackTheBox VPN process %s\n", processID) 325 | } 326 | } 327 | return "Completed checking and stopping HackTheBox VPN processes.", nil 328 | 329 | } 330 | return "", nil 331 | } 332 | 333 | func getVPNConfiguration(url string) error { 334 | parts := strings.Split(url, "=") 335 | productValue := parts[len(parts)-1] 336 | resp, err := utils.HtbRequest(http.MethodGet, url, nil) 337 | if err != nil { 338 | return err 339 | } 340 | defer resp.Body.Close() 341 | 342 | if resp.StatusCode == 401 { 343 | fmt.Printf("Product: %s\nNo information available\n\n", productValue) 344 | return nil 345 | } 346 | 347 | if resp.StatusCode != http.StatusOK { 348 | return fmt.Errorf("error: Bad status code : %d", resp.StatusCode) 349 | } 350 | 351 | jsonData, err := io.ReadAll(resp.Body) 352 | if err != nil { 353 | return err 354 | } 355 | 356 | var response Response 357 | err = json.Unmarshal(jsonData, &response) 358 | if err != nil { 359 | return err 360 | } 361 | 362 | fmt.Printf("Product: %s\nID: %d\nFriendly Name: %s\nCurrent Clients: %d\nLocation: %s\n\n", productValue, response.Data.Assigned.ID, response.Data.Assigned.FriendlyName, response.Data.Assigned.CurrentClients, response.Data.Assigned.LocationFriendly) 363 | return nil 364 | } 365 | 366 | func List() error { 367 | config.GlobalConfig.Logger.Info("Recovering VPN configurations") 368 | baseURL := fmt.Sprintf("%s/connections/servers?product=", config.BaseHackTheBoxAPIURL) 369 | urls := []string{ 370 | baseURL + "labs", 371 | baseURL + "starting_point", 372 | baseURL + "fortresses", 373 | baseURL + "competitive", 374 | } 375 | 376 | var wg sync.WaitGroup 377 | errors := make(chan error, len(urls)) 378 | 379 | for _, url := range urls { 380 | wg.Add(1) 381 | go func(url string) { 382 | defer wg.Done() 383 | err := getVPNConfiguration(url) 384 | if err != nil { 385 | errors <- err 386 | return 387 | } 388 | }(url) 389 | } 390 | 391 | wg.Wait() 392 | close(errors) 393 | 394 | for err := range errors { 395 | if err != nil { 396 | return err 397 | } 398 | } 399 | 400 | return nil 401 | } 402 | -------------------------------------------------------------------------------- /lib/webhooks/models.go: -------------------------------------------------------------------------------- 1 | package webhooks 2 | 3 | // EmbedField represents a single field in an embed. 4 | type EmbedField struct { 5 | Name string `json:"name"` 6 | Value string `json:"value"` 7 | Inline bool `json:"inline"` 8 | } 9 | 10 | type EmbedThumbnail struct { 11 | URL string `json:"url"` 12 | } 13 | 14 | // Embed represents a Discord message embed. 15 | type Embed struct { 16 | Title string `json:"title,omitempty"` 17 | Description string `json:"description,omitempty"` 18 | URL string `json:"url,omitempty"` 19 | Color int `json:"color,omitempty"` 20 | Fields []EmbedField `json:"fields,omitempty"` 21 | Thumbnail EmbedThumbnail `json:"thumbnail,omitempty"` 22 | } 23 | -------------------------------------------------------------------------------- /lib/webhooks/webhooks.go: -------------------------------------------------------------------------------- 1 | package webhooks 2 | 3 | import ( 4 | "bytes" 5 | "encoding/json" 6 | "fmt" 7 | "net/http" 8 | 9 | "github.com/GoToolSharing/htb-cli/config" 10 | "github.com/GoToolSharing/htb-cli/lib/utils" 11 | ) 12 | 13 | // SendToDiscord sends a message to a Discord channel using a webhook URL. 14 | func SendToDiscord(command string, message string) error { 15 | if config.ConfigFile["Discord"] == "False" { 16 | return nil 17 | } 18 | embed := Embed{ 19 | Title: "htb-cli", 20 | Description: fmt.Sprintf("User **%s** used the **%s** command.\n**Message:** %s", utils.GetCurrentUsername(), command, message), 21 | Color: 12345, 22 | Thumbnail: EmbedThumbnail{ 23 | URL: "https://github.com/GoToolSharing/htb-cli/blob/main/assets/logo.png?raw=true", 24 | }, 25 | } 26 | payload := map[string]interface{}{ 27 | "embeds": []Embed{embed}, 28 | } 29 | jsonData, err := json.Marshal(payload) 30 | if err != nil { 31 | return fmt.Errorf("failed to create JSON data: %w", err) 32 | } 33 | 34 | req, err := http.NewRequest(http.MethodPost, config.ConfigFile["Discord"], bytes.NewBuffer(jsonData)) 35 | if err != nil { 36 | return fmt.Errorf("failed to create request: %w", err) 37 | } 38 | req.Header.Set("Content-Type", "application/json") 39 | 40 | client := &http.Client{} 41 | resp, err := client.Do(req) 42 | if err != nil { 43 | return fmt.Errorf("failed to send request: %w", err) 44 | } 45 | defer resp.Body.Close() 46 | 47 | return nil 48 | } 49 | -------------------------------------------------------------------------------- /main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "github.com/GoToolSharing/htb-cli/cmd" 5 | ) 6 | 7 | func main() { 8 | cmd.Execute() 9 | } 10 | --------------------------------------------------------------------------------