├── .gitignore ├── Dockerfile ├── LICENSE ├── README.md ├── cmd └── main.go ├── config ├── config.json └── examples │ ├── backup.sh │ ├── configure_database.sql │ └── create_database.sql ├── docs ├── API.md ├── CONTRIBUTORS.md ├── FAQ.md ├── INSTALL.md ├── SECURITY.md ├── USECASE.md └── images │ ├── install-1.png │ ├── install-10.png │ ├── install-3.png │ ├── install-4.png │ ├── install-5.png │ ├── install-6.png │ ├── install-7.png │ ├── install-8.png │ └── install-9.png ├── go.mod ├── go.sum ├── internal ├── api │ └── api_controller.go ├── auth │ ├── auth.go │ ├── auth_controller.go │ └── auth_test.go ├── config │ ├── config.go │ └── config_test.go ├── middleware │ └── middleware.go └── models │ ├── models_functions.go │ ├── models_structs.go │ └── models_test.go ├── static ├── logo.png └── style.css └── templates ├── home.html └── login.html /.gitignore: -------------------------------------------------------------------------------- 1 | *.swp 2 | config/config.json 3 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | # Dockerfile for OpenHashAPI 2 | 3 | # Build Binary then transfer it across layers 4 | FROM golang:1.23-alpine as build-env 5 | RUN mkdir src/app 6 | WORKDIR /src/app 7 | COPY ./cmd ./cmd 8 | COPY ./internal ./internal 9 | COPY ./go.mod . 10 | COPY ./go.sum . 11 | RUN cd ./cmd && go build . 12 | 13 | # Deployment layer 14 | FROM alpine:latest 15 | 16 | # Configuration 17 | ENV GIN_MODE=release 18 | 19 | # Location of your config file 20 | ENV CONF_FILE=./config/config.json 21 | COPY ${CONF_FILE} /etc/config.json 22 | 23 | # Copy over static files 24 | COPY /static /var/www/OpenHashAPI/static 25 | COPY /templates /var/www/OpenHashAPI/templates 26 | 27 | # Make secret material 28 | # NOTE: Self-signed cert 29 | RUN apk update; apk add --no-cache openssl && \ 30 | openssl req -x509 -nodes -days 365 -newkey rsa:4096 -keyout server.key -out server.crt -subj '/CN=www.OpenHashAPI.com' && \ 31 | chmod 604 server.key && chmod 604 server.crt && \ 32 | openssl genpkey -algorithm RSA -out private_key.pem -pkeyopt rsa_keygen_bits:4096 && \ 33 | openssl rsa -in private_key.pem -pubout -out public_key.pem && \ 34 | chmod 604 private_key.pem && chmod 604 public_key.pem && \ 35 | chmod 604 /etc/config.json; 36 | 37 | # Install packages and create app user 38 | RUN addgroup --gid 10001 --system nonroot \ 39 | && adduser --uid 10000 --system --ingroup nonroot --home /home/nonroot nonroot; \ 40 | apk update; apk add --no-cache tini bind-tools; \ 41 | mkdir -p /var/www/OpenHashAPI && chown nonroot:nonroot /var/www/OpenHashAPI \ 42 | && mkdir -p /var/www/OpenHashAPI/logs && chown nonroot:nonroot /var/www/OpenHashAPI/logs \ 43 | && mkdir -p /var/www/OpenHashAPI/lists && chown nonroot:nonroot /var/www/OpenHashAPI/lists \ 44 | && chown nonroot:nonroot /var/www/OpenHashAPI/static && chown nonroot:nonroot /var/www/OpenHashAPI/static/* \ 45 | && chown nonroot:nonroot /var/www/OpenHashAPI/templates && chown nonroot:nonroot /var/www/OpenHashAPI/templates/*; 46 | 47 | # Copy app over and set entrypoint 48 | COPY --from=build-env /src/app/cmd/cmd /sbin/ohaserver 49 | ENTRYPOINT ["/sbin/tini", "--", "/sbin/ohaserver"] 50 | 51 | # Use the non-root user to run our application 52 | USER nonroot 53 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # OpenHashAPI Server 2 | 3 | OpenHashAPI (OHA) is designed to store and maintain hashes and plaintext in a centralized database. OHA is written in Go and designed for containerized deployment. 4 | 5 | OpenHashAPI provides a secure method of communicating hashes over HTTPS and enables lightweight workflows for security practitioners and enthusiasts. OpenHashAPI focuses on extracting value from plaintext and recycles values into newly generated resources such as wordlists, masks, and rules. OHA is designed to target common human password patterns and assess the security of human-generated passwords. 6 | 7 | - RESTful API 8 | - JWT Authentication 9 | - HTTPS Communication 10 | - Centralized Database 11 | - Containerized Deployment 12 | - Upload and Search API 13 | - User Administration 14 | - Server Logging 15 | - Quality Control Filtering 16 | - Async Database Validation 17 | - Async Wordlist Generation 18 | - Async Masks Generation 19 | - Async Rules Generation 20 | - Automatic Upload Rehashing 21 | - Remote Download Resource Files 22 | - Multibyte and `$HEX[...]` handling 23 | - Private file hosting 24 | - Browser-based documentation 25 | 26 | ## Getting Started: 27 | - [About](#about) 28 | - [Install](#install) 29 | - [Usage & API](#usage-&-api) 30 | - [OpenHashAPI Client](#openhashapi-client) 31 | 32 | ## About: 33 | - OpenHashAPI was created out of a need to generate hash-cracking materials using 34 | data. Using discovered material as the foundation for new resources 35 | often offers better results for security teams. OpenHashAPI provides a method to 36 | store, quality control, and validate large amounts of hash data. 37 | - The application offers features to upload and store found material as well as 38 | ensuring material meets quality standards through regex filtering. 39 | - The application features several asynchronous processes to generate new 40 | material and host it for download. Generated material is sorted by frequency. 41 | - This tool was designed to be used by small-security teams and enthusiasts 42 | within private networks. 43 | 44 | ## Install: 45 | - The application is run within a container connected to a database on the 46 | underlying host. 47 | - The installation is composed of installing and setting up the database, installing 48 | and setting up the server application, and then deploying the server. 49 | - Instructions can be found within `docs/INSTALL.md` 50 | 51 | ## Usage & API: 52 | - The API is defined in `docs/API.md` and `docs/API.yml` 53 | - Detailed usage documentation can be found in `docs/FAQ.md` 54 | - The server also supports browser interactive documentation at `/login` 55 | 56 | The following are defined API endpoints: 57 | - `/api/register` 58 | - `/api/login` 59 | - `/api/health` 60 | - `/api/found` 61 | - `/api/search` 62 | - `/api/manage` 63 | - `/api/manage/refresh/FILE` 64 | - `/api/status` 65 | - `/api/download/FILE/NUM` 66 | - `/api/lists` 67 | - `/api/lists/LISTNAME` 68 | 69 | ## OpenHashAPI Client: 70 | - The API can be communicated over HTTPS with any HTTP client 71 | - We offer a recommended client of [OpenHashAPI-Client](https://github.com/Scorpion-Security-Labs/OpenHashAPI-Client) that can be used to 72 | seamlessly communicate with the server. 73 | -------------------------------------------------------------------------------- /cmd/main.go: -------------------------------------------------------------------------------- 1 | // Package main controls launching the server and its components 2 | // 3 | // The configuration for the server is done by a JSON configuration file given 4 | // in the Dockerfile. All API routes are hosted on /api/* and some require more 5 | // granular permissions to access. 6 | package main 7 | 8 | import ( 9 | "fmt" 10 | "net/http" 11 | "ohaserver/internal/api" 12 | "ohaserver/internal/auth" 13 | "ohaserver/internal/config" 14 | "ohaserver/internal/middleware" 15 | "os" 16 | 17 | "github.com/gin-gonic/gin" 18 | ) 19 | 20 | var err error 21 | 22 | func init() { 23 | // NOTE: This is hard coded from the Dockerfile 24 | config.ServerConfig = config.LoadConfig("/etc/config.json") 25 | } 26 | 27 | func main() { 28 | // DATABASE 29 | db, err := auth.MySQLAuthenticate() 30 | if err != nil { 31 | fmt.Println(err) 32 | os.Exit(1) 33 | } 34 | 35 | // SERVER 36 | serverConfig := config.ServerConfig 37 | ginServer := gin.Default() 38 | ginServer.Static("/static", "/var/www/OpenHashAPI/static") 39 | ginServer.LoadHTMLGlob("/var/www/OpenHashAPI/templates/*") 40 | ginServer.SetTrustedProxies([]string{""}) 41 | 42 | // SELF VALIDATION 43 | if serverConfig.SelfHealDB && serverConfig.RehashUploads { 44 | go config.ValidateDatabaseHashes(db, serverConfig.SelfHealDBChunks, serverConfig.SelfHealDBWorkers, serverConfig.RehashAlgorithm) 45 | } 46 | 47 | // GENERATE FILES 48 | tasks := make(chan func(), 2) 49 | go func() { 50 | for task := range tasks { 51 | task() 52 | } 53 | }() 54 | 55 | if serverConfig.GenerateWordlist { 56 | tasks <- func() { config.GenerateWordlistFile(db) } 57 | } 58 | if serverConfig.GenerateRules { 59 | tasks <- func() { config.GenerateRulesFile(db) } 60 | } 61 | if serverConfig.GenerateMasks { 62 | tasks <- func() { config.GenerateMasksFile(db) } 63 | } 64 | 65 | close(tasks) 66 | 67 | // MIDDLEWARE 68 | ginServer.Use(middleware.MaxSizeAllowed(serverConfig.ServerGBMaxUploadSize)) 69 | ginServer.Use(middleware.LoggerMiddleware) 70 | 71 | // AUTHORIZATION LEVELS 72 | frontendPublic := ginServer.Group("/") 73 | frontendPrivate := ginServer.Group("/") 74 | frontendPrivate.Use(middleware.AuthenticationCheckMiddleware()) 75 | 76 | public := ginServer.Group("/api") 77 | private := ginServer.Group("/api") 78 | private.Use(middleware.AuthenticationCheckMiddleware()) 79 | 80 | // FRONTEND ROUTES 81 | frontendPublic.GET("/login", func(c *gin.Context) { 82 | c.HTML(http.StatusOK, "login.html", gin.H{}) 83 | }) 84 | frontendPrivate.GET("/home", func(c *gin.Context) { 85 | c.HTML(http.StatusOK, "home.html", gin.H{}) 86 | }) 87 | 88 | // API ROUTES 89 | public.GET("/status", api.StatusHandler) 90 | public.POST("/login", auth.LoginHandler) 91 | public.POST("/register", middleware.OpenRegistrationMiddleware(serverConfig.OpenRegistration), auth.RegistrationHandler) 92 | 93 | // PRIVATE ROUTES 94 | private.GET("/health", api.HealthHandler) 95 | private.GET("/download/:filename/:n", api.DownloadFileHandler) 96 | private.GET("/manage/refresh/:filename", middleware.CanManageMiddleware(), api.ManageRefreshFilesHandler) 97 | private.POST("/search", middleware.CanSearchMiddleware(), api.SearchHandler) 98 | private.POST("/found", middleware.CanUploadMiddleware(), api.SubmitHashHandler) 99 | private.POST("/manage/permissions", middleware.CanManageMiddleware(), auth.ManageUserHandler) 100 | 101 | // PRIVATE LIST ROUTES 102 | private.GET("/lists", middleware.CanListUserListsMiddleware(serverConfig.AllowUserLists), api.ViewListHandler) 103 | private.GET("/lists/:listname", middleware.CanListUserListsMiddleware(serverConfig.AllowUserLists), api.ViewListHandler) 104 | private.POST("/lists", middleware.CanEditUserListsMiddleware(serverConfig.AllowUserLists), api.EditListHandler) 105 | private.POST("/lists/:listname", middleware.CanEditUserListsMiddleware(serverConfig.AllowUserLists), api.EditListHandler) 106 | 107 | // REDIRECT ROUTE 108 | ginServer.NoRoute(func(c *gin.Context) { 109 | c.Redirect(http.StatusFound, "/login") 110 | }) 111 | 112 | // SERVER START 113 | ginServer.RunTLS(fmt.Sprintf(":%d", serverConfig.ServerPort), serverConfig.ServerTLSCertfilePath, serverConfig.ServerTLSKeyfilePath) 114 | } 115 | -------------------------------------------------------------------------------- /config/config.json: -------------------------------------------------------------------------------- 1 | { 2 | "database-user":"ohauser", 3 | "database-pwd":"password", 4 | "auth-pepper":"0H4St4ticP3pp3r", 5 | "database-idle-connections":100, 6 | "server-port":8080, 7 | "server-tls-certfile-path":"server.crt", 8 | "server-tls-keyfile-path":"server.key", 9 | "server-jwt-public-pemfile-path":"public_key.pem", 10 | "server-jwt-private-pemfile-path":"private_key.pem", 11 | "server-jwt-ttl":15, 12 | "server-gb-max-upload-size":2, 13 | "open-registration":true, 14 | "rehash-uploads":true, 15 | "rehash-algorithm":0, 16 | "quality-filter":true, 17 | "quality-filter-regex":"(xiaonei|zomato|fbobh|fccdbbcdaa)|http:\\/\\/|https:\\/\\/|\\@.*\\.net||
|| $date-oha.sql 6 | -------------------------------------------------------------------------------- /config/examples/configure_database.sql: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # Install MySQL 4 | # sudo apt update && sudo apt install -y mysql-server && sudo systemctl start mysql.service 5 | 6 | # Pre-req for mysql_secure_installation on ubuntu 7 | # STRONGLY suggest changing the default value 8 | # sudo mysql --execute "ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'password';" 9 | # sudo mysql_secure_installation 10 | 11 | # Revert auth back so sudo mysql works again 12 | # sudo mysql --execute "ALTER USER 'root'@'localhost' IDENTIFIED WITH auth_socket;" 13 | 14 | # Create DB user 15 | # STRONGLY suggest changing the default value 16 | # sudo mysql --execute "CREATE USER 'ohauser'@'localhost' IDENTIFIED BY 'password';" 17 | 18 | # Grant user 19 | # NOTE OpenHashAPI.* for database and table permissions 20 | # sudo mysql --execute "GRANT CREATE, ALTER, DROP, INSERT, UPDATE, INDEX, DELETE, SELECT, REFERENCES, RELOAD on OpenHashAPI.* TO 'ohauser'@'localhost';" 21 | # sudo mysql --execute "FLUSH PRIVILEGES;" 22 | echo "please read script before running" 23 | -------------------------------------------------------------------------------- /config/examples/create_database.sql: -------------------------------------------------------------------------------- 1 | CREATE DATABASE OpenHashAPI; 2 | USE OpenHashAPI; 3 | 4 | CREATE TABLE Hashes ( 5 | algorithm VARCHAR(8) NOT NULL, 6 | hash VARCHAR(255) NOT NULL, 7 | plaintext VARCHAR(255) NOT NULL, 8 | validated BOOLEAN DEFAULT FALSE, 9 | PRIMARY KEY (`algorithm`, `hash`) 10 | ); 11 | 12 | CREATE TABLE Users ( 13 | id int NOT NULL AUTO_INCREMENT, 14 | username VARCHAR(32) NOT NULL, 15 | password VARCHAR(255) NOT NULL, 16 | can_login BOOLEAN NOT NULL, 17 | can_search BOOLEAN NOT NULL, 18 | can_upload BOOLEAN NOT NULL, 19 | can_manage BOOLEAN NOT NULL, 20 | can_view_private BOOLEAN NOT NULL, 21 | can_edit_private BOOLEAN NOT NULL, 22 | PRIMARY KEY (`id`, `username`) 23 | ); 24 | ALTER TABLE Users ADD UNIQUE (username); 25 | 26 | -------------------------------------------------------------------------------- /docs/API.md: -------------------------------------------------------------------------------- 1 | # OpenHashAPI 2 | 3 | ## Authentication Endpoints 4 | 5 | ### POST `/api/register` 6 | - Registers a new user. 7 | - Authenticated: `false` 8 | - Query Params: `none` 9 | - Access Role: `open-registration` in server configuration 10 | - Request Body: 11 | * `username`: The username of the new user. 12 | * `password`: The password of the new user. 13 | ### POST `/api/login` 14 | - Logs in a user. 15 | - Authenticated: `false` 16 | - Query Params: `none` 17 | - Access Role: `canLogin` in user attributes 18 | - Request Body: 19 | * `username`: The username of the user logging in. 20 | * `password`: The password of the user logging in. 21 | 22 | ## Usage Endpoints 23 | 24 | ### GET `/api/health` 25 | - Fetches information about the server-side configuration. 26 | - Authenticated: `true` 27 | - Query Params: `none` 28 | - Access Role: `none` 29 | ### POST `/api/found` 30 | - Submits new material to the database through the API. 31 | - Authenticated: `true` 32 | - Query Params: `none` 33 | - Access Role: `canUpload` in user attributes 34 | - Request Body: 35 | * `algorithm`: The algorithm used to generate the hash. 36 | * `hash-plain`: An array of hashes and plain text values. 37 | * Values should be submitted as `HASH:PLAIN` or `HASH:SALT:PLAIN` 38 | * The `algorithm` parameter should be an integer representing the hash mode. 39 | ### POST `/api/search` 40 | - Allows searching the database by either `hash` or `plain` values. 41 | - Authenticated: `true` 42 | - Query Params: `hash` `plaintext` 43 | - Access Role: `canSearch` in user attributes 44 | - Query String Parameters: 45 | * `hash`: The hash to search for. 46 | * `plaintext`: The plaintext value to search for. 47 | * Both query string parameters can be used at once and expect boolean values. 48 | - Request Body: 49 | * `data`: An array of hashes or plain text values to search for. 50 | ### POST `/api/manage/permissions` 51 | - Allows for the permission management of other users. 52 | - Authenticated: `true` 53 | - Query Params: `none` 54 | - Access Role: `canManage` in user attributes 55 | - Request Body: 56 | * `userID`: The user's ID to manage permissions for. 57 | * `canLogin`: Whether the user can log in. 58 | * `canSearch`: Whether the user can search the database. 59 | * `canUpload`: If the user can upload new material to the database. 60 | * `canManage`: Whether the user can manage other users' permissions. 61 | * `canViewUserLists`: If the user can view user lists on the server. 62 | * `canEditUserLists`: Whether the user can edit user lists on the server. 63 | ### GET `/api/manage/refresh/FILE` 64 | - Refreshes the server's wordlists, masks, or rules. 65 | - Authenticated: `true` 66 | - Query Params: `none` 67 | - Access Role: `canManage` in user attributes 68 | - Parameters: 69 | * `FILE`: The file to refresh. 70 | ### GET `/api/download/FILE/NUM` 71 | - Allows the download of files from the server. 72 | - FILE can be wordlist, mask, or rules. NUM is the number of results to return. 73 | - Authenticated: `true` 74 | - Query Params: `offset` `contains` 75 | - Access Role: `none` 76 | - Parameters: 77 | * `FILE`: The name of the file to download. 78 | * `NUM`: The number of rows to download. 79 | - Query String Parameters: 80 | * `offset`: Will return results starting at Nth position. 81 | * `contains`: Will only return results that contain a substring. 82 | * `prepend`: Will only return results that do or do not contain prepend rules. 83 | * `append`: Will only return results that do or do not contain append rules. 84 | * `toggle`: Will only return results that do or do not contain toggle rules. 85 | - Responses: 86 | * `200`: OK 87 | * `Content-Type`: `application/octet-stream` 88 | * Body: The contents of the file. 89 | ### GET `/api/status` 90 | - Returns the status of the downloadable files from the server. 91 | - Authenticated: `false` 92 | - Query Params: `none` 93 | - Access Role: `none` 94 | - Responses: 95 | * `200`: OK 96 | * `Content-Type`: `application/json` 97 | * Body: 98 | * `status`: The status of the server. 99 | * `files`: An array of files and their sizes. 100 | 101 | ### GET `/api/lists` & GET `/api/lists/LISTNAME` 102 | - Fetches information about or returns content of any downloadable files stored on the server. 103 | - The `LISTNAME` parameter is the file to return contents of. 104 | - Authenticated: `true` 105 | - Query Params: `none` 106 | - Access Role: `canViewUserLists` in user attributes and `allow-user-lists` in server configuration 107 | - Responses: 108 | * `200` OK 109 | * `Content-Type`: `text/plain` 110 | * Body: 111 | * Content of the file or success message 112 | 113 | ### POST `/api/lists` & POST `/api/lists/LISTNAME` 114 | - Creates a new list or updates a posted list with new items. 115 | - The `LISTNAME` parameter will attempt to update that file with new items. 116 | - Authenticated: `true` 117 | - Query Params: `name` 118 | - Access Role: `canEditUserLists` in user attributes and `allow-user-lists` in server configuration 119 | - Responses: 120 | * `200` OK 121 | * `Content-Type`: `text/plain` 122 | * Body: 123 | * Success message 124 | -------------------------------------------------------------------------------- /docs/CONTRIBUTORS.md: -------------------------------------------------------------------------------- 1 | # Scorpion Labs: 2 | 3 | Project Owner: Jake Wnuk 4 | 5 | Documentation and Review: Dan King 6 | 7 | Code and Functionality Review: David E Baker 8 | -------------------------------------------------------------------------------- /docs/FAQ.md: -------------------------------------------------------------------------------- 1 | - [How Do I Install the Server?](#how-do-i-install-the-server) 2 | - [How Can I Change the Server Configuration?](#how-can-i-change-the-server-configuration) 3 | - [How Do I Communicate with the Server?](#how-do-i-communicate-with-the-server) 4 | - [How Can I Create a User and Login?](#how-can-i-create-a-user-and-login) 5 | - [How Can I Edit User Permissions?](#how-can-i-edit-user-permissions) 6 | - [How Can I Upload Hashes?](#how-can-i-upload-hashes) 7 | - [How Can I Search Hashes?](#how-can-i-search-hashes) 8 | - [How is Data Stored?](#how-is-data-stored) 9 | - [What is Rehashing?](#what-is-rehashing) 10 | - [What is the Quality Filter?](#what-is-the-quality-filter) 11 | - [How Does the Database Self-Heal?](#how-does-the-database-self-heal) 12 | - [How is Data Stored?](#how-is-data-stored) 13 | - [What is Rehashing?](#what-is-rehashing) 14 | - [What is the Quality Filter?](#what-is-the-quality-filter) 15 | - [How Does the Database Self-Heal?](#how-does-the-database-self-heal) 16 | - [How Can I Download Files?](#how-can-i-download-files) 17 | - [How are the Files Made?](#how-are-the-files-made) 18 | - [How Can I See if The Files Are Ready?](#how-can-i-see-if-the-files-are-ready) 19 | - [How Can I Get Different Parts of The Files?](#how-can-i-get-different-parts-of-the-files) 20 | - [How Can I Only Download Content with X in it?](#how-can-i-download-content-with-x-in-it) 21 | - [Are $HEX[...] Items Processed in All Features?](#are-hex-items-processed-in-all-features) 22 | - [Are Multibyte Items Processed?](#are-multibyte-items-processed) 23 | - [The Filter was Changed but Nothing Is Being Removed?](#the-filter-was-changed-but-nothing-is-being-removed) 24 | - [Why is the Database not Containerized?](#why-is-the-database-not-containerized) 25 | 26 | --- 27 | ## How Do I Install the Server? 28 | - Steps to install the server are found in `docs/INSTALL.md` 29 | 30 | ## How Can I Change the Server Configuration? 31 | - The server configuration can be modified using JSON configuration files. 32 | - An example configuration file can be found in `config/config.json`. 33 | - The configuration file location is set in the `Dockerfile`, which is then copied to the container when the application is built. 34 | 35 | ## How Do I Communicate with the Server? 36 | - The server responds over HTTPS, so any tool that can send HTTP requests can be used. 37 | - API routes are documented in OAS and Markdown in `docs/API.yml` and `docs/API.md`. 38 | - [OpenHashAPI-Client](#) is also recommended to interact with the server deployment. 39 | - In the default configuration, the server uses a self-signed certificate, which may cause errors on some HTTP clients. 40 | - A partial web interface is available at `https://URL/login` and `https://URL/home`. 41 | 42 | ## How Can I Create a User and Login? 43 | - The easiest way to register is by going to `https://URL/login` and use the form 44 | - The `/api/register` endpoint can be used for user registration. Users can register with the [OpenHashAPI-Client](#). 45 | - The `/api/register` endpoint must be enabled in the `config.json` file for users to self-register to the application. 46 | - After registering an account, the `/api/login` endpoint can retrieve a valid authentication token. 47 | - The application uses the `Authorization: Bearer ` HTTP header to authenticate requests. 48 | - Server administrators can disable specific users from authenticating using `/api/manage`. 49 | 50 | ## How Can I Edit User Permissions? 51 | - User permissions can be edited through the `/api/manage` endpoint. 52 | - By default, user accounts do not have permission to modify their or other user's permissions. 53 | - To grant this permission the first time, please edit the database manually. 54 | - `UPDATE Users SET can_manage = 1 WHERE id = 0;` 55 | - The following permissions can be used to restrict users access: 56 | - `canLogin` 57 | - `canSearch` 58 | - `canUpload` 59 | - `canManage` 60 | - `canViewUserLists` 61 | - `canEditUserLists` 62 | 63 | ## How Can I Upload Hashes? 64 | - Authenticated users are allowed to submit new hashes to the database. 65 | - This can be done with the `/api/found` endpoint. 66 | - Uploaded hashes will be affected by the `quality-filter` and the `rehash` feature if set. 67 | - Server administrators can disable specific users from uploading using `/api/manage`. 68 | - If server administrators allow, files not 69 | affected by filtering or database can also be uploaded. These files are stored in the container's filesystem and can be updated with new findings. 70 | - The `/api/lists` and `/api/lists/LISTNAME` endpoints accept GET and POST 71 | requests to work with user lists. 72 | 73 | ## How Can I Search Hashes? 74 | - Authenticated users can search the database for hashes or plaintext values. 75 | - This can be done with the `/api/search` endpoint. 76 | - Searched hashes or plaintext will cover all algorithms and retrieve matching entries. 77 | - Server administrators can disable specific users from searching using `/api/manage`. 78 | 79 | ## How is Data Stored? 80 | - Data is stored within two tables: `Hashes` and `Users` 81 | - `Users` contains each registered user's username, hash, and permissions matrix. 82 | - `Hashes` contains the algorithm, hash, and plaintext for each submitted hash. 83 | - Hashes are accepted as `HASH:PLAIN` or `HASH:SALT:PLAIN` values, and attempts are made to parse plaintext from hash values. 84 | - If user lists are allowed, these are stored on the container's filesystem and can be mounted to the host for persistence. 85 | - Within the container, files are stored within the `/var/www/OpenHashAPI` directory and contain the following: 86 | - `lists/` 87 | - `logs/` 88 | - `static/` 89 | - `templates/` 90 | 91 | ## What is Rehashing? 92 | - Rehashing is a feature that allows uploads to be automatically rehashed into MD5 (0), SHA1 (100), or NTLM (1000). 93 | - By enabling rehashing, the original `HASH:PLAIN` will not be stored, and only the rehashed version will be stored. 94 | - Rehashing will use the plaintext value and `$HEX[...]` plaintexts are decoded before rehashing. 95 | - Rehashing can be turned on or off within `config.json`. 96 | 97 | ## What is the Quality Filter? 98 | - Quality filtering is a feature that allows the server administrator to reject plaintexts that match a regex pattern. 99 | - This feature is used when uploading hashes and when the database is self-healing. 100 | - If uploading, items that match the filter will be rejected and not stored within the database. 101 | - If self-healing, items already in the database will be deleted. 102 | - Items in `$HEX[...]` format are decoded before comparing. 103 | - Quality filtering can be turned on or off within `config.json`. 104 | 105 | ## How Does the Database Self-Heal? 106 | - Self-healing or self-validation is a feature that allows the database to validate entries within the database asynchronously for quality and accuracy. 107 | - Self-healing requires the rehashing feature also to be enabled. 108 | - When the server starts, a process will start to enumerate the database and look for incorrect `HASH:PLAIN` combinations and items that the quality filter can catch. 109 | - When an item is validated, it is marked as `true` in the `validated` column of the `Hashes` table. 110 | - The number of chunks the database is divided into, and the number of workers assigned to enumerate the chunks can be configured in `config/config.json.` 111 | - Self-healing can be turned on or off within `config.json`. 112 | 113 | ## How Can I Download Files? 114 | - Authenticated users are allowed to download files created by the server. 115 | - This can be done with the `/api/download/FILE/NUM` endpoint. 116 | - `FILE` can be one of three values: wordlist, masks, and rules. 117 | - `NUM` must be a valid integer value, and the query will return that many rows. 118 | - If user lists are allowed, the `/api/lists/LISTNAME` endpoint can be used to retrieve content. 119 | 120 | ## How are the Files Made? 121 | - Files are made asynchronously from the database records and made ready for download. 122 | - The wordlist is made using the database records to extract base words. 123 | - The masks are made using the database records to extract masks that meet minimum complexity requirements. 124 | - The rules are made by using the database records to extract features from plaintext to generate rules. 125 | - All files are sorted by occurrence. 126 | - Each file type can be turned on or off in `config/config.json`. 127 | - To edit the logic, functions are found in `internal/config/config.go`. 128 | 129 | ## How Can I See if The Files Are Ready? 130 | - Because the files are generated asynchronously, they can take time to prepare. 131 | - The `/api/status` endpoint allows unauthenticated users access to view the status of the file generation and if they are available for download. 132 | 133 | ## How Can I Get Different Parts of The Files? 134 | - The `NUM` variable in the path can control the number of lines returned. 135 | - The query string `offset` can be added to control where the starting point is for retrieving lines. 136 | - For example, `/api/downloads/wordlist/1000?offset=1000` will take 1,000 rows starting at the 1,000th row. 137 | 138 | ## How Can I Only Download Content with X in it? 139 | - The query string `contains` can be added to control the type of content returned. 140 | - This will only return rows that contain the substring in `contains`. 141 | - For example, `/api/downloads/wordlist/1000?contains=test` will take 1,000 rows that contain "test". 142 | - Additonal query strings of `append`, `prepend`, and `toggle` can also be added for rule queries to only fetch certain rules. A boolean value is used to control these. 143 | 144 | ## Are $HEX[...] Items Processed in All Features? 145 | - Yes, `$HEX[...]` items are decoded before being used by many features that rely on plaintext values. 146 | 147 | ## Are Multibyte Items Processed? 148 | - Yes, multibyte items are processed by the application. 149 | - To ensure valid rules, multibyte items are transformed for the rule generation process. 150 | 151 | ## The Filter was Changed, but Nothing is Being Removed. 152 | - Once items are marked as validated in the `Hashes` database table, they need to 153 | be reset to `false` to be rescanned by new filters. 154 | - Once items are reset, the self-validation feature will enumerate them and 155 | remove any that match the new filter. 156 | 157 | ## Why is the Database not Containerized? 158 | - The database is not containerized to ensure the database persists beyond application restarts. Additonally, some users will use the system to house billions of records, this level of performance can benefit from fewer layers of virtualization. 159 | -------------------------------------------------------------------------------- /docs/INSTALL.md: -------------------------------------------------------------------------------- 1 | ### Installing the Database: 2 | - [Installing the Database Software](#installing-the-database-software) 3 | - [Securing the Database Installation](#securing-the-database-installation) 4 | - [Create the Database and Tables](#create-the-database-and-tables) 5 | - [Create the Database User](#create-the-database-user) 6 | 7 | ### Installing the Server: 8 | - [Install the Container Software](#install-the-container-software) 9 | - [Create the Configuration File](#create-the-configuration-file) 10 | - [Build the Docker Image](#build-the-docker-image) 11 | - [Deploy the Server Image](#deploy-the-server-image) 12 | 13 | ### Setting up a New Instance: 14 | - [Register a New User](#register-a-new-user) 15 | - [Assign Initial Permissions](#assign-initial-permissions) 16 | - [Create Routine Backups](#create-routine-backups) 17 | 18 | ### Common Issues: 19 | - [Issues Running mysql_secure_installation](#issues-running-mysql_secure_installation) 20 | - [Issues Installing Docker](#issues-installing-docker) 21 | 22 | --- 23 | 24 | ### Installing the Database Software 25 | The database is installed on the underlying host to provide data persistence, and the application runs within a container on the host system. The first step is to ensure that MySQL is installed and running. 26 | 27 | ``` 28 | sudo apt update && sudo apt install -y mysql-server && sudo systemctl start mysql.service 29 | ``` 30 | > [!TIP] 31 | > Some distros have MySQL/MariaDB installed by default. Check with `sudo systemctl status mysql && sudo systemctl start mysql.service`. 32 | 33 | The intructions will also be done in the following screen captures. We will start with a fresh install of Ubuntu 22.04.3 LTS: 34 | 35 | ![Screen capture of a terminal running uname and installing mysql with apt.](/docs/images/install-1.png) 36 | --- 37 | 38 | ### Securing the Database Installation 39 | With `mysql` installed, we want to reconfigure the database to be more secure by default. Some distributions may not be able to run the following command, if so, please see [Common Issues](#issues-running-mysql_secure_installation). 40 | 41 | ``` 42 | sudo mysql_secure_installation 43 | ``` 44 | > [!TIP] 45 | > Having issues? See [Common Issues](#issues-running-mysql_secure_installation) 46 | 47 | The following shows running `mysql_secure_installation` after installing MySQL with `apt`. For this process select "Y" or "y" for all settings to secure the MySQL installation. For the password requirement, we would suggest using the strongest value available. 48 | 49 | ![Screen capture of running the mysql_secure_installation command in a terminal.](/docs/images/install-3.png) 50 | --- 51 | 52 | ### Create the Database and Tables 53 | With `mysql` configured, the next step is configuring the database and associated tables. 54 | 55 | > [!TIP] 56 | > In `config/examples` there are two scripts that can be used to create the database and replicate the following commands. They can be used with `cat create_database.sql | mysql (-u root -p)`. 57 | 58 | Suggest running these directly in `mysql`: 59 | ``` 60 | sudo mysql 61 | ``` 62 | 63 | Create the database `OpenHashAPI`, the table `Hashes`, and the table `Users`: 64 | ``` 65 | CREATE DATABASE OpenHashAPI; 66 | USE OpenHashAPI; 67 | 68 | CREATE TABLE Hashes ( 69 | algorithm VARCHAR(8) NOT NULL, 70 | hash VARCHAR(255) NOT NULL, 71 | plaintext VARCHAR(255) NOT NULL, 72 | validated BOOLEAN DEFAULT FALSE, 73 | PRIMARY KEY (`algorithm`, `hash`) 74 | ); 75 | 76 | CREATE TABLE Users ( 77 | id int NOT NULL AUTO_INCREMENT, 78 | username VARCHAR(32) NOT NULL, 79 | password VARCHAR(255) NOT NULL, 80 | can_login BOOLEAN NOT NULL, 81 | can_search BOOLEAN NOT NULL, 82 | can_upload BOOLEAN NOT NULL, 83 | can_manage BOOLEAN NOT NULL, 84 | can_view_private BOOLEAN NOT NULL, 85 | can_edit_private BOOLEAN NOT NULL, 86 | PRIMARY KEY (`id`, `username`) 87 | ); 88 | 89 | ALTER TABLE Users ADD UNIQUE (username); 90 | exit 91 | ``` 92 | 93 | The commands can be executed as a MySQL script or directly through the command line. In the following screen capture, we enter the commands directly into the `mysql` console. 94 | 95 | ![Screen capture of a mysql terminal running the commands to create the database.](/docs/images/install-4.png) 96 | --- 97 | 98 | ### Create the Database User 99 | Next, we will need a lower privilege database user named `ohauser` for the application. Ensure you have exited `mysql`. 100 | 101 | > [!IMPORTANT] 102 | > The password for the database user is validated to be at least 12 characters and meet complexity requirements which require at least one lower, upper, digit, and special character. 103 | 104 | ``` 105 | sudo mysql --execute "CREATE USER 'ohauser'@'localhost' IDENTIFIED BY 'password';" 106 | ``` 107 | > [!TIP] 108 | > Please set a secure password between 12 and 18 characters. This account will be associated with the database. 109 | 110 | Lastly, we will give them permissions over the database and apply those privileges: 111 | ``` 112 | sudo mysql --execute "GRANT CREATE, ALTER, DROP, INSERT, UPDATE, INDEX, DELETE, SELECT, REFERENCES on OpenHashAPI.* TO 'ohauser'@'localhost';" 113 | ``` 114 | ``` 115 | sudo mysql --execute "FLUSH PRIVILEGES;" 116 | ``` 117 | 118 | The following commands will create a user and configure appropriate permissions to interact with the database then apply them. Please set a secure password when configuring this account as it will be associated with the backend database. The image also shows the next step of installing Docker. 119 | 120 | ![Screen capture of a terminal using the mysql command to configure a user and install docker.](/docs/images/install-5.png) 121 | --- 122 | 123 | ### Install the Container Software 124 | 125 | The application is run in a containerized environment. To do this, we will need `Docker`: 126 | ``` 127 | sudo apt update && sudo apt install -y docker.io 128 | ``` 129 | 130 | > [!NOTE] 131 | > [Offical install documentation](https://docs.docker.com/engine/install/) (external link) 132 | 133 | --- 134 | 135 | ### Create the Configuration File 136 | 137 | The server uses a JSON configuration file to set several variables used by the server: 138 | * `DatabaseUser`: The username of the database user. 139 | * `DatabasePwd`: The password of the database user. 140 | * `AuthenticationPepper`: The pepper value used in authentication. 141 | * `DatabaseIdleConnections`: The number of idle database connections allowed. 142 | * `ServerPort`: The port the server will host on. 143 | * `ServerTLSCertfilePath`: Local path to the cert file for TLS. 144 | * `ServerTLSKeyfilePath`: Local path to the key file for TLS. 145 | * `ServerJWTPublicPEMfilePath`: Local path to the public PEM file for auth. 146 | * `ServerJWTPrivatePEMfilePath`: Local path to the private PEM file for auth. 147 | * `ServerJWTTimeToLive`: The JWT auth token TTL value. 148 | * `ServerGBMaxUploadSize`: Max POST request size in GB. 149 | * `OpenRegistration`: If users are allowed to self-register accounts. 150 | * `RehashUploads`: If uploads should be rehashed into another algorithm. 151 | * `RehashAlgorithm`: The algorithms to use are 0, 100, and 1000. 152 | * `QualityFilter`: If uploads should be filtered before adding to the database. 153 | * `QualityFilterRegex`: Regex to match bad items to. 154 | * `SelfHealDB`: If the database should validate hashes in the background. 155 | * `SelfHealDBChunks`: Number of chunks the database is broken into for the worker pool. 156 | * `SelfHealDBWorkers`: Number of workers to spawn for the validation process. 157 | * `GenerateWordlist`: If the server should start a process to make a wordlist. 158 | * `GenerateRules`: If the server should start a process to make a rule list. 159 | * `GenerateMasks`: If the server should start a process to make a mask list. 160 | * `AllowUserLists`: If the server should allow the creation and downloading of user lists. 161 | 162 | > [!IMPORTANT] 163 | > **Ensure that the `open-registration` parameter is set; otherwise, registration will be closed!** 164 | > **Ensure that the `database-pwd` parameter is set; otherwise, you will not be able to login!** 165 | 166 | The configuration file can be found in `config/config.json` and looks like the following: 167 | ``` 168 | { 169 | "database-user":"ohauser", 170 | "database-pwd":"password", 171 | "auth-pepper":"0H4St4ticP3pp3r", 172 | "database-idle-connections":100, 173 | "server-port":8080, 174 | "server-tls-certfile-path":"server.crt", 175 | "server-tls-keyfile-path":"server.key", 176 | "server-jwt-public-pemfile-path":"public_key.pem", 177 | "server-jwt-private-pemfile-path":"private_key.pem", 178 | "server-jwt-ttl":15, 179 | "server-gb-max-upload-size":2, 180 | "open-registration":true, 181 | "rehash-uploads":true, 182 | "rehash-algorithm":0, 183 | "quality-filter":false, 184 | "quality-filter-regex":"(xiaonei|zomato|fbobh|fccdbbcdaa)|http:\\/\\/|https:\\/\\/|\\@.*\\.net||
|| [!TIP] 195 | > Consider changing the authentication pepper to a unique value per install. This value will be used in authentication hash security. Pepper must be at least 8 characters long and contain a mix of uppercase, lowercase letters, and at least one digit and one special character. Changing this to a custom value will increase the offline security of any compromised user's password hash due to the tool being open source. 196 | 197 | If we `git clone` the repository we can use the configuration file found in `/config/config.json` as a base. 198 | ![Screen capture of a terminal using vim to edit the configuration file.](/docs/images/install-6.png) 199 | 200 | Configure this file with the updated settings, including the database username and password and then ensure that the `Dockerfile` is pointed at the correct configuration file: 201 | ``` 202 | # Location of your config file 203 | ENV CONF_FILE=./config/config.json 204 | COPY ${CONF_FILE} /etc/config.json 205 | ``` 206 | 207 | > [!IMPORTANT] 208 | > **Ensure you have updated the password for the database user and open-registration is enabled before building!** 209 | 210 | After editing the configuration file, ensure that the paths for the configuration file, as well as any other items like custom certificates, are correctly stated before building the image. 211 | 212 | ![Screen capture of a terminal using vim to edit the Dockerfile to ensure the correct paths are set.](/docs/images/install-7.png) 213 | --- 214 | 215 | ### Build the Docker Image 216 | 217 | Next, we can build the image containing the server application and configuration. 218 | - Ensure you are in the same directory as the `Dockerfile` or point it to the correct path. 219 | ``` 220 | sudo docker build -t ohaserver . 221 | ``` 222 | 223 | --- 224 | 225 | ### Deploy the Server Image 226 | 227 | With everything configured correctly, we should be able to start the container on the host running the database. 228 | ``` 229 | sudo docker run --rm -it --net=host ohaserver 230 | ``` 231 | 232 | ![Screen capture of a terminal using docker to build and run the image.](/docs/images/install-8.png) 233 | --- 234 | 235 | ### Register a New User 236 | There are two options for registering a new user: 237 | - The easiest way to register is by going to `https://URL/login` and use the form 238 | - The other way is to send a formatted request to `/api/register` with the client 239 | 240 | > [!IMPORTANT] 241 | > Ensure that the `open-registration` parameter is set otherwise registration will be closed. 242 | 243 | In the capture below, we can see using a browser to register a new user with a complex password (at least 12 characters long and contain a mix of uppercase, lowercase letters, and at least one digit and one special character). 244 | ![Screen capture of a terminal and a browser showing the new user registration process](/docs/images/install-9.png) 245 | 246 | After this step you should be able to login and test most of the API endpoints. 247 | ![Screen capture of a terminal and a browser showing a successful login](/docs/images/install-10.png) 248 | 249 | > [!NOTE] 250 | > This will be the user you authenticate to the platform and API with! If using the `OpenHashAPI` client, ensure that the username and password field is updated. 251 | 252 | Once this step is completed, the `OpenHashAPI` server should be ready to use, consider testing the upload portion by submitting the example hash to the database. 253 | ``` 254 | curl -X POST \ 255 | https://192.168.40.162:8080/api/found \ 256 | -H 'Authorization: Bearer THE_JWT_VALUE' \ 257 | -H 'Content-Type: application/json' \ 258 | --data '{ 259 | "algorithm": "0", 260 | "hash-plain": [ 261 | "5f4dcc3b5aa765d61d8327deb882cf99:password" 262 | ] 263 | }' 264 | ``` 265 | 266 | > [!NOTE] 267 | > The API will be looking for an array of strings containing atleast one ":". Hashes should be in `HASH:PLAIN` or `HASH:SALT:PLAIN` and the `algorithm` should be an integer value reflecting the hash mode used. 268 | 269 | --- 270 | 271 | ### Assign Initial Permissions 272 | New users, by default, do not have the `canManage` permission and can not use `/api/manage`. A newly created Administrator user must be assigned this permission before using the API endpoint. 273 | 274 | ``` 275 | sudo mysql 276 | use OpenHashAPI; 277 | UPDATE Users SET can_manage = 1 WHERE id = 0; 278 | ``` 279 | 280 | > [!TIP] 281 | > Update the value of `id` with your created users. You can find the ID value with `SELECT * FROM Users;` 282 | 283 | --- 284 | 285 | ### Create Routine Backups 286 | Once everything is set up, strongly consider creating routine backups of the 287 | primary database. 288 | 289 | Backups can be created with the following script: 290 | ``` 291 | #!/bin/bash 292 | 293 | date=$(date +"%m-%d-%Y") 294 | mysqldump --databases --single-transaction --quick OpenHashAPI > $date-oha.sql 295 | ``` 296 | 297 | ### Common Issues 298 | 299 | #### Issues Running `mysql_secure_installation` 300 | 301 | On Ubuntu systems, you may need to reconfigure the default authentication mechanism first: 302 | ``` 303 | # STRONGLY suggest changing the password value 304 | # This command will allow for "mysql_secure_installation" to work by setting the root account with a native password 305 | sudo mysql --execute "ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'password';" && sudo mysql_secure_installation 306 | 307 | # Revert auth back so sudo mysql works again and remove the native password 308 | sudo mysql -u root -p --execute "ALTER USER 'root'@'localhost' IDENTIFIED WITH auth_socket;" 309 | ``` 310 | 311 | The commands above will allow the `root` account to authenticate with `sudo`. If you do not set this up you may have to use `-u root -p` syntax instead: 312 | ``` 313 | sudo mysql -u root -p 314 | ``` 315 | 316 | This syntax will be needed for the entire installation process pirot to the `--execute` commands. 317 | 318 | ### Issues Installing Docker 319 | 320 | Docker can have different installation requirements based on the underlying 321 | host operating system. These instructions will not be consistent for every 322 | installation so please refer to the offical Docker installation documentation 323 | for any issues. 324 | 325 | - [Offical install documentation](https://docs.docker.com/engine/install/) (external link) 326 | 327 | -------------------------------------------------------------------------------- /docs/SECURITY.md: -------------------------------------------------------------------------------- 1 | ## Known Security Issues and Discussion 2 | 3 | ### Secret Material Compromise By Lower Privilege Container User 4 | - In the event a user is able to access the underlying container being used by 5 | OpenHashAPI, the secret material stored will be readable by the `nonroot` 6 | user. 7 | - This means that the environmental variables, PEM files, and certificates used 8 | for TLS and JWT *will* be compromised in the event someone were to compromise 9 | the `nonroot` user on the container. 10 | - **Advisory:** In the event of compromise, restart the container and remove 11 | any persistent images and rotate secrets stored in the `config.json` file. 12 | In the default version of OpenHashAPI, the PEM keys and TLS certificates are 13 | generated new every run unless the container was not started with `--rm`. If 14 | the `Dockerfile` was modified to use other secret material, ensure that 15 | material is rotated for all affected devices. Restore the back-end database 16 | to prior versions to ensure no persistent accounts were created. Assume 17 | hashes have been compromised and reset the authentication pepper. 18 | 19 | ### User Lists Permissions and Default File View/Edit Visibility 20 | - The ability to allow or deny user lists to be uploaded, edited, or viewed is 21 | done with the `allow-user-lists` setting in `config.json` set on the 22 | server. 23 | - The ability to restrict users to view lists is done with the 24 | `canViewUserLists` user permission which is tied to the `can_view_private` 25 | permission in the `Users` database table. 26 | - The ability to restrict users to edit lists is done with the 27 | `canEditUserLists` user permission which is tied to the `can_edit_private` 28 | permission in the `Users` database table. 29 | - By default, all users with these permissions will be able to see and edit the 30 | same files. This means that by default, a user with these permission will be 31 | able to see and edit **all** files respectively. There is no notion of 32 | per-list restricted access within the application at this time. 33 | -------------------------------------------------------------------------------- /docs/USECASE.md: -------------------------------------------------------------------------------- 1 | - [Searching for Plaintext & Hashes](#searching-for-plaintext-&-hashes) 2 | - [Super Potfile for Hashcracking](#super-potfile-for-hashcracking) 3 | - [Data Storage for Hash & Password Security Research](#data-storage-for-hash-&-password-security) 4 | - [Rules, Wordlist, & Database](#rules-and-wordlist-database) 5 | - [Collaboration Framework for Hashcracking](#collboration-framework-for-hashcracking) 6 | - [CTF & Ephemeral Usage](#ctf-and-ephemeral-usage) 7 | 8 | --- 9 | 10 | ## Searching for Plaintext & Hashes 11 | - The system can be used to store and manage various hashes and plaintext from 12 | different sources. Teams can use these to identify likely poor human 13 | passwords for offensive and defensive purposes. 14 | 15 | ## Super Potfile for Hash Cracking 16 | - Ability to store hash and plaintext material in a data centric manner with 17 | the ability to enforce a proper authorization model surrounding access. This 18 | can be used to empower teams to make data centric decisions. With the ability 19 | to rehash items, a single algorithm can be maintained for optimized storage 20 | or multiple can be stored for every use case. 21 | 22 | ## Rules, Wordlist, & Metadata Database 23 | - With the ability to reclaim metadata from entries, the server can directly 24 | add value back to security teams by generating likely wordlist, rules, and 25 | masks based on the input data. With quality filtering and validation, items 26 | are ensured to be high quality. 27 | 28 | ## Collaboration Framework for Hash Cracking 29 | - With the ability to upload files, teams can work together when they find 30 | hashes on tests without uploading them to the central database. Files can be 31 | uploaded hashes which can be updated easily when valid plaintext's are found. 32 | Teams can also use this to pass around wordlists and rules and other 33 | temporary files. 34 | 35 | ## CTF & Ephemeral Usage 36 | - With easy set up and deployment the server can be used for individual CTFs as 37 | well as for temporary usage. Users can select what gets persisted and the 38 | rest is wiped away when the infrastructure is removed. 39 | -------------------------------------------------------------------------------- /docs/images/install-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Scorpion-Security-Labs/OpenHashAPI/d06faac0dc75ddef2b9b6c1363ead227e99eae04/docs/images/install-1.png -------------------------------------------------------------------------------- /docs/images/install-10.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Scorpion-Security-Labs/OpenHashAPI/d06faac0dc75ddef2b9b6c1363ead227e99eae04/docs/images/install-10.png -------------------------------------------------------------------------------- /docs/images/install-3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Scorpion-Security-Labs/OpenHashAPI/d06faac0dc75ddef2b9b6c1363ead227e99eae04/docs/images/install-3.png -------------------------------------------------------------------------------- /docs/images/install-4.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Scorpion-Security-Labs/OpenHashAPI/d06faac0dc75ddef2b9b6c1363ead227e99eae04/docs/images/install-4.png -------------------------------------------------------------------------------- /docs/images/install-5.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Scorpion-Security-Labs/OpenHashAPI/d06faac0dc75ddef2b9b6c1363ead227e99eae04/docs/images/install-5.png -------------------------------------------------------------------------------- /docs/images/install-6.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Scorpion-Security-Labs/OpenHashAPI/d06faac0dc75ddef2b9b6c1363ead227e99eae04/docs/images/install-6.png -------------------------------------------------------------------------------- /docs/images/install-7.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Scorpion-Security-Labs/OpenHashAPI/d06faac0dc75ddef2b9b6c1363ead227e99eae04/docs/images/install-7.png -------------------------------------------------------------------------------- /docs/images/install-8.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Scorpion-Security-Labs/OpenHashAPI/d06faac0dc75ddef2b9b6c1363ead227e99eae04/docs/images/install-8.png -------------------------------------------------------------------------------- /docs/images/install-9.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Scorpion-Security-Labs/OpenHashAPI/d06faac0dc75ddef2b9b6c1363ead227e99eae04/docs/images/install-9.png -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module ohaserver 2 | 3 | go 1.23 4 | 5 | require ( 6 | github.com/gin-gonic/gin v1.9.1 7 | github.com/go-sql-driver/mysql v1.7.1 8 | github.com/golang-jwt/jwt/v4 v4.5.0 9 | golang.org/x/crypto v0.9.0 10 | golang.org/x/text v0.9.0 11 | ) 12 | 13 | require ( 14 | github.com/bytedance/sonic v1.9.1 // indirect 15 | github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311 // indirect 16 | github.com/gabriel-vasile/mimetype v1.4.2 // indirect 17 | github.com/gin-contrib/sse v0.1.0 // indirect 18 | github.com/go-playground/locales v0.14.1 // indirect 19 | github.com/go-playground/universal-translator v0.18.1 // indirect 20 | github.com/go-playground/validator/v10 v10.14.0 // indirect 21 | github.com/goccy/go-json v0.10.2 // indirect 22 | github.com/json-iterator/go v1.1.12 // indirect 23 | github.com/klauspost/cpuid/v2 v2.2.4 // indirect 24 | github.com/leodido/go-urn v1.2.4 // indirect 25 | github.com/mattn/go-isatty v0.0.19 // indirect 26 | github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect 27 | github.com/modern-go/reflect2 v1.0.2 // indirect 28 | github.com/pelletier/go-toml/v2 v2.0.8 // indirect 29 | github.com/twitchyliquid64/golang-asm v0.15.1 // indirect 30 | github.com/ugorji/go/codec v1.2.11 // indirect 31 | golang.org/x/arch v0.3.0 // indirect 32 | golang.org/x/net v0.10.0 // indirect 33 | golang.org/x/sys v0.8.0 // indirect 34 | google.golang.org/protobuf v1.30.0 // indirect 35 | gopkg.in/yaml.v3 v3.0.1 // indirect 36 | ) 37 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/bytedance/sonic v1.5.0/go.mod h1:ED5hyg4y6t3/9Ku1R6dU/4KyJ48DZ4jPhfY1O2AihPM= 2 | github.com/bytedance/sonic v1.9.1 h1:6iJ6NqdoxCDr6mbY8h18oSO+cShGSMRGCEo7F2h0x8s= 3 | github.com/bytedance/sonic v1.9.1/go.mod h1:i736AoUSYt75HyZLoJW9ERYxcy6eaN6h4BZXU064P/U= 4 | github.com/chenzhuoyu/base64x v0.0.0-20211019084208-fb5309c8db06/go.mod h1:DH46F32mSOjUmXrMHnKwZdA8wcEefY7UVqBKYGjpdQY= 5 | github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311 h1:qSGYFH7+jGhDF8vLC+iwCD4WpbV1EBDSzWkJODFLams= 6 | github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311/go.mod h1:b583jCggY9gE99b6G5LEC39OIiVsWj+R97kbl5odCEk= 7 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 8 | github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= 9 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 10 | github.com/gabriel-vasile/mimetype v1.4.2 h1:w5qFW6JKBz9Y393Y4q372O9A7cUSequkh1Q7OhCmWKU= 11 | github.com/gabriel-vasile/mimetype v1.4.2/go.mod h1:zApsH/mKG4w07erKIaJPFiX0Tsq9BFQgN3qGY5GnNgA= 12 | github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE= 13 | github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI= 14 | github.com/gin-gonic/gin v1.9.1 h1:4idEAncQnU5cB7BeOkPtxjfCSye0AAm1R0RVIqJ+Jmg= 15 | github.com/gin-gonic/gin v1.9.1/go.mod h1:hPrL7YrpYKXt5YId3A/Tnip5kqbEAP+KLuI3SUcPTeU= 16 | github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s= 17 | github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4= 18 | github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA= 19 | github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY= 20 | github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY= 21 | github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY= 22 | github.com/go-playground/validator/v10 v10.14.0 h1:vgvQWe3XCz3gIeFDm/HnTIbj6UGmg/+t63MyGU2n5js= 23 | github.com/go-playground/validator/v10 v10.14.0/go.mod h1:9iXMNT7sEkjXb0I+enO7QXmzG6QCsPWY4zveKFVRSyU= 24 | github.com/go-sql-driver/mysql v1.7.1 h1:lUIinVbN1DY0xBg0eMOzmmtGoHwWBbvnWubQUrtU8EI= 25 | github.com/go-sql-driver/mysql v1.7.1/go.mod h1:OXbVy3sEdcQ2Doequ6Z5BW6fXNQTmx+9S1MCJN5yJMI= 26 | github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU= 27 | github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I= 28 | github.com/golang-jwt/jwt/v4 v4.5.0 h1:7cYmW1XlMY7h7ii7UhUyChSgS5wUJEnm9uZVTGqOWzg= 29 | github.com/golang-jwt/jwt/v4 v4.5.0/go.mod h1:m21LjoU+eqJr34lmDMbreY2eSTRJ1cv77w39/MY0Ch0= 30 | github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= 31 | github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU= 32 | github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= 33 | github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= 34 | github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= 35 | github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= 36 | github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg= 37 | github.com/klauspost/cpuid/v2 v2.2.4 h1:acbojRNwl3o09bUq+yDCtZFc1aiwaAAxtcn8YkZXnvk= 38 | github.com/klauspost/cpuid/v2 v2.2.4/go.mod h1:RVVoqg1df56z8g3pUjL/3lE5UfnlrJX8tyFgg4nqhuY= 39 | github.com/leodido/go-urn v1.2.4 h1:XlAE/cm/ms7TE/VMVoduSpNBoyc2dOxHs5MZSwAN63Q= 40 | github.com/leodido/go-urn v1.2.4/go.mod h1:7ZrI8mTSeBSHl/UaRyKQW1qZeMgak41ANeCNaVckg+4= 41 | github.com/mattn/go-isatty v0.0.19 h1:JITubQf0MOLdlGRuRq+jtsDlekdYPia9ZFsB8h/APPA= 42 | github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= 43 | github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= 44 | github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= 45 | github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= 46 | github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M= 47 | github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= 48 | github.com/pelletier/go-toml/v2 v2.0.8 h1:0ctb6s9mE31h0/lhu+J6OPmVeDxJn+kYnJc2jZR9tGQ= 49 | github.com/pelletier/go-toml/v2 v2.0.8/go.mod h1:vuYfssBdrU2XDZ9bYydBu6t+6a6PYNcZljzZR9VXg+4= 50 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= 51 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 52 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= 53 | github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= 54 | github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= 55 | github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= 56 | github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= 57 | github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= 58 | github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= 59 | github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= 60 | github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= 61 | github.com/stretchr/testify v1.8.3 h1:RP3t2pwF7cMEbC1dqtB6poj3niw/9gnV4Cjg5oW5gtY= 62 | github.com/stretchr/testify v1.8.3/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= 63 | github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI= 64 | github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08= 65 | github.com/ugorji/go/codec v1.2.11 h1:BMaWp1Bb6fHwEtbplGBGJ498wD+LKlNSl25MjdZY4dU= 66 | github.com/ugorji/go/codec v1.2.11/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg= 67 | golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8= 68 | golang.org/x/arch v0.3.0 h1:02VY4/ZcO/gBOH6PUaoiptASxtXU10jazRCP865E97k= 69 | golang.org/x/arch v0.3.0/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8= 70 | golang.org/x/crypto v0.9.0 h1:LF6fAI+IutBocDJ2OT0Q1g8plpYljMZ4+lty+dsqw3g= 71 | golang.org/x/crypto v0.9.0/go.mod h1:yrmDGqONDYtNj3tH8X9dzUun2m2lzPa9ngI6/RUPGR0= 72 | golang.org/x/net v0.10.0 h1:X2//UzNDwYmtCLn7To6G58Wr6f5ahEAQgKNzv9Y951M= 73 | golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg= 74 | golang.org/x/sys v0.0.0-20220704084225-05e143d24a9e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 75 | golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 76 | golang.org/x/sys v0.8.0 h1:EBmGv8NaZBZTWvrbjNoL6HVt+IVy3QDQpJs7VRIw3tU= 77 | golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 78 | golang.org/x/text v0.9.0 h1:2sjJmO8cDvYveuX97RDLsxlyUxLl+GHoLxBiRdHllBE= 79 | golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= 80 | golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4= 81 | golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= 82 | google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= 83 | google.golang.org/protobuf v1.30.0 h1:kPPoIgf3TsEvrm0PFe15JQ+570QVxYzEvvHqChK+cng= 84 | google.golang.org/protobuf v1.30.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= 85 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= 86 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 87 | gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 88 | gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= 89 | gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 90 | rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4= 91 | -------------------------------------------------------------------------------- /internal/api/api_controller.go: -------------------------------------------------------------------------------- 1 | // Package api controls REST routes not related to authentication or 2 | // authorization 3 | package api 4 | 5 | import ( 6 | "bufio" 7 | "database/sql" 8 | "fmt" 9 | "io" 10 | "net/http" 11 | "ohaserver/internal/auth" 12 | "ohaserver/internal/config" 13 | "ohaserver/internal/models" 14 | "os" 15 | "path/filepath" 16 | "regexp" 17 | "strconv" 18 | "strings" 19 | "time" 20 | 21 | "github.com/gin-gonic/gin" 22 | ) 23 | 24 | // ************************************************************************************************ 25 | // * /api/* API * 26 | // ************************************************************************************************ 27 | 28 | // HealthHandler is the endpoint handler for /api/health 29 | // 30 | // The endpoint expects an authorized GET request and returns metadata about 31 | // the server configuration and status 32 | // 33 | // Args: 34 | // 35 | // c (gin.Context): The Gin context object 36 | // 37 | // Returns: 38 | // 39 | // None 40 | func HealthHandler(c *gin.Context) { 41 | serverConfig := config.ServerConfig 42 | db, err := auth.MySQLAuthenticate() 43 | if err != nil { 44 | customErr := models.ErrorStruct{Error: err.Error(), Message: "Database authentication failed", Context: "HealthHandler"} 45 | c.JSON(http.StatusInternalServerError, customErr) 46 | return 47 | } 48 | defer db.Close() 49 | stats := db.Stats() 50 | 51 | metrics := struct { 52 | MaxGBrequestSize int `json:"max-gb-request-size"` 53 | OpenRegistration bool `json:"open-registration"` 54 | RehashUploads bool `json:"rehash-uploads"` 55 | RehashAlgo int `json:"rehash-algo"` 56 | QualityFilter bool `json:"quality-filter"` 57 | QualityFilterRegex string `json:"quality-filter-regex"` 58 | SelfHealDB bool `json:"self-heal-database"` 59 | SelfHealDBChunks int `json:"self-heal-database-chunks"` 60 | SelfHealDBWorkers int `json:"self-heal-database-workers"` 61 | MaxOpenConnections int `json:"max-open-connections"` 62 | OpenConnections int `json:"open-connections"` 63 | InUseConnections int `json:"in-use-connections"` 64 | IdleConnections int `json:"idle-connections"` 65 | }{ 66 | MaxGBrequestSize: serverConfig.ServerGBMaxUploadSize, 67 | OpenRegistration: serverConfig.OpenRegistration, 68 | RehashUploads: serverConfig.RehashUploads, 69 | RehashAlgo: serverConfig.RehashAlgorithm, 70 | QualityFilter: serverConfig.QualityFilter, 71 | QualityFilterRegex: serverConfig.QualityFilterRegex, 72 | SelfHealDB: serverConfig.SelfHealDB, 73 | SelfHealDBChunks: serverConfig.SelfHealDBChunks, 74 | SelfHealDBWorkers: serverConfig.SelfHealDBWorkers, 75 | MaxOpenConnections: stats.MaxOpenConnections, 76 | OpenConnections: stats.OpenConnections, 77 | InUseConnections: stats.InUse, 78 | IdleConnections: stats.Idle, 79 | } 80 | 81 | c.JSON(http.StatusOK, metrics) 82 | } 83 | 84 | // SearchHandler is the endpoint handler for /api/search 85 | // 86 | // The endpoint expects an authorized POST request with a JSON body and returns 87 | // any found HASH and/or PLAINS from the database that match 88 | // 89 | // The endpoint also accepts query parameters for hash and plaintext to search 90 | // for specific values 91 | // 92 | // The expected JSON object has a single property, data: 93 | // 94 | // data (string): An array of strings with either HASH or PLAIN values 95 | // 96 | // Args: 97 | // 98 | // c (gin.Context): The Gin context object 99 | // 100 | // Returns: 101 | // 102 | // None 103 | func SearchHandler(c *gin.Context) { 104 | searchHashes := c.Query("hash") 105 | searchPlaintexts := c.Query("plaintext") 106 | var searchHashesBool bool 107 | var searchPlaintextsBool bool 108 | var hashes models.HashSearchStruct 109 | var hash models.HashStruct 110 | var outarray []models.HashStruct 111 | 112 | if models.ValidateBoolInput(searchHashes) == true { 113 | searchHashesBool = true 114 | } 115 | 116 | if models.ValidateBoolInput(searchPlaintexts) == true { 117 | searchPlaintextsBool = true 118 | } 119 | 120 | db, err := auth.MySQLAuthenticate() 121 | if err != nil { 122 | customErr := models.ErrorStruct{Error: err.Error(), Message: "Database authentication failed", Context: "SearchHandler"} 123 | c.JSON(http.StatusInternalServerError, customErr) 124 | return 125 | } 126 | defer db.Close() 127 | 128 | if err := c.BindJSON(&hashes); err != nil { 129 | customErr := models.ErrorStruct{Error: err.Error(), Message: "Error binding JSON", Context: "SearchHandler"} 130 | c.JSON(http.StatusBadRequest, customErr) 131 | return 132 | } 133 | 134 | // Build query based on search parameters 135 | var stmt *sql.Stmt 136 | if searchHashesBool && searchPlaintextsBool { 137 | stmt, err = db.Prepare("SELECT * FROM Hashes WHERE hash IN (?" + strings.Repeat(",?", len(hashes.Data)-1) + ") OR plaintext IN (?" + strings.Repeat(",?", len(hashes.Data)-1) + ")") 138 | } else if searchHashesBool { 139 | stmt, err = db.Prepare("SELECT * FROM Hashes WHERE hash IN (?" + strings.Repeat(",?", len(hashes.Data)-1) + ")") 140 | } else if searchPlaintextsBool { 141 | stmt, err = db.Prepare("SELECT * FROM Hashes WHERE plaintext IN (?" + strings.Repeat(",?", len(hashes.Data)-1) + ")") 142 | } else { 143 | stmt, err = db.Prepare("SELECT * FROM Hashes WHERE plaintext IN (?" + strings.Repeat(",?", len(hashes.Data)-1) + ")") 144 | } 145 | 146 | if err != nil { 147 | config.LogError("SearchHandler: error preparing statement", err) 148 | customErr := models.ErrorStruct{Error: err.Error(), Message: "Error preparing statement", Context: "SearchHandler"} 149 | c.JSON(http.StatusInternalServerError, customErr) 150 | return 151 | } 152 | defer stmt.Close() 153 | 154 | var size int 155 | if searchHashesBool && searchPlaintextsBool { 156 | size = len(hashes.Data) * 2 157 | } else { 158 | size = len(hashes.Data) 159 | } 160 | args := make([]interface{}, size) 161 | for i, v := range hashes.Data { 162 | if searchHashesBool && searchPlaintextsBool { 163 | args[i] = v 164 | args[i+len(hashes.Data)] = v 165 | } else { 166 | args[i] = v 167 | } 168 | } 169 | 170 | rows, err := stmt.Query(args...) 171 | if err != nil { 172 | config.LogError("SearchHandler: error querying database", err) 173 | customErr := models.ErrorStruct{Error: err.Error(), Message: "Error querying database", Context: "SearchHandler"} 174 | c.JSON(http.StatusInternalServerError, customErr) 175 | return 176 | } 177 | defer rows.Close() 178 | 179 | for rows.Next() { 180 | err = rows.Scan(&hash.Algorithm, &hash.Hash, &hash.Plaintext, &hash.Validated) 181 | if err != nil { 182 | config.LogError("SearchHandler: error scanning rows", err) 183 | customErr := models.ErrorStruct{Error: err.Error(), Message: "Error scanning rows", Context: "SearchHandler"} 184 | c.JSON(http.StatusInternalServerError, customErr) 185 | return 186 | } 187 | outarray = append(outarray, hash) 188 | } 189 | 190 | c.JSON(http.StatusOK, gin.H{"found": outarray}) 191 | } 192 | 193 | // SubmitHashHandler is the endpoint handler for /api/submit 194 | // 195 | // The endpoint expects an authorized POST request with a JSON body and returns 196 | // a JSON containing the hashing algorithm, total hashes submitted, number of 197 | // filtered hashes, and number of new plaintexts from the submission. 198 | // 199 | // The expected JSON object has two properties, algorithm and hash-plain: 200 | // 201 | // algorithm (string): property that specifies the hashing algorithm used 202 | // hash-plain (string): array of strings in HASH:PLAIN or HASH:SALT:PLAIN 203 | // format 204 | // 205 | // Args: 206 | // 207 | // c (gin.Context): The Gin context object 208 | // 209 | // Returns: 210 | // 211 | // None 212 | func SubmitHashHandler(c *gin.Context) { 213 | var originalHashesLen int 214 | var hashes models.HashUploadStruct 215 | var newhashes []interface{} 216 | serverConfig := config.ServerConfig 217 | db, err := auth.MySQLAuthenticate() 218 | if err != nil { 219 | customErr := models.ErrorStruct{Error: err.Error(), Message: "Database authentication failed", Context: "SubmitHashHandler"} 220 | c.JSON(http.StatusInternalServerError, customErr) 221 | return 222 | } 223 | defer db.Close() 224 | 225 | if err := c.BindJSON(&hashes); err != nil { 226 | config.LogError("SubmitHashHandler: error binding JSON", err) 227 | customErr := models.ErrorStruct{Error: err.Error(), Message: "Error binding JSON", Context: "SubmitHashHandler"} 228 | c.JSON(http.StatusBadRequest, customErr) 229 | return 230 | } 231 | 232 | if models.ValidateIntInput(hashes.Algorithm) == false { 233 | customErr := models.ErrorStruct{Error: "Invalid algorithm selected", Message: "Invalid algorithm selected", Context: "SubmitHashHandler"} 234 | c.JSON(http.StatusBadRequest, customErr) 235 | return 236 | } 237 | 238 | originalHashesLen = len(hashes.HashPlain) 239 | errorCount := 0 240 | 241 | // if rehashing 242 | if serverConfig.RehashUploads { 243 | if hashes.Algorithm != "0" && serverConfig.RehashAlgorithm == 0 { 244 | hashes.Algorithm = "0" 245 | newhashes, err = config.RehashUpload(hashes.HashPlain, "0") 246 | if err != nil { 247 | config.LogError("SubmitHashHandler: error rehashing hashes", err) 248 | customErr := models.ErrorStruct{Error: err.Error(), Message: "Error rehashing hashes", Context: "SubmitHashHandler"} 249 | c.JSON(http.StatusInternalServerError, customErr) 250 | return 251 | } 252 | } else if hashes.Algorithm != "100" && serverConfig.RehashAlgorithm == 100 { 253 | hashes.Algorithm = "100" 254 | newhashes, err = config.RehashUpload(hashes.HashPlain, "100") 255 | if err != nil { 256 | config.LogError("SubmitHashHandler: error rehashing hashes", err) 257 | customErr := models.ErrorStruct{Error: err.Error(), Message: "Error rehashing hashes", Context: "SubmitHashHandler"} 258 | c.JSON(http.StatusInternalServerError, customErr) 259 | return 260 | } 261 | } else if hashes.Algorithm != "1000" && serverConfig.RehashAlgorithm == 1000 { 262 | hashes.Algorithm = "1000" 263 | newhashes, err = config.RehashUpload(hashes.HashPlain, "1000") 264 | if err != nil { 265 | config.LogError("SubmitHashHandler: error rehashing hashes", err) 266 | customErr := models.ErrorStruct{Error: err.Error(), Message: "Error rehashing hashes", Context: "SubmitHashHandler"} 267 | c.JSON(http.StatusInternalServerError, customErr) 268 | return 269 | } 270 | } else { 271 | for _, h := range hashes.HashPlain { 272 | newhashes = append(newhashes, h) 273 | } 274 | } 275 | } else { 276 | for _, h := range hashes.HashPlain { 277 | newhashes = append(newhashes, h) 278 | } 279 | } 280 | 281 | // if filtering 282 | if serverConfig.QualityFilter { 283 | filteredNewhashes := []interface{}{} 284 | for _, row := range newhashes { 285 | _, plaintext, err := config.ParseHashAndPlaintext(row) 286 | if err != nil { 287 | config.LogError("SubmitHashHandler: error parsing hash and plaintext", err) 288 | errorCount++ 289 | continue 290 | } 291 | 292 | // dehex when needed 293 | if config.TestHexInput(plaintext) == true { 294 | plaintext, err = config.DehexPlaintext(plaintext) 295 | if err != nil { 296 | config.LogError("SubmitHashHandler: error dehexing plaintext", err) 297 | errorCount++ 298 | continue 299 | } 300 | } 301 | 302 | if config.TestPlainQuality(plaintext) { 303 | filteredNewhashes = append(filteredNewhashes, row) 304 | } 305 | } 306 | newhashes = filteredNewhashes 307 | } 308 | 309 | if len(newhashes) <= 0 { 310 | customErr := models.ErrorStruct{Error: "No valid hashes received", Message: "No valid hashes received. Please check the filter if enabled.", Context: "SubmitHashHandler"} 311 | c.JSON(http.StatusOK, customErr) 312 | return 313 | } 314 | 315 | var parsedhashes []interface{} 316 | for _, row := range newhashes { 317 | hash, plain, err := config.ParseHashAndPlaintext(row) 318 | if err != nil { 319 | config.LogError("SubmitHashHandler: error parsing hash and plaintext", err) 320 | errorCount++ 321 | continue 322 | } 323 | parsedhashes = append(parsedhashes, hashes.Algorithm, hash, plain) 324 | } 325 | 326 | batchSize := 10000 327 | 328 | totalRowsAffected := int64(0) 329 | for i := 0; i < len(parsedhashes); i += 3 * batchSize { 330 | end := i + 3*batchSize 331 | if end > len(parsedhashes) { 332 | end = len(parsedhashes) 333 | } 334 | batch := parsedhashes[i:end] 335 | 336 | str := "INSERT IGNORE INTO Hashes (algorithm, hash, plaintext) VALUES " 337 | for i := 0; i < len(batch); i += 3 { 338 | str += "(?, ?, ?)," 339 | } 340 | str = strings.TrimSuffix(str, ",") 341 | 342 | statement, err := db.Prepare(str) 343 | if err != nil { 344 | config.LogError("SubmitHashHandler: error preparing statement", err) 345 | customErr := models.ErrorStruct{Error: err.Error(), Message: "Error preparing statement", Context: "SubmitHashHandler"} 346 | c.JSON(http.StatusInternalServerError, customErr) 347 | return 348 | } 349 | defer statement.Close() 350 | 351 | result, err := statement.Exec(batch...) 352 | if err != nil { 353 | config.LogError("SubmitHashHandler: error executing statement", err) 354 | customErr := models.ErrorStruct{Error: err.Error(), Message: "Error executing statement", Context: "SubmitHashHandler"} 355 | c.JSON(http.StatusInternalServerError, customErr) 356 | return 357 | } 358 | 359 | rowsAffected, err := result.RowsAffected() 360 | if err != nil { 361 | config.LogError("SubmitHashHandler: error getting rows affected", err) 362 | customErr := models.ErrorStruct{Error: err.Error(), Message: "Error getting rows affected", Context: "SubmitHashHandler"} 363 | c.JSON(http.StatusInternalServerError, customErr) 364 | return 365 | } 366 | 367 | totalRowsAffected += rowsAffected 368 | } 369 | 370 | config.LogEvent(fmt.Sprintf("SubmitHashHandler: processed %d [%s] hashes", originalHashesLen, hashes.Algorithm), fmt.Sprintf("New hashes added: %d", totalRowsAffected)) 371 | c.JSON(http.StatusOK, gin.H{"Algorithm": hashes.Algorithm, "Total": originalHashesLen, "Filtered": originalHashesLen - len(newhashes), "New": totalRowsAffected, "Errors": errorCount}) 372 | } 373 | 374 | // DownloadFileHandler is the endpoint handler for /api/download/FILE/NUMBER 375 | // 376 | // The endpoint expects an authorized GET request with FILE being "wordlist", 377 | // "rules", or "masks" and the NUMBER being a valid integer value 378 | // 379 | // responses include the top NUMBER of items from the FILE 380 | // 381 | // requests can include a query string parameter of "offset" (int) that will offset 382 | // the starting point of the file read by that many lines 383 | // 384 | // Args: 385 | // 386 | // c (gin.Context): The Gin context object 387 | // 388 | // Returns: 389 | // 390 | // None 391 | func DownloadFileHandler(c *gin.Context) { 392 | n := c.Param("n") 393 | offset := c.Query("offset") 394 | contains := c.Query("contains") 395 | prepends := c.Query("prepend") 396 | appends := c.Query("append") 397 | toggles := c.Query("toggle") 398 | var offsetInt int 399 | var prependBool bool 400 | var appendBool bool 401 | var toggleBool bool 402 | 403 | if models.ValidateIntInput(offset) == false { 404 | offsetInt = 0 405 | } 406 | 407 | if models.ValidateBoolInput(prepends) == true { 408 | prependBool = true 409 | } 410 | 411 | if models.ValidateBoolInput(appends) == true { 412 | appendBool = true 413 | } 414 | 415 | if models.ValidateBoolInput(toggles) == true { 416 | toggleBool = true 417 | } 418 | 419 | if !regexp.MustCompile(`^[a-zA-Z0-9!@#$%^&*()_+=. -]*$`).MatchString(contains) { 420 | customErr := models.ErrorStruct{Error: "Invalid value provided for contains", Message: fmt.Sprintf("Invalid value provided for contains: %q", contains), Context: "DownloadFileHandler"} 421 | c.JSON(http.StatusBadRequest, customErr) 422 | return 423 | } 424 | 425 | offsetInt, err := strconv.Atoi(offset) 426 | if err != nil { 427 | offsetInt = 0 428 | } 429 | filename := c.Param("filename") 430 | 431 | if filename != "wordlist" && filename != "rules" && filename != "masks" { 432 | customErr := models.ErrorStruct{Error: "Invalid value provided for filename", Message: fmt.Sprintf("Invalid value provided for filename: %q", filename), Context: "DownloadFileHandler"} 433 | c.JSON(http.StatusBadRequest, customErr) 434 | return 435 | } else if filename == "wordlist" { 436 | filename = "/var/www/OpenHashAPI/wordlist.txt" 437 | } else if filename == "rules" { 438 | filename = "/var/www/OpenHashAPI/rules.txt" 439 | } else if filename == "masks" { 440 | filename = "/var/www/OpenHashAPI/masks.txt" 441 | } 442 | 443 | if models.ValidateIntInput(n) == false { 444 | customErr := models.ErrorStruct{Error: "Invalid value provided for n", Message: fmt.Sprintf("Invalid value provided for number of entries: %q", n), Context: "DownloadFileHandler"} 445 | c.JSON(http.StatusBadRequest, customErr) 446 | return 447 | } 448 | 449 | lines, err := strconv.Atoi(n) 450 | if err != nil { 451 | customErr := models.ErrorStruct{Error: err.Error(), Message: "Error converting number of entries to integer", Context: "DownloadFileHandler"} 452 | c.JSON(http.StatusBadRequest, customErr) 453 | return 454 | } 455 | 456 | file, err := os.Open(filepath.Clean(filename)) 457 | if err != nil { 458 | customErr := models.ErrorStruct{Error: err.Error(), Message: "Error opening file", Context: "DownloadFileHandler"} 459 | c.JSON(http.StatusInternalServerError, customErr) 460 | return 461 | } 462 | defer file.Close() 463 | 464 | scanner := bufio.NewScanner(file) 465 | var sb strings.Builder 466 | lineCount := 0 467 | for scanner.Scan() { 468 | if lineCount >= offsetInt { 469 | 470 | if contains != "" && !strings.Contains(scanner.Text(), contains) { 471 | continue 472 | } 473 | 474 | if prepends != "" { 475 | 476 | prependRegex := `\^[a-zA-Z0-9!@#$%^&*()_+=.-] |\^[a-zA-Z0-9!@#$%^&*()_+=.-]$` 477 | if prependBool { 478 | if !regexp.MustCompile(prependRegex).MatchString(scanner.Text()) { 479 | continue 480 | } 481 | } else { 482 | if regexp.MustCompile(prependRegex).MatchString(scanner.Text()) { 483 | continue 484 | } 485 | } 486 | } 487 | 488 | if appends != "" { 489 | 490 | appendRegex := `\$[a-zA-Z0-9!@#$%^&*()_+=.-] |\$[a-zA-Z0-9!@#$%^&*()_+=.-]$` 491 | if appendBool { 492 | if !regexp.MustCompile(appendRegex).MatchString(scanner.Text()) { 493 | continue 494 | } 495 | } else { 496 | if regexp.MustCompile(appendRegex).MatchString(scanner.Text()) { 497 | continue 498 | } 499 | } 500 | } 501 | 502 | if toggles != "" { 503 | 504 | toggleRegex := `T[0-9A-Z] |T[0-9A-Z]$` 505 | if toggleBool { 506 | if !regexp.MustCompile(toggleRegex).MatchString(scanner.Text()) { 507 | continue 508 | } 509 | } else { 510 | if regexp.MustCompile(toggleRegex).MatchString(scanner.Text()) { 511 | continue 512 | } 513 | } 514 | } 515 | 516 | sb.WriteString(scanner.Text() + "\n") 517 | lines-- 518 | if lines == 0 { 519 | break 520 | } 521 | 522 | lineCount++ 523 | 524 | } else if contains == "" || prepends != "" || appends != "" || toggles != "" || strings.Contains(scanner.Text(), contains) { 525 | lineCount++ 526 | } 527 | } 528 | 529 | if err := scanner.Err(); err != nil { 530 | config.LogError("DownloadFileHandler: error reading file", err) 531 | customErr := models.ErrorStruct{Error: err.Error(), Message: "Error reading file", Context: "DownloadFileHandler"} 532 | c.JSON(http.StatusInternalServerError, customErr) 533 | return 534 | } 535 | 536 | c.Writer.Header().Add("Content-Disposition", "attachment; filename="+filename) 537 | c.Writer.Header().Add("Content-Type", "application/octet-stream") 538 | c.String(http.StatusOK, sb.String()) 539 | } 540 | 541 | // StatusHandler is the endpoint handler for /api/status 542 | // 543 | // The endpoint expects an unauthorized GET request and returns the status of 544 | // the downloadable files on the server 545 | // 546 | // Args: 547 | // 548 | // c (gin.Context): The Gin context object 549 | // 550 | // Returns: 551 | // 552 | // None 553 | func StatusHandler(c *gin.Context) { 554 | type Response struct { 555 | Masks bool `json:"masks"` 556 | Wordlist bool `json:"wordlist"` 557 | Rules bool `json:"rules"` 558 | } 559 | var res Response 560 | 561 | if _, err := os.Stat("/var/www/OpenHashAPI/masks.txt"); err == nil { 562 | res.Masks = true 563 | } 564 | if _, err := os.Stat("/var/www/OpenHashAPI/wordlist.txt"); err == nil { 565 | res.Wordlist = true 566 | } 567 | if _, err := os.Stat("/var/www/OpenHashAPI/rules.txt"); err == nil { 568 | res.Rules = true 569 | } 570 | 571 | c.JSON(http.StatusOK, res) 572 | } 573 | 574 | // ViewListHandler is the endpoint handler for GET /api/list and /api/list/ID 575 | // 576 | // The endpoint expects an authorized GET request and returns a list of all 577 | // lists available to the user. If an ID is provided, the endpoint returns the 578 | // list with that ID 579 | // 580 | // Args: 581 | // 582 | // c (gin.Context): The Gin context object 583 | // 584 | // Returns: 585 | // 586 | // None 587 | func ViewListHandler(c *gin.Context) { 588 | listName := c.Param("listname") 589 | if !regexp.MustCompile(`^[a-zA-Z0-9!@#$%^&*()_+=.-]*$`).MatchString(listName) { 590 | customErr := models.ErrorStruct{Error: "Invalid value provided for listName", Message: fmt.Sprintf("Invalid value provided for listName: %q", listName), Context: "ViewListHandler"} 591 | c.JSON(http.StatusBadRequest, customErr) 592 | return 593 | } 594 | 595 | if listName == "" { 596 | // list all files in /var/www/OpenHashAPI/lists 597 | dir := "/var/www/OpenHashAPI/lists" 598 | files := make([]map[string]interface{}, 0) 599 | err := filepath.Walk(dir, func(path string, info os.FileInfo, err error) error { 600 | if err != nil { 601 | return err 602 | } 603 | if !info.IsDir() { 604 | file := map[string]interface{}{ 605 | "name": strings.TrimSuffix(filepath.Base(path), filepath.Ext(filepath.Base(path))), 606 | "size": info.Size(), 607 | "creation_time": info.ModTime().Format(time.RFC3339), 608 | } 609 | files = append(files, file) 610 | } 611 | return nil 612 | }) 613 | if err != nil { 614 | customErr := models.ErrorStruct{Error: err.Error(), Message: "Error walking the path", Context: "ViewListHandler"} 615 | c.JSON(http.StatusInternalServerError, customErr) 616 | return 617 | } 618 | c.JSON(http.StatusOK, gin.H{ 619 | "files": files, 620 | }) 621 | } else { 622 | // return the file contents of /var/www/OpenHashAPI/lists/listName 623 | file, err := os.Open(filepath.Clean(fmt.Sprintf("%s/%s.%s", "/var/www/OpenHashAPI/lists", listName, "txt"))) 624 | if err != nil { 625 | customErr := models.ErrorStruct{Error: err.Error(), Message: "Error opening file", Context: "ViewListHandler"} 626 | c.JSON(http.StatusBadRequest, customErr) 627 | return 628 | } 629 | defer file.Close() 630 | 631 | scanner := bufio.NewScanner(file) 632 | var sb strings.Builder 633 | for scanner.Scan() { 634 | sb.WriteString(scanner.Text() + "\n") 635 | } 636 | 637 | if err := scanner.Err(); err != nil { 638 | customErr := models.ErrorStruct{Error: err.Error(), Message: "Error reading file", Context: "ViewListHandler"} 639 | c.JSON(http.StatusInternalServerError, customErr) 640 | return 641 | } 642 | 643 | c.Writer.Header().Add("Content-Disposition", "attachment; filename="+listName) 644 | c.Writer.Header().Add("Content-Type", "application/octet-stream") 645 | c.String(http.StatusOK, sb.String()) 646 | } 647 | } 648 | 649 | // EditListHandler is the endpoint handler for POST /api/list and /api/list/ID 650 | // 651 | // The endpoint expects an authorized POST request and creates a new list or 652 | // edits an existing list with the provided ID. If editing, the orginal list is 653 | // modified with new founds. 654 | // 655 | // Args: 656 | // 657 | // c (gin.Context): The Gin context object 658 | // 659 | // Returns: 660 | // 661 | // # None 662 | func EditListHandler(c *gin.Context) { 663 | listName := c.Param("listname") 664 | userInputListName := c.Query("name") 665 | 666 | if !regexp.MustCompile(`^[a-zA-Z0-9!@#$%^&*()_+=.-]*$`).MatchString(listName) { 667 | customErr := models.ErrorStruct{Error: "Invalid value provided for listName", Message: fmt.Sprintf("Invalid value provided for listName: %q", listName), Context: "EditListHandler"} 668 | c.JSON(http.StatusBadRequest, customErr) 669 | return 670 | } 671 | 672 | if listName == "" { 673 | body := c.Request.Body 674 | data, err := io.ReadAll(body) 675 | if err != nil { 676 | customErr := models.ErrorStruct{Error: err.Error(), Message: "Error reading request body", Context: "EditListHandler"} 677 | c.JSON(http.StatusBadRequest, customErr) 678 | return 679 | } 680 | 681 | // Use a unique ID for the filename 682 | uniqueID, err := config.GenerateInsecureUniqueID() 683 | if err != nil { 684 | customErr := models.ErrorStruct{Error: err.Error(), Message: "Error generating unique ID", Context: "EditListHandler"} 685 | c.JSON(http.StatusInternalServerError, customErr) 686 | return 687 | } 688 | 689 | // Check if the query parameter is set 690 | // If so, use that as the filename instead of the unique ID 691 | if userInputListName != "" { 692 | if models.ValidateUsernameInput(userInputListName) == false { 693 | customErr := models.ErrorStruct{Error: "Invalid value provided for name", Message: fmt.Sprintf("Invalid value provided for name: %q", userInputListName), Context: "EditListHandler"} 694 | c.JSON(http.StatusBadRequest, customErr) 695 | return 696 | } 697 | uniqueID = userInputListName 698 | } 699 | 700 | // Check if the file already exists 701 | if _, err := os.Stat(fmt.Sprintf("%s/%s.%s", "/var/www/OpenHashAPI/lists", uniqueID, "txt")); err == nil { 702 | customErr := models.ErrorStruct{Error: "File already exists", Message: fmt.Sprintf("File already exists: %q", uniqueID), Context: "EditListHandler"} 703 | c.JSON(http.StatusBadRequest, customErr) 704 | return 705 | } 706 | 707 | // Write the file 708 | filename := fmt.Sprintf("%s/%s.%s", "/var/www/OpenHashAPI/lists", uniqueID, "txt") 709 | err = os.WriteFile(filename, data, 0664) 710 | if err != nil { 711 | customErr := models.ErrorStruct{Error: err.Error(), Message: "Error writing file", Context: "EditListHandler"} 712 | c.JSON(http.StatusInternalServerError, customErr) 713 | return 714 | } 715 | 716 | c.JSON(http.StatusOK, gin.H{ 717 | "filename": strings.TrimSuffix(filepath.Base(filename), filepath.Ext(filepath.Base(filename))), 718 | }) 719 | } else { 720 | // edit the file contents of /var/www/OpenHashAPI/lists/listName 721 | // any matching hashes are added with the format HASH:PLAIN 722 | // non-matching hashes are ignored 723 | // WARNING: no validation is done on the algorithmic values of the HASH:PLAIN 724 | if listName == "" { 725 | customErr := models.ErrorStruct{Error: "Missing listname parameter", Message: "Missing listname parameter", Context: "EditListHandler"} 726 | c.JSON(http.StatusBadRequest, customErr) 727 | return 728 | } 729 | 730 | body := c.Request.Body 731 | data, err := io.ReadAll(body) 732 | if err != nil { 733 | customErr := models.ErrorStruct{Error: err.Error(), Message: "Error reading request body", Context: "EditListHandler"} 734 | c.JSON(http.StatusBadRequest, customErr) 735 | return 736 | } 737 | 738 | // Read the existing file 739 | existingData, err := os.ReadFile(fmt.Sprintf("%s/%s.%s", "/var/www/OpenHashAPI/lists", listName, "txt")) 740 | if err != nil { 741 | customErr := models.ErrorStruct{Error: err.Error(), Message: "Error reading existing file", Context: "EditListHandler"} 742 | c.JSON(http.StatusInternalServerError, customErr) 743 | return 744 | } 745 | 746 | // Compare the new data with the existing data 747 | newData := string(data) 748 | existingLines := strings.Split(string(existingData), "\n") 749 | newLines := strings.Split(newData, "\n") 750 | 751 | // Create a map to hold the final lines and lefts 752 | finalLines := make(map[string]string) 753 | leftLines := make(map[string]string) 754 | 755 | // Add existing lines to the map 756 | for _, line := range existingLines { 757 | if strings.Contains(line, ":") && line != "" { 758 | cipher, plain, err := config.ParseHashAndPlaintext(line) 759 | if err != nil { 760 | c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) 761 | return 762 | } 763 | finalLines[cipher] = fmt.Sprintf("%s:%s", cipher, plain) 764 | } else { 765 | leftLines[line] = line 766 | } 767 | } 768 | 769 | // Add new lines to the map 770 | for _, line := range newLines { 771 | if strings.Contains(line, ":") && line != "" { 772 | cipher, plain, err := config.ParseHashAndPlaintext(line) 773 | if err != nil { 774 | customErr := models.ErrorStruct{Error: err.Error(), Message: "Error parsing hash and plaintext", Context: "EditListHandler"} 775 | c.JSON(http.StatusInternalServerError, customErr) 776 | return 777 | } 778 | 779 | // Check if the cipher already exists in the map if not ignore 780 | if _, ok := leftLines[cipher]; ok { 781 | finalLines[cipher] = fmt.Sprintf("%s:%s", cipher, plain) 782 | delete(leftLines, cipher) 783 | } 784 | 785 | } 786 | } 787 | 788 | // Add the left lines to the final lines 789 | for _, line := range leftLines { 790 | finalLines[line] = line 791 | } 792 | 793 | // Convert the map back to a slice 794 | updatedLines := make([]string, 0, len(finalLines)) 795 | for _, line := range finalLines { 796 | updatedLines = append(updatedLines, line) 797 | } 798 | 799 | // Write the updated data back to the file 800 | err = os.WriteFile(fmt.Sprintf("%s/%s.%s", "/var/www/OpenHashAPI/lists", listName, "txt"), []byte(strings.Join(updatedLines, "\n")), 0664) 801 | if err != nil { 802 | customErr := models.ErrorStruct{Error: err.Error(), Message: "Error writing file", Context: "EditListHandler"} 803 | c.JSON(http.StatusInternalServerError, customErr) 804 | return 805 | } 806 | 807 | c.JSON(http.StatusOK, gin.H{"status": "file updated"}) 808 | 809 | } 810 | } 811 | 812 | // ************************************************************************************************ 813 | // * /api/manage/* API * 814 | // ************************************************************************************************ 815 | 816 | // ManageRefreshFilesHandler is the endpoint handler for api/manage/refresh/FILE 817 | // 818 | // The endpoint expects an authorized GET request and refreshes the target 819 | // FILE. The FILE can be "wordlist", "rules", or "masks". 820 | // 821 | // Args: 822 | // c (gin.Context): The Gin context object 823 | // 824 | // Returns: 825 | // None 826 | func ManageRefreshFilesHandler(c *gin.Context) { 827 | filename := c.Param("filename") 828 | if filename != "wordlist" && filename != "rules" && filename != "masks" { 829 | customErr := models.ErrorStruct{Error: "Invalid value provided for filename", Message: fmt.Sprintf("Invalid value provided for filename: %q", filename), Context: "ManageRefreshFilesHandler"} 830 | c.JSON(http.StatusBadRequest, customErr) 831 | return 832 | } 833 | 834 | if filename == "wordlist" { 835 | filename = "/var/www/OpenHashAPI/wordlist.txt" 836 | } else if filename == "rules" { 837 | filename = "/var/www/OpenHashAPI/rules.txt" 838 | } else if filename == "masks" { 839 | filename = "/var/www/OpenHashAPI/masks.txt" 840 | } 841 | 842 | db, err := auth.MySQLAuthenticate() 843 | if err != nil { 844 | customErr := models.ErrorStruct{Error: err.Error(), Message: "Database authentication failed", Context: "ManageRefreshFilesHandler"} 845 | c.JSON(http.StatusInternalServerError, customErr) 846 | return 847 | } 848 | // Not closing the database connection because it ends up being closed 849 | // before the task is finished 850 | //defer db.Close() 851 | 852 | tasks := make(chan func(), 1) 853 | go func() { 854 | for task := range tasks { 855 | task() 856 | } 857 | }() 858 | 859 | if filename == "/var/www/OpenHashAPI/wordlist.txt" { 860 | os.Remove(filename) 861 | tasks <- func() { config.GenerateWordlistFile(db) } 862 | } else if filename == "/var/www/OpenHashAPI/rules.txt" { 863 | os.Remove(filename) 864 | tasks <- func() { config.GenerateRulesFile(db) } 865 | } else if filename == "/var/www/OpenHashAPI/masks.txt" { 866 | os.Remove(filename) 867 | tasks <- func() { config.GenerateMasksFile(db) } 868 | } 869 | 870 | c.JSON(http.StatusOK, gin.H{"status": "file refresh started"}) 871 | close(tasks) 872 | } 873 | -------------------------------------------------------------------------------- /internal/auth/auth.go: -------------------------------------------------------------------------------- 1 | // Package auth controls REST routes related to authentication or authorization 2 | // 3 | // The package structure is broken into three components: 4 | // auth.go which contains the functions and structs for the routes 5 | // auth_controller.go which contains the route handlers 6 | // auth_test.go which contains unit tests 7 | package auth 8 | 9 | import ( 10 | "crypto/hmac" 11 | "crypto/sha256" 12 | "crypto/sha512" 13 | "database/sql" 14 | "encoding/base64" 15 | "encoding/json" 16 | "errors" 17 | "fmt" 18 | "ohaserver/internal/config" 19 | "ohaserver/internal/models" 20 | "os" 21 | "regexp" 22 | "strconv" 23 | "strings" 24 | "time" 25 | 26 | "github.com/gin-gonic/gin" 27 | "github.com/go-sql-driver/mysql" 28 | "github.com/golang-jwt/jwt/v4" 29 | "golang.org/x/crypto/bcrypt" 30 | ) 31 | 32 | // CredentialInput is a struct used to hold user provided credential input 33 | // 34 | // The struct has two fields, Username and Password: 35 | // 36 | // Username: The username of the user 37 | // Password: The password of the user 38 | type CredentialInput struct { 39 | Username string `json:"username" binding:"required"` 40 | Password string `json:"password" binding:"required"` 41 | } 42 | 43 | // User is a struct used to hold user data 44 | // 45 | // The struct contains the following fields: 46 | // 47 | // ID: The ID of the user 48 | // Username: The username of the user 49 | // Password: The password of the user 50 | // CanLogin: Whether the user can log in 51 | // CanSearch: Whether the user can search 52 | // CanUpload: Whether the user can upload 53 | // CanManage: Whether the user can manage other users 54 | // CanViewUserLists: Whether the user can view and download user lists 55 | // CanEditUserLists: Whether the user can edit and upload to user list 56 | type User struct { 57 | ID uint `json:"id"` 58 | Username string `json:"username"` 59 | Password string `json:"password"` 60 | CanLogin bool `json:"can_login"` 61 | CanSearch bool `json:"can_search"` 62 | CanUpload bool `json:"can_upload"` 63 | CanManage bool `json:"can_manage"` 64 | CanViewUserLists bool `json:"can_view_user_lists"` 65 | CanEditUserLists bool `json:"can_edit_user_lists"` 66 | } 67 | 68 | // MySQLAuthenticate authorizes a connection to the backend DB 69 | // 70 | // Args: 71 | // 72 | // None 73 | // 74 | // Returns: 75 | // 76 | // db (*sql.DB): The database connection 77 | // err (error): Error data 78 | func MySQLAuthenticate() (*sql.DB, error) { 79 | var db *sql.DB 80 | var err error 81 | serverConfig := config.ServerConfig 82 | 83 | mysqlConfig := mysql.Config{ 84 | User: serverConfig.DatabaseUser, 85 | Passwd: serverConfig.DatabasePwd, 86 | Net: "tcp", 87 | Addr: "127.0.0.1:3306", 88 | DBName: "OpenHashAPI", 89 | AllowNativePasswords: true, 90 | } 91 | 92 | db, err = sql.Open("mysql", mysqlConfig.FormatDSN()) 93 | if err != nil { 94 | return nil, err 95 | } 96 | 97 | db.SetMaxIdleConns(serverConfig.DatabaseIdleConnections) 98 | db.SetConnMaxLifetime(time.Hour) 99 | 100 | err = db.Ping() 101 | if err != nil { 102 | return nil, err 103 | } 104 | 105 | return db, nil 106 | 107 | } 108 | 109 | // GenerateToken will create a valid JWT using the provided claims 110 | // 111 | // Args: 112 | // 113 | // userID (uint): The ID of the user 114 | // canLogin (bool): Whether the user can log in 115 | // canSearch (bool): Whether the user can search 116 | // canUpload (bool): Whether the user can upload 117 | // canManage (bool): Whether the user can manage other users 118 | // canViewUserLists (bool): Whether the user can view and download user lists 119 | // canEditUserLists (bool): Whether the user can edit and upload to user list 120 | // 121 | // Returns: 122 | // 123 | // tokenString (string): The created JWT token 124 | // err (error): Error data 125 | func GenerateToken(userID uint, canLogin bool, canSearch bool, canUpload bool, canManage bool, canViewUserLists bool, canEditUserLists bool) (string, error) { 126 | 127 | if !canLogin { 128 | return "", errors.New("User is not allowed to login") 129 | } 130 | 131 | serverConfig := config.ServerConfig 132 | pemEncodedPrivateKey, err := LoadPemEncodedKeyFromFile(serverConfig.ServerJWTPrivatePEMfilePath) 133 | if err != nil { 134 | return "", err 135 | } 136 | 137 | secretKey, err := jwt.ParseRSAPrivateKeyFromPEM(pemEncodedPrivateKey) 138 | if err != nil { 139 | return "", err 140 | } 141 | 142 | tokenLifespan := serverConfig.ServerJWTTimeToLive 143 | 144 | claims := jwt.MapClaims{} 145 | claims["authorized"] = true 146 | claims["userID"] = userID 147 | claims["canLogin"] = canLogin 148 | claims["canSearch"] = canSearch 149 | claims["canUpload"] = canUpload 150 | claims["canManage"] = canManage 151 | claims["canViewUserLists"] = canViewUserLists 152 | claims["canEditUserLists"] = canEditUserLists 153 | claims["exp"] = time.Now().Add(time.Minute * time.Duration(tokenLifespan)).Unix() 154 | 155 | token := jwt.NewWithClaims(jwt.SigningMethodRS256, claims) 156 | tokenString, err := token.SignedString(secretKey) 157 | 158 | if err != nil { 159 | return "", err 160 | } 161 | 162 | err = ValidateTokenClaims(claims) 163 | if err != nil { 164 | return "", err 165 | } 166 | 167 | return tokenString, nil 168 | 169 | } 170 | 171 | // ValidateTokenClaims will validate the claims made by a JWT 172 | // 173 | // Args: 174 | // 175 | // claims (jwt.MapClaims): The claims to be validated 176 | // 177 | // Return: 178 | // 179 | // err (error): Error data 180 | func ValidateTokenClaims(claims jwt.MapClaims) error { 181 | if claims["authorized"] != true { 182 | return errors.New("Unauthorized") 183 | } 184 | 185 | expirationTimeStr, ok := claims["exp"].(string) 186 | if ok { 187 | expirationTimeInt, err := strconv.ParseInt(expirationTimeStr, 10, 64) 188 | if err != nil { 189 | return err 190 | } 191 | 192 | if time.Now().Unix() > expirationTimeInt { 193 | return errors.New("Token has expired") 194 | } 195 | 196 | } else { 197 | expirationTime, ok := claims["exp"].(int64) 198 | if ok { 199 | if time.Now().Unix() > expirationTime { 200 | return errors.New("Token has expired") 201 | } 202 | } 203 | } 204 | 205 | _, ok = claims["canLogin"].(bool) 206 | if !ok { 207 | return errors.New("Invalid canLogin value") 208 | } 209 | 210 | _, ok = claims["canSearch"].(bool) 211 | if !ok { 212 | return errors.New("Invalid canSearch value") 213 | } 214 | 215 | _, ok = claims["canUpload"].(bool) 216 | if !ok { 217 | return errors.New("Invalid canUpload value") 218 | } 219 | 220 | _, ok = claims["canManage"].(bool) 221 | if !ok { 222 | return errors.New("Invalid canManage value") 223 | } 224 | 225 | _, ok = claims["canViewUserLists"].(bool) 226 | if !ok { 227 | return errors.New("Invalid canViewUserLists value") 228 | } 229 | 230 | _, ok = claims["canEditUserLists"].(bool) 231 | if !ok { 232 | return errors.New("Invalid canEditUserLists value") 233 | } 234 | 235 | return nil 236 | } 237 | 238 | // ValidateToken will validate JWT claims through gin.Context 239 | // 240 | // Args: 241 | // 242 | // c (gin.Context): The Gin context object 243 | // 244 | // Returns: 245 | // 246 | // err (error): Error data 247 | func ValidateToken(c *gin.Context) error { 248 | serverConfig := config.ServerConfig 249 | pemEncodedPrivateKey, err := LoadPemEncodedKeyFromFile(serverConfig.ServerJWTPublicPEMfilePath) 250 | if err != nil { 251 | return err 252 | } 253 | 254 | secretKey, err := jwt.ParseRSAPublicKeyFromPEM(pemEncodedPrivateKey) 255 | if err != nil { 256 | return err 257 | } 258 | 259 | tokenString, err := ExtractToken(c) 260 | if err != nil { 261 | return err 262 | } 263 | 264 | token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) { 265 | if token.Method.Alg() != "RS256" { 266 | return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"]) 267 | } 268 | return secretKey, nil 269 | }) 270 | if err != nil { 271 | return err 272 | } 273 | 274 | claims := token.Claims.(jwt.MapClaims) 275 | err = ValidateTokenClaims(claims) 276 | if err != nil { 277 | return err 278 | } 279 | 280 | return nil 281 | } 282 | 283 | // ExtractToken will parse the JWT from the Authorization HTTP header 284 | // or the auth_cookie HTTP cookie 285 | // 286 | // Args: 287 | // 288 | // c (gin.Context): The Gin context object 289 | // 290 | // Returns: 291 | // 292 | // token (string): The parsed JWT token 293 | // error (err): Error data 294 | func ExtractToken(c *gin.Context) (string, error) { 295 | const bearerTokenPrefix = "Bearer " 296 | authorizationHeader := c.Request.Header.Get("Authorization") 297 | authCookie, _ := c.Request.Cookie("auth_token") 298 | 299 | if authorizationHeader == "" && authCookie == nil { 300 | return "", errors.New("Authorization header is missing") 301 | } else if authCookie != nil { 302 | if models.ValidateJWTCharacters(authCookie.Value) { 303 | authorizationHeader = fmt.Sprintf("Bearer %s", authCookie.Value) 304 | } else { 305 | return "", errors.New("Authorization header is missing") 306 | } 307 | } 308 | 309 | if !strings.HasPrefix(authorizationHeader, bearerTokenPrefix) { 310 | return "", errors.New("Authorization header must start with 'Bearer '") 311 | } 312 | 313 | token := strings.TrimPrefix(authorizationHeader, bearerTokenPrefix) 314 | 315 | return token, nil 316 | } 317 | 318 | // ExtractClaimsFromContext extracts the JWT claims from the gin.Context 319 | // 320 | // Args: 321 | // 322 | // c (gin.Context): The Gin context object 323 | // 324 | // Returns: 325 | // 326 | // claims (jwt.MapClaims): The JWT claims 327 | // err (error): Error data 328 | func ExtractClaimsFromContext(c *gin.Context) (jwt.MapClaims, error) { 329 | serverConfig := config.ServerConfig 330 | pemEncodedPrivateKey, err := LoadPemEncodedKeyFromFile(serverConfig.ServerJWTPublicPEMfilePath) 331 | if err != nil { 332 | return nil, err 333 | } 334 | 335 | secretKey, err := jwt.ParseRSAPublicKeyFromPEM(pemEncodedPrivateKey) 336 | if err != nil { 337 | return nil, err 338 | } 339 | 340 | tokenString, err := ExtractToken(c) 341 | if err != nil { 342 | return nil, err 343 | } 344 | 345 | token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) { 346 | if token.Method.Alg() != "RS256" { 347 | return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"]) 348 | } 349 | return secretKey, nil 350 | }) 351 | 352 | if err != nil { 353 | return nil, err 354 | } 355 | 356 | claims := token.Claims.(jwt.MapClaims) 357 | 358 | return claims, nil 359 | } 360 | 361 | // LoadPemEncodedKeyFromFile will load a public/private PEM-encoded key file 362 | // from the file system 363 | // 364 | // Args: 365 | // 366 | // filename (string): The full path to the file 367 | // 368 | // Return: 369 | // 370 | // pemEncodedPrivateKey([]byte): Byte slice of the PEM key file 371 | // err (error): Error data 372 | func LoadPemEncodedKeyFromFile(filename string) ([]byte, error) { 373 | pemEncodedPrivateKey, err := os.ReadFile(filename) 374 | if err != nil { 375 | return nil, err 376 | } 377 | 378 | return pemEncodedPrivateKey, nil 379 | } 380 | 381 | // AuthenticationCheck validates the provided credentials and returns a valid 382 | // authentication token if correct 383 | // 384 | // Args: 385 | // 386 | // username (string): The username of the user 387 | // password (string): The password of the user 388 | // 389 | // Returns: 390 | // 391 | // token (string): The generated authentication token 392 | // err (error): Error data 393 | func AuthenticationCheck(username string, password string) (string, error) { 394 | 395 | var err error 396 | serverConfig := config.ServerConfig 397 | 398 | u := User{} 399 | db, err := MySQLAuthenticate() 400 | if err != nil { 401 | return "", err 402 | } 403 | defer db.Close() 404 | 405 | rows, err := db.Query("SELECT * FROM Users WHERE username = ?", username) 406 | 407 | if err != nil { 408 | return "", err 409 | } 410 | 411 | defer rows.Close() 412 | 413 | for rows.Next() { 414 | err = rows.Scan(&u.ID, &u.Username, &u.Password, &u.CanLogin, &u.CanSearch, &u.CanUpload, &u.CanManage, &u.CanViewUserLists, &u.CanEditUserLists) 415 | } 416 | err = rows.Err() 417 | 418 | if err != nil { 419 | return "", err 420 | } 421 | 422 | salt := []byte(u.Username) 423 | pepper := []byte(serverConfig.AuthenticationPepper) 424 | givenPass := fmt.Sprintf("%s%s", password, salt) 425 | passwordBytes := []byte(givenPass) 426 | 427 | // Pre-hash 428 | preHash := hmac.New(sha512.New, salt) 429 | preHash.Write(passwordBytes) 430 | preHashString := base64.StdEncoding.EncodeToString(preHash.Sum(nil)) 431 | 432 | // Hash 433 | preHashPasswordWithPepper := append([]byte(preHashString), pepper...) 434 | hashedPassword := sha256.Sum256([]byte(preHashPasswordWithPepper)) 435 | 436 | // Compare to bcrypt 437 | auth := VerifyPassword(hashedPassword[:], []byte(u.Password)) 438 | if auth == false { 439 | return "", errors.New("Invalid Credentials") 440 | } 441 | 442 | token, err := GenerateToken(u.ID, u.CanLogin, u.CanSearch, u.CanUpload, u.CanManage, u.CanViewUserLists, u.CanEditUserLists) 443 | 444 | if err != nil { 445 | return "", err 446 | } 447 | 448 | return token, nil 449 | } 450 | 451 | // VerifyPassword compares the hash and password values for validation 452 | // 453 | // Args: 454 | // 455 | // password ([]byte): The provided user password 456 | // hashedPassword ([]byte): The hash value to compare against 457 | // 458 | // Returns: 459 | // 460 | // (bool): If err = nil 461 | func VerifyPassword(password []byte, hashedPassword []byte) bool { 462 | err := bcrypt.CompareHashAndPassword(hashedPassword, password) 463 | return err == nil 464 | } 465 | 466 | // RegisterNewUser registers a new user account for the API 467 | // 468 | // NOTE: By default new users are not allowed to manage others 469 | // 470 | // Args: 471 | // 472 | // username (string): The username to register 473 | // password (string): The password to register 474 | // 475 | // Returns: 476 | // 477 | // err (error): Error data 478 | func RegisterNewUser(username string, password string) error { 479 | 480 | serverConfig := config.ServerConfig 481 | 482 | db, err := MySQLAuthenticate() 483 | if err != nil { 484 | return fmt.Errorf("something went wrong") 485 | } 486 | defer db.Close() 487 | 488 | salt := []byte(username) 489 | pepper := []byte(serverConfig.AuthenticationPepper) 490 | cost := 13 491 | givenPass := fmt.Sprintf("%s%s", password, salt) 492 | passwordBytes := []byte(givenPass) 493 | 494 | // Pre-hash 495 | preHash := hmac.New(sha512.New, salt) 496 | preHash.Write(passwordBytes) 497 | preHashString := base64.StdEncoding.EncodeToString(preHash.Sum(nil)) 498 | 499 | // Hash 500 | preHashPasswordWithPepper := append([]byte(preHashString), pepper...) 501 | hashedPassword := sha256.Sum256([]byte(preHashPasswordWithPepper)) 502 | bcryptHash, err := bcrypt.GenerateFromPassword(hashedPassword[:], cost) 503 | if err != nil { 504 | return fmt.Errorf("hashing password failed") 505 | } 506 | 507 | password = string(bcryptHash) 508 | 509 | res, err := db.Query("INSERT INTO Users (username, password, can_login, can_search, can_upload, can_manage, can_view_private, can_edit_private) VALUES (?, ?, ?, ?, ?, ?, ?, ?)", username, password, true, true, true, false, false, false) 510 | defer res.Close() 511 | 512 | if err != nil { 513 | re := regexp.MustCompile("Duplicate entry") 514 | if re.MatchString(err.Error()) { 515 | return fmt.Errorf("username already exists") 516 | } 517 | return fmt.Errorf("something went wrong") 518 | } 519 | return nil 520 | } 521 | 522 | // UpdateUserPermissions updates the permission matrix for a user 523 | // 524 | // Args: 525 | // 526 | // userID (uint): The ID of the user 527 | // permissionsJSON ([]byte) Byte slice of the new JSON permissions 528 | // 529 | // Returns: 530 | // 531 | // err (error): Error data 532 | func UpdateUserPermissions(userID uint, permissionsJSON []byte) error { 533 | db, err := MySQLAuthenticate() 534 | if err != nil { 535 | return err 536 | } 537 | defer db.Close() 538 | 539 | var permissions map[string]interface{} 540 | err = json.Unmarshal(permissionsJSON, &permissions) 541 | if err != nil { 542 | return err 543 | } 544 | 545 | userIDStr := fmt.Sprintf("%v", userID) 546 | if models.ValidateIntInput(userIDStr) == false { 547 | return errors.New("Missing or invalid userID field") 548 | } 549 | 550 | canLogin, ok := permissions["canLogin"] 551 | if !ok || models.ValidateBoolInput(fmt.Sprintf("%v", canLogin)) == false { 552 | return errors.New("Missing or invalid canLogin field") 553 | } 554 | 555 | canSearch, ok := permissions["canSearch"] 556 | if !ok || models.ValidateBoolInput(fmt.Sprintf("%v", canSearch)) == false { 557 | return errors.New("Missing or invalid canSearch field") 558 | } 559 | 560 | canUpload, ok := permissions["canUpload"] 561 | if !ok || models.ValidateBoolInput(fmt.Sprintf("%v", canUpload)) == false { 562 | return errors.New("Missing or invalid canUpload field") 563 | } 564 | 565 | canManage, ok := permissions["canManage"] 566 | if !ok || models.ValidateBoolInput(fmt.Sprintf("%v", canManage)) == false { 567 | return errors.New("Missing or invalid canManage field") 568 | } 569 | 570 | canViewPrivateLists, ok := permissions["canViewUserLists"] 571 | if !ok || models.ValidateBoolInput(fmt.Sprintf("%v", canViewPrivateLists)) == false { 572 | return errors.New("Missing or invalid canViewUserLists field") 573 | } 574 | 575 | canEditPrivateLists, ok := permissions["canEditUserLists"] 576 | if !ok || models.ValidateBoolInput(fmt.Sprintf("%v", canEditPrivateLists)) == false { 577 | return errors.New("Missing or invalid canEditUserLists field") 578 | } 579 | 580 | _, err = db.Exec(`UPDATE Users SET can_login = ?, can_search = ?, can_upload = ?, can_manage = ?, can_view_private = ?, can_edit_private = ? WHERE id = ?`, 581 | canLogin, canSearch, canUpload, canManage, canViewPrivateLists, canEditPrivateLists, userID) 582 | if err != nil { 583 | return err 584 | } 585 | 586 | // Log the event 587 | config.LogError(fmt.Sprintf("UpdateUserPermissions: User %d permissions have been updated", userID), fmt.Errorf("can_login %s, can_search %s, can_upload %s, can_manage:%s, can_view_private:%s, can_edit_private:%s", canLogin, canSearch, canUpload, canManage, canViewPrivateLists, canEditPrivateLists)) 588 | return nil 589 | } 590 | -------------------------------------------------------------------------------- /internal/auth/auth_controller.go: -------------------------------------------------------------------------------- 1 | // Package auth controls REST routes related to authentication or authorization 2 | // 3 | // The package structure is broken into three components: 4 | // auth.go which contains the functions and structs for the routes 5 | // auth_controller.go which contains the route handlers 6 | // auth_test.go which contains unit tests 7 | package auth 8 | 9 | import ( 10 | "database/sql" 11 | "encoding/json" 12 | "errors" 13 | "fmt" 14 | "html" 15 | "net/http" 16 | "ohaserver/internal/config" 17 | "ohaserver/internal/models" 18 | "regexp" 19 | "strings" 20 | 21 | "github.com/gin-gonic/gin" 22 | "golang.org/x/crypto/bcrypt" 23 | ) 24 | 25 | // RegistrationHandler is the endpoint handler for /api/register 26 | // 27 | // The endpoint expects an unauthorized POST request and returns a JSON 28 | // showing success or error 29 | // 30 | // This endpoint is unauthorized but affected by middleware that restricts 31 | // access based on the server configuration. 32 | // 33 | // The expected JSON object has two properties, username and password: 34 | // 35 | // username (string): The username of the user 36 | // password (string): The password of the user 37 | // 38 | // Args: 39 | // 40 | // c (gin.Context): The Gin context object 41 | // 42 | // Returns: 43 | // 44 | // None 45 | func RegistrationHandler(c *gin.Context) { 46 | var input CredentialInput 47 | 48 | if err := c.ShouldBindJSON(&input); err != nil { 49 | config.LogError("RegistrationHandler: Invalid JSON provided", err) 50 | customErr := models.ErrorStruct{Error: err.Error(), Message: "Invalid JSON provided", Context: "RegistrationHandler"} 51 | c.JSON(http.StatusBadRequest, customErr) 52 | return 53 | } 54 | 55 | upper := regexp.MustCompile(`[A-Z]`) 56 | lower := regexp.MustCompile(`[a-z]`) 57 | number := regexp.MustCompile(`[0-9]`) 58 | special := regexp.MustCompile(`[^a-zA-Z0-9\s]`) 59 | if len(input.Password) < 12 || !(upper.MatchString(input.Password) && lower.MatchString(input.Password) && special.MatchString(input.Password) && number.MatchString(input.Password)) || !regexp.MustCompile(`^[a-zA-Z0-9!@#$%^&*()_+=. -]*$`).MatchString(input.Password) { 60 | customErr := models.ErrorStruct{Error: "password must be at least 12 characters long and contain only letters, numbers, and the following special characters: !@#$%^&*()_+", Message: "Invalid password provided", Context: "RegistrationHandler"} 61 | c.JSON(http.StatusBadRequest, customErr) 62 | return 63 | } 64 | 65 | input.Username = html.EscapeString(strings.TrimSpace(input.Username)) 66 | 67 | if models.ValidateUsernameInput(input.Username) == false { 68 | customErr := models.ErrorStruct{Error: "username contains invalid characters", Message: "Invalid username provided", Context: "RegistrationHandler"} 69 | c.JSON(http.StatusBadRequest, customErr) 70 | return 71 | } 72 | 73 | err := RegisterNewUser(input.Username, input.Password) 74 | if err != nil { 75 | customErr := models.ErrorStruct{Error: err.Error(), Message: "Failed to register new user", Context: "RegistrationHandler"} 76 | c.JSON(http.StatusBadRequest, customErr) 77 | return 78 | } 79 | 80 | c.JSON(http.StatusOK, "Success!") 81 | } 82 | 83 | // LoginHandler is the endpoint handler for /api/login 84 | // 85 | // The endpoint expects an unauthorized POST request and returns JSON with 86 | // a valid JWT if successful 87 | // 88 | // The expected JSON object has two properties, username and password: 89 | // 90 | // username (string): The username of the user 91 | // password (string): The password of the user 92 | // 93 | // Args: 94 | // 95 | // c (gin.Context): The Gin context object 96 | // 97 | // Returns: 98 | // 99 | // None 100 | func LoginHandler(c *gin.Context) { 101 | 102 | var input CredentialInput 103 | 104 | if err := c.ShouldBindJSON(&input); err != nil { 105 | config.LogError("LoginHandler: Invalid JSON provided", err) 106 | customErr := models.ErrorStruct{Error: err.Error(), Message: "Invalid JSON provided", Context: "LoginHandler"} 107 | c.JSON(http.StatusBadRequest, customErr) 108 | return 109 | } 110 | 111 | u := User{} 112 | 113 | u.Username = input.Username 114 | u.Password = input.Password 115 | 116 | token, err := AuthenticationCheck(u.Username, u.Password) 117 | 118 | if err != nil { 119 | if errors.Is(err, sql.ErrNoRows) { 120 | config.LogError("LoginHandler: Invalid username or password", err) 121 | customErr := models.ErrorStruct{Error: "invalid username or password", Message: "Invalid username or password", Context: "LoginHandler"} 122 | c.JSON(http.StatusBadRequest, customErr) 123 | return 124 | } else if err == bcrypt.ErrMismatchedHashAndPassword { 125 | config.LogError("LoginHandler: Invalid username or password", err) 126 | customErr := models.ErrorStruct{Error: "invalid username or password", Message: "Invalid username or password", Context: "LoginHandler"} 127 | c.JSON(http.StatusBadRequest, customErr) 128 | return 129 | } else if err.Error() == "User is not allowed to login" { 130 | config.LogError("LoginHandler: User is not allowed to login", err) 131 | customErr := models.ErrorStruct{Error: "user is not allowed to login", Message: "User is not allowed to login", Context: "LoginHandler"} 132 | c.JSON(http.StatusForbidden, customErr) 133 | return 134 | } 135 | config.LogError("LoginHandler: Something went wrong", err) 136 | customErr := models.ErrorStruct{Error: err.Error(), Message: "Something went wrong", Context: "LoginHandler"} 137 | c.JSON(http.StatusInternalServerError, customErr) 138 | return 139 | } 140 | 141 | jwtParts := strings.Split(token, ".")[:2] 142 | partsStr := strings.Join(jwtParts, ".") 143 | config.LogEvent(fmt.Sprintf("LoginHandler: User %s logged in", u.Username), partsStr) 144 | c.JSON(http.StatusOK, gin.H{"token": token}) 145 | 146 | } 147 | 148 | // ManageUserHandler is the endpoint handler for /api/manage 149 | // 150 | // The endpoint expects an authorized POST request and returns a JSON 151 | // confirming if the request was successful 152 | // 153 | // The expected JSON object has the following properties: 154 | // 155 | // userID (int): The target users ID value 156 | // canLogin (bool): Whether the user can log in 157 | // canSearch (bool): Whether the user can search 158 | // canUpload (bool): Whether the user can upload 159 | // canManage (bool): Whether the user can manage other users 160 | // canViewUserLists (bool): Whether the user can view user lists 161 | // canEditUserLists (bool): Whether the user can edit user lists 162 | // 163 | // Args: 164 | // 165 | // c (gin.Context): The Gin context object 166 | // 167 | // Returns: 168 | // 169 | // None 170 | func ManageUserHandler(c *gin.Context) { 171 | permissionsJSON, err := c.GetRawData() 172 | if err != nil { 173 | config.LogError("ManageUserHandler: Invalid JSON provided", err) 174 | customErr := models.ErrorStruct{Error: err.Error(), Message: "Invalid JSON provided", Context: "ManageUserHandler"} 175 | c.JSON(http.StatusBadRequest, customErr) 176 | return 177 | } 178 | 179 | var permissions map[string]interface{} 180 | err = json.Unmarshal(permissionsJSON, &permissions) 181 | if err != nil { 182 | config.LogError("ManageUserHandler: Invalid JSON provided", err) 183 | customErr := models.ErrorStruct{Error: err.Error(), Message: "Invalid JSON provided", Context: "ManageUserHandler"} 184 | c.JSON(http.StatusBadRequest, customErr) 185 | return 186 | } 187 | 188 | userID, ok := permissions["userID"].(float64) 189 | if !ok { 190 | config.LogError("ManageUserHandler: Invalid userID value", err) 191 | customErr := models.ErrorStruct{Error: "invalid userID value", Message: "Invalid userID value", Context: "ManageUserHandler"} 192 | c.JSON(http.StatusBadRequest, customErr) 193 | return 194 | } 195 | 196 | err = UpdateUserPermissions(uint(userID), permissionsJSON) 197 | if err != nil { 198 | config.LogError("ManageUserHandler: Failed to update user permissions", err) 199 | customErr := models.ErrorStruct{Error: err.Error(), Message: "Failed to update user permissions", Context: "ManageUserHandler"} 200 | c.JSON(http.StatusInternalServerError, customErr) 201 | return 202 | } 203 | 204 | c.JSON(http.StatusOK, gin.H{"success": true}) 205 | } 206 | -------------------------------------------------------------------------------- /internal/auth/auth_test.go: -------------------------------------------------------------------------------- 1 | // Package auth controls REST routes related to authentication or authorization 2 | // 3 | // Note: For unit tests packages that required access to the backend database 4 | // were not replicated 5 | // 6 | // In auth_test.go functions that required a valid JWT were not replicated 7 | // 8 | // The package structure is broken into three components: 9 | // auth.go which contains the functions and structs for the routes 10 | // auth_controller.go which contains the route handlers 11 | // auth_test.go which contains unit tests 12 | package auth 13 | 14 | import ( 15 | "net/http" 16 | "net/http/httptest" 17 | "strconv" 18 | "testing" 19 | "time" 20 | 21 | "github.com/gin-gonic/gin" 22 | "github.com/golang-jwt/jwt/v4" 23 | "golang.org/x/crypto/bcrypt" 24 | ) 25 | 26 | func TestValidateTokenClaims(t *testing.T) { 27 | // Test that ValidateTokenClaims returns an error if the "authorized" claim is not true 28 | claims := jwt.MapClaims{ 29 | "authorized": false, 30 | } 31 | err := ValidateTokenClaims(claims) 32 | if err == nil { 33 | t.Error("Expected ValidateTokenClaims to return an error if the 'authorized' claim is not true") 34 | } 35 | 36 | // Test that ValidateTokenClaims returns an error if the "exp" claim is a string and the token has expired 37 | claims = jwt.MapClaims{ 38 | "authorized": true, 39 | "exp": strconv.FormatInt(time.Now().Add(-time.Hour).Unix(), 10), 40 | } 41 | err = ValidateTokenClaims(claims) 42 | if err == nil { 43 | t.Error("Expected ValidateTokenClaims to return an error if the 'exp' claim is a string and the token has expired") 44 | } 45 | 46 | // Test that ValidateTokenClaims returns an error if the "exp" claim is an int64 and the token has expired 47 | claims = jwt.MapClaims{ 48 | "authorized": true, 49 | "exp": time.Now().Add(-time.Hour).Unix(), 50 | } 51 | err = ValidateTokenClaims(claims) 52 | if err == nil { 53 | t.Error("Expected ValidateTokenClaims to return an error if the 'exp' claim is an int64 and the token has expired") 54 | } 55 | 56 | // Test that ValidateTokenClaims returns an error if any of the required claims are missing 57 | requiredClaims := []string{"canLogin", "canSearch", "canUpload", "canManage"} 58 | for _, claim := range requiredClaims { 59 | claims = jwt.MapClaims{ 60 | "authorized": true, 61 | "exp": time.Now().Add(time.Hour).Unix(), 62 | } 63 | err = ValidateTokenClaims(claims) 64 | if err == nil { 65 | t.Errorf("Expected ValidateTokenClaims to return an error if the '%s' claim is missing", claim) 66 | } 67 | } 68 | 69 | // Test that ValidateTokenClaims returns nil for valid claims 70 | claims = jwt.MapClaims{ 71 | "authorized": true, 72 | "exp": time.Now().Add(time.Hour).Unix(), 73 | "canLogin": true, 74 | "canSearch": true, 75 | "canUpload": true, 76 | "canManage": true, 77 | "canViewUserLists": true, 78 | "canEditUserLists": true, 79 | } 80 | err = ValidateTokenClaims(claims) 81 | if err != nil { 82 | t.Errorf("Expected ValidateTokenClaims to return nil for valid claims, got %v", err) 83 | } 84 | } 85 | 86 | func TestExtractToken(t *testing.T) { 87 | w := httptest.NewRecorder() 88 | c, _ := gin.CreateTestContext(w) 89 | 90 | // Initialize the c.Request field 91 | c.Request, _ = http.NewRequest("GET", "/", nil) 92 | 93 | // Set the Authorization header 94 | tokenString := "test_token" 95 | c.Request.Header.Set("Authorization", "Bearer "+tokenString) 96 | 97 | // Call the ExtractToken function 98 | token, err := ExtractToken(c) 99 | if err != nil { 100 | t.Fatal(err) 101 | } 102 | 103 | // Check that ExtractToken returns the expected token 104 | if token != tokenString { 105 | t.Errorf("Expected ExtractToken to return %q, got %q", tokenString, token) 106 | } 107 | } 108 | 109 | func TestVerifyPassword(t *testing.T) { 110 | // Hash a test password 111 | password := "password123" 112 | hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost) 113 | if err != nil { 114 | t.Fatal(err) 115 | } 116 | 117 | // Test that VerifyPassword returns true for the correct password 118 | if !VerifyPassword([]byte(password), []byte(hashedPassword)) { 119 | t.Error("Expected VerifyPassword to return true for the correct password") 120 | } 121 | 122 | // Test that VerifyPassword returns false for an incorrect password 123 | if VerifyPassword([]byte("incorrect"), []byte(hashedPassword)) { 124 | t.Error("Expected VerifyPassword to return false for an incorrect password") 125 | } 126 | } 127 | -------------------------------------------------------------------------------- /internal/config/config_test.go: -------------------------------------------------------------------------------- 1 | // Package config controls server-side configuration 2 | // 3 | // The validation and definition of the configuration file is done within 4 | // models and config is used to store logic related to server-side components 5 | // 6 | // Note: For unit tests packages that required access to the backend database 7 | // were not replicated 8 | // 9 | // The package structure is broken into two components: 10 | // config.go which contains the functions 11 | // config_test.go which contains the unit tests 12 | package config 13 | 14 | import ( 15 | "fmt" 16 | "ohaserver/internal/models" 17 | "reflect" 18 | "testing" 19 | ) 20 | 21 | func TestDehexPlaintext(t *testing.T) { 22 | tests := []struct { 23 | input string 24 | plain string 25 | err error 26 | }{ 27 | {"$HEX[48656c6c6f20576f726c64]", "Hello World", nil}, 28 | {"$HEX[48656c6c6f]", "Hello", nil}, 29 | {"$HEX[48656c6c6f20576f726c64b", "Hello World", fmt.Errorf("error decoding hex string: 48656c6c6f20576f726c64b")}, 30 | {"$HEX[]", "", nil}, 31 | } 32 | 33 | for _, test := range tests { 34 | plain, err := DehexPlaintext(test.input) 35 | if plain != test.plain || (err != nil && test.err != nil && err.Error() != test.err.Error()) { 36 | t.Errorf("DehexPlaintext(%v) = (%v, %v), want (%v, %v)", test.input, plain, err, test.plain, test.err) 37 | } 38 | } 39 | } 40 | 41 | func TestRehashMD5(t *testing.T) { 42 | tests := []struct { 43 | input string 44 | hash string 45 | }{ 46 | {"password", "5f4dcc3b5aa765d61d8327deb882cf99"}, 47 | {"12345", "827ccb0eea8a706c4c34a16891f84e7b"}, 48 | {"test", "098f6bcd4621d373cade4e832627b4f6"}, 49 | } 50 | 51 | for _, test := range tests { 52 | hash := RehashMD5(test.input) 53 | if hash != test.hash { 54 | t.Errorf("RehashMD5(%v) = %v, want %v", test.input, hash, test.hash) 55 | } 56 | } 57 | } 58 | 59 | func TestRehashSHA1(t *testing.T) { 60 | tests := []struct { 61 | input string 62 | hash string 63 | }{ 64 | {"password", "5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8"}, 65 | {"12345", "8cb2237d0679ca88db6464eac60da96345513964"}, 66 | {"test", "a94a8fe5ccb19ba61c4c0873d391e987982fbbd3"}, 67 | } 68 | 69 | for _, test := range tests { 70 | hash := RehashSHA1(test.input) 71 | if hash != test.hash { 72 | t.Errorf("RehashSHA1(%v) = %v, want %v", test.input, hash, test.hash) 73 | } 74 | } 75 | } 76 | 77 | func TestRehashNTLM(t *testing.T) { 78 | tests := []struct { 79 | input string 80 | hash string 81 | }{ 82 | {"password", "8846f7eaee8fb117ad06bdd830b7586c"}, 83 | {"12345", "7a21990fcd3d759941e45c490f143d5f"}, 84 | {"test", "0cb6948805f797bf2a82807973b89537"}, 85 | } 86 | 87 | for _, test := range tests { 88 | hash := RehashNTLM(test.input) 89 | if hash != test.hash { 90 | t.Errorf("RehashNTLM(%v) = %v, want %v", test.input, hash, test.hash) 91 | } 92 | } 93 | } 94 | 95 | func TestTestHexInput(t *testing.T) { 96 | tests := []struct { 97 | input string 98 | valid bool 99 | }{ 100 | {"$HEX[123abc]", true}, 101 | {"$HEX[123ABC]", true}, 102 | {"$HEX[123abC]", true}, 103 | {"$HEX[123abC", false}, 104 | {"HEX[123abC]", false}, 105 | {"$HEX[]", true}, 106 | {"$HEX", false}, 107 | } 108 | 109 | for _, test := range tests { 110 | valid := TestHexInput(test.input) 111 | if valid != test.valid { 112 | t.Errorf("TestHexInput(%v) = %v, want %v", test.input, valid, test.valid) 113 | } 114 | } 115 | } 116 | 117 | func TestParseHashAndPlaintext(t *testing.T) { 118 | tests := []struct { 119 | input interface{} 120 | cipher string 121 | plain string 122 | err error 123 | }{ 124 | {"hash:plain", "hash", "plain", nil}, 125 | {"hash:salt:plain", "hash:salt", "plain", nil}, 126 | {"hash:salt:s:al:t:plain", "hash:salt:s:al:t", "plain", nil}, 127 | {"invalid", "", "", fmt.Errorf("error parsing hash from plaintext: invalid")}, 128 | } 129 | 130 | for _, test := range tests { 131 | cipher, plain, err := ParseHashAndPlaintext(test.input) 132 | if cipher != test.cipher || plain != test.plain || (err != nil && test.err != nil && err.Error() != test.err.Error()) { 133 | t.Errorf("ParseHashAndPlaintext(%v) = (%v, %v, %v), want (%v, %v, %v)", test.input, cipher, plain, err, test.cipher, test.plain, test.err) 134 | } 135 | } 136 | } 137 | 138 | func TestRehashUpload(t *testing.T) { 139 | md5Hashes := []string{ 140 | "5f4dcc3b5aa765d61d8327deb882cf99:password", 141 | "i982d903e447368f3933999607f9b776a:hash:hash", 142 | } 143 | ntlmHashes := []string{ 144 | "8846f7eaee8fb117ad06bdd830b7586c:password", 145 | "a6f03e97a08e1045c4ee5d5593241bef:hash:hash", 146 | } 147 | uploadStruct, err := RehashUpload(ntlmHashes, "0") 148 | if err != nil { 149 | t.Errorf("error rehashing hashes: %v", err) 150 | } 151 | if len(uploadStruct) != len(md5Hashes) { 152 | t.Errorf("expected %d hashes, got %d", len(md5Hashes), len(uploadStruct)) 153 | } 154 | for i, h := range md5Hashes { 155 | _, p, _ := ParseHashAndPlaintext(h) 156 | expectedHash := fmt.Sprintf("%s:%s", RehashMD5(p), p) 157 | if uploadStruct[i] != expectedHash { 158 | t.Errorf("expected hash '%s', got '%s'", expectedHash, uploadStruct[i]) 159 | } 160 | } 161 | } 162 | 163 | func TestValidateHashItem(t *testing.T) { 164 | hashStruct := models.HashStruct{ 165 | Plaintext: "password", 166 | Algorithm: "0", 167 | Hash: "5f4dcc3b5aa765d61d8327deb882cf99", 168 | } 169 | err := ValidateHashItem(hashStruct, "0") 170 | if err != nil { 171 | t.Errorf("error validating valid hash: %v", err) 172 | } 173 | 174 | hashStruct.Hash = "invalid_hash" 175 | err = ValidateHashItem(hashStruct, "0") 176 | if err == nil { 177 | t.Errorf("expected error validating invalid hash, got nil") 178 | } 179 | if err.Error() != "hashes do not match: 5f4dcc3b5aa765d61d8327deb882cf99 (rehashed) != invalid_hash (provided)" { 180 | t.Errorf("expected error message 'hashes do not match: 5f4dcc3b5aa765d61d8327deb882cf99 (rehashed) != invalid_hash (provided)', got '%s'", err.Error()) 181 | } 182 | 183 | hashStruct.Algorithm = "100" 184 | hashStruct.Hash = "5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8" 185 | err = ValidateHashItem(hashStruct, "100") 186 | if err != nil { 187 | t.Errorf("error validating valid SHA1 hash: %v", err) 188 | } 189 | 190 | hashStruct.Algorithm = "1000" 191 | hashStruct.Hash = "8846f7eaee8fb117ad06bdd830b7586c" 192 | err = ValidateHashItem(hashStruct, "1000") 193 | if err != nil { 194 | t.Errorf("error validating valid NTLM hash: %v", err) 195 | } 196 | } 197 | 198 | func TestStringToToggle(t *testing.T) { 199 | tests := []struct { 200 | str string 201 | index int 202 | want string 203 | }{ 204 | {"HelloWorld", 0, "T0 T5"}, 205 | {"HelloWorld", 5, "T5 TA"}, 206 | } 207 | 208 | for _, test := range tests { 209 | got := StringToToggle(test.str, test.index) 210 | if got != test.want { 211 | t.Errorf("StringToToggle(%q, %q) = %q; want %q", test.str, test.index, got, test.want) 212 | } 213 | } 214 | } 215 | 216 | func TestCharToRule(t *testing.T) { 217 | tests := []struct { 218 | str string 219 | rule string 220 | want string 221 | }{ 222 | {"hello", "^", "^h ^e ^l ^l ^o"}, 223 | {"world", "$", "$w $o $r $l $d"}, 224 | } 225 | 226 | for _, test := range tests { 227 | got := CharToRule(test.str, test.rule) 228 | if got != test.want { 229 | t.Errorf("CharToRule(%q, %q) = %q; want %q", test.str, test.rule, got, test.want) 230 | } 231 | } 232 | } 233 | 234 | func TestCheckASCIIString(t *testing.T) { 235 | tests := []struct { 236 | input string 237 | expected bool 238 | }{ 239 | {"Hello, 世界", false}, 240 | {"Hello, World!", true}, 241 | {"", true}, 242 | {"世界", false}, 243 | } 244 | 245 | for _, test := range tests { 246 | result := CheckASCIIString(test.input) 247 | if result != test.expected { 248 | t.Errorf("CheckASCIIString(%q) = %v; want %v", test.input, result, test.expected) 249 | } 250 | } 251 | } 252 | 253 | func TestConvertCharacterMultiByteString(t *testing.T) { 254 | tests := []struct { 255 | name string 256 | str string 257 | want string 258 | }{ 259 | { 260 | name: "All ASCII characters", 261 | str: "$H $e $l $l $o $ $W $o $r $l $d $!", 262 | want: "$H $e $l $l $o $ $W $o $r $l $d $!", 263 | }, 264 | { 265 | name: "Contains non-ASCII character", 266 | str: "$H $e $l $l $o $ $世 $界 $!", 267 | want: "$H $e $l $l $o $ $\\xE4 $\\xB8 $\\x96 $\\xE7 $\\x95 $\\x8C $!", 268 | }, 269 | { 270 | name: "Contains non-ASCII character with ^", 271 | str: "^! ^界 ^世 ^ ^o ^l ^l ^e ^H", 272 | want: "^! ^\\x8C ^\\x95 ^\\xE7 ^\\x96 ^\\xB8 ^\\xE4 ^ ^o ^l ^l ^e ^H", 273 | }, 274 | } 275 | 276 | for _, tt := range tests { 277 | t.Run(tt.name, func(t *testing.T) { 278 | got := ConvertCharacterMultiByteString(tt.str) 279 | if got != tt.want { 280 | t.Errorf("ConvertCharacterMultiByteString(%q) = %v, want %v", tt.str, got, tt.want) 281 | } 282 | }) 283 | } 284 | } 285 | 286 | func TestMakeMask(t *testing.T) { 287 | str := "Hello, World1!" 288 | replacements := ConstructReplacements("ulds") 289 | want := "?u?l?l?l?l?s?s?u?l?l?l?l?d?s" 290 | got := MakeMask(str, replacements) 291 | if got != want { 292 | t.Errorf("MakeMask(%q, %q) = %q; want %q", str, replacements, got, want) 293 | } 294 | } 295 | 296 | func TestConvertMaskMultiByteString(t *testing.T) { 297 | tests := []struct { 298 | input string 299 | want string 300 | }{ 301 | { 302 | input: "Hello, 世界", 303 | want: "Hello, ?b?b?b?b?b?b", 304 | }, 305 | { 306 | input: "", 307 | want: "", 308 | }, 309 | { 310 | input: "Hello", 311 | want: "Hello", 312 | }, 313 | { 314 | input: "?u?l?l?l?l世界", 315 | want: "?u?l?l?l?l?b?b?b?b?b?b", 316 | }, 317 | } 318 | 319 | for _, test := range tests { 320 | got := ConvertMaskMultiByteString(test.input) 321 | if got != test.want { 322 | t.Errorf("ConvertMaskMultiByteString(%q) = %v; want %v", 323 | test.input, got, test.want) 324 | } 325 | } 326 | } 327 | 328 | func TestConstructReplacements(t *testing.T) { 329 | tests := []struct { 330 | name string 331 | str string 332 | want []string 333 | }{ 334 | { 335 | name: "Test lower case", 336 | str: "l", 337 | want: []string{"a", "?l", "b", "?l", "c", "?l", "d", "?l", "e", "?l", "f", "?l", "g", "?l", "h", "?l", "i", "?l", "j", "?l", "k", "?l", "l", "?l", "m", "?l", "n", "?l", "o", "?l", "p", "?l", "q", "?l", "r", "?l", "s", "?l", "t", "?l", "u", "?l", "v", "?l", "w", "?l", "x", "?l", "y", "?l", "z", "?l"}, 338 | }, 339 | { 340 | name: "Test upper case", 341 | str: "u", 342 | want: []string{"A", "?u", "B", "?u", "C", "?u", "D", "?u", "E", "?u", "F", "?u", "G", "?u", "H", "?u", "I", "?u", "J", "?u", "K", "?u", "L", "?u", "M", "?u", "N", "?u", "O", "?u", "P", "?u", "Q", "?u", "R", "?u", "S", "?u", "T", "?u", "U", "?u", "V", "?u", "W", "?u", "X", "?u", "Y", "?u", "Z", "?u"}, 343 | }, 344 | { 345 | name: "Test digits", 346 | str: "d", 347 | want: []string{"0", "?d", "1", "?d", "2", "?d", "3", "?d", "4", "?d", "5", "?d", "6", "?d", "7", "?d", "8", "?d", "9", "?d"}, 348 | }, 349 | { 350 | name: "Test special characters", 351 | str: "s", 352 | want: []string{" ", "?s", "!", "?s", "\"", "?s", "#", "?s", "$", "?s", "%", "?s", "&", "?s", "\\", "?s", "(", "?s", ")", "?s", "*", "?s", "+", "?s", ",", "?s", "-", "?s", ".", "?s", "/", "?s", ":", "?s", ";", "?s", "<", "?s", "=", "?s", ">", "?s", "?", "?s", "@", "?s", "[", "?s", "\\", "?s", "]", "?s", "^", "?s", "_", "?s", "`", "?s", "{", "?s", "|", "?s", "}", "?s", "~", "?s", "'", "?s"}, 353 | }, 354 | } 355 | 356 | for _, tt := range tests { 357 | t.Run(tt.name, func(t *testing.T) { 358 | got := ConstructReplacements(tt.str) 359 | if !reflect.DeepEqual(got, tt.want) { 360 | t.Errorf("ConstructReplacements() = %v, want %v", got, tt.want) 361 | } 362 | }) 363 | } 364 | } 365 | 366 | func TestReverseString(t *testing.T) { 367 | tests := []struct { 368 | str string 369 | want string 370 | }{ 371 | {"hello", "olleh"}, 372 | {"world", "dlrow"}, 373 | } 374 | 375 | for _, test := range tests { 376 | got := ReverseString(test.str) 377 | if got != test.want { 378 | t.Errorf("ReverseString(%q) = %q; want %q", test.str, got, test.want) 379 | } 380 | } 381 | } 382 | 383 | func TestContainsSubstring(t *testing.T) { 384 | tests := []struct { 385 | word string 386 | substrings []string 387 | expected bool 388 | }{ 389 | {"password123", []string{"pass", "123"}, true}, 390 | {"applepie", []string{"banana", "orange"}, false}, 391 | {"helloworld", []string{}, false}, 392 | {"", []string{"a", "b"}, false}, 393 | } 394 | 395 | for _, test := range tests { 396 | result := containsSubstring(test.word, test.substrings) 397 | if result != test.expected { 398 | t.Errorf("Word '%s' with substrings %v: expected %v, got %v", test.word, test.substrings, test.expected, result) 399 | } 400 | } 401 | } 402 | 403 | func TestHasUniqueChars(t *testing.T) { 404 | tests := []struct { 405 | str string 406 | expected bool 407 | }{ 408 | {"ABCDefg123", true}, 409 | {"apie", true}, 410 | {"", false}, 411 | {"aA", false}, 412 | } 413 | 414 | for _, test := range tests { 415 | result := hasUniqueChars(test.str) 416 | if result != test.expected { 417 | t.Errorf("String '%s': expected %v, got %v", test.str, test.expected, result) 418 | } 419 | } 420 | } 421 | -------------------------------------------------------------------------------- /internal/middleware/middleware.go: -------------------------------------------------------------------------------- 1 | // Package middleware contains server-side middleware for HTTP requests 2 | // 3 | // Middleware is applied at three locations: 4 | // - On all server routes 5 | // - On public and private routes 6 | // - On particular REST endpoints 7 | // 8 | // The authorization model is designed to allow more granular control over 9 | // endpoints which is then enforced by middleware and authentication 10 | package middleware 11 | 12 | import ( 13 | "fmt" 14 | "log" 15 | "net/http" 16 | "ohaserver/internal/auth" 17 | "os" 18 | "path/filepath" 19 | "time" 20 | 21 | "github.com/gin-gonic/gin" 22 | ) 23 | 24 | // AuthenticationCheckMiddleware verifies authentication of a request and if the 25 | // authentication token is valid the request is allowed otherwise return an 26 | // unauthorized response 27 | // 28 | // Args: 29 | // 30 | // None 31 | // 32 | // Returns: 33 | // 34 | // (gin.HandlerFunc): gin.Handler object 35 | func AuthenticationCheckMiddleware() gin.HandlerFunc { 36 | return func(c *gin.Context) { 37 | err := auth.ValidateToken(c) 38 | if err != nil { 39 | c.AbortWithStatus(http.StatusUnauthorized) 40 | return 41 | } 42 | c.Next() 43 | } 44 | } 45 | 46 | // OpenRegistrationMiddleware controls access to the registration process 47 | // 48 | // If open registration is set to false then registration will be closed and 49 | // the server will respond with a forbidden status code 50 | // 51 | // Args: 52 | // 53 | // openRegistration (bool): controls allowance of registration requests 54 | // 55 | // Returns: 56 | // 57 | // (gin.HandlerFunc): gin.Handler object 58 | func OpenRegistrationMiddleware(openRegistration bool) gin.HandlerFunc { 59 | return func(c *gin.Context) { 60 | if !openRegistration { 61 | c.AbortWithStatus(http.StatusForbidden) 62 | return 63 | } 64 | c.Next() 65 | } 66 | } 67 | 68 | // LoggerMiddleware controls logging incoming requests 69 | // 70 | // By default all requests are logged to /var/www/OpenHashAPI/OpenHashAPI.log and the logfile 71 | // is reset at 5 GB 72 | // 73 | // Args: 74 | // 75 | // c (gin.Context): The Gin context object 76 | // 77 | // Returns: 78 | // 79 | // (gin.HandlerFunc): gin.Handler object 80 | func LoggerMiddleware(c *gin.Context) { 81 | startTime := time.Now() 82 | c.Next() 83 | endTime := time.Now() 84 | latency := endTime.Sub(startTime) 85 | 86 | logPath := filepath.Join("/var/www/OpenHashAPI/logs", "OpenHashAPI-Endpoint.log") 87 | f, err := os.OpenFile(logPath, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0664) 88 | if err != nil { 89 | fmt.Println(err) 90 | return 91 | } 92 | defer f.Close() 93 | 94 | fileInfo, err := f.Stat() 95 | if err != nil { 96 | fmt.Println(err) 97 | return 98 | } 99 | if fileInfo.Size() > 512*1024*1024*1024 { 100 | err = f.Truncate(0) 101 | if err != nil { 102 | fmt.Println(err) 103 | return 104 | } 105 | _, err = f.Seek(0, 0) 106 | if err != nil { 107 | fmt.Println(err) 108 | return 109 | } 110 | } 111 | 112 | logger := log.New(f, "", 0) 113 | logger.Printf("[OHA] %v | %3d | %13v | %15s | %-7s %s\n", 114 | endTime.Format("2006/01/02 - 15:04:05"), 115 | c.Writer.Status(), 116 | latency, 117 | c.ClientIP(), 118 | c.Request.Method, 119 | c.Request.URL.Path, 120 | ) 121 | } 122 | 123 | // CanSearchMiddleware controls access to search the database via API 124 | // 125 | // This middleware checks for authentication and then verifies the 126 | // authentication token claims for access 127 | // 128 | // Args: 129 | // 130 | // None 131 | // 132 | // Returns: 133 | // 134 | // (gin.HandlerFunc): gin.Handler object 135 | func CanSearchMiddleware() gin.HandlerFunc { 136 | return func(c *gin.Context) { 137 | claims, err := auth.ExtractClaimsFromContext(c) 138 | if err != nil { 139 | c.AbortWithStatus(http.StatusForbidden) 140 | return 141 | } 142 | canSearch, ok := claims["canSearch"].(bool) 143 | if !ok || !canSearch { 144 | c.AbortWithStatus(http.StatusForbidden) 145 | return 146 | } 147 | c.Next() 148 | } 149 | } 150 | 151 | // CanUploadMiddleware controls access to upload data to the database via API 152 | // 153 | // This middleware checks for authentication and then verifies the 154 | // authentication token claims for access 155 | // 156 | // Args: 157 | // 158 | // None 159 | // 160 | // Returns: 161 | // 162 | // (gin.HandlerFunc): gin.Handler object 163 | func CanUploadMiddleware() gin.HandlerFunc { 164 | return func(c *gin.Context) { 165 | claims, err := auth.ExtractClaimsFromContext(c) 166 | if err != nil { 167 | c.AbortWithStatus(http.StatusForbidden) 168 | return 169 | } 170 | canUpload, ok := claims["canUpload"].(bool) 171 | if !ok || !canUpload { 172 | c.AbortWithStatus(http.StatusForbidden) 173 | return 174 | } 175 | c.Next() 176 | } 177 | } 178 | 179 | // CanManageMiddleware controls access to manage other users permissions via 180 | // the API 181 | // 182 | // This middleware checks for authentication and then verifies the 183 | // authentication token claims for access 184 | // 185 | // Args: 186 | // 187 | // None 188 | // 189 | // Returns: 190 | // 191 | // (gin.HandlerFunc): gin.Handler object 192 | func CanManageMiddleware() gin.HandlerFunc { 193 | return func(c *gin.Context) { 194 | claims, err := auth.ExtractClaimsFromContext(c) 195 | if err != nil { 196 | c.AbortWithStatus(http.StatusForbidden) 197 | return 198 | } 199 | canManage, ok := claims["canManage"].(bool) 200 | if !ok || !canManage { 201 | c.AbortWithStatus(http.StatusForbidden) 202 | return 203 | } 204 | c.Next() 205 | } 206 | } 207 | 208 | // CanListUserListsMiddleware controls access to list all user lists via the API 209 | // 210 | // This middleware checks for authentication and then verifies the 211 | // authentication token claims for access 212 | // 213 | // Args: 214 | // 215 | // allowUserLists (bool): controls allowance of user list requests 216 | // 217 | // Returns: 218 | // (gin.HandlerFunc): gin.Handler object 219 | func CanListUserListsMiddleware(allowUserLists bool) gin.HandlerFunc { 220 | return func(c *gin.Context) { 221 | if !allowUserLists { 222 | c.AbortWithStatus(http.StatusForbidden) 223 | return 224 | } 225 | claims, err := auth.ExtractClaimsFromContext(c) 226 | if err != nil { 227 | c.AbortWithStatus(http.StatusForbidden) 228 | return 229 | } 230 | canList, ok := claims["canViewUserLists"].(bool) 231 | if !ok || !canList { 232 | c.AbortWithStatus(http.StatusForbidden) 233 | return 234 | } 235 | c.Next() 236 | } 237 | } 238 | 239 | // CanEditUserListsMiddleware controls access to edit user lists via the API 240 | // 241 | // This middleware checks for authentication and then verifies the 242 | // authentication token claims for access 243 | // 244 | // Args: 245 | // 246 | // allowUserLists (bool): controls allowance of user list requests 247 | // 248 | // Returns: 249 | // (gin.HandlerFunc): gin.Handler object 250 | func CanEditUserListsMiddleware(allowUserLists bool) gin.HandlerFunc { 251 | return func(c *gin.Context) { 252 | if !allowUserLists { 253 | c.AbortWithStatus(http.StatusForbidden) 254 | return 255 | } 256 | claims, err := auth.ExtractClaimsFromContext(c) 257 | if err != nil { 258 | c.AbortWithStatus(http.StatusForbidden) 259 | return 260 | } 261 | canEdit, ok := claims["canEditUserLists"].(bool) 262 | if !ok || !canEdit { 263 | c.AbortWithStatus(http.StatusForbidden) 264 | return 265 | } 266 | c.Next() 267 | } 268 | } 269 | 270 | // MaxSizeAllowed limits the max request size to prevent errors 271 | // 272 | // Args: 273 | // 274 | // None 275 | // 276 | // Returns: 277 | // 278 | // (gin.HandlerFunc): gin.Handler object 279 | func MaxSizeAllowed(n int) gin.HandlerFunc { 280 | return func(c *gin.Context) { 281 | // Convert n from gigabytes to bytes 282 | nBytes := int64(n) * 1024 * 1024 * 1024 283 | c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, nBytes) 284 | c.Next() 285 | } 286 | } 287 | -------------------------------------------------------------------------------- /internal/models/models_functions.go: -------------------------------------------------------------------------------- 1 | // Package models contains object definitions and validation functions 2 | // 3 | // The package structure is broken into three components: 4 | // models_structs.go which contains all the structs 5 | // models_functions.go which contains all of the functions 6 | // models_test.go which contains all of the unit tests 7 | package models 8 | 9 | import ( 10 | "fmt" 11 | "reflect" 12 | "regexp" 13 | ) 14 | 15 | // ValidateConfigFile validates a server configuration JSON file after loading 16 | // it into a Configuration object 17 | // 18 | // If the quality filter regex is found to be invalid a default regex is set 19 | // to allow all values through 20 | // 21 | // Args: 22 | // 23 | // config (Configuration): The loaded configuration settings 24 | // 25 | // Return: 26 | // 27 | // config (Configuration): The loaded configuration settings 28 | // err (error): Error data 29 | func ValidateConfigFile(config Configuration) (Configuration, error) { 30 | // Validate the database user 31 | if !ValidateUsernameInput(config.DatabaseUser) { 32 | return config, fmt.Errorf("Invalid database user. Expected a string with at most 32 alphanumeric characters. Got: %s", config.DatabaseUser) 33 | } 34 | // Validate the database password 35 | upper := regexp.MustCompile(`[A-Z]`) 36 | lower := regexp.MustCompile(`[a-z]`) 37 | number := regexp.MustCompile(`[0-9]`) 38 | special := regexp.MustCompile(`[^a-zA-Z0-9\s]`) 39 | 40 | if len(config.DatabasePwd) < 12 || !(upper.MatchString(config.DatabasePwd) && lower.MatchString(config.DatabasePwd) && special.MatchString(config.DatabasePwd) && number.MatchString(config.DatabasePwd)) { 41 | return config, fmt.Errorf("Invalid password. Passwords must be at least 12 characters long and contain a mix of uppercase, lowercase letters, and at least one digit and one special character") 42 | } 43 | // Validate the authentication pepper 44 | if len(config.AuthenticationPepper) < 8 || !regexp.MustCompile(`^[a-zA-Z0-9!@#$%^&*()_+]{12,}$`).MatchString(config.AuthenticationPepper) { 45 | return config, fmt.Errorf("Invalid authentication pepper. Pepper must be at least 8 characters long and contain a mix of uppercase, lowercase letters, and at least one digit and one special character") 46 | } 47 | // Validate the number of idle database connections 48 | if config.DatabaseIdleConnections < 0 || config.DatabaseIdleConnections > 1000 { 49 | return config, fmt.Errorf("Invalid number of idle database connections. Expected a value between 0 and 1000. Got: %d", config.ServerPort) 50 | } 51 | // Validate the server port 52 | if config.ServerPort < 0 || config.ServerPort > 65535 { 53 | return config, fmt.Errorf("Invalid server port. Expected a value between 0 and 65535. Got: %d", config.ServerPort) 54 | } 55 | // Validate the JWT TTL 56 | if config.ServerJWTTimeToLive < 5 || config.ServerJWTTimeToLive > 90 { 57 | return config, fmt.Errorf("Invalid JWT TTL. Expected a value between 5 and 90. Got: %d", config.ServerJWTTimeToLive) 58 | } 59 | // Validate the server GB max upload size 60 | if config.ServerGBMaxUploadSize < 0 { 61 | return config, fmt.Errorf("Invalid server GB max upload size. Expected a positive value. Got: %d", config.ServerGBMaxUploadSize) 62 | } 63 | // Validate the rehash algorithm 64 | if config.RehashAlgorithm != 0 && config.RehashAlgorithm != 100 && config.RehashAlgorithm != 1000 { 65 | return config, fmt.Errorf("Invalid rehash algorithm. Expected a value of 0, 100, or 1000. Got: %d", config.RehashAlgorithm) 66 | } 67 | // Validate the open registration field 68 | if reflect.TypeOf(config.OpenRegistration).Kind() != reflect.Bool { 69 | return config, fmt.Errorf("Invalid open registration value. Expected a boolean value. Got: %v", config.OpenRegistration) 70 | } 71 | // Validate the rehash uploads field 72 | if reflect.TypeOf(config.RehashUploads).Kind() != reflect.Bool { 73 | return config, fmt.Errorf("Invalid rehash uploads value. Expected a boolean value. Got: %v", config.RehashUploads) 74 | } 75 | // Validate the quality filter field 76 | if reflect.TypeOf(config.QualityFilter).Kind() != reflect.Bool { 77 | return config, fmt.Errorf("Invalid quality filter value. Expected a boolean value. Got: %v", config.QualityFilter) 78 | } 79 | // Validate the quality filter regex field 80 | if config.QualityFilterRegex == "" { 81 | config.QualityFilterRegex = "^default.{1000}$" 82 | } 83 | 84 | _, err := regexp.Compile(config.QualityFilterRegex) 85 | if err != nil { 86 | config.QualityFilterRegex = "^default.{1000}$" 87 | } 88 | // Validate the self heal database field 89 | if reflect.TypeOf(config.SelfHealDB).Kind() != reflect.Bool { 90 | return config, fmt.Errorf("Invalid self heal database value. Expected a boolean value. Got: %v", config.SelfHealDB) 91 | } 92 | // Validate the number of database chunks for self heal 93 | if config.SelfHealDBChunks < 0 || config.SelfHealDBChunks > 100000 { 94 | return config, fmt.Errorf("Invalid number of self heal database chunks. Expected a value between 0 and 100000. Got: %d", config.ServerPort) 95 | } 96 | // Validate the number of database workers for self heal 97 | if config.SelfHealDBWorkers < 0 || config.SelfHealDBWorkers > 10000 { 98 | return config, fmt.Errorf("Invalid number of self heal database chunks. Expected a value between 0 and 10000. Got: %d", config.ServerPort) 99 | } 100 | 101 | // Validate the allow user lists field 102 | if reflect.TypeOf(config.AllowUserLists).Kind() != reflect.Bool { 103 | return config, fmt.Errorf("Invalid allow user list value. Expected a boolean value. Got: %v", config.AllowUserLists) 104 | } 105 | 106 | // Validate the path fields 107 | pathFields := []string{ 108 | config.ServerTLSCertfilePath, 109 | config.ServerTLSKeyfilePath, 110 | config.ServerJWTPublicPEMfilePath, 111 | config.ServerJWTPrivatePEMfilePath, 112 | } 113 | for _, path := range pathFields { 114 | if !regexp.MustCompile(`^[a-zA-Z0-9\.\-_\/]+$`).MatchString(path) { 115 | return config, fmt.Errorf("Invalid path. Got: %s", path) 116 | } 117 | } 118 | 119 | return config, nil 120 | } 121 | 122 | // ValidateIntInput checks input for only valid numerical values 123 | // 124 | // Args: 125 | // 126 | // s (string): string to be validated 127 | // 128 | // Returns: 129 | // 130 | // (bool): Returns true if it matches and false if it did not 131 | func ValidateIntInput(s string) bool { 132 | var validateInput = regexp.MustCompile(`^[0-9]+$`).MatchString 133 | if validateInput(s) == false { 134 | return false 135 | } 136 | return true 137 | } 138 | 139 | // ValidateUsernameInput checks input for only valid alphanumerical values 140 | // 141 | // Args: 142 | // 143 | // s (string): string to be validated 144 | // 145 | // Returns: 146 | // 147 | // (bool): Returns true if it matches and false if it did not 148 | func ValidateUsernameInput(s string) bool { 149 | var validateInput = regexp.MustCompile(`^[a-zA-Z0-9]+$`).MatchString 150 | if len(s) > 32 { 151 | return false 152 | } 153 | if validateInput(s) == false { 154 | return false 155 | } 156 | return true 157 | } 158 | 159 | // ValidateJWTCharacters checks the JWT token for valid characters. 160 | // 161 | // Args: 162 | // 163 | // jwtToken (string): The JWT token to validate. 164 | // 165 | // Returns: 166 | // 167 | // bool: True if the token is valid, False otherwise. 168 | func ValidateJWTCharacters(jwtToken string) bool { 169 | return bool(regexp.MustCompile(`^[a-zA-Z0-9-_]+={0,2}\.[a-zA-Z0-9-_]+={0,2}\.[a-zA-Z0-9-_]+={0,2}$`).MatchString(jwtToken)) 170 | } 171 | 172 | // ValidateBoolInput checks input for only valid boolean values 173 | // 174 | // Args: 175 | // s (string): string to be validated 176 | // 177 | // Returns: 178 | // (bool): Returns true if it matches and false if it did not 179 | func ValidateBoolInput(s string) bool { 180 | if s == "true" { 181 | return true 182 | } 183 | return false 184 | } 185 | -------------------------------------------------------------------------------- /internal/models/models_structs.go: -------------------------------------------------------------------------------- 1 | // Package models contains object definitions and validation functions 2 | // 3 | // The package structure is broken into three components: 4 | // models_structs.go which contains all the structs 5 | // models_functions.go which contains all of the functions 6 | // models_test.go which contains all of the unit tests 7 | package models 8 | 9 | // 10 | // Structs 11 | // 12 | 13 | // Configuration is a struct used to load JSON config files 14 | // 15 | // The struct contains the following fields: 16 | // 17 | // DatabaseUser: The username of the database user 18 | // DatabasePwd: The password of the database user 19 | // AuthenticationPepper: The pepper value used in authentication 20 | // DatabaseIdleConnections: The number of idle database connections allowed 21 | // ServerPort: The port the server will host on 22 | // ServerTLSCertfilePath: Local path to the cert file for TLS 23 | // ServerTLSKeyfilePath: Local path to the key file for TLS 24 | // ServerJWTPublicPEMfilePath: Local path to the public PEM file for auth 25 | // ServerJWTPrivatePEMfilePath: Local path to the private PEM file for auth 26 | // ServerJWTTimeToLive: The JWT auth token TTL value 27 | // ServerGBMaxUploadSize: Max POST request size in GB 28 | // OpenRegistration: If users are allowed to self register accounts 29 | // RehashUploads: If uploads should be rehashed into another algorithm 30 | // RehashAlgorithm: Algorithm to use are 0, 100, 1000 31 | // QualityFilter: If uploads should be filtered before adding to database 32 | // QualityFilterRegex: Regex to match bad items to 33 | // SelfHealDB: If the database should validate hashes in the background 34 | // SelfHealDBChunks: Number of chunks the database is broken into for the 35 | // worker pool 36 | // SelfHealDBWorkers: Number of workers to spawn for the validation process 37 | // GenerateWordlist: If the server should start a process to make a wordlist 38 | // GenerateRules: If the server should start a process to make a rule list 39 | // GenerateMasks: If the server should start a process to make a mask list 40 | // AllowUserLists: If the server should allow user lists 41 | type Configuration struct { 42 | DatabaseUser string `json:"database-user"` 43 | DatabasePwd string `json:"database-pwd"` 44 | AuthenticationPepper string `json:"auth-pepper"` 45 | DatabaseIdleConnections int `json:"database-idle-connections"` 46 | ServerPort int `json:"server-port"` 47 | ServerTLSCertfilePath string `json:"server-tls-certfile-path"` 48 | ServerTLSKeyfilePath string `json:"server-tls-keyfile-path"` 49 | ServerJWTPublicPEMfilePath string `json:"server-jwt-public-pemfile-path"` 50 | ServerJWTPrivatePEMfilePath string `json:"server-jwt-private-pemfile-path"` 51 | ServerJWTTimeToLive int `json:"server-jwt-ttl"` 52 | ServerGBMaxUploadSize int `json:"server-gb-max-upload-size"` 53 | OpenRegistration bool `json:"open-registration"` 54 | RehashUploads bool `json:"rehash-uploads"` 55 | RehashAlgorithm int `json:"rehash-algorithm"` 56 | QualityFilter bool `json:"quality-filter"` 57 | QualityFilterRegex string `json:"quality-filter-regex"` 58 | SelfHealDB bool `json:"self-heal-database"` 59 | SelfHealDBChunks int `json:"self-heal-database-chunks"` 60 | SelfHealDBWorkers int `json:"self-heal-database-workers"` 61 | GenerateWordlist bool `json:"generate-wordlist"` 62 | GenerateRules bool `json:"generate-rules"` 63 | GenerateMasks bool `json:"generate-masks"` 64 | AllowUserLists bool `json:"allow-user-lists"` 65 | } 66 | 67 | // HashSearchStruct is a struct used for searching the database 68 | // 69 | // The struct has one field, data: 70 | // 71 | // Data: Array of either HASH and/or PLAIN to search the database for 72 | type HashSearchStruct struct { 73 | Data []string `json:"data"` 74 | } 75 | 76 | // HashUploadStruct is a struct used to upload data to the database 77 | // 78 | // The struct has two fields, Algorithm and HashPlain: 79 | // 80 | // Algorithm: The algorithm of the HASH value 81 | // HashPlain: Array in HASH:PLAIN or HASH:SALT:PLAIN format 82 | type HashUploadStruct struct { 83 | Algorithm string `json:"algorithm"` 84 | HashPlain []string `json:"hash-plain"` 85 | } 86 | 87 | // HashStruct is a struct used to hold individual hash data 88 | // 89 | // The struct has the following fields: 90 | // 91 | // Algorithm: The algorithm of the HASH value 92 | // Hash: The HASH value 93 | // Plaintext: The PLAINTEXT value 94 | // Validated: If the HASH has been validated 95 | type HashStruct struct { 96 | Algorithm string `json:"algorithm"` 97 | Hash string `json:"hash"` 98 | Plaintext string `json:"plaintext"` 99 | Validated string `json:"validated"` 100 | } 101 | 102 | // ErrorStruct is a struct used to hold error data 103 | // 104 | // The struct has the following fields: 105 | // Error: The error message 106 | // Message: The message to display 107 | // Context: The context of the error 108 | // 109 | type ErrorStruct struct { 110 | Error string `json:"error"` 111 | Message string `json:"message"` 112 | Context string `json:"context"` 113 | } 114 | -------------------------------------------------------------------------------- /internal/models/models_test.go: -------------------------------------------------------------------------------- 1 | // Package models contains object definitions and validation functions 2 | // 3 | // The package structure is broken into three components: 4 | // models_structs.go which contains all the structs 5 | // models_functions.go which contains all of the functions 6 | // models_test.go which contains all of the unit tests 7 | package models 8 | 9 | import ( 10 | "regexp" 11 | "testing" 12 | ) 13 | 14 | func TestValidateConfigFile(t *testing.T) { 15 | config := Configuration{ 16 | DatabaseUser: "testUser", 17 | DatabasePwd: "testPassword123!@#", 18 | AuthenticationPepper: "0H4St4ticP3pp3r", 19 | DatabaseIdleConnections: 100, 20 | ServerPort: 8080, 21 | ServerTLSCertfilePath: "server.crt", 22 | ServerTLSKeyfilePath: "server.key", 23 | ServerJWTPublicPEMfilePath: "jwt.pub", 24 | ServerJWTPrivatePEMfilePath: "jwt.priv", 25 | ServerJWTTimeToLive: 30, 26 | ServerGBMaxUploadSize: 10, 27 | OpenRegistration: true, 28 | RehashUploads: true, 29 | RehashAlgorithm: 0, 30 | QualityFilter: true, 31 | QualityFilterRegex: "default.{1000}$", 32 | SelfHealDB: true, 33 | SelfHealDBChunks: 100, 34 | SelfHealDBWorkers: 10, 35 | } 36 | 37 | _, err := ValidateConfigFile(config) 38 | if err != nil { 39 | t.Errorf("error validating config file: %v", err) 40 | } 41 | 42 | config.DatabaseUser = "invalid_user" 43 | _, err = ValidateConfigFile(config) 44 | if err == nil { 45 | t.Errorf("expected error validating invalid database user, got nil") 46 | } 47 | 48 | config.DatabasePwd = "invalid_password" 49 | _, err = ValidateConfigFile(config) 50 | if err == nil { 51 | t.Errorf("expected error validating invalid database password, got nil") 52 | } 53 | 54 | config.DatabaseIdleConnections = -1 55 | _, err = ValidateConfigFile(config) 56 | if err == nil { 57 | t.Errorf("expected error validating invalid database idle connections, got nil") 58 | } 59 | 60 | config.ServerPort = -1 61 | _, err = ValidateConfigFile(config) 62 | if err == nil { 63 | t.Errorf("expected error validating invalid server port, got nil") 64 | } 65 | 66 | config.ServerJWTTimeToLive = -1 67 | _, err = ValidateConfigFile(config) 68 | if err == nil { 69 | t.Errorf("expected error validating invalid JWT TTL, got nil") 70 | } 71 | 72 | config.ServerGBMaxUploadSize = -1 73 | _, err = ValidateConfigFile(config) 74 | if err == nil { 75 | t.Errorf("expected error validating invalid server GB max upload size, got nil") 76 | } 77 | 78 | config.RehashAlgorithm = 1001 79 | _, err = ValidateConfigFile(config) 80 | if err == nil { 81 | t.Errorf("expected error validating invalid rehash algorithm, got nil") 82 | } 83 | 84 | config.OpenRegistration = false 85 | _, err = ValidateConfigFile(config) 86 | if err == nil { 87 | t.Errorf("expected error validating invalid open registration, got nil") 88 | } 89 | 90 | config.RehashUploads = false 91 | _, err = ValidateConfigFile(config) 92 | if err == nil { 93 | t.Errorf("expected error validating invalid rehash uploads, got nil") 94 | } 95 | 96 | config.QualityFilter = false 97 | _, err = ValidateConfigFile(config) 98 | if err == nil { 99 | t.Errorf("expected error validating invalid quality filter, got nil") 100 | } 101 | 102 | config.QualityFilterRegex = "" 103 | _, err = ValidateConfigFile(config) 104 | if err == nil { 105 | t.Errorf("expected error validating empty quality filter regex, got nil") 106 | } 107 | 108 | config.QualityFilterRegex = "^default.{1000}$" 109 | _, err = regexp.Compile(config.QualityFilterRegex) 110 | if err != nil { 111 | t.Errorf("expected error validating invalid quality filter regex, got nil") 112 | } 113 | 114 | config.SelfHealDB = false 115 | _, err = ValidateConfigFile(config) 116 | if err == nil { 117 | t.Errorf("expected error validating invalid self heal database, got nil") 118 | } 119 | 120 | config.SelfHealDBChunks = -1 121 | _, err = ValidateConfigFile(config) 122 | if err == nil { 123 | t.Errorf("expected error validating invalid number of self heal database chunks, got nil") 124 | } 125 | 126 | config.SelfHealDBWorkers = -1 127 | _, err = ValidateConfigFile(config) 128 | if err == nil { 129 | t.Errorf("expected error validating invalid number of self heal database workers, got nil") 130 | } 131 | 132 | pathFields := []string{ 133 | config.ServerTLSCertfilePath, 134 | config.ServerTLSKeyfilePath, 135 | config.ServerJWTPublicPEMfilePath, 136 | config.ServerJWTPrivatePEMfilePath, 137 | } 138 | for _, path := range pathFields { 139 | if !regexp.MustCompile(`^[a-zA-Z0-9\.\-_\/]+$`).MatchString(path) { 140 | t.Errorf("Invalid path. Got: %s", path) 141 | } 142 | } 143 | } 144 | 145 | func TestValidateIntInput(t *testing.T) { 146 | validInputs := []string{"123", "0", "1", "999999999"} 147 | for _, input := range validInputs { 148 | if !ValidateIntInput(input) { 149 | t.Errorf("Expected input '%s' to be valid", input) 150 | } 151 | } 152 | 153 | invalidInputs := []string{"test", "123a", "1.23", "-1", "+1"} 154 | for _, input := range invalidInputs { 155 | if ValidateIntInput(input) { 156 | t.Errorf("Expected input '%s' to be invalid", input) 157 | } 158 | } 159 | } 160 | 161 | func TestValidateUsernameInput(t *testing.T) { 162 | validInputs := []string{"testuser", "TestUser123", "TESTUSER"} 163 | for _, input := range validInputs { 164 | if !ValidateUsernameInput(input) { 165 | t.Errorf("Expected input '%s' to be valid", input) 166 | } 167 | } 168 | 169 | invalidInputs := []string{"test user", "Test@User", "Test.User", "Test-User", "Test_User", "TestUser123456789012345678901234567890123"} 170 | for _, input := range invalidInputs { 171 | if ValidateUsernameInput(input) { 172 | t.Errorf("Expected input '%s' to be invalid", input) 173 | } 174 | } 175 | } 176 | 177 | func TestValidateJWTCharacters(t *testing.T) { 178 | tests := []struct { 179 | name string 180 | token string 181 | want bool 182 | }{ 183 | // Valid JWT tokens: 184 | { 185 | name: "Valid token with no padding", 186 | token: "eyJhbGciOiJIUzI1NiJ9.SFRNTkNWS1I1.QdpNL-YqP_1tBRUd2_u-QNP6Fz-6a_C9-X0aWLVl-8", 187 | want: true, 188 | }, 189 | { 190 | name: "Valid token with base64url padding", 191 | token: "eyJhbGciOiJIUzI1NiJ9.SFRNTkNWS1I1.QdpNL-YqP_1tBRUd2_u-QNP6Fz-6a_C9-X0aWLVl-8==", 192 | want: true, 193 | }, 194 | 195 | // Invalid JWT tokens: 196 | { 197 | name: "Missing dot separators", 198 | token: "invalidtoken", 199 | want: false, 200 | }, 201 | { 202 | name: "Invalid characters", 203 | token: "eyJhbGciOiJIUzI1NiJ9.S!RNTkNWS1I1.QdpNL-YqP_1tBRUd2_u-QNP6Fz-6a_C9-X0aWLVl-8", 204 | want: false, 205 | }, 206 | { 207 | name: "Extra dot separator", 208 | token: "eyJhbGciOiJIUzI1NiJ9.SFRNTkNWS1I1..QdpNL-YqP_1tBRUd2_u-QNP6Fz-6a_C9-X0aWLVl-8", 209 | want: false, 210 | }, 211 | { 212 | name: "Invalid padding", 213 | token: "eyJhbGciOiJIUzI1NiJ9.SFRNTkNWS1I1.QdpNL-YqP_1tBRUd2_u-QNP6Fz-6a_C9-X0aWLVl-8$", 214 | want: false, 215 | }, 216 | { 217 | name: "Empty string", 218 | token: "", 219 | want: false, 220 | }, 221 | } 222 | 223 | for _, tt := range tests { 224 | t.Run(tt.name, func(t *testing.T) { 225 | got := ValidateJWTCharacters(tt.token) 226 | if got != tt.want { 227 | t.Errorf("ValidateJWTCharacters(%q) want: %v, got: %v", tt.token, tt.want, got) 228 | } 229 | }) 230 | } 231 | } 232 | 233 | func TestValidateBoolInput(t *testing.T) { 234 | tests := []struct { 235 | name string 236 | input string 237 | want bool 238 | }{ 239 | // Valid boolean values: 240 | { 241 | name: "True", 242 | input: "true", 243 | want: true, 244 | }, 245 | { 246 | name: "Talse (case sensitive)", 247 | input: "True", 248 | want: false, 249 | }, 250 | 251 | // Invalid boolean values: 252 | { 253 | name: "Empty string", 254 | input: "", 255 | want: false, 256 | }, 257 | { 258 | name: "Number", 259 | input: "123", 260 | want: false, 261 | }, 262 | } 263 | 264 | for _, tt := range tests { 265 | t.Run(tt.name, func(t *testing.T) { 266 | got := ValidateBoolInput(tt.input) 267 | if got != tt.want { 268 | t.Errorf("ValidateBoolInput(%q) want: %v, got: %v", tt.input, tt.want, got) 269 | } 270 | }) 271 | } 272 | } 273 | -------------------------------------------------------------------------------- /static/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Scorpion-Security-Labs/OpenHashAPI/d06faac0dc75ddef2b9b6c1363ead227e99eae04/static/logo.png -------------------------------------------------------------------------------- /static/style.css: -------------------------------------------------------------------------------- 1 | .logo { 2 | display: block; 3 | margin: 0 auto; 4 | max-width: 200px; 5 | } 6 | 7 | h1 { 8 | text-align: center; 9 | margin-bottom: 20px; 10 | } 11 | 12 | form { 13 | display: flex; 14 | flex-direction: column; 15 | } 16 | 17 | label { 18 | margin-bottom: 5px; 19 | font-weight: bold; 20 | } 21 | 22 | input { 23 | padding: 5px; 24 | border: 1px solid #ddd; 25 | border-radius: 3px; 26 | margin-bottom: 10px; 27 | width: 100%; 28 | } 29 | 30 | button { 31 | padding: 5px 10px; 32 | border: none; 33 | border-radius: 5px; 34 | background-color: #444; 35 | color: #ddd; 36 | cursor: pointer; 37 | } 38 | 39 | .copyright { 40 | text-align: center; 41 | font-size: 12px; 42 | margin-top: 20px; 43 | } 44 | 45 | body { 46 | background-color: #222; 47 | color: #ddd; 48 | font-family: sans-serif; 49 | margin: 0; 50 | padding: 0; 51 | } 52 | 53 | .login-container { 54 | width: 400px; 55 | margin: 0 auto; 56 | padding: 20px; 57 | border-radius: 5px; 58 | background-color: #333; 59 | } 60 | 61 | .container { 62 | width: 800px; 63 | margin: 0 auto; 64 | padding: 20px; 65 | border-radius: 5px; 66 | background-color: #333; 67 | } 68 | 69 | #curl-command { 70 | color: #eee; 71 | background-color: #1e1f27; 72 | padding: 10px; 73 | border-radius: 5px; 74 | white-space: pre-wrap; 75 | word-wrap: break-word; 76 | overflow-y: auto; 77 | max-height: 300px; 78 | font-family: monospace; 79 | border: 1px solid #333; 80 | } 81 | 82 | .link-wrapper { 83 | margin-bottom: 15px; 84 | } 85 | 86 | .link { 87 | display: inline-block; 88 | padding: 5px 5px; 89 | background-color: #eee; 90 | border-radius: 5px; 91 | text-decoration: none; 92 | color: #333; 93 | transition: background-color 0.2s ease; 94 | } 95 | 96 | .link:hover { 97 | background-color: #ddd; 98 | } 99 | 100 | code { 101 | display: inline-block; 102 | background-color: #282c34; 103 | padding: 3px 5px; 104 | border-radius: 4px; 105 | font-family: monospace; 106 | font-size: 0.9em; 107 | color: #abb2bf; 108 | border: 1px solid #353b45; 109 | } 110 | -------------------------------------------------------------------------------- /templates/home.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | OpenHashAPI Home Page 7 | 8 | 9 | 10 |
11 | 14 |
15 | 16 |
17 |

GET Requests

18 |
39 | 40 |
41 | 42 |
43 |

GET /api/status

44 | 45 | 57 | 58 |
curl -X GET \ 59 | ${baseURL}/api/status 60 |
61 |
62 | 63 |
64 | 65 |
66 |

GET /api/download/FILE/NUM

67 | 68 | 102 | 103 |
curl -X GET \ 104 | ${baseURL}/api/download/wordlist/10 \ 105 | -H 'Authorization: Bearer ${auth_token}' 106 |
107 |
108 |
curl -X GET \ 109 | ${baseURL}/api/download/rules/10 \ 110 | -H 'Authorization: Bearer ${auth_token}' 111 |
112 |
113 |
curl -X GET \ 114 | ${baseURL}/api/download/masks/10 \ 115 | -H 'Authorization: Bearer ${auth_token}' 116 |
117 |
118 | 119 |
120 | 121 |
122 |

GET /api/lists & GET /api/lists/LISTNAME

123 | 124 | 138 | 139 |
curl -X GET \ 140 | ${baseURL}/api/lists/ \ 141 | -H 'Authorization: Bearer ${auth_token}' 142 |
143 |
144 |
curl -X GET \ 145 | ${baseURL}/api/lists/LISTNAME \ 146 | -H 'Authorization: Bearer ${auth_token}' 147 |
148 |
149 | 150 |
151 | 152 |
153 |

GET /api/manage/refresh/FILE

154 | 155 | 168 |
curl -X GET \ 169 | ${baseURL}/api/manage/refresh/wordlist \ 170 | -H 'Authorization: Bearer ${auth_token}' 171 |
172 |
173 |
curl -X GET \ 174 | ${baseURL}/api/manage/refresh/rules \ 175 | -H 'Authorization: Bearer ${auth_token}' 176 |
177 |
178 |
curl -X GET \ 179 | ${baseURL}/api/manage/refresh/masks \ 180 | -H 'Authorization: Bearer ${auth_token}' 181 |
182 |
183 | 184 |
185 | 186 |
187 | 188 |

POST Requests

189 | 190 |
191 |

POST /api/login

192 | 193 | 203 | 204 |
curl -X POST \ 205 | ${baseURL}/api/login \ 206 | -H 'Content-Type: application/json' \ 207 | --data '{ 208 | "username": "username", 209 | "password": "password" 210 | }' 211 |
212 |
213 | 214 |
215 | 216 |
217 |

POST /api/register

218 | 219 | 229 | 230 |
curl -X POST \ 231 | ${baseURL}/api/login \ 232 | -H 'Content-Type: application/json' \ 233 | --data '{ 234 | "username": "username", 235 | "password": "password" 236 | }' 237 |
238 |
239 | 240 |
241 | 242 |
243 |

POST /api/found

244 | 245 | 256 | 257 |
curl -X POST \ 258 | ${baseURL}/api/found \ 259 | -H 'Authorization: Bearer ${auth_token}' \ 260 | -H 'Content-Type: application/json' \ 261 | --data '{ 262 | "algorithm": "0", 263 | "hash-plain": [ 264 | "5f4dcc3b5aa765d61d8327deb882cf99:password" 265 | ] 266 | }' 267 |
268 |
269 | 270 |
271 | 272 |
273 |

POST /api/search

274 | 275 | 294 | 295 |
curl -X POST \ 296 | ${baseURL}/api/search \ 297 | -H 'Authorization: Bearer ${auth_token}' \ 298 | -H 'Content-Type: application/json' \ 299 | --data '{ 300 | "data": [ 301 | "5f4dcc3b5aa765d61d8327deb882cf99", 302 | "password" 303 | ] 304 | }' 305 |
306 |
307 | 308 |
309 | 310 |
311 |

POST /api/manage/permissions

312 | 313 | 323 | 324 |
curl -X POST \ 325 | ${baseURL}/api/manage/permissions \ 326 | -H 'Authorization: Bearer ${auth_token}' \ 327 | -H 'Content-Type: application/json' \ 328 | --data '{ 329 | "userID":0, 330 | "canLogin": false, 331 | "canSearch": false, 332 | "canUpload": false, 333 | "canManage": false, 334 | "canViewUserLists": false, 335 | "canEditUserLists": false 336 | }' 337 |
338 |
339 | 340 |
341 | 342 |
343 |

POST /api/lists & POST /api/lists/LISTNAME

344 | 345 | 363 | 364 |
curl -X POST \ 365 | ${baseURL}/api/lists \ 366 | -H 'Authorization: Bearer ${auth_token}' \ 367 | -H 'Content-Type: text/plain' \ 368 | --data '5f4dcc3b5aa765d61d8327deb882cf99' 369 |
370 |
371 |
curl -X POST \ 372 | ${baseURL}/api/lists/LISTNAME \ 373 | -H 'Authorization: Bearer ${auth_token}' \ 374 | -H 'Content-Type: text/plain' \ 375 | --data '5f4dcc3b5aa765d61d8327deb882cf99:password' 376 |
377 |
378 | 379 | 380 | 381 | 394 | 395 |
396 | 399 |
400 | 401 | 402 | 403 | 404 | -------------------------------------------------------------------------------- /templates/login.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | OpenHashAPI Authentication Page 7 | 8 | 9 | 10 | 30 | 31 | 103 | 104 | 105 | 106 | --------------------------------------------------------------------------------