├── .devcontainer
├── Dockerfile
├── devcontainer.json
├── docker-compose.yml
└── windows
│ ├── Dockerfile
│ ├── docker-compose.yml
│ ├── entrypoint.ps1
│ └── fix-hosts.ps1
├── .gitignore
├── .travis.yml
├── .vscode
└── launch.json
├── LICENSE.txt
├── README.md
├── __main__.py
├── build.sh
├── changelog.md
├── htpclient
├── __init__.py
├── binarydownload.py
├── chunk.py
├── config.py
├── dicts.py
├── download.py
├── files.py
├── generic_cracker.py
├── generic_status.py
├── hashcat_cracker.py
├── hashcat_status.py
├── hashlist.py
├── helpers.py
├── initialize.py
├── jsonRequest.py
├── session.py
└── task.py
├── requirements-tests.txt
├── requirements.txt
└── tests
├── README.md
├── __init__.py
├── create_file_001.json
├── create_hashlist_001.json
├── create_hashlist_002.json
├── create_task_001.json
├── create_task_002.json
├── create_task_003.json
├── create_task_004.json
├── create_task_005.json
├── hashtopolis-test.yaml
├── hashtopolis.py
├── test_hashcat_brain.py
├── test_hashcat_files.py
├── test_hashcat_files_7z.py
├── test_hashcat_preprocessor.py
├── test_hashcat_runtime.py
└── test_hashcat_simple.py
/.devcontainer/Dockerfile:
--------------------------------------------------------------------------------
1 | FROM ubuntu:20.04
2 |
3 | ARG DEV_CONTAINER_USER_CMD_PRE
4 | ARG DEV_CONTAINER_USER_CMD_POST
5 |
6 | # Avoid warnings by switching to noninteractive
7 | ENV DEBIAN_FRONTEND=noninteractive
8 | ENV NODE_OPTIONS='--use-openssl-ca'
9 |
10 | # Check for and run optional user-supplied command to enable (advanced) customizations of the dev container
11 | RUN if [ -n "${DEV_CONTAINER_USER_CMD_PRE}" ]; then echo "${DEV_CONTAINER_USER_CMD_PRE}" | sh ; fi
12 |
13 | RUN groupadd vscode && useradd -rm -d /app -s /bin/bash -g vscode -u 1001 vscode
14 |
15 | RUN apt-get update \
16 | && apt-get install python3 python3-pip -y \
17 | && apt-get install git -y
18 |
19 | # Install Intel OpenCL Runtime
20 | RUN cd /tmp \
21 | && apt install wget lsb-core libnuma-dev pciutils clinfo -y \
22 | && wget http://registrationcenter-download.intel.com/akdlm/irc_nas/vcp/15532/l_opencl_p_18.1.0.015.tgz \
23 | && tar xzvf l_opencl_p_18.1.0.015.tgz \
24 | && cd l_opencl_p_18.1.0.015 \
25 | && echo "ACCEPT_EULA=accept" > silent.cfg \
26 | && echo "PSET_INSTALL_DIR=/opt/intel" >> silent.cfg \
27 | && echo "CONTINUE_WITH_OPTIONAL_ERROR=yes" >> silent.cfg \
28 | && echo "CONTINUE_WITH_INSTALLDIR_OVERWRITE=yes" >> silent.cfg \
29 | && echo "COMPONENTS=DEFAULTS" >> silent.cfg \
30 | && echo "PSET_MODE=install" >> silent.cfg \
31 | && ./install.sh -s silent.cfg
32 |
33 | # Clean
34 | RUN apt-get autoremove -y \
35 | && apt-get clean -y \
36 | && rm -rf /var/lib/apt/lists/* \
37 | && rm -rf /tmp/l_opencl_p_18.1.0.015*
38 |
39 | # Switch back to dialog for any ad-hoc use of apt-get
40 | ENV DEBIAN_FRONTEND=dialog
41 |
42 | # Configuring app / python requirements
43 | WORKDIR /app
44 | USER vscode
45 | COPY requirements.txt /app/src/
46 | COPY requirements-tests.txt /app/src/
47 | RUN /usr/bin/pip3 install -r src/requirements.txt
48 | RUN /usr/bin/pip3 install -r src/requirements-tests.txt
49 |
50 | # Check for and run optional user-supplied command to enable (advanced) customizations of the dev container
51 | RUN if [ -n "${DEV_CONTAINER_USER_CMD_POST}" ]; then echo "${DEV_CONTAINER_USER_CMD_POST}" | sh ; fi
52 |
53 | # Preventing container from exiting
54 | CMD tail -f /dev/null
55 |
--------------------------------------------------------------------------------
/.devcontainer/devcontainer.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "Hashtopolis-agent Devcontainer",
3 | "dockerComposeFile": "docker-compose.yml",
4 | "service": "hashtopolis-agent",
5 |
6 | "workspaceFolder": "/app/src",
7 | "remoteEnv": {
8 | "NODE_OPTIONS": "--use-openssl-ca"
9 | },
10 | "customizations": {
11 | "vscode": {
12 | "extensions": [
13 | "ms-python.python"
14 | ]
15 | }
16 | },
17 | "remoteUser": "vscode"
18 | }
19 |
--------------------------------------------------------------------------------
/.devcontainer/docker-compose.yml:
--------------------------------------------------------------------------------
1 | version: "3.5"
2 | services:
3 | hashtopolis-agent:
4 | container_name: hashtopolis_agent
5 | build:
6 | context: ..
7 | dockerfile: .devcontainer/Dockerfile
8 | args:
9 | - DEV_CONTAINER_USER_CMD_PRE
10 | - DEV_CONTAINER_USER_CMD_POST
11 | volumes:
12 | # This is where VS Code should expect to find your project's source code
13 | # and the value of "workspaceFolder" in .devcontainer/devcontainer.json
14 | - ..:/app/src
15 | networks:
16 | - hashtopolis_dev
17 |
18 | networks:
19 | hashtopolis_dev:
20 | # This network will also be used by the hashtopolis server and db
21 | name: hashtopolis_dev
--------------------------------------------------------------------------------
/.devcontainer/windows/Dockerfile:
--------------------------------------------------------------------------------
1 | FROM mcr.microsoft.com/windows-cssc/python3.7.2server:ltsc2022
2 | # Nano image doesn't work because some API are not available
3 |
4 | # TODO: Support for USER_CMD_PRE and POST?
5 | # TODO: Create a vscode user?
6 | # TODO: OpenCL/Nvidia?
7 |
8 | WORKDIR C:/App/
9 |
10 | # Installing python requirements
11 | COPY requirements.txt C:/App/
12 | COPY requirements-tests.txt C:/App/
13 | RUN pip3 install -r requirements.txt -r requirements-tests.txt
14 |
15 | # Fix for host.docker.internal not working
16 | COPY .devcontainer/windows/entrypoint.ps1 C:/
17 | COPY .devcontainer/windows/fix-hosts.ps1 C:/
18 |
19 | # Setting entrypoint
20 | ENTRYPOINT "C:\entrypoint.ps1"
21 |
--------------------------------------------------------------------------------
/.devcontainer/windows/docker-compose.yml:
--------------------------------------------------------------------------------
1 | version: "3"
2 | services:
3 | hashtopolis-agent-windows:
4 | container_name: hashtopolis_agent_windows
5 | build:
6 | context: ../..
7 | dockerfile: .devcontainer/windows/Dockerfile
8 | volumes:
9 | - ../..:C:\App\
10 |
--------------------------------------------------------------------------------
/.devcontainer/windows/entrypoint.ps1:
--------------------------------------------------------------------------------
1 | powershell C:\fix-hosts.ps1
2 | cmd /c ping -t localhost > $null
--------------------------------------------------------------------------------
/.devcontainer/windows/fix-hosts.ps1:
--------------------------------------------------------------------------------
1 | # Source https://github.com/docker/for-win/issues/1976
2 | # Credits https://github.com/brunnotelma
3 | $hostsFile = "C:\Windows\System32\drivers\etc\hosts"
4 |
5 | try {
6 | $DnsEntries = @("host.docker.internal", "gateway.docker.internal")
7 | # Tries resolving names for Docker
8 | foreach ($Entry in $DnsEntries) {
9 | # If any of the names are not resolved, throws an exception
10 | Resolve-DnsName -Name $Entry -ErrorAction Stop
11 | }
12 |
13 | # If it passes, means that DNS is already configured
14 | Write-Host("DNS settings are already configured.")
15 | } catch {
16 | # Gets the gateway IP address, that is the Host's IP address in the Docker network
17 | $ip = (ipconfig | where-object {$_ -match "Default Gateway"} | foreach-object{$_.Split(":")[1]}).Trim()
18 | # Read the current content from Hosts file
19 | $src = [System.IO.File]::ReadAllLines($hostsFile)
20 | # Add the a new line after the content
21 | $lines = $src += ""
22 |
23 | # Check the hosts file and write it in if its not there...
24 | if((cat $hostsFile | Select-String -Pattern "host.docker.internal") -And (cat $hostsFile | Select-String -Pattern "gateway.docker.internal")) {
25 | For ($i=0; $i -le $lines.length; $i++) {
26 | if ($lines[$i].Contains("host.docker.internal"))
27 | {
28 | $lines[$i] = ("{0} host.docker.internal" -f $ip)
29 | $lines[$i+1] = ("{0} gateway.docker.internal" -f $ip)
30 | break
31 | }
32 | }
33 | } else {
34 | $lines = $lines += "# Added by Docker for Windows"
35 | $lines = $lines += ("{0} host.docker.internal" -f $ip)
36 | $lines = $lines += ("{0} gateway.docker.internal" -f $ip)
37 | $lines = $lines += "# End of section"
38 | }
39 | # Writes the new content to the Hosts file
40 | [System.IO.File]::WriteAllLines($hostsFile, [string[]]$lines)
41 |
42 | Write-Host("New DNS settings written successfully.")
43 | }
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | *.iml
2 | *.exe
3 | 7zr
4 | *.log
5 | *.json
6 | !/tests/*.json
7 | crackers
8 | preprocessors
9 | prince
10 | files
11 | hashlists
12 | __pycache__
13 | *.zip
14 | .idea
15 | venv
16 | lock.pid
17 | .env
18 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | language: python
2 | python:
3 | - "3.5"
4 | - "3.6"
5 | - "3.7"
6 | dist: xenial
7 | sudo: true
8 | install:
9 | - pip install -r requirements.txt
10 | script:
11 | - ./build.sh
12 | - python hashtopolis.zip --version
13 |
--------------------------------------------------------------------------------
/.vscode/launch.json:
--------------------------------------------------------------------------------
1 | {
2 | "version": "0.2.0",
3 | "configurations": [
4 | {
5 | "name": "Python: Current File",
6 | "type": "python",
7 | "request": "launch",
8 | "program": ".",
9 | "args": ["--url", "http://hashtopolis/api/server.php", "--debug", "--voucher", "devvoucher"],
10 | "console": "integratedTerminal",
11 | "justMyCode": true
12 | }
13 | ]
14 | }
15 |
--------------------------------------------------------------------------------
/LICENSE.txt:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 | {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 .
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 | {project} Copyright (C) {year} {fullname}
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Hashtopolis Python Agent
2 |
3 | [](https://www.codefactor.io/repository/github/hashtopolis/agent-python)
4 | [](https://github.com/hashtopolis/agent-python)
5 | [](https://travis-ci.com/hashtopolis/agent-python)
6 |
7 | This agent is used with [Hashtopolis](https://github.com/hashtopolis/server), read the wiki or create issues there, visit the [Forum](https://hashtopolis.org).
8 | This Hashtopolis agent is only compatible with Hashtopolis versions 0.5.0 and higher.
9 |
10 | ## Prerequisites
11 |
12 | You need python3 installed on your agent system.
13 | Following python packages are required:
14 |
15 | * requests
16 | * psutil
17 |
18 | ## Manual
19 |
20 | You can either download the agent from the Hashtopolis new agent page or you can use the url shown there to download the agent with
21 | wget/curl.
22 |
23 | ### Run
24 |
25 | To run the agent you simply need to call `python3 hashtopolis.zip`. The settings/configurations normally are done via the config file, described in one of the following sections.
26 |
27 | Please note:
28 | - The client does not correctly recognize the OS when you are running in Cygwin or similar on Windows. You need to run it in Windows command line.
29 | - If you unpack the agent out of the .zip file, the automatic updating from the server won't work correctly.
30 |
31 | ### Command Line Arguments
32 |
33 | ```
34 | usage: python3 hashtopolis.zip [-h] [--de-register] [--version] [--number-only] [--disable-update] [--debug] [--voucher VOUCHER] [--url URL] [--cert CERT] [--files-path FILES_PATH]
35 | [--crackers-path CRACKERS_PATH] [--hashlists-path HASHLISTS_PATH] [--preprocessors-path PREPROCESSORS_PATH] [--zaps-path ZAPS_PATH] [--cpu-only]
36 |
37 |
38 | Hashtopolis Client v0.7.3
39 |
40 | optional arguments:
41 | -h, --help show this help message and exit
42 | --de-register client should automatically de-register from server now
43 | --version show version information
44 | --number-only when using --version show only the number
45 | --disable-update disable retrieving auto-updates of the client from the server
46 | --debug, -d enforce debugging output
47 | --voucher VOUCHER voucher to use to automatically register
48 | --url URL URL to Hashtopolis client API
49 | --cert CERT Client TLS cert bundle for Hashtopolis client API
50 | --files-path FILES_PATH
51 | Use given folder path as files location
52 | --crackers-path CRACKERS_PATH
53 | Use given folder path as crackers location
54 | --hashlists-path HASHLISTS_PATH
55 | Use given folder path as hashlists location
56 | --preprocessors-path PREPROCESSORS_PATH
57 | Use given folder path as preprocessors location
58 | --zaps-path ZAPS_PATH
59 | Use given folder path as zaps location
60 | --cpu-only Force client to register as CPU only and also only reading out CPU information
61 | ```
62 |
63 | ### Config
64 |
65 | When you run the client for the first time it will ask automatically for all the requirement settings and then saves it automatically to a config file called `config.json`. This could for example look like this:
66 |
67 | ```
68 | {
69 | "url": "https://example.org/hashtopolis/api/server.php",
70 | "token": "ABCDEFGHIJ",
71 | "uuid": "49dcd31c-3637-4f2a-8df1-b545202df5b3"
72 | }
73 | ```
74 |
75 | ### Config Options
76 |
77 | | field | type | default | description |
78 | |-----------------------|---------|---------|----------------------------------------------------------------------------|
79 | | voucher | string | | Used for agent registration (will be prompted on first start) |
80 | | url | string | | The hashtopolis API endpoint (will be prompted on first start) |
81 | | token | string | | The access token for the API (sent by server on registration) |
82 | | uuid | string | | Unique identifier of the agent (generated on registration) |
83 | | debug | boolean | false | Enables debug output |
84 | | allow-piping | boolean | false | Allows hashcat to read password candidates from stdin |
85 | | piping-threshold | integer | 95 | Restarts chunk in piping mode when GPU UTIL is below this value |
86 | | rsync | boolean | false | Enables download of wordlists and rules via rsync |
87 | | rsync-path | string | | Remote path to hashtopolis files directory |
88 | | multicast-device | string | eth0 | Device which is used to retrieve UDP multicast file distribution |
89 | | file-deletion-disable | boolean | false | Disable requesting the server for files to delete |
90 | | file-deletion-interval| integer | 600 | Interval time in seconds in which the agent should check for deleted files |
91 | | proxies | object | | Specify proxies e.g. `"proxies": {"https": "localhost:8433"}` |
92 | | auth-user | string | | HTTP Basic Auth user |
93 | | auth-password | string | | HTTP Basic Auth password |
94 | | outfile-history | boolean | false | Keep old hashcat outfiles with founds and not getting them overwritten |
95 | | files-path | string | | Use given folder path as files location |
96 | | crackers-path | string | | Use given folder path as crackers location |
97 | | hashlists-path | string | | Use given folder path as hashlists location |
98 | | preprocessors-path | string | | Use given folder path as preprocessors location |
99 | | zaps-path | string | | Use given folder path as zaps location |
100 | | cpu-only | boolean | false | Only send CPU information about agent (for CPU only agents) |
101 |
102 | ### Debug example
103 |
104 | ```
105 | {
106 | "url": "https://example.org/hashtopolis/api/server.php",
107 | "token": "7RNDqtnPxm",
108 | "uuid": "49dcd31c-3637-4f2a-8df1-b545202df5b3",
109 | "debug": true
110 | }
111 | ```
112 |
113 | ### rsync
114 |
115 | You need a user on the server which can automatically login (e.g. SSH keys) and has read access to the files directory of hashtopolis. On the client side you need rsync installed and set the following lines in your agent config.
116 |
117 | ```
118 | "rsync": true,
119 | "rsync-path": "user@yourserver:/path/to/hashtopolis/files"
120 | ```
121 |
122 | ### Multicast
123 |
124 | In order to use the multicast distribution for files, please make sure that the agents and server are prepared according to this:https://github.com/hashtopolis/runner
125 |
126 | ## Hashcat Compatibility
127 |
128 | The list contains all Hashcat versions with which the client was tested and is able to work with (other versions might work):
129 |
130 | * 6.2.6
131 | * 6.2.5
132 | * 6.2.4
133 | * 6.2.3
134 | * 6.2.2
135 | * 6.2.1
136 | * 6.2.0
137 | * 6.1.1
138 | * 6.1.0
139 | * 6.0.0
140 | * 5.1.0
141 | * 5.0.0
142 | * 4.2.1
143 | * 4.2.0
144 | * 4.1.0
145 | * 4.0.1
146 | * 4.0.0
147 |
148 | ## Generic Crackers
149 |
150 | This client is able to run generic Hashtopolis cracker binaries which fulfill the minimal functionality requirements, described [here](https://github.com/s3inlc/hashtopolis/tree/master/doc/README.md). An example implementation can be found [here](https://github.com/hashtopolis/generic-cracker)
151 |
--------------------------------------------------------------------------------
/__main__.py:
--------------------------------------------------------------------------------
1 | import glob
2 | import shutil
3 | import signal
4 | import sys
5 | import os
6 | import time
7 | from time import sleep
8 |
9 | import psutil as psutil
10 | import argparse
11 |
12 | from htpclient.binarydownload import BinaryDownload
13 | from htpclient.chunk import Chunk
14 | from htpclient.files import Files
15 | from htpclient.generic_cracker import GenericCracker
16 | from htpclient.hashcat_cracker import HashcatCracker
17 | from htpclient.hashlist import Hashlist
18 | from htpclient.helpers import start_uftpd, file_get_contents
19 | from htpclient.initialize import Initialize
20 | from htpclient.jsonRequest import *
21 | from htpclient.dicts import *
22 | import logging
23 |
24 | from htpclient.task import Task
25 |
26 | CONFIG = None
27 | binaryDownload = None
28 |
29 |
30 | def run_health_check():
31 | global CONFIG, binaryDownload
32 |
33 | logging.info("Health check requested by server!")
34 | logging.info("Retrieving health check settings...")
35 | query = copy_and_set_token(dict_getHealthCheck, CONFIG.get_value('token'))
36 | req = JsonRequest(query)
37 | ans = req.execute()
38 | if ans is None:
39 | logging.error("Failed to get health check!")
40 | sleep(5)
41 | return
42 | elif ans['response'] != 'SUCCESS':
43 | logging.error("Error on getting health check: " + str(ans))
44 | sleep(5)
45 | return
46 | binaryDownload.check_version(ans['crackerBinaryId'])
47 | check_id = ans['checkId']
48 | logging.info("Starting check ID " + str(check_id))
49 |
50 | # write hashes to file
51 | hash_file = open(CONFIG.get_value('hashlists-path') + "/health_check.txt", "w")
52 | hash_file.write("\n".join(ans['hashes']))
53 | hash_file.close()
54 |
55 | # delete old file if necessary
56 | if os.path.exists(CONFIG.get_value('hashlists-path') + "/health_check.out"):
57 | os.unlink(CONFIG.get_value('hashlists-path') + "/health_check.out")
58 |
59 | # run task
60 | cracker = HashcatCracker(ans['crackerBinaryId'], binaryDownload)
61 | start = int(time.time())
62 | [states, errors] = cracker.run_health_check(ans['attack'], ans['hashlistAlias'])
63 | end = int(time.time())
64 |
65 | # read results
66 | if os.path.exists(CONFIG.get_value('hashlists-path') + "/health_check.out"):
67 | founds = file_get_contents(CONFIG.get_value('hashlists-path') + "/health_check.out").replace("\r\n", "\n").split("\n")
68 | else:
69 | founds = []
70 | if len(states) > 0:
71 | num_gpus = len(states[0].get_temps())
72 | else:
73 | errors.append("Faild to retrieve one successful cracker state, most likely due to failing.")
74 | num_gpus = 0
75 | query = copy_and_set_token(dict_sendHealthCheck, CONFIG.get_value('token'))
76 | query['checkId'] = check_id
77 | query['start'] = start
78 | query['end'] = end
79 | query['numGpus'] = num_gpus
80 | query['numCracked'] = len(founds) - 1
81 | query['errors'] = errors
82 | req = JsonRequest(query)
83 | ans = req.execute()
84 | if ans is None:
85 | logging.error("Failed to send health check results!")
86 | sleep(5)
87 | return
88 | elif ans['response'] != 'OK':
89 | logging.error("Error on sending health check results: " + str(ans))
90 | sleep(5)
91 | return
92 | logging.info("Health check completed successfully!")
93 |
94 |
95 | # Sets up the logging to stdout and to file with different styles and with the level as set in the config if available
96 | def init_logging(args):
97 | global CONFIG
98 |
99 | log_format = '[%(asctime)s] [%(levelname)-5s] %(message)s'
100 | print_format = '%(message)s'
101 | date_format = '%Y-%m-%d %H:%M:%S'
102 | log_level = logging.INFO
103 | logfile = open('client.log', "a", encoding="utf-8")
104 |
105 | logging.getLogger("requests").setLevel(logging.WARNING)
106 |
107 | CONFIG = Config()
108 | if args.debug:
109 | CONFIG.set_value('debug', True)
110 | if CONFIG.get_value('debug'):
111 | log_level = logging.DEBUG
112 | logging.getLogger("requests").setLevel(logging.DEBUG)
113 | logging.basicConfig(level=log_level, format=print_format, datefmt=date_format)
114 | file_handler = logging.StreamHandler(logfile)
115 | file_handler.setFormatter(logging.Formatter(log_format))
116 | logging.getLogger().addHandler(file_handler)
117 |
118 |
119 | def init(args):
120 | global CONFIG, binaryDownload
121 |
122 | if len(CONFIG.get_value('files-path')) == 0:
123 | CONFIG.set_value('files-path', os.path.abspath('files'))
124 | if len(CONFIG.get_value('crackers-path')) == 0:
125 | CONFIG.set_value('crackers-path', os.path.abspath('crackers'))
126 | if len(CONFIG.get_value('hashlists-path')) == 0:
127 | CONFIG.set_value('hashlists-path', os.path.abspath('hashlists'))
128 | if len(CONFIG.get_value('zaps-path')) == 0:
129 | CONFIG.set_value('zaps-path', os.path.abspath('.'))
130 | if len(CONFIG.get_value('preprocessors-path')) == 0:
131 | CONFIG.set_value('preprocessors-path', os.path.abspath('preprocessors'))
132 |
133 | if args.files_path and len(args.files_path):
134 | CONFIG.set_value('files-path', os.path.abspath(args.files_path))
135 | if args.crackers_path and len(args.crackers_path):
136 | CONFIG.set_value('crackers-path', os.path.abspath(args.crackers_path))
137 | if args.hashlists_path and len(args.hashlists_path):
138 | CONFIG.set_value('hashlists-path', os.path.abspath(args.hashlists_path))
139 | if args.zaps_path and len(args.zaps_path):
140 | CONFIG.set_value('zaps-path', os.path.abspath(args.zaps_path))
141 | if args.preprocessors_path and len(args.preprocessors_path):
142 | CONFIG.set_value('preprocessors-path', os.path.abspath(args.preprocessors_path))
143 |
144 | logging.info("Starting client '" + Initialize.get_version() + "'...")
145 |
146 | # check if there are running hashcat.pid files around (as we assume that nothing is running anymore if the client gets newly started)
147 | if os.path.exists(CONFIG.get_value('crackers-path')):
148 | for root, dirs, files in os.walk(CONFIG.get_value('crackers-path')):
149 | for folder in dirs:
150 | if folder.isdigit() and os.path.exists(CONFIG.get_value('crackers-path') + "/" + folder + "/hashtopolis.pid"):
151 | logging.info("Cleaning hashcat PID file from " + CONFIG.get_value('crackers-path') + "/" + folder)
152 | os.unlink(CONFIG.get_value('crackers-path') + "/" + folder + "/hashtopolis.pid")
153 |
154 | session = Session(requests.Session()).s
155 | session.headers.update({'User-Agent': Initialize.get_version()})
156 |
157 | if CONFIG.get_value('proxies'):
158 | session.proxies = CONFIG.get_value('proxies')
159 |
160 | if CONFIG.get_value('auth-user') and CONFIG.get_value('auth-password'):
161 | session.auth = (CONFIG.get_value('auth-user'), CONFIG.get_value('auth-password'))
162 |
163 | # connection initialization
164 | Initialize().run(args)
165 | # download and updates
166 | binaryDownload = BinaryDownload(args)
167 | binaryDownload.run()
168 |
169 | # if multicast is set to run, we need to start the daemon
170 | if CONFIG.get_value('multicast') and Initialize().get_os() == 0:
171 | start_uftpd(Initialize().get_os_extension(), CONFIG)
172 |
173 |
174 | def loop():
175 | global binaryDownload, CONFIG
176 |
177 | logging.debug("Entering loop...")
178 | task = Task()
179 | chunk = Chunk()
180 | files = Files()
181 | hashlist = Hashlist()
182 | task_change = True
183 | last_task_id = 0
184 | cracker = None
185 | while True:
186 | CONFIG.update()
187 | files.deletion_check() # check if there are deletion orders from the server
188 | if task.get_task() is not None:
189 | last_task_id = task.get_task()['taskId']
190 | task.load_task()
191 | if task.get_task_id() == -1: # get task returned to run a health check
192 | run_health_check()
193 | task.reset_task()
194 | continue
195 | elif task.get_task() is None:
196 | task_change = True
197 | continue
198 | else:
199 | if task.get_task()['taskId'] is not last_task_id:
200 | task_change = True
201 | # try to download the needed cracker (if not already present)
202 | if not binaryDownload.check_version(task.get_task()['crackerId']):
203 | task_change = True
204 | task.reset_task()
205 | continue
206 | # if prince is used, make sure it's downloaded (deprecated, as preprocessors are integrated generally now)
207 | if 'usePrince' in task.get_task() and task.get_task()['usePrince']:
208 | if not binaryDownload.check_prince():
209 | continue
210 | # if preprocessor is used, make sure it's downloaded
211 | if 'usePreprocessor' in task.get_task() and task.get_task()['usePreprocessor']:
212 | if not binaryDownload.check_preprocessor(task):
213 | continue
214 | # check if all required files are present
215 | if not files.check_files(task.get_task()['files'], task.get_task()['taskId']):
216 | task.reset_task()
217 | continue
218 | # download the hashlist for the task
219 | if task_change and not hashlist.load_hashlist(task.get_task()['hashlistId']):
220 | task.reset_task()
221 | continue
222 | if task_change: # check if the client version is up-to-date and load the appropriate cracker
223 | binaryDownload.check_client_version()
224 | logging.info("Got cracker binary type " + binaryDownload.get_version()['name'])
225 | if binaryDownload.get_version()['name'].lower() == 'hashcat':
226 | cracker = HashcatCracker(task.get_task()['crackerId'], binaryDownload)
227 | else:
228 | cracker = GenericCracker(task.get_task()['crackerId'], binaryDownload)
229 | # if it's a task using hashcat brain, we need to load the found hashes
230 | if task_change and 'useBrain' in task.get_task() and task.get_task()['useBrain'] and not hashlist.load_found(task.get_task()['hashlistId'], task.get_task()['crackerId']):
231 | task.reset_task()
232 | continue
233 | task_change = False
234 | chunk_resp = chunk.get_chunk(task.get_task()['taskId'])
235 | if chunk_resp == 0:
236 | task.reset_task()
237 | continue
238 | elif chunk_resp == -1:
239 | # measure keyspace
240 | if not cracker.measure_keyspace(task, chunk): # failure case
241 | task.reset_task()
242 | continue
243 | elif chunk_resp == -3:
244 | run_health_check()
245 | task.reset_task()
246 | continue
247 | elif chunk_resp == -2:
248 | # measure benchmark
249 | logging.info("Benchmark task...")
250 | result = cracker.run_benchmark(task.get_task())
251 | if result == 0:
252 | sleep(10)
253 | task.reset_task()
254 | # some error must have occurred on benchmarking
255 | continue
256 | # send result of benchmark
257 | query = copy_and_set_token(dict_sendBenchmark, CONFIG.get_value('token'))
258 | query['taskId'] = task.get_task()['taskId']
259 | query['result'] = result
260 | query['type'] = task.get_task()['benchType']
261 | req = JsonRequest(query)
262 | ans = req.execute()
263 | if ans is None:
264 | logging.error("Failed to send benchmark!")
265 | sleep(5)
266 | task.reset_task()
267 | continue
268 | elif ans['response'] != 'SUCCESS':
269 | logging.error("Error on sending benchmark: " + str(ans))
270 | sleep(5)
271 | task.reset_task()
272 | continue
273 | else:
274 | logging.info("Server accepted benchmark!")
275 | continue
276 |
277 | # check if we have an invalid chunk
278 | if chunk.chunk_data() is not None and chunk.chunk_data()['length'] == 0:
279 | logging.error("Invalid chunk size (0) retrieved! Retrying...")
280 | task.reset_task()
281 | continue
282 |
283 | # run chunk
284 | logging.info("Start chunk...")
285 | cracker.run_chunk(task.get_task(), chunk.chunk_data(), task.get_preprocessor())
286 | if cracker.agent_stopped():
287 | # if the chunk was aborted by a stop from the server, we need to ask for a task again first
288 | task.reset_task()
289 | task_change = True
290 | binaryDownload.check_client_version()
291 |
292 |
293 | def de_register():
294 | global CONFIG
295 |
296 | logging.info("De-registering client..")
297 | query = copy_and_set_token(dict_deregister, CONFIG.get_value('token'))
298 | req = JsonRequest(query)
299 | ans = req.execute()
300 | if ans is None:
301 | logging.error("De-registration failed!")
302 | elif ans['response'] != 'SUCCESS':
303 | logging.error("Error on de-registration: " + str(ans))
304 | else:
305 | logging.info("Successfully de-registered!")
306 | # cleanup
307 | dirs = [CONFIG.get_value('crackers-path'), CONFIG.get_value('preprocessors-path'), CONFIG.get_value('hashlists-path'), CONFIG.get_value('files-path')]
308 | files = ['config.json', '7zr.exe', '7zr']
309 | for file in files:
310 | if os.path.exists(file):
311 | os.unlink(file)
312 | for directory in dirs:
313 | if os.path.exists(directory):
314 | shutil.rmtree(directory)
315 | r = glob.glob(CONFIG.get_value('zaps-path') + '/hashlist_*')
316 | for i in r:
317 | shutil.rmtree(i)
318 | logging.info("Cleanup finished!")
319 |
320 |
321 | if __name__ == "__main__":
322 | parser = argparse.ArgumentParser(description='Hashtopolis Client v' + Initialize.get_version_number(), prog='python3 hashtopolis.zip')
323 | parser.add_argument('--de-register', action='store_true', help='client should automatically de-register from server now')
324 | parser.add_argument('--version', action='store_true', help='show version information')
325 | parser.add_argument('--number-only', action='store_true', help='when using --version show only the number')
326 | parser.add_argument('--disable-update', action='store_true', help='disable retrieving auto-updates of the client from the server')
327 | parser.add_argument('--debug', '-d', action='store_true', help='enforce debugging output')
328 | parser.add_argument('--voucher', type=str, required=False, help='voucher to use to automatically register')
329 | parser.add_argument('--url', type=str, required=False, help='URL to Hashtopolis client API')
330 | parser.add_argument('--cert', type=str, required=False, help='Client TLS cert bundle for Hashtopolis client API')
331 | parser.add_argument('--files-path', type=str, required=False, help='Use given folder path as files location')
332 | parser.add_argument('--crackers-path', type=str, required=False, help='Use given folder path as crackers location')
333 | parser.add_argument('--hashlists-path', type=str, required=False, help='Use given folder path as hashlists location')
334 | parser.add_argument('--preprocessors-path', type=str, required=False, help='Use given folder path as preprocessors location')
335 | parser.add_argument('--zaps-path', type=str, required=False, help='Use given folder path as zaps location')
336 | parser.add_argument('--cpu-only', action='store_true', help='Force client to register as CPU only and also only reading out CPU information')
337 | args = parser.parse_args()
338 |
339 | if args.version:
340 | if args.number_only:
341 | print(Initialize.get_version_number())
342 | else:
343 | print(Initialize.get_version())
344 | sys.exit(0)
345 |
346 | if args.de_register:
347 | init_logging(args)
348 | session = Session(requests.Session()).s
349 | session.headers.update({'User-Agent': Initialize.get_version()})
350 | de_register()
351 | sys.exit(0)
352 |
353 | try:
354 | init_logging(args)
355 |
356 | # check if there is a lock file and check if this pid is still running hashtopolis
357 | if os.path.exists("lock.pid") and os.path.isfile("lock.pid"):
358 | pid = file_get_contents("lock.pid")
359 | logging.info("Found existing lock.pid, checking if python process is running...")
360 | if pid.isdigit() and psutil.pid_exists(int(pid)):
361 | try:
362 | command = psutil.Process(int(pid)).cmdline()[0].replace('\\', '/').split('/')
363 | print(command)
364 | if str.startswith(command[-1], "python"):
365 | logging.fatal("There is already a hashtopolis agent running in this directory!")
366 | sys.exit(-1)
367 | except Exception:
368 | # if we fail to determine the cmd line we assume that it's either not running anymore or another process (non-hashtopolis)
369 | pass
370 | logging.info("Ignoring lock.pid file because PID is not existent anymore or not running python!")
371 |
372 | # create lock file
373 | with open("lock.pid", 'w') as f:
374 | f.write(str(os.getpid()))
375 | f.close()
376 |
377 | init(args)
378 | loop()
379 | except KeyboardInterrupt:
380 | logging.info("Exiting...")
381 | # if lock file exists, remove
382 | if os.path.exists("lock.pid"):
383 | os.unlink("lock.pid")
384 | sys.exit()
385 |
--------------------------------------------------------------------------------
/build.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | if [ -f hashtopolis.zip ]; then
4 | rm hashtopolis.zip
5 | fi
6 |
7 | # write commit count since release into version number when compiling into zip
8 | count=$(git log $(git describe --tags --abbrev=0)..HEAD --oneline | wc -l)
9 | if [ ${count} \> 0 ];
10 | then
11 | sed -i -E 's/return "([0-9]+)\.([0-9]+)\.([0-9]+)"/return "\1.\2.\3.'$count'"/g' htpclient/initialize.py
12 | fi;
13 | zip -r hashtopolis.zip __main__.py htpclient -x "*__pycache__*"
14 | if [ ${count} \> 0 ];
15 | then
16 | sed -i -E 's/return "([0-9]+)\.([0-9]+)\.([0-9]+)\.([0-9]+)"/return "\1.\2.\3"/g' htpclient/initialize.py
17 | fi;
--------------------------------------------------------------------------------
/changelog.md:
--------------------------------------------------------------------------------
1 | ## v0.7.3-> v0.7.x
2 |
3 | ### bugfixes
4 |
5 | * Fixed bug in healthcheck on windows #hashtopolis/server/1019
6 |
7 | ## v0.7.2 -> v0.7.3
8 |
9 | ### Bugfixes
10 |
11 | * When there is an empty pid file, the agent crashes #hashtopolis/server/1028
12 |
13 | ### Enhancements
14 |
15 | * Added Windows 11 support. #hashtopolis/server/1159
16 |
17 | ## v0.7.1 -> v0.7.2
18 |
19 | ### Bugfixes
20 |
21 | * When using older hashcat version Hashtopolis doesn't detect the binary correctly (hashcat64.bin) #hashtopolis/server/1012
22 |
23 | ## v0.7.0 -> v0.7.1
24 |
25 | ### Bugfixes
26 |
27 | * Agent working again on Windows, all paths have been converted to Pathlib.Path and using the correct quoting of arguments.
28 | * 7z wordlist not extracting correctly on Windows.
29 | * preprocessor not working correctly on both Windows and Linux.
30 |
31 | ## v0.6.1 -> v0.7.0
32 |
33 | ### Enhancements
34 |
35 | * Paths for files, crackers, hashlists, zaps and preprocessors can be set via command line args or config.
36 |
37 | ### Features
38 |
39 | * Allow the agent to register as CPU only on the server and sending only CPU information.
40 |
41 | ### Bugfixes
42 |
43 | * Introduced time delay to prevent spamming server with requests when connection is refused (issue #799).
44 | * Fixed crash occurring when a custom hashcat version tag is used which contains non-numerical parts.
45 |
46 | ## v0.6.0 -> v0.6.1
47 |
48 | ### Features
49 |
50 | * Added monitoring of cpu utilization and sending to server.
51 | * Allow setting a certs bundle using for the connections.
52 |
53 | ### Bugfixes
54 | * Fixed missing space with certain attack commands.
55 | * Fixed crashing agent when hashcat benchmark output contained warnings.
56 | * Fixed version detection on Hashcat release versions.
57 | * Fixed parsing of hashcat status with no temp values.
58 |
59 | ## v0.5.0 -> v0.6.0
60 |
61 | ### Features
62 |
63 | * Generic integration of preprocessors.
64 | * Added compatibility for newer Hashcat versions with different outfile format specification.
65 |
66 | ### Bugfixes
67 |
68 | * Fixed crash handling on generic cracker for invalid binary names.
69 |
70 | ## v0.4.0 -> v0.5.0
71 |
72 | ### Enhancements
73 |
74 | * Adapt to path change of Hashcat which dropped pre-builds for 32-bit.
75 |
76 | ### Bugfixes
77 |
78 | * Increased waiting time after full hashlist crack as hashcat quits too fast.
79 |
80 | ## v0.3.0 -> v0.4.0
81 |
82 | ### Features
83 |
84 | * Agents can de-register from server automatically on quitting.
85 |
86 | ### Bugfixes
87 |
88 | * Fixed benchmark commands for hashes with have salts separated from hash.
89 |
90 | ### Enhancements
91 |
92 | * Agent checks if there is already an agent running in the same directory.
93 | * Agent cleans up old hashcat PID files on startup.
94 | * Outfile names can be unique if configured.
95 |
96 | ## v0.2.0 -> v0.3.0
97 |
98 | ### Features
99 |
100 | * Agents can run health checks requested from the server.
101 |
102 | ### Bugfixes
103 |
104 | * Fixed benchmark results when having many GPUs in one agent.
105 | * Fixed sleep after finishing of task to avoid cracks not being caught.
106 |
107 | ### Enhancements
108 |
109 | * Added check for chunk length 0 sent from the server to avoid full agent crash on running.
110 | * Using requests session
111 | * Added option for using proxies
112 | * Added HTTP Basic Auth support
113 |
114 | ## v0.1.8 -> v0.2.0
115 |
116 | ### Features
117 |
118 | * Added support for UDP multicast downloads on linux computers in local environments
119 |
120 | ### Bugfixes
121 |
122 | * Fixed when a agent starts the first time there was no logging output
123 |
124 | ## v0.1.7 -> v0.1.8
125 |
126 | ### Features
127 |
128 | * The agent can request a to-delete filename list from the server and then cleanup them locally
129 | * Piping can be enforced from the server for specific tasks.
130 |
131 | ## v0.1.6 -> v0.1.7
132 |
133 | ### Features
134 |
135 | * Agent sends GPU utilization and temperature (if available)
136 | * Added support for downloading files via rsync
137 |
138 | ### Bugfixes
139 |
140 | * Catching the correct exception on downloads
141 | * Avoiding endless loop on hashlist download error
142 |
143 | ## v0.1.5 -> v0.1.6
144 |
145 | ### Features
146 |
147 | * The agent binary can update itself automatically and restart afterwards
148 |
149 | ### Bugfixes
150 |
151 | * Fixed reading of allow-piping config variable
152 |
153 | ## v0.1.4 -> v0.1.5
154 |
155 | ### Features
156 |
157 | * When a chunk can not ideally fully use the GPU it tries to use piping to increase the speed to the most possible.
158 | * Agents can now run PRINCE tasks
159 | * Device detection for CPUs now is independent from localization on Linux computers
160 |
161 | ### Bugfixes
162 |
163 | * Fixed zap handling (including also unsalted hashes)
164 | * Added delay to avoid very fast looping on agent errors
165 |
166 | ## v0.1.3 -> v0.1.4
167 |
168 | ### Bugfixes
169 |
170 | * Fixed endless loop on error from server when sending chunk progress
171 | * Fixed a critical bug in parsing the hashcat status when TEMP values are included
172 |
173 | ## v0.1.2 -> v0.1.3
174 |
175 | * Fixed detection of 32/64 bit operating systems
176 | * Changed timestamp format on logging
177 | * Catching connection problems on downloads
178 | * Added switch to 7z extraction to force overwrite of conflicting files
179 |
180 | ## v0.1.1 -> v0.1.2
181 |
182 | * Added support for reading the 32/64bit settings from the client itself and use the appropriate hashcat binary
183 | * On the logfile output timestamp and log level are now reported
184 | * Fixed sending error function
185 | * Fixed bug with killing hashcat process in case the server sends 'stop' or an error occurs
186 | * Changed running directory for hashcat cracker, changed all paths
187 | * Extracting is overwriting existing files if present to make sure files are up-to-date
188 |
--------------------------------------------------------------------------------
/htpclient/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hashtopolis/agent-python/54c853b91004e0e554514278088da22be5f03b84/htpclient/__init__.py
--------------------------------------------------------------------------------
/htpclient/binarydownload.py:
--------------------------------------------------------------------------------
1 | import logging
2 | import os.path
3 | from pathlib import Path
4 | import stat
5 | import sys
6 | from time import sleep
7 |
8 | from htpclient.config import Config
9 | from htpclient.download import Download
10 | from htpclient.initialize import Initialize
11 | from htpclient.jsonRequest import JsonRequest
12 | from htpclient.dicts import *
13 |
14 |
15 | class BinaryDownload:
16 | def __init__(self, args):
17 | self.config = Config()
18 | self.last_version = None
19 | self.args = args
20 |
21 | def run(self):
22 | self.check_client_version()
23 | self.__check_utils()
24 |
25 | def get_version(self):
26 | return self.last_version
27 |
28 | def check_client_version(self):
29 | if self.args.disable_update:
30 | return
31 | if os.path.isfile("old.zip"):
32 | os.unlink("old.zip") # cleanup old version
33 | query = copy_and_set_token(dict_checkVersion, self.config.get_value('token'))
34 | query['version'] = Initialize.get_version_number()
35 | req = JsonRequest(query)
36 | ans = req.execute()
37 | if ans is None:
38 | logging.error("Agent version check failed!")
39 | elif ans['response'] != 'SUCCESS':
40 | logging.error("Error from server: " + str(ans['message']))
41 | else:
42 | if ans['version'] == 'OK':
43 | logging.info("Client is up-to-date!")
44 | else:
45 | url = ans['url']
46 | if not url:
47 | logging.warning("Got empty URL for client update!")
48 | else:
49 | logging.info("New client version available!")
50 | if os.path.isfile("update.zip"):
51 | os.unlink("update.zip")
52 | Download.download(url, "update.zip")
53 | if os.path.isfile("update.zip") and os.path.getsize("update.zip"):
54 | if os.path.isfile("old.zip"):
55 | os.unlink("old.zip")
56 | os.rename("hashtopolis.zip", "old.zip")
57 | os.rename("update.zip", "hashtopolis.zip")
58 | logging.info("Update received, restarting client...")
59 | if os.path.exists("lock.pid"):
60 | os.unlink("lock.pid")
61 | os.execl(sys.executable, sys.executable, "hashtopolis.zip")
62 | exit(0)
63 |
64 | def __check_utils(self):
65 | path = '7zr' + Initialize.get_os_extension()
66 | if not os.path.isfile(path):
67 | query = copy_and_set_token(dict_downloadBinary, self.config.get_value('token'))
68 | query['type'] = '7zr'
69 | req = JsonRequest(query)
70 | ans = req.execute()
71 | if ans is None:
72 | logging.error("Failed to get 7zr!")
73 | sleep(5)
74 | self.__check_utils()
75 | elif ans['response'] != 'SUCCESS' or not ans['executable']:
76 | logging.error("Getting 7zr failed: " + str(ans))
77 | sleep(5)
78 | self.__check_utils()
79 | else:
80 | Download.download(ans['executable'], path)
81 | os.chmod(path, os.stat(path).st_mode | stat.S_IEXEC)
82 | path = 'uftpd' + Initialize.get_os_extension()
83 | if not os.path.isfile(path) and self.config.get_value('multicast'):
84 | query = copy_and_set_token(dict_downloadBinary, self.config.get_value('token'))
85 | query['type'] = 'uftpd'
86 | req = JsonRequest(query)
87 | ans = req.execute()
88 | if ans is None:
89 | logging.error("Failed to get uftpd!")
90 | sleep(5)
91 | self.__check_utils()
92 | elif ans['response'] != 'SUCCESS' or not ans['executable']:
93 | logging.error("Getting uftpd failed: " + str(ans))
94 | sleep(5)
95 | self.__check_utils()
96 | else:
97 | Download.download(ans['executable'], path)
98 | os.chmod(path, os.stat(path).st_mode | stat.S_IEXEC)
99 |
100 | def check_prince(self):
101 | logging.debug("Checking if PRINCE is present...")
102 | path = "prince/"
103 | if os.path.isdir(path): # if it already exists, we don't need to download it
104 | logging.debug("PRINCE is already downloaded")
105 | return True
106 | logging.debug("PRINCE not found, download...")
107 | query = copy_and_set_token(dict_downloadBinary, self.config.get_value('token'))
108 | query['type'] = 'prince'
109 | req = JsonRequest(query)
110 | ans = req.execute()
111 | if ans is None:
112 | logging.error("Failed to load prince!")
113 | sleep(5)
114 | return False
115 | elif ans['response'] != 'SUCCESS' or not ans['url']:
116 | logging.error("Getting prince failed: " + str(ans))
117 | sleep(5)
118 | return False
119 | else:
120 | if not Download.download(ans['url'], "prince.7z"):
121 | logging.error("Download of prince failed!")
122 | sleep(5)
123 | return False
124 | if Initialize.get_os() == 1:
125 | os.system("7zr" + Initialize.get_os_extension() + " x -otemp prince.7z")
126 | else:
127 | os.system("./7zr" + Initialize.get_os_extension() + " x -otemp prince.7z")
128 | for name in os.listdir("temp"): # this part needs to be done because it is compressed with the main subfolder of prince
129 | if os.path.isdir("temp/" + name):
130 | os.rename("temp/" + name, "prince")
131 | break
132 | os.unlink("prince.7z")
133 | os.rmdir("temp")
134 | logging.debug("PRINCE downloaded and extracted")
135 | return True
136 |
137 | def check_preprocessor(self, task):
138 | logging.debug("Checking if requested preprocessor is present...")
139 | path = Path(self.config.get_value('preprocessors-path'), str(task.get_task()['preprocessor']))
140 | query = copy_and_set_token(dict_downloadBinary, self.config.get_value('token'))
141 | query['type'] = 'preprocessor'
142 | query['preprocessorId'] = task.get_task()['preprocessor']
143 | req = JsonRequest(query)
144 | ans = req.execute()
145 | if ans is None:
146 | logging.error("Failed to load preprocessor settings!")
147 | sleep(5)
148 | return False
149 | elif ans['response'] != 'SUCCESS' or not ans['url']:
150 | logging.error("Getting preprocessor settings failed: " + str(ans))
151 | sleep(5)
152 | return False
153 | else:
154 | task.set_preprocessor(ans)
155 | if os.path.isdir(path): # if it already exists, we don't need to download it
156 | logging.debug("Preprocessor is already downloaded")
157 | return True
158 | logging.debug("Preprocessor not found, download...")
159 | if not Download.download(ans['url'], "temp.7z"):
160 | logging.error("Download of preprocessor failed!")
161 | sleep(5)
162 | return False
163 | if Initialize.get_os() == 1:
164 | os.system(f"7zr{Initialize.get_os_extension()} x -otemp temp.7z")
165 | else:
166 | os.system(f"./7zr{Initialize.get_os_extension()} x -otemp temp.7z")
167 | for name in os.listdir("temp"): # this part needs to be done because it is compressed with the main subfolder of prince
168 | if os.path.isdir(Path('temp', name)):
169 | os.rename(Path('temp', name), path)
170 | break
171 | os.unlink("temp.7z")
172 | os.rmdir("temp")
173 | logging.debug("Preprocessor downloaded and extracted")
174 | return True
175 |
176 | def check_version(self, cracker_id):
177 | path = Path(self.config.get_value('crackers-path'), str(cracker_id))
178 | query = copy_and_set_token(dict_downloadBinary, self.config.get_value('token'))
179 | query['type'] = 'cracker'
180 | query['binaryVersionId'] = cracker_id
181 | req = JsonRequest(query)
182 | ans = req.execute()
183 | if ans is None:
184 | logging.error("Failed to load cracker!")
185 | sleep(5)
186 | return False
187 | elif ans['response'] != 'SUCCESS' or not ans['url']:
188 | logging.error("Getting cracker failed: " + str(ans))
189 | sleep(5)
190 | return False
191 | else:
192 | self.last_version = ans
193 | if not os.path.isdir(path):
194 | # we need to download the 7zip
195 | if not Download.download(ans['url'], self.config.get_value('crackers-path') + "/" + str(cracker_id) + ".7z"):
196 | logging.error("Download of cracker binary failed!")
197 | sleep(5)
198 | return False
199 |
200 | # we need to extract the 7zip
201 | temp_folder = Path(self.config.get_value('crackers-path'), 'temp')
202 | zip_file = Path(self.config.get_value('crackers-path'), f'{cracker_id}.7z')
203 |
204 | if Initialize.get_os() == 1:
205 | # Windows
206 | cmd = f'7zr{Initialize.get_os_extension()} x -o"{temp_folder}" "{zip_file}"'
207 | else:
208 | # Linux
209 | cmd = f"./7zr{Initialize.get_os_extension()} x -o'{temp_folder}' '{zip_file}'"
210 | os.system(cmd)
211 |
212 | # Clean up 7zip
213 | os.unlink(zip_file)
214 |
215 | # Workaround for a 7zip containing a folder name or already the contents of a cracker
216 | for name in os.listdir(temp_folder):
217 | to_check_path = Path(temp_folder, name)
218 | if os.path.isdir(to_check_path):
219 | os.rename(to_check_path, path)
220 | else:
221 | os.rename(temp_folder, path)
222 | break
223 | return True
224 |
--------------------------------------------------------------------------------
/htpclient/chunk.py:
--------------------------------------------------------------------------------
1 | import logging
2 | from time import sleep
3 |
4 | from htpclient.config import Config
5 | from htpclient.jsonRequest import JsonRequest
6 | from htpclient.dicts import *
7 |
8 |
9 | class Chunk:
10 | def __init__(self):
11 | self.config = Config()
12 | self.chunk = None
13 |
14 | def chunk_data(self):
15 | return self.chunk
16 |
17 | def get_chunk(self, task_id):
18 | query = copy_and_set_token(dict_getChunk, self.config.get_value('token'))
19 | query['taskId'] = task_id
20 | req = JsonRequest(query)
21 | ans = req.execute()
22 | if ans is None:
23 | logging.error("Failed to get chunk!")
24 | sleep(5)
25 | return 0
26 | elif ans['response'] != 'SUCCESS':
27 | logging.error("Getting of chunk failed: " + str(ans))
28 | sleep(5)
29 | return 0
30 | else:
31 | # test what kind the answer is
32 | if ans['status'] == 'keyspace_required':
33 | return -1
34 | elif ans['status'] == 'benchmark':
35 | return -2
36 | elif ans['status'] == 'fully_dispatched':
37 | return 0
38 | elif ans['status'] == 'health_check':
39 | return -3
40 | else:
41 | self.chunk = ans
42 | return 1
43 |
44 | def send_keyspace(self, keyspace, task_id):
45 | query = copy_and_set_token(dict_sendKeyspace, self.config.get_value('token'))
46 | query['taskId'] = task_id
47 | query['keyspace'] = int(keyspace)
48 | req = JsonRequest(query)
49 | ans = req.execute()
50 | if ans is None:
51 | logging.error("Failed to send keyspace!")
52 | sleep(5)
53 | return False
54 | elif ans['response'] != 'SUCCESS':
55 | logging.error("Sending of keyspace failed: " + str(ans))
56 | sleep(5)
57 | return False
58 | else:
59 | logging.info("Keyspace got accepted!")
60 | return True
61 |
--------------------------------------------------------------------------------
/htpclient/config.py:
--------------------------------------------------------------------------------
1 | import os.path
2 | import json
3 |
4 |
5 | class Config:
6 | CONFIG_FILE = "config.json"
7 | config = {}
8 |
9 | def __init__(self):
10 | # load from file
11 | if os.path.isfile(self.CONFIG_FILE):
12 | self.config = json.load(open(self.CONFIG_FILE))
13 | else:
14 | self.__save()
15 |
16 | def update(self):
17 | self.config = json.load(open(self.CONFIG_FILE))
18 |
19 | def get_value(self, key):
20 | if key in self.config:
21 | return self.config[key]
22 | return ''
23 |
24 | def set_value(self, key, val):
25 | self.config[key] = val
26 | self.__save()
27 |
28 | def __save(self):
29 | with open(self.CONFIG_FILE, 'w') as f:
30 | json.dump(self.config, f, indent=2, ensure_ascii=False)
31 |
--------------------------------------------------------------------------------
/htpclient/dicts.py:
--------------------------------------------------------------------------------
1 | from types import MappingProxyType
2 |
3 |
4 | def copy_and_set_token(dictionary, token):
5 | dict_copy = dictionary.copy()
6 | dict_copy["token"] = token
7 | return dict_copy
8 |
9 |
10 | """
11 | These dictionaries are defined using MappingProxyType() which makes them read-only.
12 | If you need to change a value you must create a copy of it. E.g.
13 | foo = dict_foo.copy()
14 | foo["key"] = "value"
15 | """
16 |
17 | dict_os = MappingProxyType(
18 | {'Linux': 0,
19 | 'Windows': 1,
20 | 'Darwin': 2})
21 |
22 | dict_ext = MappingProxyType(
23 | {0: '', # Linux
24 | 1: '.exe', # Windows
25 | 2: ''}) # Mac OS
26 |
27 | dict_sendBenchmark = MappingProxyType(
28 | {'action': 'sendBenchmark',
29 | 'token': '',
30 | 'taskId': '',
31 | 'type': '',
32 | 'result': ''})
33 |
34 | dict_getHealthCheck = MappingProxyType(
35 | {'action': 'getHealthCheck',
36 | 'token': ''}
37 | )
38 |
39 | dict_sendHealthCheck = MappingProxyType(
40 | {'action': 'sendHealthCheck',
41 | 'token': '',
42 | 'numCracked': 0,
43 | 'start': 0,
44 | 'end': 0,
45 | 'numGpus': 0,
46 | 'errors': '',
47 | 'checkId': 0}
48 | )
49 |
50 | dict_checkVersion = MappingProxyType(
51 | {'action': 'checkClientVersion',
52 | 'token': '',
53 | 'version': '',
54 | 'type': 'python'})
55 |
56 | dict_downloadBinary = MappingProxyType(
57 | {'action': 'downloadBinary',
58 | 'token': '',
59 | 'type': ''})
60 |
61 | dict_login = MappingProxyType(
62 | {'action': 'login',
63 | 'token': '',
64 | 'clientSignature': ''})
65 |
66 | dict_updateInformation = MappingProxyType(
67 | {'action': 'updateInformation',
68 | 'token': '',
69 | 'uid': '',
70 | 'os': '',
71 | 'devices': ''})
72 |
73 | dict_register = MappingProxyType(
74 | {'action': 'register',
75 | 'voucher': '',
76 | 'name': ''})
77 |
78 | dict_testConnection = MappingProxyType(
79 | {'action': 'testConnection'})
80 |
81 | dict_getChunk = MappingProxyType(
82 | {'action': 'getChunk',
83 | 'token': '',
84 | 'taskId': ''})
85 |
86 | dict_sendKeyspace = MappingProxyType(
87 | {'action': 'sendKeyspace',
88 | 'token': '',
89 | 'taskId': '',
90 | 'keyspace': 0})
91 |
92 | dict_getTask = MappingProxyType(
93 | {'action': 'getTask',
94 | 'token': ''})
95 |
96 | dict_sendProgress = MappingProxyType(
97 | {'action': 'sendProgress',
98 | 'token': '',
99 | 'chunkId': '',
100 | 'keyspaceProgress': '',
101 | 'relativeProgress': '',
102 | 'speed': '',
103 | 'state': '',
104 | 'cracks': ''})
105 |
106 | dict_clientError = MappingProxyType(
107 | {'action': 'clientError',
108 | 'token': '',
109 | 'taskId': '',
110 | 'chunkId': None,
111 | 'message': ''})
112 |
113 | dict_getHashlist = MappingProxyType(
114 | {'action': 'getHashlist',
115 | 'token': '',
116 | 'hashlistId': ''})
117 |
118 | dict_getFound = MappingProxyType(
119 | {'action': 'getFound',
120 | 'token': '',
121 | 'hashlistId': ''})
122 |
123 | dict_getFile = MappingProxyType(
124 | {'action': 'getFile',
125 | 'token': '',
126 | 'taskId': '',
127 | 'file': ''})
128 |
129 | dict_getFileStatus = MappingProxyType(
130 | {'action': 'getFileStatus',
131 | 'token': ''})
132 |
133 | dict_deregister = MappingProxyType(
134 | {'action': 'deregister',
135 | 'token': ''})
136 |
--------------------------------------------------------------------------------
/htpclient/download.py:
--------------------------------------------------------------------------------
1 | import logging
2 | from time import sleep
3 |
4 | import requests
5 | import sys
6 | import os
7 |
8 | from htpclient.initialize import Initialize
9 | from htpclient.session import Session
10 |
11 |
12 | class Download:
13 | @staticmethod
14 | def download(url, output, no_header=False):
15 | try:
16 | session = Session().s
17 |
18 | # Check header
19 | if not no_header:
20 | head = session.head(url)
21 | # not sure if we only should allow 200/301/302, but then it's present for sure
22 | if head.status_code not in [200, 301, 302]:
23 | logging.error("File download header reported wrong status code: " + str(head.status_code))
24 | return False
25 |
26 | with open(output, "wb") as file:
27 | response = session.get(url, stream=True)
28 | total_length = response.headers.get('Content-Length')
29 |
30 | if total_length is None: # no content length header
31 | file.write(response.content)
32 | else:
33 | dl = 0
34 | total_length = int(total_length)
35 | for data in response.iter_content(chunk_size=4096):
36 | dl += len(data)
37 | file.write(data)
38 | done = int(50 * dl / total_length)
39 | sys.stdout.write("\rDownloading: [%s%s]" % ('=' * done, ' ' * (50 - done)))
40 | sys.stdout.flush()
41 | sys.stdout.write("\n")
42 | return True
43 | except requests.exceptions.ConnectionError as e:
44 | logging.error("Download error: " + str(e))
45 | sleep(30)
46 | return False
47 |
48 | @staticmethod
49 | def rsync(remote_path, local_path):
50 | logging.info('getting file "%s" via rsync' % local_path.split('/')[-1])
51 | os.system('rsync -avzP --partial %s %s' % (remote_path, local_path))
52 |
--------------------------------------------------------------------------------
/htpclient/files.py:
--------------------------------------------------------------------------------
1 | import logging
2 | import time
3 | from time import sleep
4 | from pathlib import Path
5 |
6 | import os
7 |
8 | from htpclient.config import Config
9 | from htpclient.download import Download
10 | from htpclient.initialize import Initialize
11 | from htpclient.jsonRequest import JsonRequest
12 | from htpclient.dicts import *
13 |
14 |
15 | class Files:
16 | def __init__(self):
17 | self.config = Config()
18 | self.chunk = None
19 | self.last_check = None
20 | self.check_interval = 600
21 | if self.config.get_value('file-deletion-interval'):
22 | self.check_interval = int(self.config.get_value('file-deletion-interval'))
23 |
24 | def deletion_check(self):
25 | if self.config.get_value('file-deletion-disable'):
26 | return
27 | elif self.last_check is not None and time.time() - self.last_check < self.check_interval:
28 | return
29 | query = copy_and_set_token(dict_getFileStatus, self.config.get_value('token'))
30 | req = JsonRequest(query)
31 | ans = req.execute()
32 | self.last_check = time.time()
33 | if ans is None:
34 | logging.error("Failed to get file status!")
35 | elif ans['response'] != 'SUCCESS':
36 | logging.error("Getting of file status failed: " + str(ans))
37 | else:
38 | files = ans['filenames']
39 | for filename in files:
40 | file_path = Path(self.config.get_value('files-path'), filename)
41 | if filename.find("/") != -1 or filename.find("\\") != -1:
42 | continue # ignore invalid file names
43 | elif os.path.dirname(file_path) != "files":
44 | continue # ignore any case in which we would leave the files folder
45 | elif os.path.exists(file_path):
46 | logging.info("Delete file '" + filename + "' as requested by server...")
47 | # When we get the delete requests, this function will check if the .7z maybe as
48 | # an extracted text file. That file will also be deleted.
49 | if os.path.splitext(file_path)[1] == '.7z':
50 | txt_file = Path(f"{os.path.splitext(file_path)[0]}.txt")
51 | if os.path.exists(txt_file):
52 | logging.info("Also delete assumed wordlist from archive of same file...")
53 | os.unlink(txt_file)
54 | os.unlink(file_path)
55 |
56 | def check_files(self, files, task_id):
57 | for file in files:
58 | file_localpath = Path(self.config.get_value('files-path'), file)
59 | txt_file = Path(f"{os.path.splitext(file_localpath)[0]}.txt")
60 | query = copy_and_set_token(dict_getFile, self.config.get_value('token'))
61 | query['taskId'] = task_id
62 | query['file'] = file
63 | req = JsonRequest(query)
64 | ans = req.execute()
65 |
66 | # Process request
67 | if ans is None:
68 | logging.error("Failed to get file!")
69 | sleep(5)
70 | return False
71 | elif ans['response'] != 'SUCCESS':
72 | logging.error("Getting of file failed: " + str(ans))
73 | sleep(5)
74 | return False
75 | else:
76 | # Filesize is OK
77 | file_size = int(ans['filesize'])
78 | if os.path.isfile(file_localpath) and os.stat(file_localpath).st_size == file_size:
79 | logging.debug("File is present on agent and has matching file size.")
80 | continue
81 |
82 | # Multicasting configured
83 | elif self.config.get_value('multicast'):
84 | logging.debug("Multicast is enabled, need to wait until it was delivered!")
85 | sleep(5) # in case the file is not there yet (or not completely), we just wait some time and then try again
86 | return False
87 |
88 | # TODO: we might need a better check for this
89 | if os.path.isfile(txt_file):
90 | continue
91 |
92 | # Rsync
93 | if self.config.get_value('rsync') and Initialize.get_os() != 1:
94 | Download.rsync(Path(self.config.get_value('rsync-path'), file), file_localpath)
95 | else:
96 | logging.debug("Starting download of file from server...")
97 | Download.download(self.config.get_value('url').replace("api/server.php", "") + ans['url'], file_localpath)
98 |
99 | # Mismatch filesize
100 | if os.path.isfile(file_localpath) and os.stat(file_localpath).st_size != file_size:
101 | logging.error("file size mismatch on file: %s" % file)
102 | sleep(5)
103 | return False
104 |
105 | # 7z extraction, check if the .txt does exist.
106 | if os.path.splitext(file_localpath)[1] == '.7z' and not os.path.isfile(txt_file):
107 | # extract if needed
108 | files_path = Path(self.config.get_value('files-path'))
109 | if Initialize.get_os() == 1:
110 | # Windows
111 | cmd = f'7zr{Initialize.get_os_extension()} x -aoa -o"{files_path}" -y "{file_localpath}"'
112 | else:
113 | # Linux
114 | cmd = f"./7zr{Initialize.get_os_extension()} x -aoa -o'{files_path}' -y '{file_localpath}'"
115 | os.system(cmd)
116 | return True
117 |
--------------------------------------------------------------------------------
/htpclient/generic_cracker.py:
--------------------------------------------------------------------------------
1 | import logging
2 | import subprocess
3 | from time import sleep
4 | from queue import Queue, Empty
5 | from threading import Thread
6 |
7 | from htpclient.config import Config
8 | from htpclient.generic_status import GenericStatus
9 | from htpclient.helpers import send_error
10 | from htpclient.initialize import Initialize
11 | from htpclient.jsonRequest import JsonRequest
12 | from htpclient.dicts import *
13 |
14 |
15 | class GenericCracker:
16 | def __init__(self, cracker_id, binary_download):
17 | self.config = Config()
18 | self.io_q = Queue()
19 | self.callPath = self.config.get_value('crackers-path') + "/" + str(cracker_id) + "/" + binary_download.get_version()['executable']
20 | self.executable_name = binary_download.get_version()['executable']
21 | self.keyspace = 0
22 |
23 | def run_chunk(self, task, chunk, preprocessor):
24 | args = " crack -s " + str(chunk['skip'])
25 | args += " -l " + str(chunk['length'])
26 | hl_path = self.config.get_value('hashlists-path') + "/" + str(task['hashlistId'])
27 | args += " " + task['attackcmd'].replace(task['hashlistAlias'], f"'{hl_path}'")
28 | full_cmd = f"'{self.callPath}'" + args
29 | if Initialize.get_os() == 1:
30 | full_cmd = full_cmd.replace("/", '\\')
31 | logging.debug("CALL: " + full_cmd)
32 | process = subprocess.Popen(full_cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=self.config.get_value('files-path'))
33 |
34 | logging.debug("started cracking")
35 | out_thread = Thread(target=self.stream_watcher, name='stdout-watcher', args=('OUT', process.stdout))
36 | err_thread = Thread(target=self.stream_watcher, name='stderr-watcher', args=('ERR', process.stderr))
37 | out_thread.start()
38 | err_thread.start()
39 |
40 | main_thread = Thread(target=self.run_loop, name='run_loop', args=(process, chunk, task))
41 | main_thread.start()
42 |
43 | # wait for all threads to finish
44 | process.wait()
45 | out_thread.join()
46 | err_thread.join()
47 | logging.info("finished chunk")
48 |
49 | def run_loop(self, process, chunk, task):
50 | cracks = []
51 | while True:
52 | try:
53 | # Block for 1 second.
54 | item = self.io_q.get(True, 1)
55 | except Empty:
56 | # No output in either streams for a second. Are we done?
57 | if process.poll() is not None:
58 | # is the case when the process is finished
59 | break
60 | else:
61 | identifier, line = item
62 | if identifier == 'OUT':
63 | status = GenericStatus(line.decode())
64 | if status.is_valid():
65 | # send update to server
66 | progress = status.get_progress()
67 | speed = status.get_speed()
68 | initial = True
69 | while cracks or initial:
70 | initial = False
71 | cracks_backup = []
72 | if len(cracks) > 1000:
73 | # we split
74 | cnt = 0
75 | new_cracks = []
76 | for crack in cracks:
77 | cnt += 1
78 | if cnt > 1000:
79 | cracks_backup.append(crack)
80 | else:
81 | new_cracks.append(crack)
82 | cracks = new_cracks
83 |
84 | query = copy_and_set_token(dict_sendProgress, self.config.get_value('token'))
85 | query['chunkId'] = chunk['chunkId']
86 | query['keyspaceProgress'] = chunk['skip']
87 | query['relativeProgress'] = progress
88 | query['speed'] = speed
89 | query['state'] = (4 if progress == 10000 else 2)
90 | query['cracks'] = cracks
91 | req = JsonRequest(query)
92 |
93 | logging.debug("Sending " + str(len(cracks)) + " cracks...")
94 | ans = req.execute()
95 | if ans is None:
96 | logging.error("Failed to send solve!")
97 | elif ans['response'] != 'SUCCESS':
98 | logging.error("Error from server on solve: " + str(ans))
99 | else:
100 | if ans['zaps']:
101 | with open(self.config.get_value('files-path') + "/zap", "wb") as zapfile: # need to check if we are in the main dir here
102 | zapfile.write('\n'.join(ans['zaps']).encode())
103 | zapfile.close()
104 | cracks = cracks_backup
105 | logging.info(
106 | "Progress: " + str(progress / 100) + "% Cracks: " + str(len(cracks)) +
107 | " Accepted: " + str(ans['cracked']) + " Skips: " + str(ans['skipped']) + " Zaps: " + str(len(ans['zaps'])))
108 | else:
109 | line = line.decode()
110 | if ":" in line:
111 | cracks.append(line.strip())
112 | else:
113 | logging.warning("OUT: " + line.strip())
114 | else:
115 | print("ERROR: " + str(line).strip())
116 | # TODO: send error and abort cracking
117 |
118 | def measure_keyspace(self, task, chunk):
119 | task = task.get_task()
120 | full_cmd = self.callPath + " keyspace " + task['attackcmd'].replace("-a " + task['hashlistAlias'] + " ", "")
121 | if Initialize.get_os() == 1:
122 | full_cmd = full_cmd.replace("/", '\\')
123 | try:
124 | logging.debug("CALL: " + full_cmd)
125 | output = subprocess.check_output(full_cmd, shell=True, cwd=self.config.get_value('files-path'))
126 | except subprocess.CalledProcessError as e:
127 | logging.error("Error during keyspace measurement: " + str(e))
128 | send_error("Keyspace measure failed!", self.config.get_value('token'), task['taskId'], None)
129 | sleep(5)
130 | return False
131 | output = output.decode(encoding='utf-8').replace("\r\n", "\n").split("\n")
132 | keyspace = "0"
133 | for line in output:
134 | if not line:
135 | continue
136 | keyspace = line
137 | self.keyspace = int(keyspace)
138 | return chunk.send_keyspace(int(keyspace), task['taskId'])
139 |
140 | def run_benchmark(self, task):
141 | ksp = self.keyspace
142 | if ksp == 0:
143 | ksp = task['keyspace']
144 | hl_path = self.config.get_value('hashlists-path') + "/" + str(task['hashlistId'])
145 | args = task['attackcmd'].replace(task['hashlistAlias'], f"'{hl_path}'")
146 | full_cmd = self.callPath + " crack " + args + " -s 0 -l " + str(ksp) + " --timeout=" + str(task['bench'])
147 | if Initialize.get_os() == 1:
148 | full_cmd = full_cmd.replace("/", '\\')
149 | logging.debug("CALL: " + full_cmd)
150 | output = subprocess.check_output(full_cmd, shell=True, cwd=self.config.get_value('files-path'))
151 | if output:
152 | output = output.replace(b"\r\n", b"\n").decode('utf-8')
153 | output = output.split('\n')
154 | last_valid_status = None
155 | for line in output:
156 | if not line:
157 | continue
158 | status = GenericStatus(line)
159 | if status.is_valid():
160 | last_valid_status = status
161 | if last_valid_status is None:
162 | query = copy_and_set_token(dict_clientError, self.config.get_value('token'))
163 | query['taskId'] = task['taskId']
164 | query['message'] = "Generic benchmark failed!"
165 | req = JsonRequest(query)
166 | req.execute()
167 | return 0
168 | return float(last_valid_status.get_progress()) / 10000
169 | else:
170 | query = copy_and_set_token(dict_clientError, self.config.get_value('token'))
171 | query['taskId'] = task['taskId']
172 | query['message'] = "Generic benchmark gave no output!"
173 | req = JsonRequest(query)
174 | req.execute()
175 | return 0
176 |
177 | def stream_watcher(self, identifier, stream):
178 | for line in stream:
179 | self.io_q.put((identifier, line))
180 |
181 | if not stream.closed:
182 | stream.close()
183 |
184 | def agent_stopped(self):
185 | return False
186 |
--------------------------------------------------------------------------------
/htpclient/generic_status.py:
--------------------------------------------------------------------------------
1 | class GenericStatus:
2 | def __init__(self, line):
3 | # parse
4 | self.valid = False
5 | self.speed = 0
6 | self.progress = 0
7 |
8 | line = line.split(" ")
9 | if line[0] != "STATUS":
10 | # invalid line
11 | return
12 | elif len(line) != 3:
13 | # invalid line
14 | return
15 | self.progress = int(line[1])
16 | self.speed = int(line[2])
17 | self.valid = True
18 |
19 | def is_valid(self):
20 | return self.valid
21 |
22 | def get_progress(self):
23 | return self.progress
24 |
25 | def get_speed(self):
26 | return self.speed
27 |
--------------------------------------------------------------------------------
/htpclient/hashcat_status.py:
--------------------------------------------------------------------------------
1 | class HashcatStatus:
2 | def __init__(self, line):
3 | # parse
4 | self.status = -1
5 | self.speed = []
6 | self.exec_runtime = []
7 | self.curku = 0
8 | self.progress = [0, 0]
9 | self.rec_hash = [0, 0]
10 | self.rec_salt = [0, 0]
11 | self.rejected = 0
12 | self.util = []
13 | self.temp = []
14 |
15 | line = line.split("\t")
16 | if line[0] != "STATUS":
17 | # invalid line
18 | return
19 | elif len(line) < 19:
20 | # invalid line
21 | return
22 | self.status = int(line[1])
23 | index = 3
24 | while line[index] != "EXEC_RUNTIME":
25 | self.speed.append([int(line[index]), int(line[index + 1])])
26 | index += 2
27 | while line[index] != "CURKU":
28 | index += 1
29 | self.curku = int(line[index + 1])
30 | self.progress[0] = int(line[index + 3])
31 | self.progress[1] = int(line[index + 4])
32 | self.rec_hash[0] = int(line[index + 6])
33 | self.rec_hash[1] = int(line[index + 7])
34 | self.rec_salt[0] = int(line[index + 9])
35 | self.rec_salt[1] = int(line[index + 10])
36 | if line[index + 11] == "TEMP":
37 | # we have temp values
38 | index += 12
39 | while line[index] != "REJECTED":
40 | self.temp.append(int(line[index]))
41 | index += 1
42 | else:
43 | index += 11
44 | self.rejected = int(line[index + 1])
45 | if len(line) > index + 2:
46 | index += 2
47 | if line[index] == "UTIL":
48 | index += 1
49 | while len(line) - 1 > index: # -1 because the \r\n is also included in the split
50 | self.util.append(int(line[index]))
51 | index += 1
52 |
53 | def is_valid(self):
54 | return self.status >= 0
55 |
56 | def get_progress(self):
57 | return self.progress[0]
58 |
59 | def get_state(self):
60 | return self.status - 1
61 |
62 | def get_curku(self):
63 | return self.curku
64 |
65 | def get_temps(self):
66 | return self.temp
67 |
68 | def get_progress_total(self):
69 | return self.progress[1]
70 |
71 | def get_all_util(self):
72 | return self.util
73 |
74 | def get_util(self):
75 | if not self.util:
76 | return -1
77 | util_sum = 0
78 | for u in self.util:
79 | util_sum += u
80 | return int(util_sum/len(self.util))
81 |
82 | def get_speed(self):
83 | total_speed = 0
84 | for s in self.speed:
85 | total_speed += int(float(s[0]) * 1000 / s[1])
86 | return total_speed
87 |
88 | def get_rejected(self):
89 | return self.rejected
90 |
--------------------------------------------------------------------------------
/htpclient/hashlist.py:
--------------------------------------------------------------------------------
1 | import logging
2 | from time import sleep
3 |
4 | from htpclient.config import Config
5 | from htpclient.download import Download
6 | from htpclient.jsonRequest import JsonRequest
7 | from htpclient.dicts import *
8 |
9 |
10 | class Hashlist:
11 | def __init__(self):
12 | self.config = Config()
13 | self.chunk = None
14 |
15 | def load_hashlist(self, hashlist_id):
16 | query = copy_and_set_token(dict_getHashlist, self.config.get_value('token'))
17 | query['hashlistId'] = hashlist_id
18 | req = JsonRequest(query)
19 | ans = req.execute()
20 | if ans is None:
21 | logging.error("Failed to get hashlist!")
22 | sleep(5)
23 | return False
24 | elif ans['response'] != 'SUCCESS':
25 | logging.error("Getting of hashlist failed: " + str(ans))
26 | sleep(5)
27 | return False
28 | else:
29 | Download.download(self.config.get_value('url').replace("api/server.php", "") + ans['url'], self.config.get_value('hashlists-path') + "/" + str(hashlist_id), True)
30 | return True
31 |
32 | def load_found(self, hashlist_id, cracker_id):
33 | query = copy_and_set_token(dict_getFound, self.config.get_value('token'))
34 | query['hashlistId'] = hashlist_id
35 | req = JsonRequest(query)
36 | ans = req.execute()
37 | if ans is None:
38 | logging.error("Failed to get found of hashlist!")
39 | sleep(5)
40 | return False
41 | elif ans['response'] != 'SUCCESS':
42 | logging.error("Getting of hashlist founds failed: " + str(ans))
43 | sleep(5)
44 | return False
45 | else:
46 | logging.info("Saving found hashes to hashcat potfile...")
47 | Download.download(self.config.get_value('url').replace("api/server.php", "") + ans['url'], self.config.get_value('crackers-path') + "/" + str(cracker_id) + "/hashcat.potfile", True)
48 | return True
49 |
--------------------------------------------------------------------------------
/htpclient/helpers.py:
--------------------------------------------------------------------------------
1 | import re
2 | import signal
3 | import sys
4 | import platform
5 | import logging
6 | import time
7 | from types import MappingProxyType
8 | from pathlib import Path
9 |
10 | import os
11 | import subprocess
12 |
13 | from htpclient.dicts import copy_and_set_token, dict_clientError
14 | from htpclient.jsonRequest import JsonRequest
15 | from htpclient.config import Config
16 |
17 |
18 | def log_error_and_exit(message):
19 | logging.error(message)
20 | sys.exit(1)
21 |
22 |
23 | def print_speed(speed):
24 | prefixes = MappingProxyType(
25 | {0: "",
26 | 1: "k",
27 | 2: "M",
28 | 3: "G",
29 | 4: "T"})
30 | exponent = 0
31 | while speed > 1000:
32 | exponent += 1
33 | speed = float(speed) / 1000
34 | return str("{:6.2f}".format(speed)) + prefixes[exponent] + "H/s"
35 |
36 |
37 | def get_bit():
38 | if platform.machine().endswith('64'):
39 | return "64"
40 | return "32"
41 |
42 |
43 | def kill_hashcat(pid, get_os):
44 | if get_os != 1:
45 | os.killpg(os.getpgid(pid), signal.SIGTERM)
46 | else:
47 | subprocess.Popen("TASKKILL /F /PID {pid} /T".format(pid=pid))
48 |
49 |
50 | def send_error(error, token, task_id, chunk_id):
51 | query = copy_and_set_token(dict_clientError, token)
52 | query['message'] = error
53 | query['chunkId'] = chunk_id
54 | query['taskId'] = task_id
55 | req = JsonRequest(query)
56 | req.execute()
57 |
58 |
59 | def file_get_contents(filename):
60 | with open(filename) as f:
61 | return f.read()
62 |
63 |
64 | def start_uftpd(os_extension, config):
65 | try:
66 | subprocess.check_output("killall -s 9 uftpd", shell=True) # stop running service to make sure we can start it again
67 | except subprocess.CalledProcessError:
68 | pass # ignore in case uftpd was not running
69 | path = './uftpd' + os_extension
70 | cmd = path + ' '
71 | if config.get_value('multicast-device'):
72 | cmd += "-I " + config.get_value('multicast-device') + ' '
73 | else:
74 | cmd += "-I eth0 " # wild guess as default
75 | cmd += "-D " + os.path.abspath(config.get_value('files-path') + "/") + ' '
76 | cmd += "-L " + os.path.abspath("multicast/" + str(time.time()) + ".log")
77 | logging.debug("CALL: " + cmd)
78 | subprocess.check_output(cmd, shell=True)
79 | logging.info("Started multicast daemon")
80 |
81 |
82 | def get_wordlist(command):
83 | split = clean_list(command.split(" "))
84 | for index, part in enumerate(split):
85 | if part[0] == '-':
86 | continue
87 | elif index == 0 or split[index - 1][0] != '-':
88 | return part
89 | return ''
90 |
91 |
92 | def get_rules_and_hl(command, alias):
93 | split = clean_list(command.split(" "))
94 | rules = []
95 | for index, part in enumerate(split):
96 | if index > 0 and (split[index - 1] == '-r' or split[index - 1] == '--rules-file'):
97 | rules.append(split[index - 1])
98 | rules.append(split[index - 0])
99 | if part == alias:
100 | rules.append(part)
101 | return " ".join(rules)
102 |
103 |
104 | def clean_list(element_list):
105 | index = 0
106 | for part in element_list:
107 | if not part:
108 | del element_list[index]
109 | index -= 1
110 | index += 1
111 | return element_list
112 |
113 |
114 | # the prince flag is deprecated
115 | def update_files(command, prince=False):
116 | config = Config()
117 |
118 | split = command.split(" ")
119 | ret = []
120 | for part in split:
121 | # test if file exists
122 | if not part:
123 | continue
124 | path = Path(config.get_value('files-path'), part)
125 | if os.path.exists(path):
126 | ret.append(f'"{path}"')
127 | else:
128 | ret.append(str(part))
129 | return " %s " % " ".join(ret)
130 |
131 |
132 | def escape_ansi(line):
133 | ansi_escape = re.compile(r'(\x9B|\x1B\[)[0-?]*[ -/]*[@-~]')
134 | return ansi_escape.sub('', line)
135 |
--------------------------------------------------------------------------------
/htpclient/initialize.py:
--------------------------------------------------------------------------------
1 | import uuid
2 | from time import sleep
3 |
4 | from htpclient.dicts import *
5 | from htpclient.helpers import *
6 | from htpclient.jsonRequest import *
7 |
8 |
9 | class Initialize:
10 | def __init__(self):
11 | self.config = Config()
12 |
13 | @staticmethod
14 | def get_version():
15 | return "s3-python-" + Initialize.get_version_number()
16 |
17 | @staticmethod
18 | def get_version_number():
19 | return "0.7.3"
20 |
21 | def run(self, args):
22 | self.__check_cert(args)
23 | self.__check_url(args)
24 | self.__check_token(args)
25 | self.__update_information()
26 | self.__login()
27 | self.__build_directories()
28 |
29 | @staticmethod
30 | def get_os():
31 | operating_system = platform.system()
32 | try:
33 | return dict_os[operating_system]
34 | except KeyError:
35 | logging.debug("OS: %s" % operating_system)
36 | log_error_and_exit("It seems your operating system is not supported.")
37 |
38 | @staticmethod
39 | def get_os_extension():
40 | operating_system = Initialize.get_os()
41 | return dict_ext[operating_system]
42 |
43 | def __login(self):
44 | query = copy_and_set_token(dict_login, self.config.get_value('token'))
45 | query['clientSignature'] = self.get_version()
46 | req = JsonRequest(query)
47 | ans = req.execute()
48 | if ans is None:
49 | logging.error("Login failed!")
50 | sleep(5)
51 | self.__login()
52 | elif ans['response'] != 'SUCCESS':
53 | logging.error("Error from server: " + str(ans))
54 | self.config.set_value('token', '')
55 | self.__login()
56 | else:
57 | logging.info("Login successful!")
58 | if 'server-version' in ans:
59 | logging.info("Hashtopolis Server version: " + ans['server-version'])
60 | if 'multicastEnabled' in ans and ans['multicastEnabled'] and self.get_os() == 0: # currently only allow linux
61 | logging.info("Multicast enabled!")
62 | self.config.set_value('multicast', True)
63 | if not os.path.isdir("multicast"):
64 | os.mkdir("multicast")
65 |
66 | def decode_output(self, output):
67 | return output.decode(encoding='utf-8').replace("\r\n", "\n").split("\n")
68 |
69 | def __update_information(self):
70 | if not self.config.get_value('uuid'):
71 | self.config.set_value('uuid', str(uuid.uuid4()))
72 |
73 | # collect devices
74 | logging.info("Collecting agent data...")
75 | devices = []
76 | if Initialize.get_os() == 0: # linux
77 | output = subprocess.check_output("cat /proc/cpuinfo", shell=True)
78 | output = self.decode_output(output)
79 | tmp = []
80 | for line in output:
81 | line = line.strip()
82 | if not line.startswith('model name') and not line.startswith('physical id'):
83 | continue
84 | value = line.split(':', 1)[1].strip()
85 | while ' ' in value:
86 | value = value.replace(' ', ' ')
87 | tmp.append(value)
88 |
89 | pairs = []
90 | for i in range(0, len(tmp), 2):
91 | pairs.append("%s:%s" % (tmp[i + 1], tmp[i]))
92 |
93 | for line in sorted(set(pairs)):
94 | devices.append(line.split(':', 1)[1].replace('\t', ' '))
95 |
96 | if not self.config.get_value('cpu-only'):
97 | try:
98 | output = subprocess.check_output("lspci | grep -E 'VGA compatible controller|3D controller'", shell=True)
99 | except subprocess.CalledProcessError:
100 | # we silently ignore this case on machines where lspci is not present or architecture has no pci bus
101 | output = b""
102 | output = self.decode_output(output)
103 | for line in output:
104 | if not line:
105 | continue
106 | line = ' '.join(line.split(' ')[1:]).split(':')
107 | devices.append(line[1].strip())
108 |
109 | elif Initialize.get_os() == 1: # windows
110 | platform_release = platform.uname().release
111 | if platform_release == "" or int(platform_release) >= 10:
112 | processor_information = subprocess.check_output(
113 | 'powershell -Command "Get-CimInstance Win32_Processor | Select-Object -ExpandProperty Name"',
114 | shell=True)
115 | processor_information = self.decode_output(processor_information)
116 | video_controller = subprocess.check_output(
117 | 'powershell -Command "Get-CimInstance Win32_VideoController | Select-Object -ExpandProperty Name"',
118 | shell=True)
119 | video_controller = self.decode_output(video_controller)
120 | else:
121 | processor_information = subprocess.check_output(
122 | 'wmic cpu get name',
123 | shell=True)
124 | processor_information = self.decode_output(processor_information)
125 | video_controller = subprocess.check_output('wmic path win32_VideoController get name', shell=True)
126 | video_controller = self.decode_output(video_controller)
127 |
128 | for source in (processor_information, video_controller):
129 | for line in source:
130 | line = line.rstrip("\r\n ")
131 | if line and line != "Name":
132 | devices.append(line)
133 |
134 | else: # OS X
135 | output = subprocess.check_output("system_profiler SPDisplaysDataType -detaillevel mini", shell=True)
136 | output = self.decode_output(output)
137 | for line in output:
138 | line = line.rstrip("\r\n ")
139 | if "Chipset Model" not in line:
140 | continue
141 | line = line.split(":")
142 | devices.append(line[1].strip())
143 |
144 | query = copy_and_set_token(dict_updateInformation, self.config.get_value('token'))
145 | query['uid'] = self.config.get_value('uuid')
146 | query['os'] = self.get_os()
147 | query['devices'] = devices
148 | req = JsonRequest(query)
149 | ans = req.execute()
150 | if ans is None:
151 | logging.error("Information update failed!")
152 | sleep(5)
153 | self.__update_information()
154 | elif ans['response'] != 'SUCCESS':
155 | logging.error("Error from server: " + str(ans))
156 | sleep(5)
157 | self.__update_information()
158 |
159 | def __check_token(self, args):
160 | if not self.config.get_value('token'):
161 | if self.config.get_value('voucher'):
162 | # voucher is set in config and can be used to autoregister
163 | voucher = self.config.get_value('voucher')
164 | elif args.voucher:
165 | voucher = args.voucher
166 | else:
167 | voucher = input("No token found! Please enter a voucher to register your agent:\n").strip()
168 | name = platform.node()
169 | query = dict_register.copy()
170 | query['voucher'] = voucher
171 | query['name'] = name
172 | if self.config.get_value('cpu-only'):
173 | query['cpu-only'] = True
174 |
175 | req = JsonRequest(query)
176 | ans = req.execute()
177 | if ans is None:
178 | logging.error("Request failed!")
179 | self.__check_token(args)
180 | elif ans['response'] != 'SUCCESS' or not ans['token']:
181 | logging.error("Registering failed: " + str(ans))
182 | self.__check_token(args)
183 | else:
184 | token = ans['token']
185 | self.config.set_value('voucher', '')
186 | self.config.set_value('token', token)
187 | logging.info("Successfully registered!")
188 |
189 | def __check_cert(self, args):
190 | cert = self.config.get_value('cert')
191 | if cert is None:
192 | if args.cert is not None:
193 | cert = os.path.abspath(args.cert)
194 | logging.debug("Setting cert to: " + cert)
195 | self.config.set_value('cert', cert)
196 |
197 | if cert is not None:
198 | Session().s.cert = cert
199 | logging.debug("Configuration session cert to: " + cert)
200 |
201 | def __check_url(self, args):
202 | if not self.config.get_value('url'):
203 | # ask for url
204 | if args.url is None:
205 | url = input("Please enter the url to the API of your Hashtopolis installation:\n").strip()
206 | else:
207 | url = args.url
208 | logging.debug("Setting url to: " + url)
209 | self.config.set_value('url', url)
210 | else:
211 | return
212 | query = dict_testConnection.copy()
213 | req = JsonRequest(query)
214 | ans = req.execute()
215 | if ans is None:
216 | logging.error("Connection test failed!")
217 | self.config.set_value('url', '')
218 | self.__check_url(args)
219 | elif ans['response'] != 'SUCCESS':
220 | logging.error("Connection test failed: " + str(ans))
221 | self.config.set_value('url', '')
222 | self.__check_url(args)
223 | else:
224 | logging.debug("Connection test successful!")
225 |
226 | if args.cpu_only is not None and args.cpu_only:
227 | logging.debug("Setting agent to be CPU only..")
228 | self.config.set_value('cpu-only', True)
229 |
230 | def __build_directories(self):
231 | if not os.path.isdir(self.config.get_value('crackers-path')):
232 | os.makedirs(self.config.get_value('crackers-path'))
233 | if not os.path.isdir(self.config.get_value('files-path')):
234 | os.makedirs(self.config.get_value('files-path'))
235 | if not os.path.isdir(self.config.get_value('hashlists-path')):
236 | os.makedirs(self.config.get_value('hashlists-path'))
237 | if not os.path.isdir(self.config.get_value('preprocessors-path')):
238 | os.makedirs(self.config.get_value('preprocessors-path'))
239 |
--------------------------------------------------------------------------------
/htpclient/jsonRequest.py:
--------------------------------------------------------------------------------
1 | import logging
2 |
3 | from htpclient.config import *
4 | from htpclient.session import *
5 |
6 |
7 | class JsonRequest:
8 | def __init__(self, data):
9 | self.data = data
10 | self.config = Config()
11 | self.session = Session().s
12 |
13 | def execute(self):
14 | try:
15 | logging.debug(self.data)
16 | r = self.session.post(self.config.get_value('url'), json=self.data, timeout=30)
17 | if r.status_code != 200:
18 | logging.error("Status code from server: " + str(r.status_code))
19 | return None
20 | logging.debug(r.content)
21 | return r.json()
22 | except Exception as e:
23 | logging.error("Error occurred: " + str(e))
24 | return None
25 |
--------------------------------------------------------------------------------
/htpclient/session.py:
--------------------------------------------------------------------------------
1 | import requests
2 |
3 |
4 | class Session:
5 | __instance = None
6 |
7 | def __new__(cls, s=None):
8 | if Session.__instance is None:
9 | Session.__instance = object.__new__(cls)
10 | Session.__instance.s = s
11 | return Session.__instance
12 |
--------------------------------------------------------------------------------
/htpclient/task.py:
--------------------------------------------------------------------------------
1 | import logging
2 | from time import sleep
3 |
4 | from htpclient.config import Config
5 | from htpclient.jsonRequest import JsonRequest
6 | from htpclient.dicts import *
7 |
8 |
9 | class Task:
10 | def __init__(self):
11 | self.taskId = 0
12 | self.task = None
13 | self.config = Config()
14 | self.preprocessor = None
15 |
16 | def reset_task(self):
17 | self.task = None
18 | self.taskId = 0
19 |
20 | def load_task(self):
21 | if self.taskId != 0:
22 | return
23 | self.task = None
24 | query = copy_and_set_token(dict_getTask, self.config.get_value('token'))
25 | req = JsonRequest(query)
26 | ans = req.execute()
27 | if ans is None:
28 | logging.error("Failed to get task!")
29 | sleep(5)
30 | elif ans['response'] != 'SUCCESS':
31 | logging.error("Error from server: " + str(ans))
32 | sleep(5)
33 | else:
34 | if ans['taskId'] is None:
35 | logging.info("No task available!")
36 | sleep(5)
37 | return
38 | elif ans['taskId'] == -1:
39 | self.taskId = -1
40 | return
41 | self.task = ans
42 | self.taskId = ans['taskId']
43 | logging.info("Got task with id: " + str(ans['taskId']))
44 |
45 | def get_task(self):
46 | return self.task
47 |
48 | def get_task_id(self):
49 | return self.taskId
50 |
51 | def set_preprocessor(self, settings):
52 | self.preprocessor = settings
53 |
54 | def get_preprocessor(self):
55 | return self.preprocessor
56 |
--------------------------------------------------------------------------------
/requirements-tests.txt:
--------------------------------------------------------------------------------
1 | pytest
2 | confidence
3 | tuspy
4 | py7zr
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | requests
2 | psutil
--------------------------------------------------------------------------------
/tests/README.md:
--------------------------------------------------------------------------------
1 | # Testing
2 | ## Setup - Linux
3 | Currently the testing of the agent is limited and a bit complicated. Once APIv2 is release the testing framework
4 | can be extended.
5 |
6 | 1. Start the development container for the server, make sure you use the branch: feature/apiv2.
7 | 2. Start the development container for the agent.
8 | 3. Start the agent once to setup the config.json file (Run -> Start Debugging).
9 | 4. Set the agent to CPU only.
10 | 5. You should be able to run the tests with `python3 -m pytest` or run them directly from 'Testing' in VSCode.
11 |
12 | ## Setup - Windows - Docker
13 | Currently you cannot run the tests from a devcontainer on Windows, because vscode does not support devcontainers running on Windows containers.
14 |
15 | Only possible to run tests on a Windows platform.
16 | Does not really allow to run tests windows hashcat, no GPU support
17 |
18 | 1. Start the development container for the server, make sure you use the branch: feature/apiv2.
19 | 2. Git clone the repo into the Windows file system
20 | 3. Switch Docker Desktop to Windows Containers. Right click the Docker Desktop tray icon. Select 'Switch to Windows Containers'
21 | 4. Open powershell, cd to the agent folder `.devcontainer\windows`
22 | 5. `docker compose build`
23 | 6. `docker compose up`
24 | 7. Everything should install, now attach to the container `docker exec -it hashtopolis_agent_windows cmd.exe`
25 | 8. Start the agent once `python -d . --url http://host.docker.internal:8080/api/server.php --debug --voucher devvoucher`
26 | 9. Run the tests `python -m pytest`
27 |
28 | ## Setup - Windows - locally
29 |
30 | Requires some OpenCL device for example a GPU to run tests.
31 |
32 | 1. Start the development container for the server, make sure you use the branch: feature/apiv2.
33 | 2. Git clone the repo into the Windows file system
34 | 3. Install Python3.10 through https://www.python.org/downloads/ (as Admin/systemwide) + add python to path
35 | 4. Install requirements-test.txt and requirements.txt `pip3 install -r .\requirements-tests.txt -r .\requirements.txt`
36 | 5. Run VSCode install Python extension
37 | 6. Run agent once `python -d . --url http://127.0.0.1:8080/api/server.php --debug --voucher devvoucher`
38 | 7. You should be able to run the tests with `python3 -m pytest` or run them directly from 'Testing' in VSCode.
39 |
40 | ## Debugging
41 |
42 | 1. Clear the who database through Config -> Server -> Delete all
43 | 2. Check if the agent is still active
44 | 3. Clear the agent folder
45 | 4. Check if the agent is marked CPU only
46 |
47 | ## Limitations
48 | 1. Only one environment can be tested at a time.
49 | 2. Only works with APIv2.
50 | 3. No support yet for Github actions, waiting for release of APIv2 to prevent having to fix it again.
--------------------------------------------------------------------------------
/tests/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hashtopolis/agent-python/54c853b91004e0e554514278088da22be5f03b84/tests/__init__.py
--------------------------------------------------------------------------------
/tests/create_file_001.json:
--------------------------------------------------------------------------------
1 | {
2 | "sourceType": "import",
3 | "isSecret": false,
4 | "accessGroupId": 1
5 | }
6 |
--------------------------------------------------------------------------------
/tests/create_hashlist_001.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "Hashlist-md5sum-test123",
3 | "hashTypeId": 1,
4 | "format": 0,
5 | "separator": ";",
6 | "isSalted": false,
7 | "isHexSalt": false,
8 | "accessGroupId": 1,
9 | "useBrain": false,
10 | "brainFeatures": 3,
11 | "notes": "gj",
12 | "sourceType": "paste",
13 | "sourceData": "Y2MwM2U3NDdhNmFmYmJjYmY4YmU3NjY4YWNmZWJlZTUK",
14 | "hashCount": 0,
15 | "isArchived": false,
16 | "isSecret": false
17 | }
18 |
--------------------------------------------------------------------------------
/tests/create_hashlist_002.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "Hashlist-md5sum-brain",
3 | "hashTypeId": 1,
4 | "format": 0,
5 | "separator": ";",
6 | "isSalted": false,
7 | "isHexSalt": false,
8 | "accessGroupId": 1,
9 | "useBrain": true,
10 | "brainFeatures": 3,
11 | "notes": "gj",
12 | "sourceType": "paste",
13 | "sourceData": "Y2MwM2U3NDdhNmFmYmJjYmY4YmU3NjY4YWNmZWJlZTUK",
14 | "hashCount": 0,
15 | "isArchived": false,
16 | "isSecret": false
17 | }
18 |
--------------------------------------------------------------------------------
/tests/create_task_001.json:
--------------------------------------------------------------------------------
1 | {
2 | "attackCmd": "#HL# -a3 ?l?l?l?l",
3 | "chunkSize": 1000,
4 | "chunkTime": 600,
5 | "color": "7C6EFF",
6 | "crackerBinaryId": 1,
7 | "crackerBinaryTypeId": 1,
8 | "forcePipe": true,
9 | "files": [],
10 | "isArchived": false,
11 | "isCpuTask": true,
12 | "isSmall": false,
13 | "maxAgents": 112,
14 | "notes": "example-note",
15 | "preprocessorCommand": "",
16 | "priority": 10,
17 | "skipKeyspace": 500,
18 | "staticChunks": 2,
19 | "statusTimer": 5,
20 | "taskName": "Example - Rijmen and Daemen",
21 | "useNewBench": true,
22 | "preprocessorId": 0
23 | }
24 |
--------------------------------------------------------------------------------
/tests/create_task_002.json:
--------------------------------------------------------------------------------
1 | {
2 | "attackCmd": "#HL# -a3 ?l?l?l?l",
3 | "chunkSize": 1000,
4 | "chunkTime": 600,
5 | "color": "7C6EFF",
6 | "crackerBinaryId": 1,
7 | "crackerBinaryTypeId": 1,
8 | "forcePipe": true,
9 | "files": [],
10 | "isArchived": false,
11 | "isCpuTask": true,
12 | "isSmall": false,
13 | "maxAgents": 112,
14 | "notes": "example-note",
15 | "preprocessorCommand": "",
16 | "priority": 10,
17 | "skipKeyspace": 500,
18 | "staticChunks": 2,
19 | "statusTimer": 5,
20 | "taskName": "Example - runtime",
21 | "useNewBench": false,
22 | "preprocessorId": 0
23 | }
24 |
--------------------------------------------------------------------------------
/tests/create_task_003.json:
--------------------------------------------------------------------------------
1 | {
2 | "attackCmd": "#HL#",
3 | "chunkSize": 1000,
4 | "chunkTime": 600,
5 | "color": "7C6EFF",
6 | "crackerBinaryId": 1,
7 | "crackerBinaryTypeId": 1,
8 | "forcePipe": true,
9 | "files": [],
10 | "isArchived": false,
11 | "isCpuTask": true,
12 | "isSmall": false,
13 | "maxAgents": 112,
14 | "notes": "example-note",
15 | "preprocessorCommand": "--pw-min=1 --pw-max=2 ../../crackers/1/example.dict",
16 | "priority": 10,
17 | "skipKeyspace": 500,
18 | "staticChunks": 2,
19 | "statusTimer": 5,
20 | "taskName": "Example - preprocessor",
21 | "useNewBench": true,
22 | "preprocessorId": 1
23 | }
24 |
--------------------------------------------------------------------------------
/tests/create_task_004.json:
--------------------------------------------------------------------------------
1 | {
2 | "attackCmd": "#HL# -a0 create-task-004.txt",
3 | "chunkSize": 1000,
4 | "chunkTime": 600,
5 | "color": "7C6EFF",
6 | "crackerBinaryId": 1,
7 | "crackerBinaryTypeId": 1,
8 | "forcePipe": true,
9 | "files": [],
10 | "isArchived": false,
11 | "isCpuTask": true,
12 | "isSmall": false,
13 | "maxAgents": 112,
14 | "notes": "example-note",
15 | "preprocessorCommand": "",
16 | "priority": 10,
17 | "skipKeyspace": 0,
18 | "staticChunks": 2,
19 | "statusTimer": 5,
20 | "taskName": "Example - files and rules",
21 | "useNewBench": true,
22 | "preprocessorId": 0
23 | }
24 |
--------------------------------------------------------------------------------
/tests/create_task_005.json:
--------------------------------------------------------------------------------
1 | {
2 | "attackCmd": "#HL# -a3 ?l?l?l?l",
3 | "chunkSize": 1000,
4 | "chunkTime": 600,
5 | "color": "7C6EFF",
6 | "crackerBinaryId": 1,
7 | "crackerBinaryTypeId": 1,
8 | "forcePipe": true,
9 | "files": [],
10 | "isArchived": false,
11 | "isCpuTask": true,
12 | "isSmall": false,
13 | "maxAgents": 112,
14 | "notes": "example-note",
15 | "preprocessorCommand": "",
16 | "priority": 10,
17 | "skipKeyspace": 5000,
18 | "staticChunks": 2,
19 | "statusTimer": 5,
20 | "taskName": "Example - Rijmen and Daemen",
21 | "useNewBench": true,
22 | "preprocessorId": 0
23 | }
24 |
--------------------------------------------------------------------------------
/tests/hashtopolis-test.yaml:
--------------------------------------------------------------------------------
1 | hashtopolis_uri: 'http://hashtopolis'
2 | username: 'root'
3 | password: 'hashtopolis'
4 |
--------------------------------------------------------------------------------
/tests/hashtopolis.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # -*- coding: utf-8 -*-
3 | #
4 | # PoC testing/development framework for APIv2
5 | # Written in python to work on creation of hashtopolis APIv2 python binding.
6 | #
7 | import json
8 | import requests
9 | import unittest
10 | import datetime
11 | from pathlib import Path
12 | from io import BytesIO
13 |
14 | import requests
15 | import unittest
16 | import logging
17 | from pathlib import Path
18 | import abc
19 |
20 | import http
21 | import confidence
22 | import tusclient.client
23 |
24 | #logging.basicConfig(level=logging.DEBUG)
25 |
26 | logger = logging.getLogger(__name__)
27 |
28 | HTTP_DEBUG = False
29 |
30 | # Monkey patching to allow http debugging
31 | if HTTP_DEBUG:
32 | http_logger = logging.getLogger('http.client')
33 | http.client.HTTPConnection.debuglevel = 0
34 | def print_to_log(*args):
35 | http_logger.debug(" ".join(args))
36 | http.client.print = print_to_log
37 |
38 | cls_registry = {}
39 |
40 |
41 | class HashtopolisConfig(object):
42 | def __init__(self):
43 | # Request access TOKEN, used throughout the test
44 | load_order = confidence.DEFAULT_LOAD_ORDER + (str(Path(__file__).parent.joinpath('{name}.{extension}')),)
45 | self._cfg = confidence.load_name('hashtopolis-test', load_order=load_order)
46 | self._hashtopolis_uri = self._cfg['hashtopolis_uri']
47 | self._api_endpoint = self._hashtopolis_uri + '/api/v2'
48 | self.username = self._cfg['username']
49 | self.password = self._cfg['password']
50 |
51 |
52 |
53 |
54 | class HashtopolisConnector(object):
55 | # Cache authorisation token per endpoint
56 | token = {}
57 | token_expires = {}
58 |
59 | def __init__(self, model_uri, config):
60 | self._model_uri = model_uri
61 | self._api_endpoint = config._api_endpoint
62 | self._hashtopolis_uri = config._hashtopolis_uri
63 | self.config = config
64 |
65 | def authenticate(self):
66 | if not self._api_endpoint in HashtopolisConnector.token:
67 | # Request access TOKEN, used throughout the test
68 |
69 | logger.info("Start authentication")
70 | auth_uri = self._api_endpoint + '/auth/token'
71 | auth = (self.config.username, self.config.password)
72 | r = requests.post(auth_uri, auth=auth)
73 |
74 | HashtopolisConnector.token[self._api_endpoint] = r.json()['token']
75 | HashtopolisConnector.token_expires[self._api_endpoint] = r.json()['token']
76 |
77 | self._token = HashtopolisConnector.token[self._api_endpoint]
78 | self._token_expires = HashtopolisConnector.token_expires[self._api_endpoint]
79 |
80 | self._headers = {
81 | 'Authorization': 'Bearer ' + self._token,
82 | 'Content-Type': 'application/json'
83 | }
84 |
85 |
86 | def filter(self, expand, filter):
87 | self.authenticate()
88 | uri = self._api_endpoint + self._model_uri
89 | headers = self._headers
90 |
91 | filter_list = []
92 | cast = {
93 | '__gt': '>',
94 | '__gte': '>=',
95 | '__lt': '<',
96 | '__lte': '<=',
97 | }
98 | for k,v in filter.items():
99 | l = None
100 | for k2,v2 in cast.items():
101 | if k.endswith(k2):
102 | l = f'{k[:-len(k2)]}{v2}{v}'
103 | break
104 | # Default to equal assignment
105 | if l == None:
106 | l = f'{k}={v}'
107 | filter_list.append(l)
108 |
109 | payload = {
110 | 'filter': filter_list,
111 | 'expand': expand
112 | }
113 |
114 | r = requests.get(uri, headers=headers, data=json.dumps(payload))
115 | if r.status_code != 201:
116 | logger.exception("Filter failed: %s", r.text)
117 | return r.json().get('values')
118 |
119 | def patch_one(self, obj):
120 | if not obj.has_changed():
121 | logger.debug("Object '%s' has not changed, no PATCH required", obj)
122 | return
123 |
124 | self.authenticate()
125 | uri = self._hashtopolis_uri + obj._self
126 | headers = self._headers
127 | payload = {}
128 |
129 | for k,v in obj.diff().items():
130 | logger.debug("Going to patch object '%s' property '%s' from '%s' to '%s'", obj, k, v[0], v[1])
131 | payload[k] = v[1]
132 |
133 | r = requests.patch(uri, headers=headers, data=json.dumps(payload))
134 | if r.status_code != 201:
135 | logger.exception("Patching failed: %s", r.text)
136 |
137 | # TODO: Validate if return objects matches digital twin
138 | obj.set_initial(r.json().copy())
139 |
140 | def create(self, obj):
141 | # Check if object to be created is new
142 | assert(not hasattr(obj, '_self'))
143 |
144 | self.authenticate()
145 | uri = self._api_endpoint + self._model_uri
146 | headers = self._headers
147 | payload = dict([(k,v[1]) for (k,v) in obj.diff().items()])
148 |
149 | r = requests.post(uri, headers=headers, data=json.dumps(payload))
150 | if r.status_code != 201:
151 | logger.exception("Creation of object failed: %s", r.text)
152 |
153 | # TODO: Validate if return objects matches digital twin
154 | obj.set_initial(r.json().copy())
155 |
156 |
157 | def delete(self, obj):
158 | """ Delete object from database """
159 | # TODO: Check if object to be deleted actually exists
160 | assert(hasattr(obj, '_self'))
161 |
162 | self.authenticate()
163 | uri = self._hashtopolis_uri + obj._self
164 | headers = self._headers
165 | payload = {}
166 |
167 |
168 | r = requests.delete(uri, headers=headers, data=json.dumps(payload))
169 | if r.status_code != 204:
170 | logger.exception("Deletion of object failed: %s", r.text)
171 |
172 | # TODO: Cleanup object to allow re-creation
173 |
174 |
175 | class ManagerBase(type):
176 | conn = {}
177 | # Cache configuration values
178 | config = None
179 | @classmethod
180 | def get_conn(cls):
181 | if cls.config is None:
182 | cls.config = HashtopolisConfig()
183 |
184 | if cls._model_uri not in cls.conn:
185 | cls.conn[cls._model_uri] = HashtopolisConnector(cls._model_uri, cls.config)
186 | return cls.conn[cls._model_uri]
187 |
188 | @classmethod
189 | def all(cls, expand=None):
190 | """
191 | Retrieve all backend objects
192 | TODO: Make iterator supporting loading of objects via pages
193 | """
194 | return cls.filter(expand)
195 |
196 |
197 | @classmethod
198 | def patch(cls, obj):
199 | cls.get_conn().patch_one(obj)
200 |
201 | @classmethod
202 | def create(cls, obj):
203 | cls.get_conn().create(obj)
204 |
205 | @classmethod
206 | def delete(cls, obj):
207 | cls.get_conn().delete(obj)
208 |
209 | @classmethod
210 | def get_first(cls):
211 | """
212 | Retrieve first object
213 | TODO: Error handling if first object does not exists
214 | TODO: Request object with limit parameter instead
215 | """
216 | return cls.all()[0]
217 |
218 | @classmethod
219 | def get(cls, expand=None, **kwargs):
220 | objs = cls.filter(expand, **kwargs)
221 | assert(len(objs) == 1)
222 | return objs[0]
223 |
224 | @classmethod
225 | def filter(cls, expand=None, **kwargs):
226 | # Get all objects
227 | api_objs = cls.get_conn().filter(expand, kwargs)
228 |
229 | # Convert into class
230 | objs = []
231 | if api_objs:
232 | for api_obj in api_objs:
233 | new_obj = cls._model(**api_obj)
234 | objs.append(new_obj)
235 | return objs
236 |
237 | # Build Django ORM style 'ModelName.objects' interface
238 | class ModelBase(type):
239 | def __new__(cls, clsname, bases, attrs, uri=None, **kwargs):
240 | parents = [b for b in bases if isinstance(b, ModelBase)]
241 | if not parents:
242 | return super().__new__(cls, clsname, bases, attrs)
243 |
244 | new_class = super().__new__(cls, clsname, bases, attrs)
245 |
246 | setattr(new_class, 'objects', type('Manager', (ManagerBase,), {'_model_uri': uri}))
247 | setattr(new_class.objects, '_model', new_class)
248 | cls_registry[clsname] = new_class
249 |
250 | return new_class
251 |
252 |
253 | class Model(metaclass=ModelBase):
254 | def __init__(self, *args, **kwargs):
255 | self.set_initial(kwargs)
256 | super().__init__()
257 |
258 | def _dict2obj(self, dict):
259 | # Function to convert a dict to an object.
260 | uri = dict.get('_self')
261 |
262 | # Loop through all the registers classes
263 | for modelname, model in cls_registry.items():
264 | model_uri = model.objects._model_uri
265 | # Check if part of the uri is in the model uri
266 | if model_uri in uri:
267 |
268 | obj = model()
269 |
270 | # Set all the attributes of the object.
271 | for k2,v2 in dict.items():
272 | setattr(obj, k2, v2)
273 | if not k2.startswith('_'):
274 | obj.__fields.append(k2)
275 | return obj
276 | # If we are here, it means that no uri matched, thus we don't know the object.
277 | raise(TypeError('Object not valid model'))
278 |
279 | def set_initial(self, kv):
280 | self.__fields = []
281 | # Store fields allowing us to detect changed values
282 | if '_self' in kv:
283 | self.__initial = kv.copy()
284 | else:
285 | # New model
286 | self.__initial = {}
287 |
288 | # Create attribute values
289 | for k,v in kv.items():
290 |
291 | # In case expand is true, there can be a attribute which also is an object.
292 | # Example: Users in AccessGroups. This part will convert the returned data.
293 | # Into proper objects.
294 | if type(v) is list and len(v) > 0:
295 |
296 | # Many-to-Many relation
297 | obj_list = []
298 | # Loop through all the values in the list and convert them to objects.
299 | for dict_v in v:
300 | if type(dict_v) is dict and dict_v.get('_self'):
301 | # Double check that it really is an object
302 | obj = self._dict2obj(dict_v)
303 | obj_list.append(obj)
304 | # Set the attribute of the current object to a set object (like Django)
305 | # Also check if it really were objects
306 | if len(obj_list) > 0:
307 | setattr(self, f"{k}_set", obj_list)
308 | continue
309 | # This does the same as above, only one-to-one relations
310 | if type(v) is dict:
311 | setattr(self, f"{k}_set", self._dict2obj(v))
312 | continue
313 | setattr(self, k, v)
314 | if not k.startswith('_'):
315 | self.__fields.append(k)
316 |
317 | def diff(self):
318 | d1 = self.__initial
319 | d2 = dict([(k, getattr(self, k)) for k in self.__fields])
320 | diffs = [(k, (v, d2[k])) for k, v in d2.items() if v != d1.get(k, None)]
321 | return dict(diffs)
322 |
323 | def has_changed(self):
324 | return bool(self.diff())
325 |
326 | def save(self):
327 | if hasattr(self, '_self'):
328 | self.objects.patch(self)
329 | else:
330 | self.objects.create(self)
331 |
332 | def delete(self):
333 | if hasattr(self, '_self'):
334 | self.objects.delete(self)
335 |
336 | def serialize(self):
337 | return [x for x in vars(self) if not x.startswith('_')]
338 |
339 | @property
340 | def id(self):
341 | return self._id
342 |
343 |
344 | class Agent(Model, uri="/ui/agents"):
345 | def __repr__(self):
346 | return self._self
347 |
348 | class Task(Model, uri="/ui/tasks"):
349 | def __repr__(self):
350 | return self._self
351 |
352 | class Pretask(Model, uri="/ui/pretasks"):
353 | def __repr__(self):
354 | return self._self
355 |
356 | class User(Model, uri="/ui/users"):
357 | def __repr__(self):
358 | return self._self
359 |
360 |
361 | class Hashlist(Model, uri="/ui/hashlists"):
362 | def __repr__(self):
363 | return self._self
364 |
365 | class AccessGroup(Model, uri="/ui/accessgroups"):
366 | def __repr__(self):
367 | return self._self
368 |
369 | class Cracker(Model, uri="/ui/crackers"):
370 | def __repr__(self):
371 | return self._self
372 |
373 | class CrackerType(Model, uri="/ui/crackertypes"):
374 | def __repr__(self):
375 | return self._self
376 |
377 | class Config(Model, uri="/ui/configs"):
378 | def __repr__(self):
379 | return self._self
380 |
381 | class File(Model, uri="/ui/files"):
382 | def __repr__(self):
383 | return self._self
384 |
385 |
386 | class FileImport(HashtopolisConnector):
387 | def __init__(self):
388 | super().__init__("/ui/files/import", HashtopolisConfig())
389 |
390 | def __repr__(self):
391 | return self._self
392 |
393 | def do_upload(self, filename, file_stream):
394 | self.authenticate()
395 |
396 | uri = self._api_endpoint + self._model_uri
397 |
398 | my_client = tusclient.client.TusClient(uri)
399 | del self._headers['Content-Type']
400 | my_client.set_headers(self._headers)
401 |
402 | metadata = {"filename": filename,
403 | "filetype": "application/text"}
404 | uploader = my_client.uploader(
405 | file_stream=file_stream,
406 | chunk_size=1000000000,
407 | upload_checksum=True,
408 | metadata=metadata
409 | )
410 | uploader.upload()
411 |
412 |
--------------------------------------------------------------------------------
/tests/test_hashcat_brain.py:
--------------------------------------------------------------------------------
1 | import pytest
2 | from unittest import mock
3 | import unittest
4 | from unittest.mock import MagicMock
5 | import os
6 | import subprocess
7 | import shutil
8 | import requests
9 | import json
10 | from pathlib import Path
11 | from argparse import Namespace
12 | import sys
13 | import datetime
14 | from io import BytesIO
15 |
16 | from htpclient.hashcat_cracker import HashcatCracker
17 | from htpclient.binarydownload import BinaryDownload
18 | from htpclient.session import Session
19 | from htpclient.config import Config
20 | from htpclient.initialize import Initialize
21 | from htpclient.chunk import Chunk
22 | from htpclient.hashlist import Hashlist
23 | from htpclient.task import Task
24 | from htpclient.dicts import copy_and_set_token
25 | from htpclient.dicts import dict_sendBenchmark
26 | from htpclient.jsonRequest import JsonRequest
27 | from htpclient.files import Files
28 |
29 | from tests.hashtopolis import Hashlist as Hashlist_v2
30 | from tests.hashtopolis import Task as Task_v2
31 | from tests.hashtopolis import FileImport as FileImport_v2
32 | from tests.hashtopolis import File as File_v2
33 | from tests.hashtopolis import Config as Config_v2
34 | from tests.hashtopolis import Agent as Agent_v2
35 |
36 |
37 |
38 | class HashcatBrain(unittest.TestCase):
39 | @mock.patch('subprocess.Popen', side_effect=subprocess.Popen)
40 | @mock.patch('subprocess.check_output', side_effect=subprocess.check_output)
41 | @mock.patch('os.unlink', side_effect=os.unlink)
42 | @mock.patch('os.system', side_effect=os.system)
43 | def test_brain_linux(self, mock_system, mock_unlink, mock_check_output, mock_Popen):
44 | if sys.platform != 'linux':
45 | return
46 |
47 | # Setup session object
48 | session = Session(requests.Session()).s
49 | session.headers.update({'User-Agent': Initialize.get_version()})
50 |
51 | # Cmd parameters setup
52 | test_args = Namespace( cert=None, cpu_only=False, crackers_path=None, de_register=False, debug=True, disable_update=False, files_path=None, hashlists_path=None, number_only=False, preprocessors_path=None, url='http://hashtopolis/api/server.php', version=False, voucher='devvoucher', zaps_path=None)
53 |
54 | # Set config and variables
55 | cracker_id = 1
56 | config = Config()
57 |
58 | crackers_path = config.get_value('crackers-path')
59 |
60 | # Setting Brain configuration
61 | set_config = {
62 | 'hashcatBrainEnable': '1',
63 | 'hashcatBrainHost': '127.0.0.1',
64 | 'hashcatBrainPort': '8080',
65 | 'hashcatBrainPass': 'password',
66 | }
67 |
68 | for k,v in set_config.items():
69 | config_item = Config_v2.objects.get(item=k)
70 | config_item.value = v
71 | config_item.save()
72 |
73 | # Create hashlist
74 | p = Path(__file__).parent.joinpath('create_hashlist_002.json')
75 | payload = json.loads(p.read_text('UTF-8'))
76 | hashlist_v2 = Hashlist_v2(**payload)
77 | hashlist_v2.save()
78 |
79 | # Create task
80 | p = Path(__file__).parent.joinpath('create_task_005.json')
81 | payload = json.loads(p.read_text('UTF-8'))
82 | payload['hashlistId'] = int(hashlist_v2._id)
83 | task_obj = Task_v2(**payload)
84 | task_obj.save()
85 |
86 | # Try to download cracker 1
87 | executeable_path = Path(crackers_path, str(cracker_id), 'hashcat.bin')
88 |
89 | binaryDownload = BinaryDownload(test_args)
90 | binaryDownload.check_version(cracker_id)
91 |
92 | cracker = HashcatCracker(1, binaryDownload)
93 | mock_check_output.assert_called_with([str(executeable_path), '--version'], cwd=Path(crackers_path, str(cracker_id)))
94 |
95 | # --keyspace
96 | chunk = Chunk()
97 | task = Task()
98 | task.load_task()
99 | hashlist = Hashlist()
100 |
101 | hashlist.load_hashlist(task.get_task()['hashlistId'])
102 | hashlist_id = task.get_task()['hashlistId']
103 | hashlists_path = config.get_value('hashlists-path')
104 |
105 | cracker.measure_keyspace(task, chunk)
106 | mock_check_output.assert_called_with(
107 | "'./hashcat.bin' --keyspace --quiet -a3 ?l?l?l?l --hash-type=0 -S",
108 | shell=True,
109 | cwd=Path(crackers_path, str(cracker_id)),
110 | stderr=-2
111 | )
112 |
113 | # benchmark
114 | result = cracker.run_benchmark(task.get_task())
115 | assert result != 0
116 | mock_check_output.assert_called_with(
117 | f"'./hashcat.bin' --machine-readable --quiet --progress-only --restore-disable --potfile-disable --session=hashtopolis -p \"\t\" \"{Path(hashlists_path, str(hashlist_id))}\" -a3 ?l?l?l?l --hash-type=0 -S -o \"{Path(hashlists_path, str(hashlist_id))}.out\"",
118 | shell=True,
119 | cwd=Path(crackers_path, str(cracker_id)),
120 | stderr=-2
121 | )
122 |
123 | # Sending benchmark to server
124 | query = copy_and_set_token(dict_sendBenchmark, config.get_value('token'))
125 | query['taskId'] = task.get_task()['taskId']
126 | query['result'] = result
127 | query['type'] = task.get_task()['benchType']
128 | req = JsonRequest(query)
129 | req.execute()
130 |
131 | # cracking
132 | chunk.get_chunk(task.get_task()['taskId'])
133 | cracker.run_chunk(task.get_task(), chunk.chunk_data(), task.get_preprocessor())
134 | zaps_path = config.get_value('zaps-path')
135 | zaps_dir = f"hashlist_{hashlist_id}"
136 | skip = str(chunk.chunk_data()['skip'])
137 | limit = str(chunk.chunk_data()['length'])
138 |
139 | full_cmd = [
140 | "'./hashcat.bin'",
141 | '--machine-readable',
142 | '--quiet',
143 | '--status',
144 | '--restore-disable',
145 | '--session=hashtopolis',
146 | '--status-timer 5',
147 | '--outfile-check-timer=5',
148 | f'--outfile-check-dir="{Path(zaps_path, zaps_dir)}"',
149 | f'-o "{Path(hashlists_path, str(hashlist_id))}.out"',
150 | '--outfile-format=1,2,3,4',
151 | f'-p "\t"',
152 | f'-s {skip} -l {limit}',
153 | '--brain-client',
154 | '--brain-host', '127.0.0.1',
155 | '--brain-port', '8080',
156 | '--brain-password', 'password',
157 | '--brain-client-features', '3 ',
158 | f'"{Path(hashlists_path, str(hashlist_id))}"',
159 | '-a3 ?l?l?l?l ',
160 | ' --hash-type=0 ',
161 | ]
162 |
163 | full_cmd = ' '.join(full_cmd)
164 |
165 | mock_Popen.assert_called_with(
166 | full_cmd,
167 | shell=True,
168 | stdout=-1,
169 | stderr=-1,
170 | cwd=Path(crackers_path, str(cracker_id)),
171 | preexec_fn=mock.ANY
172 | )
173 |
174 | # Cleanup
175 | task_obj.delete()
176 | hashlist_v2.delete()
177 |
178 | # Revert config
179 | set_config = {
180 | 'hashcatBrainEnable': '0',
181 | 'hashcatBrainHost': '',
182 | 'hashcatBrainPort': '',
183 | 'hashcatBrainPass': '',
184 | }
185 |
186 | for k,v in set_config.items():
187 | config_item = Config_v2.objects.get(item=k)
188 | config_item.value = v
189 | config_item.save()
190 |
191 | # Re-enable agents, because the the hashcat command will fail
192 | agent = Agent_v2.objects.get(token=config.get_value('token'))
193 | agent.isActive = True
194 | agent.save()
195 |
--------------------------------------------------------------------------------
/tests/test_hashcat_files.py:
--------------------------------------------------------------------------------
1 | import pytest
2 | from unittest import mock
3 | import unittest
4 | from unittest.mock import MagicMock
5 | import os
6 | import subprocess
7 | import shutil
8 | import requests
9 | import json
10 | from pathlib import Path
11 | from argparse import Namespace
12 | import sys
13 | import datetime
14 | from io import BytesIO
15 |
16 | from htpclient.hashcat_cracker import HashcatCracker
17 | from htpclient.binarydownload import BinaryDownload
18 | from htpclient.session import Session
19 | from htpclient.config import Config
20 | from htpclient.initialize import Initialize
21 | from htpclient.chunk import Chunk
22 | from htpclient.hashlist import Hashlist
23 | from htpclient.task import Task
24 | from htpclient.dicts import copy_and_set_token
25 | from htpclient.dicts import dict_sendBenchmark
26 | from htpclient.jsonRequest import JsonRequest
27 | from htpclient.files import Files
28 |
29 | from tests.hashtopolis import Hashlist as Hashlist_v2
30 | from tests.hashtopolis import Task as Task_v2
31 | from tests.hashtopolis import FileImport as FileImport_v2
32 | from tests.hashtopolis import File as File_v2
33 |
34 |
35 | class HashcatFiles(unittest.TestCase):
36 | @mock.patch('subprocess.Popen', side_effect=subprocess.Popen)
37 | @mock.patch('subprocess.check_output', side_effect=subprocess.check_output)
38 | @mock.patch('os.unlink', side_effect=os.unlink)
39 | @mock.patch('os.system', side_effect=os.system)
40 | def test_files_linux(self, mock_system, mock_unlink, mock_check_output, mock_Popen):
41 | if sys.platform != 'linux':
42 | return
43 |
44 | # Setup session object
45 | session = Session(requests.Session()).s
46 | session.headers.update({'User-Agent': Initialize.get_version()})
47 |
48 | # Cmd parameters setup
49 | test_args = Namespace( cert=None, cpu_only=False, crackers_path=None, de_register=False, debug=True, disable_update=False, files_path=None, hashlists_path=None, number_only=False, preprocessors_path=None, url='http://hashtopolis/api/server.php', version=False, voucher='devvoucher', zaps_path=None)
50 |
51 | # Set config and variables
52 | cracker_id = 1
53 | config = Config()
54 |
55 | crackers_path = config.get_value('crackers-path')
56 | files_path = config.get_value('files-path')
57 |
58 |
59 | # Create hashlist
60 | p = Path(__file__).parent.joinpath('create_hashlist_001.json')
61 | payload = json.loads(p.read_text('UTF-8'))
62 | hashlist_v2 = Hashlist_v2(**payload)
63 | hashlist_v2.save()
64 |
65 | # Upload wordlist
66 | stamp = datetime.datetime.now().isoformat()
67 | filename = f'wordlist-{stamp}.txt'
68 | file_import = FileImport_v2()
69 | text = '12345678\n123456\nprincess\n'.encode('utf-8')
70 | fs = BytesIO(text)
71 | file_import.do_upload(filename, fs)
72 |
73 | # Create wordlist
74 | p = Path(__file__).parent.joinpath('create_file_001.json')
75 | payload = json.loads(p.read_text('UTF-8'))
76 | payload['sourceData'] = filename
77 | payload['filename'] = filename
78 | payload['fileType'] = 0
79 | file_obj = File_v2(**payload)
80 | file_obj.save()
81 |
82 | wordlist_id = file_obj.id
83 | wordlist_name = file_obj.filename
84 |
85 | # Upload Rule file
86 | stamp = datetime.datetime.now().isoformat()
87 | filename = f'rule-{stamp}.txt'
88 | file_import = FileImport_v2()
89 | text = ':\n$1\n$2\n'.encode('utf-8')
90 | fs = BytesIO(text)
91 | file_import.do_upload(filename, fs)
92 |
93 | # Create rule file
94 | p = Path(__file__).parent.joinpath('create_file_001.json')
95 | payload = json.loads(p.read_text('UTF-8'))
96 | payload['sourceData'] = filename
97 | payload['filename'] = filename
98 | payload['fileType'] = 1
99 | file_obj2 = File_v2(**payload)
100 | file_obj2.save()
101 |
102 | rule_id = file_obj2.id
103 | rule_name = file_obj2.filename
104 |
105 | # Create task
106 | p = Path(__file__).parent.joinpath('create_task_004.json')
107 | payload = json.loads(p.read_text('UTF-8'))
108 | payload['hashlistId'] = int(hashlist_v2._id)
109 | payload['attackCmd'] = f'#HL# -a0 {wordlist_name} -r {rule_name}'
110 | payload['files'] = [wordlist_id, rule_id]
111 | task_obj = Task_v2(**payload)
112 | task_obj.save()
113 |
114 | # Delete files locally if they are already downloaded in a prev run
115 | wordlist_path = Path(files_path, wordlist_name)
116 | rule_path = Path(files_path, rule_name)
117 | if os.path.isfile(wordlist_path):
118 | os.remove(wordlist_path)
119 | if os.path.isfile(rule_path):
120 | os.remove(rule_path)
121 |
122 | # Try to download cracker 1
123 | executeable_path = Path(crackers_path, str(cracker_id), 'hashcat.bin')
124 |
125 | binaryDownload = BinaryDownload(test_args)
126 | binaryDownload.check_version(cracker_id)
127 |
128 | # --version
129 | cracker = HashcatCracker(1, binaryDownload)
130 | mock_check_output.assert_called_with([str(executeable_path), '--version'], cwd=Path(crackers_path, str(cracker_id)))
131 |
132 | # --keyspace
133 | chunk = Chunk()
134 | task = Task()
135 | task.load_task()
136 | hashlist = Hashlist()
137 | files = Files()
138 |
139 | hashlist.load_hashlist(task.get_task()['hashlistId'])
140 | hashlist_id = task.get_task()['hashlistId']
141 | hashlists_path = config.get_value('hashlists-path')
142 |
143 | # Download required files
144 | assert files.check_files(task.get_task()['files'], task.get_task()['taskId'])
145 |
146 | # Test if the files are really downloaded
147 | assert os.path.isfile(wordlist_path) == True
148 | assert os.path.isfile(rule_path) == True
149 |
150 | cracker.measure_keyspace(task, chunk)
151 | mock_check_output.assert_called_with(
152 | f"'./hashcat.bin' --keyspace --quiet -a0 \"{wordlist_path}\" -r \"{rule_path}\" --hash-type=0 ",
153 | shell=True,
154 | cwd=Path(crackers_path, str(cracker_id)),
155 | stderr=-2
156 | )
157 |
158 | # benchmark
159 | result = cracker.run_benchmark(task.get_task())
160 | assert result != 0
161 | mock_check_output.assert_called_with(
162 | f"'./hashcat.bin' --machine-readable --quiet --progress-only --restore-disable --potfile-disable --session=hashtopolis -p \"\t\" \"{Path(hashlists_path, str(hashlist_id))}\" -a0 \"{wordlist_path}\" -r \"{rule_path}\" --hash-type=0 -o \"{Path(hashlists_path, str(hashlist_id))}.out\"",
163 | shell=True,
164 | cwd=Path(crackers_path, str(cracker_id)),
165 | stderr=-2
166 | )
167 |
168 | # Sending benchmark to server
169 | query = copy_and_set_token(dict_sendBenchmark, config.get_value('token'))
170 | query['taskId'] = task.get_task()['taskId']
171 | query['result'] = result
172 | query['type'] = task.get_task()['benchType']
173 | req = JsonRequest(query)
174 | req.execute()
175 |
176 | # cracking
177 | chunk.get_chunk(task.get_task()['taskId'])
178 | cracker.run_chunk(task.get_task(), chunk.chunk_data(), task.get_preprocessor())
179 | zaps_path = config.get_value('zaps-path')
180 | zaps_dir = f"hashlist_{hashlist_id}"
181 | skip = str(chunk.chunk_data()['skip'])
182 | limit = str(chunk.chunk_data()['length'])
183 |
184 | full_cmd = [
185 | "'./hashcat.bin'",
186 | '--machine-readable',
187 | '--quiet',
188 | '--status',
189 | '--restore-disable',
190 | '--session=hashtopolis',
191 | '--status-timer 5',
192 | '--outfile-check-timer=5',
193 | f'--outfile-check-dir="{Path(zaps_path, zaps_dir)}"',
194 | f'-o "{Path(hashlists_path, str(hashlist_id))}.out"',
195 | '--outfile-format=1,2,3,4',
196 | f'-p "\t"',
197 | f'-s {skip} -l {limit}',
198 | '--potfile-disable',
199 | '--remove',
200 | '--remove-timer=5 ',
201 | f'"{Path(hashlists_path, str(hashlist_id))}"',
202 | f'-a0 "{wordlist_path}" -r "{rule_path}" ',
203 | ' --hash-type=0 ',
204 | ]
205 |
206 | full_cmd = ' '.join(full_cmd)
207 |
208 | mock_Popen.assert_called_with(
209 | full_cmd,
210 | shell=True,
211 | stdout=-1,
212 | stderr=-1,
213 | cwd=Path(crackers_path, str(cracker_id)),
214 | preexec_fn=mock.ANY
215 | )
216 |
217 | # Cleanup
218 | task_obj.delete()
219 | hashlist_v2.delete()
220 | file_obj.delete()
221 | file_obj2.delete()
222 | if os.path.isfile(wordlist_path):
223 | os.remove(wordlist_path)
224 | if os.path.isfile(rule_path):
225 | os.remove(rule_path)
226 |
227 |
228 | if __name__ == '__main__':
229 | unittest.main()
--------------------------------------------------------------------------------
/tests/test_hashcat_files_7z.py:
--------------------------------------------------------------------------------
1 | import pytest
2 | from unittest import mock
3 | import unittest
4 | from unittest.mock import MagicMock
5 | import os
6 | import subprocess
7 | import shutil
8 | import requests
9 | import json
10 | from pathlib import Path
11 | from argparse import Namespace
12 | import sys
13 | import datetime
14 | import time
15 | from io import BytesIO
16 |
17 | from htpclient.hashcat_cracker import HashcatCracker
18 | from htpclient.binarydownload import BinaryDownload
19 | from htpclient.session import Session
20 | from htpclient.config import Config
21 | from htpclient.initialize import Initialize
22 | from htpclient.chunk import Chunk
23 | from htpclient.hashlist import Hashlist
24 | from htpclient.task import Task
25 | from htpclient.dicts import copy_and_set_token
26 | from htpclient.dicts import dict_sendBenchmark
27 | from htpclient.jsonRequest import JsonRequest
28 | from htpclient.files import Files
29 |
30 | import py7zr
31 |
32 | from tests.hashtopolis import Hashlist as Hashlist_v2
33 | from tests.hashtopolis import Task as Task_v2
34 | from tests.hashtopolis import FileImport as FileImport_v2
35 | from tests.hashtopolis import File as File_v2
36 |
37 | class HashcatFiles7z(unittest.TestCase):
38 | @mock.patch('subprocess.Popen', side_effect=subprocess.Popen)
39 | @mock.patch('subprocess.check_output', side_effect=subprocess.check_output)
40 | @mock.patch('os.unlink', side_effect=os.unlink)
41 | @mock.patch('os.system', side_effect=os.system)
42 | def test_files_7z_linux(self, mock_system, mock_unlink, mock_check_output, mock_Popen):
43 | if sys.platform != 'linux':
44 | return
45 |
46 | # Setup session object
47 | session = Session(requests.Session()).s
48 | session.headers.update({'User-Agent': Initialize.get_version()})
49 |
50 | # Cmd parameters setup
51 | test_args = Namespace( cert=None, cpu_only=False, crackers_path=None, de_register=False, debug=True, disable_update=False, files_path=None, hashlists_path=None, number_only=False, preprocessors_path=None, url='http://hashtopolis/api/server.php', version=False, voucher='devvoucher', zaps_path=None)
52 |
53 | # Set config and variables
54 | cracker_id = 1
55 | config = Config()
56 |
57 | crackers_path = config.get_value('crackers-path')
58 | files_path = config.get_value('files-path')
59 |
60 | # Create hashlist
61 | p = Path(__file__).parent.joinpath('create_hashlist_001.json')
62 | payload = json.loads(p.read_text('UTF-8'))
63 | hashlist_v2 = Hashlist_v2(**payload)
64 | hashlist_v2.save()
65 |
66 | # Create 7z file
67 | stamp = datetime.datetime.now().isoformat()
68 | wordlist = f'wordlist-{stamp}.txt'
69 | sevenzip = f'wordlist-{stamp}.7z'
70 |
71 | with open(wordlist, 'w') as file_obj:
72 | file_obj.write('12345678\n123456\nprincess\n')
73 |
74 | with py7zr.SevenZipFile(sevenzip, 'w') as z:
75 | z.writeall(f'./{wordlist}')
76 |
77 | # Upload wordlist
78 | file_import = FileImport_v2()
79 | with open(sevenzip, 'rb') as fs:
80 | file_import.do_upload(sevenzip, fs)
81 |
82 | # Create wordlist
83 | p = Path(__file__).parent.joinpath('create_file_001.json')
84 | payload = json.loads(p.read_text('UTF-8'))
85 | payload['sourceData'] = sevenzip
86 | payload['filename'] = sevenzip
87 | payload['fileType'] = 0
88 | file_obj = File_v2(**payload)
89 | file_obj.save()
90 |
91 | wordlist_id = file_obj.id
92 |
93 | # Create task
94 | p = Path(__file__).parent.joinpath('create_task_004.json')
95 | payload = json.loads(p.read_text('UTF-8'))
96 | payload['hashlistId'] = int(hashlist_v2._id)
97 | payload['attackCmd'] = f'#HL# -a0 {wordlist}'
98 | payload['files'] = [wordlist_id]
99 | task_obj = Task_v2(**payload)
100 | task_obj.save()
101 |
102 | # Cleanup files
103 | os.remove(wordlist)
104 | os.remove(sevenzip)
105 | wordlist_path = Path(files_path, wordlist)
106 | if os.path.isfile(wordlist_path):
107 | os.remove(wordlist_path)
108 |
109 | # Try to download cracker 1
110 | executeable_path = Path(crackers_path, str(cracker_id), 'hashcat.bin')
111 |
112 | binaryDownload = BinaryDownload(test_args)
113 | binaryDownload.check_version(cracker_id)
114 |
115 | # --version
116 | cracker = HashcatCracker(1, binaryDownload)
117 | mock_check_output.assert_called_with([str(executeable_path), '--version'], cwd=Path(crackers_path, str(cracker_id)))
118 |
119 | # --keyspace
120 | chunk = Chunk()
121 | task = Task()
122 | task.load_task()
123 | hashlist = Hashlist()
124 | files = Files()
125 |
126 | hashlist.load_hashlist(task.get_task()['hashlistId'])
127 | hashlist_id = task.get_task()['hashlistId']
128 | hashlists_path = config.get_value('hashlists-path')
129 |
130 | # Download required files
131 | assert files.check_files(task.get_task()['files'], task.get_task()['taskId'])
132 |
133 | file_path = Path(files_path, sevenzip)
134 |
135 | mock_system.assert_called_with(f"./7zr{Initialize.get_os_extension()} x -aoa -o'{files_path}' -y '{file_path}'")
136 |
137 | # Test if the files are really downloaded
138 | assert os.path.isfile(wordlist_path) == True
139 |
140 | cracker.measure_keyspace(task, chunk)
141 | mock_check_output.assert_called_with(
142 | f"'./hashcat.bin' --keyspace --quiet -a0 \"{wordlist_path}\" --hash-type=0 ",
143 | shell=True,
144 | cwd=Path(crackers_path, str(cracker_id)),
145 | stderr=-2
146 | )
147 |
148 | # benchmark
149 | result = cracker.run_benchmark(task.get_task())
150 | assert result != 0
151 | mock_check_output.assert_called_with(
152 | f"'./hashcat.bin' --machine-readable --quiet --progress-only --restore-disable --potfile-disable --session=hashtopolis -p \"\t\" \"{Path(hashlists_path, str(hashlist_id))}\" -a0 \"{wordlist_path}\" --hash-type=0 -o \"{Path(hashlists_path, str(hashlist_id))}.out\"",
153 | shell=True,
154 | cwd=Path(crackers_path, str(cracker_id)),
155 | stderr=-2
156 | )
157 |
158 | # Sending benchmark to server
159 | query = copy_and_set_token(dict_sendBenchmark, config.get_value('token'))
160 | query['taskId'] = task.get_task()['taskId']
161 | query['result'] = result
162 | query['type'] = task.get_task()['benchType']
163 | req = JsonRequest(query)
164 | req.execute()
165 |
166 | # cracking
167 | chunk.get_chunk(task.get_task()['taskId'])
168 | cracker.run_chunk(task.get_task(), chunk.chunk_data(), task.get_preprocessor())
169 | zaps_path = config.get_value('zaps-path')
170 | zaps_dir = f"hashlist_{hashlist_id}"
171 | skip = str(chunk.chunk_data()['skip'])
172 | limit = str(chunk.chunk_data()['length'])
173 |
174 | full_cmd = [
175 | "'./hashcat.bin'",
176 | '--machine-readable',
177 | '--quiet',
178 | '--status',
179 | '--restore-disable',
180 | '--session=hashtopolis',
181 | '--status-timer 5',
182 | '--outfile-check-timer=5',
183 | f'--outfile-check-dir="{Path(zaps_path, zaps_dir)}"',
184 | f'-o "{Path(hashlists_path, str(hashlist_id))}.out"',
185 | '--outfile-format=1,2,3,4',
186 | f'-p "\t"',
187 | f'-s {skip} -l {limit}',
188 | '--potfile-disable',
189 | '--remove',
190 | '--remove-timer=5 ',
191 | f'"{Path(hashlists_path, str(hashlist_id))}"',
192 | f'-a0 "{wordlist_path}" ',
193 | ' --hash-type=0 ',
194 | ]
195 |
196 | full_cmd = ' '.join(full_cmd)
197 |
198 | mock_Popen.assert_called_with(
199 | full_cmd,
200 | shell=True,
201 | stdout=-1,
202 | stderr=-1,
203 | cwd=Path(crackers_path, str(cracker_id)),
204 | preexec_fn=mock.ANY
205 | )
206 |
207 | # Cleanup
208 | task_obj.delete()
209 | hashlist_v2.delete()
210 | file_obj.delete()
211 | if os.path.isfile(wordlist_path):
212 | os.remove(wordlist_path)
213 |
214 |
215 | @mock.patch('subprocess.Popen', side_effect=subprocess.Popen)
216 | @mock.patch('subprocess.check_output', side_effect=subprocess.check_output)
217 | @mock.patch('os.unlink', side_effect=os.unlink)
218 | @mock.patch('os.system', side_effect=os.system)
219 | def test_files_7z_windows(self, mock_system, mock_unlink, mock_check_output, mock_Popen):
220 | if sys.platform != 'win32':
221 | return
222 |
223 | # Setup session object
224 | session = Session(requests.Session()).s
225 | session.headers.update({'User-Agent': Initialize.get_version()})
226 |
227 | # Cmd parameters setup
228 | test_args = Namespace( cert=None, cpu_only=False, crackers_path=None, de_register=False, debug=True, disable_update=False, files_path=None, hashlists_path=None, number_only=False, preprocessors_path=None, url='http://hashtopolis/api/server.php', version=False, voucher='devvoucher', zaps_path=None)
229 |
230 | # Set config and variables
231 | cracker_id = 1
232 | config = Config()
233 |
234 | crackers_path = config.get_value('crackers-path')
235 | files_path = config.get_value('files-path')
236 |
237 | # Create hashlist
238 | p = Path(__file__).parent.joinpath('create_hashlist_001.json')
239 | payload = json.loads(p.read_text('UTF-8'))
240 | hashlist_v2 = Hashlist_v2(**payload)
241 | hashlist_v2.save()
242 |
243 | # Create 7z file
244 | stamp = int(time.time())
245 | wordlist = f'wordlist-{stamp}.txt'
246 | sevenzip = f'wordlist-{stamp}.7z'
247 |
248 | with open(wordlist, 'w') as file_obj:
249 | file_obj.write('12345678\n123456\nprincess\n')
250 |
251 | with py7zr.SevenZipFile(sevenzip, 'w') as z:
252 | z.writeall(f'./{wordlist}')
253 |
254 | # Upload wordlist
255 | file_import = FileImport_v2()
256 | with open(sevenzip, 'rb') as fs:
257 | file_import.do_upload(sevenzip, fs)
258 |
259 | # Create wordlist
260 | p = Path(__file__).parent.joinpath('create_file_001.json')
261 | payload = json.loads(p.read_text('UTF-8'))
262 | payload['sourceData'] = sevenzip
263 | payload['filename'] = sevenzip
264 | payload['fileType'] = 0
265 | file_obj = File_v2(**payload)
266 | file_obj.save()
267 |
268 | wordlist_id = file_obj.id
269 |
270 | # Create task
271 | p = Path(__file__).parent.joinpath('create_task_004.json')
272 | payload = json.loads(p.read_text('UTF-8'))
273 | payload['hashlistId'] = int(hashlist_v2._id)
274 | payload['attackCmd'] = f'#HL# -a0 {wordlist}'
275 | payload['files'] = [wordlist_id]
276 | task_obj = Task_v2(**payload)
277 | task_obj.save()
278 |
279 | # Cleanup files
280 | os.remove(wordlist)
281 | os.remove(sevenzip)
282 | wordlist_path = Path(files_path, wordlist)
283 | if os.path.isfile(wordlist_path):
284 | os.remove(wordlist_path)
285 |
286 | # Try to download cracker 1
287 | executeable_path = Path(crackers_path, str(cracker_id), 'hashcat.exe')
288 |
289 | binaryDownload = BinaryDownload(test_args)
290 | binaryDownload.check_version(cracker_id)
291 |
292 | # --version
293 | cracker = HashcatCracker(1, binaryDownload)
294 | mock_check_output.assert_called_with([str(executeable_path), '--version'], cwd=Path(crackers_path, str(cracker_id)))
295 |
296 | # --keyspace
297 | chunk = Chunk()
298 | task = Task()
299 | task.load_task()
300 | hashlist = Hashlist()
301 | files = Files()
302 |
303 | hashlist.load_hashlist(task.get_task()['hashlistId'])
304 | hashlist_id = task.get_task()['hashlistId']
305 | hashlists_path = config.get_value('hashlists-path')
306 |
307 | # Download required files
308 | assert files.check_files(task.get_task()['files'], task.get_task()['taskId'])
309 |
310 | file_path = Path(files_path, sevenzip)
311 |
312 | mock_system.assert_called_with(f'7zr{Initialize.get_os_extension()} x -aoa -o"{files_path}" -y "{file_path}"')
313 |
314 | # Test if the files are really downloaded
315 | assert os.path.isfile(wordlist_path) == True
316 |
317 | cracker.measure_keyspace(task, chunk)
318 | mock_check_output.assert_called_with(
319 | f'"hashcat.exe" --keyspace --quiet -a0 "{wordlist_path}" --hash-type=0 ',
320 | shell=True,
321 | cwd=Path(crackers_path, str(cracker_id)),
322 | stderr=-2
323 | )
324 |
325 | # benchmark
326 | result = cracker.run_benchmark(task.get_task())
327 | assert result != 0
328 | mock_check_output.assert_called_with(
329 | f'"hashcat.exe" --machine-readable --quiet --progress-only --restore-disable --potfile-disable --session=hashtopolis -p \"\t\" \"{Path(hashlists_path, str(hashlist_id))}\" -a0 "{wordlist_path}" --hash-type=0 -o \"{Path(hashlists_path, str(hashlist_id))}.out\"',
330 | shell=True,
331 | cwd=Path(crackers_path, str(cracker_id)),
332 | stderr=-2
333 | )
334 |
335 | # Sending benchmark to server
336 | query = copy_and_set_token(dict_sendBenchmark, config.get_value('token'))
337 | query['taskId'] = task.get_task()['taskId']
338 | query['result'] = result
339 | query['type'] = task.get_task()['benchType']
340 | req = JsonRequest(query)
341 | req.execute()
342 |
343 | # cracking
344 | chunk.get_chunk(task.get_task()['taskId'])
345 | cracker.run_chunk(task.get_task(), chunk.chunk_data(), task.get_preprocessor())
346 | zaps_path = config.get_value('zaps-path')
347 | zaps_dir = f"hashlist_{hashlist_id}"
348 | skip = str(chunk.chunk_data()['skip'])
349 | limit = str(chunk.chunk_data()['length'])
350 |
351 | full_cmd = [
352 | '"hashcat.exe"',
353 | '--machine-readable',
354 | '--quiet',
355 | '--status',
356 | '--restore-disable',
357 | '--session=hashtopolis',
358 | '--status-timer 5',
359 | '--outfile-check-timer=5',
360 | f'--outfile-check-dir="{Path(zaps_path, zaps_dir)}"',
361 | f'-o "{Path(hashlists_path, str(hashlist_id))}.out"',
362 | '--outfile-format=1,2,3,4',
363 | f'-p "\t"',
364 | f'-s {skip} -l {limit}',
365 | '--potfile-disable',
366 | '--remove',
367 | '--remove-timer=5 ',
368 | f'"{Path(hashlists_path, str(hashlist_id))}"',
369 | f'-a0 "{wordlist_path}" ',
370 | ' --hash-type=0 ',
371 | ]
372 |
373 | full_cmd = ' '.join(full_cmd)
374 |
375 | mock_Popen.assert_called_with(
376 | full_cmd,
377 | shell=True,
378 | stdout=-1,
379 | stderr=-1,
380 | cwd=Path(crackers_path, str(cracker_id)),
381 | )
382 |
383 | # Cleanup
384 | task_obj.delete()
385 | hashlist_v2.delete()
386 | file_obj.delete()
387 | if os.path.isfile(wordlist_path):
388 | os.remove(wordlist_path)
--------------------------------------------------------------------------------
/tests/test_hashcat_preprocessor.py:
--------------------------------------------------------------------------------
1 | import pytest
2 | from unittest import mock
3 | import unittest
4 | from unittest.mock import MagicMock
5 | import os
6 | import subprocess
7 | import shutil
8 | import requests
9 | import json
10 | from pathlib import Path
11 | from argparse import Namespace
12 | import sys
13 | import datetime
14 | from io import BytesIO
15 |
16 | from htpclient.hashcat_cracker import HashcatCracker
17 | from htpclient.binarydownload import BinaryDownload
18 | from htpclient.session import Session
19 | from htpclient.config import Config
20 | from htpclient.initialize import Initialize
21 | from htpclient.chunk import Chunk
22 | from htpclient.hashlist import Hashlist
23 | from htpclient.task import Task
24 | from htpclient.dicts import copy_and_set_token
25 | from htpclient.dicts import dict_sendBenchmark
26 | from htpclient.jsonRequest import JsonRequest
27 | from htpclient.files import Files
28 |
29 | from tests.hashtopolis import Hashlist as Hashlist_v2
30 | from tests.hashtopolis import Task as Task_v2
31 | from tests.hashtopolis import FileImport as FileImport_v2
32 | from tests.hashtopolis import File as File_v2
33 |
34 |
35 | class HashcatPreprocessor(unittest.TestCase):
36 | @mock.patch('subprocess.Popen', side_effect=subprocess.Popen)
37 | @mock.patch('subprocess.check_output', side_effect=subprocess.check_output)
38 | @mock.patch('os.unlink', side_effect=os.unlink)
39 | @mock.patch('os.system', side_effect=os.system)
40 | def test_preprocessor_linux(self, mock_system, mock_unlink, mock_check_output, mock_Popen):
41 | if sys.platform != 'linux':
42 | return
43 |
44 | # Setup session object
45 | session = Session(requests.Session()).s
46 | session.headers.update({'User-Agent': Initialize.get_version()})
47 |
48 | # Create hashlist
49 | p = Path(__file__).parent.joinpath('create_hashlist_001.json')
50 | payload = json.loads(p.read_text('UTF-8'))
51 | hashlist_v2 = Hashlist_v2(**payload)
52 | hashlist_v2.save()
53 |
54 | # Create Task
55 | p = Path(__file__).parent.joinpath('create_task_003.json')
56 | payload = json.loads(p.read_text('UTF-8'))
57 | payload['hashlistId'] = int(hashlist_v2._id)
58 | obj = Task_v2(**payload)
59 | obj.save()
60 | preprocessor_id = payload.get('preprocessorId')
61 | preprocessor_path = Path('preprocessors', str(preprocessor_id))
62 | if os.path.exists(preprocessor_path):
63 | shutil.rmtree(preprocessor_path)
64 |
65 | # Cmd parameters setup
66 | test_args = Namespace( cert=None, cpu_only=False, crackers_path=None, de_register=False, debug=True, disable_update=False, files_path=None, hashlists_path=None, number_only=False, preprocessors_path=None, url='http://hashtopolis/api/server.php', version=False, voucher='devvoucher', zaps_path=None)
67 |
68 | # Try to download cracker 1
69 | cracker_id = 1
70 | config = Config()
71 | crackers_path = config.get_value('crackers-path')
72 |
73 | # executeable_path = Path(crackers_path, str(cracker_id), 'hashcat.bin')
74 |
75 | binaryDownload = BinaryDownload(test_args)
76 |
77 | task = Task()
78 | task.load_task()
79 |
80 | binaryDownload.check_preprocessor(task)
81 | assert os.path.exists(preprocessor_path)
82 |
83 | binaryDownload.check_version(cracker_id)
84 | cracker = HashcatCracker(1, binaryDownload)
85 |
86 | # --keyspace
87 | chunk = Chunk()
88 | hashlist = Hashlist()
89 |
90 | hashlist.load_hashlist(task.get_task()['hashlistId'])
91 | hashlist_id = task.get_task()['hashlistId']
92 | hashlists_path = config.get_value('hashlists-path')
93 |
94 | preprocessors_path = config.get_value('preprocessors-path')
95 | assert cracker.measure_keyspace(task, chunk) == True
96 | mock_check_output.assert_called_with(
97 | '"./pp64.bin" --keyspace --pw-min=1 --pw-max=2 ../../crackers/1/example.dict ',
98 | shell=True,
99 | cwd=Path(preprocessors_path, str(preprocessor_id)),
100 | )
101 |
102 | # --benchmark
103 | result = cracker.run_benchmark(task.get_task())
104 | assert int(result.split(':')[0]) > 0
105 | mock_check_output.assert_called_with(
106 | f"'./hashcat.bin' --machine-readable --quiet --progress-only --restore-disable --potfile-disable --session=hashtopolis -p \"\t\" \"{Path(hashlists_path, str(hashlist_id))}\" --hash-type=0 example.dict -o \"{Path(hashlists_path, str(hashlist_id))}.out\"",
107 | shell=True,
108 | cwd=Path(crackers_path, str(cracker_id)),
109 | stderr=-2
110 | )
111 |
112 | # Sending benchmark to server
113 | query = copy_and_set_token(dict_sendBenchmark, config.get_value('token'))
114 | query['taskId'] = task.get_task()['taskId']
115 | query['result'] = result
116 | query['type'] = task.get_task()['benchType']
117 | req = JsonRequest(query)
118 | req.execute()
119 |
120 | # cracking
121 | chunk.get_chunk(task.get_task()['taskId'])
122 | cracker.run_chunk(task.get_task(), chunk.chunk_data(), task.get_preprocessor())
123 | zaps_path = config.get_value('zaps-path')
124 | zaps_dir = f"hashlist_{hashlist_id}"
125 | skip = str(chunk.chunk_data()['skip'])
126 | limit = str(chunk.chunk_data()['length'])
127 |
128 | full_cmd = [
129 | '"/app/src/preprocessors/1/pp64.bin"',
130 | f'--skip {skip}',
131 | f'--limit {limit}',
132 | ' --pw-min=1 --pw-max=2',
133 | '../../crackers/1/example.dict'
134 | ' |',
135 | "'./hashcat.bin'",
136 | '--machine-readable',
137 | '--quiet',
138 | '--status',
139 | '--remove',
140 | '--restore-disable',
141 | '--potfile-disable',
142 | '--session=hashtopolis',
143 | '--status-timer 5',
144 | '--outfile-check-timer=5',
145 | f'--outfile-check-dir="{Path(zaps_path, zaps_dir)}"',
146 | f'-o "{Path(hashlists_path, str(hashlist_id))}.out"',
147 | '--outfile-format=1,2,3,4',
148 | f'-p "\t"',
149 | '--remove-timer=5',
150 | f'"{Path(hashlists_path, str(hashlist_id))}"',
151 | ' --hash-type=0 ',
152 | ]
153 |
154 | full_cmd = ' '.join(full_cmd)
155 |
156 | mock_Popen.assert_called_with(
157 | full_cmd,
158 | shell=True,
159 | stdout=-1,
160 | stderr=-1,
161 | cwd=Path(crackers_path, str(cracker_id)),
162 | preexec_fn=mock.ANY
163 | )
164 |
165 | # Cleanup
166 | obj.delete()
167 | hashlist_v2.delete()
168 |
169 | @mock.patch('subprocess.Popen', side_effect=subprocess.Popen)
170 | @mock.patch('subprocess.check_output', side_effect=subprocess.check_output)
171 | @mock.patch('os.unlink', side_effect=os.unlink)
172 | @mock.patch('os.system', side_effect=os.system)
173 | def test_preprocessor_windows(self, mock_system, mock_unlink, mock_check_output, mock_Popen):
174 | if sys.platform != 'win32':
175 | return
176 |
177 | # Setup session object
178 | session = Session(requests.Session()).s
179 | session.headers.update({'User-Agent': Initialize.get_version()})
180 |
181 | # Create hashlist
182 | p = Path(__file__).parent.joinpath('create_hashlist_001.json')
183 | payload = json.loads(p.read_text('UTF-8'))
184 | hashlist_v2 = Hashlist_v2(**payload)
185 | hashlist_v2.save()
186 |
187 | # Create Task
188 | p = Path(__file__).parent.joinpath('create_task_003.json')
189 | payload = json.loads(p.read_text('UTF-8'))
190 | payload['hashlistId'] = int(hashlist_v2._id)
191 | obj = Task_v2(**payload)
192 | obj.save()
193 |
194 | config = Config()
195 | preprocessor_id = payload.get('preprocessorId')
196 | preprocessor_path = Path(config.get_value('preprocessors-path'), str(preprocessor_id))
197 | preprocessor_path_binary = preprocessor_path / 'pp64.exe'
198 | if os.path.exists(preprocessor_path):
199 | shutil.rmtree(preprocessor_path)
200 |
201 | # Cmd parameters setup
202 | test_args = Namespace( cert=None, cpu_only=False, crackers_path=None, de_register=False, debug=True, disable_update=False, files_path=None, hashlists_path=None, number_only=False, preprocessors_path=None, url='http://hashtopolis/api/server.php', version=False, voucher='devvoucher', zaps_path=None)
203 |
204 | # Try to download cracker 1
205 | cracker_id = 1
206 | crackers_path = config.get_value('crackers-path')
207 |
208 | # executeable_path = Path(crackers_path, str(cracker_id), 'hashcat.bin')
209 |
210 | binaryDownload = BinaryDownload(test_args)
211 |
212 | task = Task()
213 | task.load_task()
214 |
215 | binaryDownload.check_preprocessor(task)
216 | assert os.path.exists(preprocessor_path)
217 |
218 | binaryDownload.check_version(cracker_id)
219 | cracker = HashcatCracker(1, binaryDownload)
220 |
221 | # --keyspace
222 | chunk = Chunk()
223 | hashlist = Hashlist()
224 |
225 | hashlist.load_hashlist(task.get_task()['hashlistId'])
226 | hashlist_id = task.get_task()['hashlistId']
227 | hashlists_path = config.get_value('hashlists-path')
228 |
229 | preprocessors_path = config.get_value('preprocessors-path')
230 | assert cracker.measure_keyspace(task, chunk) == True
231 | mock_check_output.assert_called_with(
232 | '"pp64.exe" --keyspace --pw-min=1 --pw-max=2 ../../crackers/1/example.dict ',
233 | shell=True,
234 | cwd=Path(preprocessors_path, str(preprocessor_id)),
235 | )
236 |
237 | # benchmark
238 | hashlist_path = Path(hashlists_path, str(hashlist_id))
239 | hashlist_out_path = Path(hashlists_path, f'{hashlist_id}.out')
240 | result = cracker.run_benchmark(task.get_task())
241 | assert result != 0
242 |
243 | full_cmd = [
244 | '"hashcat.exe"',
245 | '--machine-readable',
246 | '--quiet',
247 | '--progress-only',
248 | '--restore-disable',
249 | '--potfile-disable',
250 | '--session=hashtopolis',
251 | '-p',
252 | '"\t"',
253 | f' "{hashlist_path}"',
254 | ' --hash-type=0 ',
255 | 'example.dict',
256 | '-o',
257 | f'"{hashlist_out_path}"'
258 | ]
259 |
260 | full_cmd = ' '.join(full_cmd)
261 | mock_Popen.assert_called_with(
262 | full_cmd,
263 | shell=True,
264 | cwd=Path(crackers_path, str(cracker_id)),
265 | stdout=-1,
266 | stderr=-2
267 | )
268 |
269 | # Sending benchmark to server
270 | query = copy_and_set_token(dict_sendBenchmark, config.get_value('token'))
271 | query['taskId'] = task.get_task()['taskId']
272 | query['result'] = result
273 | query['type'] = task.get_task()['benchType']
274 | req = JsonRequest(query)
275 | req.execute()
276 |
277 | # cracking
278 | chunk.get_chunk(task.get_task()['taskId'])
279 | cracker.run_chunk(task.get_task(), chunk.chunk_data(), task.get_preprocessor())
280 | zaps_path = config.get_value('zaps-path')
281 | zaps_dir = f"hashlist_{hashlist_id}"
282 | skip = str(chunk.chunk_data()['skip'])
283 | limit = str(chunk.chunk_data()['length'])
284 |
285 | full_cmd = [
286 | f'"{preprocessor_path_binary}"',
287 | f'--skip {skip}',
288 | f'--limit {limit}',
289 | ' --pw-min=1 --pw-max=2',
290 | '../../crackers/1/example.dict'
291 | ' |',
292 | '"hashcat.exe"',
293 | '--machine-readable',
294 | '--quiet',
295 | '--status',
296 | '--remove',
297 | '--restore-disable',
298 | '--potfile-disable',
299 | '--session=hashtopolis',
300 | '--status-timer 5',
301 | '--outfile-check-timer=5',
302 | f'--outfile-check-dir="{Path(zaps_path, zaps_dir)}"',
303 | f'-o "{Path(hashlists_path, str(hashlist_id))}.out"',
304 | '--outfile-format=1,2,3,4',
305 | f'-p "\t"',
306 | '--remove-timer=5',
307 | f'"{Path(hashlists_path, str(hashlist_id))}"',
308 | ' --hash-type=0 ',
309 | ]
310 |
311 | full_cmd = ' '.join(full_cmd)
312 |
313 | mock_Popen.assert_called_with(
314 | full_cmd,
315 | shell=True,
316 | stdout=-1,
317 | stderr=-1,
318 | cwd=Path(crackers_path, str(cracker_id)),
319 | )
320 |
321 | # Cleanup
322 | obj.delete()
323 | hashlist_v2.delete()
324 |
325 | if __name__ == '__main__':
326 | unittest.main()
327 |
--------------------------------------------------------------------------------
/tests/test_hashcat_runtime.py:
--------------------------------------------------------------------------------
1 | import pytest
2 | from unittest import mock
3 | import unittest
4 | from unittest.mock import MagicMock
5 | import os
6 | import subprocess
7 | import shutil
8 | import requests
9 | import json
10 | from pathlib import Path
11 | from argparse import Namespace
12 | import sys
13 | import datetime
14 | from io import BytesIO
15 |
16 | from htpclient.hashcat_cracker import HashcatCracker
17 | from htpclient.binarydownload import BinaryDownload
18 | from htpclient.session import Session
19 | from htpclient.config import Config
20 | from htpclient.initialize import Initialize
21 | from htpclient.chunk import Chunk
22 | from htpclient.hashlist import Hashlist
23 | from htpclient.task import Task
24 | from htpclient.dicts import copy_and_set_token
25 | from htpclient.dicts import dict_sendBenchmark
26 | from htpclient.jsonRequest import JsonRequest
27 | from htpclient.files import Files
28 |
29 | from tests.hashtopolis import Hashlist as Hashlist_v2
30 | from tests.hashtopolis import Task as Task_v2
31 | from tests.hashtopolis import FileImport as FileImport_v2
32 | from tests.hashtopolis import File as File_v2
33 |
34 |
35 |
36 | class HashcatRuntime(unittest.TestCase):
37 | @mock.patch('subprocess.Popen', side_effect=subprocess.Popen)
38 | @mock.patch('subprocess.check_output', side_effect=subprocess.check_output)
39 | def test_runtime_windows(self, mock_check_output, moch_popen):
40 | if sys.platform != 'win32':
41 | return
42 |
43 | # Setup session object
44 | session = Session(requests.Session()).s
45 | session.headers.update({'User-Agent': Initialize.get_version()})
46 |
47 | # Create hashlist
48 | p = Path(__file__).parent.joinpath('create_hashlist_001.json')
49 | payload = json.loads(p.read_text('UTF-8'))
50 | hashlist_v2 = Hashlist_v2(**payload)
51 | hashlist_v2.save()
52 |
53 | # Create Task
54 | for p in sorted(Path(__file__).parent.glob('create_task_002.json')):
55 | payload = json.loads(p.read_text('UTF-8'))
56 | payload['hashlistId'] = int(hashlist_v2._id)
57 | obj = Task_v2(**payload)
58 | obj.save()
59 |
60 | # Cmd parameters setup
61 | test_args = Namespace( cert=None, cpu_only=False, crackers_path=None, de_register=False, debug=True, disable_update=False, files_path=None, hashlists_path=None, number_only=False, preprocessors_path=None, url='http://hashtopolis/api/server.php', version=False, voucher='devvoucher', zaps_path=None)
62 |
63 | # Try to download cracker 1
64 | cracker_id = 1
65 | config = Config()
66 | crackers_path = config.get_value('crackers-path')
67 |
68 | binaryDownload = BinaryDownload(test_args)
69 | binaryDownload.check_version(cracker_id)
70 |
71 | # --version
72 | cracker = HashcatCracker(1, binaryDownload)
73 |
74 | # --keyspace
75 | chunk = Chunk()
76 | task = Task()
77 | task.load_task()
78 | hashlist = Hashlist()
79 |
80 | hashlist.load_hashlist(task.get_task()['hashlistId'])
81 | hashlist_id = task.get_task()['hashlistId']
82 | hashlists_path = config.get_value('hashlists-path')
83 |
84 | cracker.measure_keyspace(task, chunk)
85 |
86 | full_cmd = f'"hashcat.exe" --keyspace --quiet -a3 ?l?l?l?l --hash-type=0 '
87 | mock_check_output.assert_called_with(
88 | full_cmd,
89 | shell=True,
90 | cwd=Path(crackers_path, str(cracker_id)),
91 | stderr=-2
92 | )
93 |
94 | # benchmark
95 | hashlist_path = Path(hashlists_path, str(hashlist_id))
96 | hashlist_out_path = Path(hashlists_path, f'{hashlist_id}.out')
97 | result = cracker.run_benchmark(task.get_task())
98 | assert result != 0
99 |
100 | full_cmd = [
101 | '"hashcat.exe"',
102 | '--machine-readable',
103 | '--quiet',
104 | '--runtime=30',
105 | '--restore-disable',
106 | '--potfile-disable',
107 | '--session=hashtopolis',
108 | '-p',
109 | '"\t"',
110 | f' "{hashlist_path}"',
111 | '-a3 ?l?l?l?l',
112 | ' --hash-type=0 ',
113 | '-o',
114 | f'"{hashlist_out_path}"'
115 | ]
116 |
117 | full_cmd = ' '.join(full_cmd)
118 |
119 | moch_popen.assert_called_with(
120 | full_cmd,
121 | shell=True,
122 | cwd=Path(crackers_path, str(cracker_id)),
123 | stdout=-1,
124 | stderr=-1
125 | )
126 |
127 | task_id = task.get_task()['taskId']
128 |
129 | # Sending benchmark to server
130 | query = copy_and_set_token(dict_sendBenchmark, config.get_value('token'))
131 | query['taskId'] = task_id
132 | query['result'] = result
133 | query['type'] = task.get_task()['benchType']
134 | req = JsonRequest(query)
135 | req.execute()
136 |
137 | assert chunk.get_chunk(task_id) == 1
138 |
139 | # Cleanup
140 | obj.delete()
141 | hashlist_v2.delete()
142 |
143 | if __name__ == '__main__':
144 | unittest.main()
145 |
--------------------------------------------------------------------------------
/tests/test_hashcat_simple.py:
--------------------------------------------------------------------------------
1 | import pytest
2 | from unittest import mock
3 | import unittest
4 | from unittest.mock import MagicMock
5 | import os
6 | import subprocess
7 | import shutil
8 | import requests
9 | import json
10 | from pathlib import Path
11 | from argparse import Namespace
12 | import sys
13 | import datetime
14 | from io import BytesIO
15 |
16 | from htpclient.hashcat_cracker import HashcatCracker
17 | from htpclient.binarydownload import BinaryDownload
18 | from htpclient.session import Session
19 | from htpclient.config import Config
20 | from htpclient.initialize import Initialize
21 | from htpclient.chunk import Chunk
22 | from htpclient.hashlist import Hashlist
23 | from htpclient.task import Task
24 | from htpclient.dicts import copy_and_set_token
25 | from htpclient.dicts import dict_sendBenchmark
26 | from htpclient.jsonRequest import JsonRequest
27 | from htpclient.files import Files
28 |
29 | from tests.hashtopolis import Hashlist as Hashlist_v2
30 | from tests.hashtopolis import Task as Task_v2
31 | from tests.hashtopolis import FileImport as FileImport_v2
32 | from tests.hashtopolis import File as File_v2
33 |
34 | class HashcatSimple(unittest.TestCase):
35 | @mock.patch('subprocess.Popen', side_effect=subprocess.Popen)
36 | @mock.patch('subprocess.check_output', side_effect=subprocess.check_output)
37 | @mock.patch('os.unlink', side_effect=os.unlink)
38 | @mock.patch('os.system', side_effect=os.system)
39 | def test_simple_linux(self, mock_system, mock_unlink, mock_check_output, mock_Popen):
40 | if sys.platform != 'linux':
41 | return
42 | # Clean up cracker folder
43 | if os.path.exists('crackers/1'):
44 | shutil.rmtree('crackers/1')
45 |
46 | #TODO: Delete tasks / hashlist to ensure clean
47 | #TODO: Verify setup agent
48 |
49 | # Setup session object
50 | session = Session(requests.Session()).s
51 | session.headers.update({'User-Agent': Initialize.get_version()})
52 |
53 | # Create hashlist
54 | p = Path(__file__).parent.joinpath('create_hashlist_001.json')
55 | payload = json.loads(p.read_text('UTF-8'))
56 | hashlist_v2 = Hashlist_v2(**payload)
57 | hashlist_v2.save()
58 |
59 | # Create Task
60 | for p in sorted(Path(__file__).parent.glob('create_task_001.json')):
61 | payload = json.loads(p.read_text('UTF-8'))
62 | payload['hashlistId'] = int(hashlist_v2._id)
63 | obj = Task_v2(**payload)
64 | obj.save()
65 |
66 | # Cmd parameters setup
67 | test_args = Namespace( cert=None, cpu_only=False, crackers_path=None, de_register=False, debug=True, disable_update=False, files_path=None, hashlists_path=None, number_only=False, preprocessors_path=None, url='http://hashtopolis/api/server.php', version=False, voucher='devvoucher', zaps_path=None)
68 |
69 | # Try to download cracker 1
70 | cracker_id = 1
71 | config = Config()
72 | crackers_path = config.get_value('crackers-path')
73 |
74 | executeable_path = Path(crackers_path, str(cracker_id), 'hashcat.bin')
75 |
76 | binaryDownload = BinaryDownload(test_args)
77 | binaryDownload.check_version(cracker_id)
78 |
79 | cracker_zip = Path(crackers_path, f'{cracker_id}.7z')
80 | crackers_temp = Path(crackers_path, 'temp')
81 | zip_binary = './7zr'
82 | mock_unlink.assert_called_with(cracker_zip)
83 |
84 | mock_system.assert_called_with(f"{zip_binary} x -o'{crackers_temp}' '{cracker_zip}'")
85 |
86 | # --version
87 | cracker = HashcatCracker(1, binaryDownload)
88 | mock_check_output.assert_called_with([str(executeable_path), '--version'], cwd=Path(crackers_path, str(cracker_id)))
89 |
90 | # --keyspace
91 | chunk = Chunk()
92 | task = Task()
93 | task.load_task()
94 | hashlist = Hashlist()
95 |
96 | hashlist.load_hashlist(task.get_task()['hashlistId'])
97 | hashlist_id = task.get_task()['hashlistId']
98 | hashlists_path = config.get_value('hashlists-path')
99 |
100 | cracker.measure_keyspace(task, chunk)
101 | mock_check_output.assert_called_with(
102 | "'./hashcat.bin' --keyspace --quiet -a3 ?l?l?l?l --hash-type=0 ",
103 | shell=True,
104 | cwd=Path(crackers_path, str(cracker_id)),
105 | stderr=-2
106 | )
107 |
108 | # benchmark
109 | result = cracker.run_benchmark(task.get_task())
110 | assert result != 0
111 | mock_check_output.assert_called_with(
112 | f"'./hashcat.bin' --machine-readable --quiet --progress-only --restore-disable --potfile-disable --session=hashtopolis -p \"\t\" \"{Path(hashlists_path, str(hashlist_id))}\" -a3 ?l?l?l?l --hash-type=0 -o \"{Path(hashlists_path, str(hashlist_id))}.out\"",
113 | shell=True,
114 | cwd=Path(crackers_path, str(cracker_id)),
115 | stderr=-2
116 | )
117 |
118 | # Sending benchmark to server
119 | query = copy_and_set_token(dict_sendBenchmark, config.get_value('token'))
120 | query['taskId'] = task.get_task()['taskId']
121 | query['result'] = result
122 | query['type'] = task.get_task()['benchType']
123 | req = JsonRequest(query)
124 | req.execute()
125 |
126 | # cracking
127 | chunk.get_chunk(task.get_task()['taskId'])
128 | cracker.run_chunk(task.get_task(), chunk.chunk_data(), task.get_preprocessor())
129 | zaps_path = config.get_value('zaps-path')
130 | zaps_dir = f"hashlist_{hashlist_id}"
131 | skip = str(chunk.chunk_data()['skip'])
132 | limit = str(chunk.chunk_data()['length'])
133 |
134 | full_cmd = [
135 | "'./hashcat.bin'",
136 | '--machine-readable',
137 | '--quiet',
138 | '--status',
139 | '--restore-disable',
140 | '--session=hashtopolis',
141 | '--status-timer 5',
142 | '--outfile-check-timer=5',
143 | f'--outfile-check-dir="{Path(zaps_path, zaps_dir)}"',
144 | f'-o "{Path(hashlists_path, str(hashlist_id))}.out"',
145 | '--outfile-format=1,2,3,4',
146 | f'-p "\t"',
147 | f'-s {skip} -l {limit}',
148 | '--potfile-disable',
149 | '--remove',
150 | '--remove-timer=5 ',
151 | f'"{Path(hashlists_path, str(hashlist_id))}"',
152 | '-a3 ?l?l?l?l ',
153 | ' --hash-type=0 ',
154 | ]
155 |
156 | full_cmd = ' '.join(full_cmd)
157 |
158 | mock_Popen.assert_called_with(
159 | full_cmd,
160 | shell=True,
161 | stdout=-1,
162 | stderr=-1,
163 | cwd=Path(crackers_path, str(cracker_id)),
164 | preexec_fn=mock.ANY
165 | )
166 |
167 | # Cleanup
168 | obj.delete()
169 | hashlist_v2.delete()
170 |
171 | @mock.patch('subprocess.Popen', side_effect=subprocess.Popen)
172 | @mock.patch('subprocess.check_output', side_effect=subprocess.check_output)
173 | @mock.patch('os.unlink', side_effect=os.unlink)
174 | @mock.patch('os.system', side_effect=os.system)
175 | def test_simple_windows(self, mock_system, mock_unlink, mock_check_output, mock_Popen):
176 | if sys.platform != 'win32':
177 | return
178 |
179 | # Clean up cracker folder
180 | if os.path.exists('crackers/1'):
181 | shutil.rmtree('crackers/1')
182 |
183 | #TODO: Delete tasks / hashlist to ensure clean
184 | #TODO: Verify setup agent
185 |
186 | # Setup session object
187 | session = Session(requests.Session()).s
188 | session.headers.update({'User-Agent': Initialize.get_version()})
189 |
190 | # Create hashlist
191 | p = Path(__file__).parent.joinpath('create_hashlist_001.json')
192 | payload = json.loads(p.read_text('UTF-8'))
193 | hashlist_v2 = Hashlist_v2(**payload)
194 | hashlist_v2.save()
195 |
196 | # Create Task
197 | for p in sorted(Path(__file__).parent.glob('create_task_001.json')):
198 | payload = json.loads(p.read_text('UTF-8'))
199 | payload['hashlistId'] = int(hashlist_v2._id)
200 | obj = Task_v2(**payload)
201 | obj.save()
202 |
203 | # Cmd parameters setup
204 | test_args = Namespace( cert=None, cpu_only=False, crackers_path=None, de_register=False, debug=True, disable_update=False, files_path=None, hashlists_path=None, number_only=False, preprocessors_path=None, url='http://hashtopolis/api/server.php', version=False, voucher='devvoucher', zaps_path=None)
205 |
206 | # Try to download cracker 1
207 | cracker_id = 1
208 | config = Config()
209 | crackers_path = config.get_value('crackers-path')
210 |
211 | binaryDownload = BinaryDownload(test_args)
212 | binaryDownload.check_version(cracker_id)
213 |
214 | cracker_zip = Path(crackers_path, f'{cracker_id}.7z')
215 | crackers_temp = Path(crackers_path, 'temp')
216 | zip_binary = '7zr.exe'
217 | mock_unlink.assert_called_with(cracker_zip)
218 |
219 | mock_system.assert_called_with(f'{zip_binary} x -o"{crackers_temp}" "{cracker_zip}"')
220 |
221 | executeable_path = Path(crackers_path, str(cracker_id), 'hashcat.exe')
222 |
223 | # --version
224 | cracker = HashcatCracker(1, binaryDownload)
225 | mock_check_output.assert_called_with([str(executeable_path), '--version'], cwd=Path(crackers_path, str(cracker_id)))
226 |
227 | # --keyspace
228 | chunk = Chunk()
229 | task = Task()
230 | task.load_task()
231 | hashlist = Hashlist()
232 |
233 | hashlist.load_hashlist(task.get_task()['hashlistId'])
234 | hashlist_id = task.get_task()['hashlistId']
235 | hashlists_path = config.get_value('hashlists-path')
236 |
237 | cracker.measure_keyspace(task, chunk)
238 |
239 | full_cmd = f'"hashcat.exe" --keyspace --quiet -a3 ?l?l?l?l --hash-type=0 '
240 | mock_check_output.assert_called_with(
241 | full_cmd,
242 | shell=True,
243 | cwd=Path(crackers_path, str(cracker_id)),
244 | stderr=-2
245 | )
246 |
247 | # benchmark
248 | hashlist_path = Path(hashlists_path, str(hashlist_id))
249 | hashlist_out_path = Path(hashlists_path, f'{hashlist_id}.out')
250 | result = cracker.run_benchmark(task.get_task())
251 | assert result != 0
252 |
253 | full_cmd = [
254 | '"hashcat.exe"',
255 | '--machine-readable',
256 | '--quiet',
257 | '--progress-only',
258 | '--restore-disable',
259 | '--potfile-disable',
260 | '--session=hashtopolis',
261 | '-p',
262 | '"\t"',
263 | f' "{hashlist_path}"',
264 | '-a3',
265 | '?l?l?l?l',
266 | ' --hash-type=0 ',
267 | '-o',
268 | f'"{hashlist_out_path}"'
269 | ]
270 |
271 | full_cmd = ' '.join(full_cmd)
272 |
273 | mock_check_output.assert_called_with(
274 | full_cmd,
275 | shell=True,
276 | cwd=Path(crackers_path, str(cracker_id)),
277 | stderr=-2
278 | )
279 |
280 | # Sending benchmark to server
281 | query = copy_and_set_token(dict_sendBenchmark, config.get_value('token'))
282 | query['taskId'] = task.get_task()['taskId']
283 | query['result'] = result
284 | query['type'] = task.get_task()['benchType']
285 | req = JsonRequest(query)
286 | req.execute()
287 |
288 | # cracking
289 | chunk.get_chunk(task.get_task()['taskId'])
290 | cracker.run_chunk(task.get_task(), chunk.chunk_data(), task.get_preprocessor())
291 | zaps_path = config.get_value('zaps-path')
292 | zaps_dir = f"hashlist_{hashlist_id}"
293 | skip = str(chunk.chunk_data()['skip'])
294 | limit = str(chunk.chunk_data()['length'])
295 |
296 | full_cmd = [
297 | '"hashcat.exe"',
298 | '--machine-readable',
299 | '--quiet',
300 | '--status',
301 | '--restore-disable',
302 | '--session=hashtopolis',
303 | '--status-timer 5',
304 | '--outfile-check-timer=5',
305 | f'--outfile-check-dir="{Path(zaps_path, zaps_dir)}"',
306 | f'-o "{Path(hashlists_path, str(hashlist_id))}.out"',
307 | '--outfile-format=1,2,3,4',
308 | f'-p "\t"',
309 | f'-s {skip} -l {limit}',
310 | '--potfile-disable',
311 | '--remove',
312 | '--remove-timer=5 ',
313 | f'"{Path(hashlists_path, str(hashlist_id))}"',
314 | '-a3 ?l?l?l?l ',
315 | ' --hash-type=0 ',
316 | ]
317 |
318 | full_cmd = ' '.join(full_cmd)
319 |
320 | mock_Popen.assert_called_with(
321 | full_cmd,
322 | shell=True,
323 | stdout=-1,
324 | stderr=-1,
325 | cwd=Path(crackers_path, str(cracker_id)),
326 | )
327 |
328 | # Cleanup
329 | obj.delete()
330 | hashlist_v2.delete()
331 |
332 | if __name__ == '__main__':
333 | unittest.main()
--------------------------------------------------------------------------------