├── .github └── workflows │ └── maven-publish.yml ├── .gitignore ├── .idea ├── .gitignore ├── codeStyles │ ├── Project.xml │ └── codeStyleConfig.xml ├── encodings.xml ├── jwt-heartbreaker.iml ├── misc.xml ├── modules.xml └── vcs.xml ├── LICENSE ├── pom.xml └── src └── main └── java ├── burp └── BurpExtender.java └── pingvin ├── JwtKeyProvider.java ├── JwtListener.java ├── JwtPublicSecretsTab.java ├── JwtScannerCheck.java ├── JwtTokenKeyScannerIssue.java └── tokenposition ├── AuthorizationBearerHeader.java ├── Body.java ├── Config.java ├── Cookie.java ├── CookieFlagWrapper.java ├── CustomJWToken.java ├── Dummy.java ├── ITokenPosition.java ├── KeyValuePair.java ├── Minify.java ├── Output.java ├── PostBody.java ├── PublicKeyBroker.java ├── TimeClaim.java ├── TokenCheck.java └── algorithm ├── AlgorithmLinker.java ├── AlgorithmType.java └── AlgorithmWrapper.java /.github/workflows/maven-publish.yml: -------------------------------------------------------------------------------- 1 | # This workflow will build a package using Maven and then publish it to GitHub packages when a release is created 2 | # For more information see: https://github.com/actions/setup-java#apache-maven-with-a-settings-path 3 | 4 | name: Maven Package 5 | 6 | on: 7 | release: 8 | types: [created] 9 | 10 | jobs: 11 | build: 12 | 13 | runs-on: ubuntu-latest 14 | 15 | steps: 16 | - uses: actions/checkout@v2 17 | - name: Set up JDK 1.8 18 | uses: actions/setup-java@v1 19 | with: 20 | java-version: 1.8 21 | server-id: github # Value of the distributionManagement/repository/id field of the pom.xml 22 | settings-path: ${{ github.workspace }} # location for the settings.xml file 23 | 24 | - name: Build with Maven 25 | run: mvn -B package --file pom.xml 26 | 27 | - name: Publish to GitHub Packages Apache Maven 28 | run: mvn deploy -s $GITHUB_WORKSPACE/settings.xml 29 | env: 30 | GITHUB_TOKEN: ${{ github.token }} 31 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Created by .ignore support plugin (hsz.mobi) 2 | ### JetBrains template 3 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider 4 | # Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 5 | 6 | # User-specific stuff 7 | .idea/**/workspace.xml 8 | .idea/**/tasks.xml 9 | .idea/**/usage.statistics.xml 10 | .idea/**/dictionaries 11 | .idea/**/shelf 12 | 13 | # Generated files 14 | .idea/**/contentModel.xml 15 | 16 | # Sensitive or high-churn files 17 | .idea/**/dataSources/ 18 | .idea/**/dataSources.ids 19 | .idea/**/dataSources.local.xml 20 | .idea/**/sqlDataSources.xml 21 | .idea/**/dynamic.xml 22 | .idea/**/uiDesigner.xml 23 | .idea/**/dbnavigator.xml 24 | 25 | # Gradle 26 | .idea/**/gradle.xml 27 | .idea/**/libraries 28 | 29 | # Gradle and Maven with auto-import 30 | # When using Gradle or Maven with auto-import, you should exclude module files, 31 | # since they will be recreated, and may cause churn. Uncomment if using 32 | # auto-import. 33 | # .idea/artifacts 34 | # .idea/compiler.xml 35 | # .idea/jarRepositories.xml 36 | # .idea/modules.xml 37 | # .idea/*.iml 38 | # .idea/modules 39 | # *.iml 40 | # *.ipr 41 | 42 | # CMake 43 | cmake-build-*/ 44 | 45 | # Mongo Explorer plugin 46 | .idea/**/mongoSettings.xml 47 | 48 | # File-based project format 49 | *.iws 50 | 51 | # IntelliJ 52 | out/ 53 | 54 | # mpeltonen/sbt-idea plugin 55 | .idea_modules/ 56 | 57 | # JIRA plugin 58 | atlassian-ide-plugin.xml 59 | 60 | # Cursive Clojure plugin 61 | .idea/replstate.xml 62 | 63 | # Crashlytics plugin (for Android Studio and IntelliJ) 64 | com_crashlytics_export_strings.xml 65 | crashlytics.properties 66 | crashlytics-build.properties 67 | fabric.properties 68 | 69 | # Editor-based Rest Client 70 | .idea/httpRequests 71 | 72 | # Android studio 3.1+ serialized cache file 73 | .idea/caches/build_file_checksums.ser 74 | 75 | ### Maven template 76 | target/ 77 | pom.xml.tag 78 | pom.xml.releaseBackup 79 | pom.xml.versionsBackup 80 | pom.xml.next 81 | release.properties 82 | dependency-reduced-pom.xml 83 | buildNumber.properties 84 | .mvn/timing.properties 85 | # https://github.com/takari/maven-wrapper#usage-without-binary-jar 86 | .mvn/wrapper/maven-wrapper.jar 87 | 88 | ### Windows template 89 | # Windows thumbnail cache files 90 | Thumbs.db 91 | Thumbs.db:encryptable 92 | ehthumbs.db 93 | ehthumbs_vista.db 94 | 95 | # Dump file 96 | *.stackdump 97 | 98 | # Folder config file 99 | [Dd]esktop.ini 100 | 101 | # Recycle Bin used on file shares 102 | $RECYCLE.BIN/ 103 | 104 | # Windows Installer files 105 | *.cab 106 | *.msi 107 | *.msix 108 | *.msm 109 | *.msp 110 | 111 | # Windows shortcuts 112 | *.lnk 113 | 114 | ### macOS template 115 | # General 116 | .DS_Store 117 | .AppleDouble 118 | .LSOverride 119 | 120 | # Icon must end with two \r 121 | Icon 122 | 123 | # Thumbnails 124 | ._* 125 | 126 | # Files that might appear in the root of a volume 127 | .DocumentRevisions-V100 128 | .fseventsd 129 | .Spotlight-V100 130 | .TemporaryItems 131 | .Trashes 132 | .VolumeIcon.icns 133 | .com.apple.timemachine.donotpresent 134 | 135 | # Directories potentially created on remote AFP share 136 | .AppleDB 137 | .AppleDesktop 138 | Network Trash Folder 139 | Temporary Items 140 | .apdisk 141 | 142 | /.idea/ 143 | -------------------------------------------------------------------------------- /.idea/.gitignore: -------------------------------------------------------------------------------- 1 | # Default ignored files 2 | /shelf/ 3 | /workspace.xml 4 | # Datasource local storage ignored files 5 | /dataSources/ 6 | /dataSources.local.xml 7 | # Editor-based HTTP Client requests 8 | /httpRequests/ 9 | -------------------------------------------------------------------------------- /.idea/codeStyles/Project.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 6 | 7 | -------------------------------------------------------------------------------- /.idea/codeStyles/codeStyleConfig.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 5 | -------------------------------------------------------------------------------- /.idea/encodings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /.idea/jwt-heartbreaker.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 6 | 7 | 12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /.idea/modules.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | pingvin 8 | jwt-heartbreaker 9 | 1.0-SNAPSHOT 10 | 11 | 12 | 13 | net.portswigger.burp.extender 14 | burp-extender-api 15 | 1.7.13 16 | 17 | 18 | 19 | com.auth0 20 | java-jwt 21 | 3.1.0 22 | 23 | 24 | commons-lang 25 | commons-lang 26 | 2.6 27 | 28 | 29 | com.eclipsesource.minimal-json 30 | minimal-json 31 | 0.9.4 32 | 33 | 34 | org.projectlombok 35 | lombok 36 | 1.18.12 37 | 38 | 39 | 40 | 41 | 42 | 43 | maven-compiler-plugin 44 | 3.1 45 | 46 | 1.8 47 | 1.8 48 | 49 | 50 | 51 | maven-assembly-plugin 52 | 3.3.0 53 | 54 | 55 | jar-with-dependencies 56 | 57 | 58 | 59 | 60 | make-assembly 61 | package 62 | 63 | single 64 | 65 | 66 | 67 | 68 | 69 | 70 | -------------------------------------------------------------------------------- /src/main/java/burp/BurpExtender.java: -------------------------------------------------------------------------------- 1 | package burp; 2 | 3 | import pingvin.JwtKeyProvider; 4 | import pingvin.JwtPublicSecretsTab; 5 | import pingvin.JwtScannerCheck; 6 | import pingvin.tokenposition.Config; 7 | 8 | import java.io.PrintWriter; 9 | 10 | public class BurpExtender implements IBurpExtender { 11 | 12 | public void registerExtenderCallbacks(IBurpExtenderCallbacks callbacks) { 13 | Config.stdout = new PrintWriter(callbacks.getStdout(), true); 14 | Config.stderr = new PrintWriter(callbacks.getStderr(), true); 15 | 16 | Config.loadConfig(); 17 | JwtKeyProvider.loadKeys(); 18 | 19 | callbacks.setExtensionName("JWT heartbreaker"); 20 | 21 | JwtPublicSecretsTab jwtPublicSecretsTab = new JwtPublicSecretsTab(callbacks); 22 | callbacks.addSuiteTab(jwtPublicSecretsTab); 23 | 24 | JwtScannerCheck jwtScannerCheck = new JwtScannerCheck(callbacks); 25 | callbacks.registerScannerCheck(jwtScannerCheck); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/pingvin/JwtKeyProvider.java: -------------------------------------------------------------------------------- 1 | package pingvin; 2 | 3 | import lombok.Getter; 4 | import lombok.SneakyThrows; 5 | import lombok.experimental.UtilityClass; 6 | import pingvin.tokenposition.Config; 7 | 8 | import java.net.URL; 9 | import java.util.*; 10 | 11 | @UtilityClass 12 | public class JwtKeyProvider { 13 | 14 | @Getter 15 | private static Map secrets; 16 | @Getter 17 | private static Set keys; 18 | 19 | @SneakyThrows 20 | public static void loadKeys() { 21 | secrets = new HashMap<>(); 22 | keys = new HashSet<>(); 23 | for (String secret : Config.secrets) { 24 | final Set tempKeys = new HashSet<>(); 25 | final URL url = new URL(secret); 26 | final Scanner sc = new Scanner(url.openStream()); 27 | 28 | while (sc.hasNextLine()) { 29 | tempKeys.add(sc.nextLine()); 30 | } 31 | secrets.put(url, tempKeys.size()); 32 | keys.addAll(tempKeys); 33 | } 34 | } 35 | 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/pingvin/JwtListener.java: -------------------------------------------------------------------------------- 1 | package pingvin; 2 | 3 | import burp.*; 4 | import com.auth0.jwt.JWT; 5 | import com.auth0.jwt.JWTVerifier; 6 | import com.auth0.jwt.exceptions.JWTVerificationException; 7 | import pingvin.tokenposition.CustomJWToken; 8 | import pingvin.tokenposition.ITokenPosition; 9 | import pingvin.tokenposition.Output; 10 | import pingvin.tokenposition.algorithm.AlgorithmLinker; 11 | 12 | import java.io.UnsupportedEncodingException; 13 | import java.net.MalformedURLException; 14 | import java.net.URL; 15 | 16 | public class JwtListener implements IHttpListener { 17 | 18 | private final IExtensionHelpers helpers; 19 | private final IBurpExtenderCallbacks callbacks; 20 | 21 | public JwtListener(IBurpExtenderCallbacks callbacks) { 22 | this.helpers = callbacks.getHelpers(); 23 | this.callbacks = callbacks; 24 | } 25 | 26 | public void processHttpMessage(int toolFlag, boolean isRequest, IHttpRequestResponse messageInfo) { 27 | byte[] content = isRequest ? messageInfo.getRequest() : messageInfo.getResponse(); 28 | 29 | final ITokenPosition token = ITokenPosition.findTokenPositionImplementation(content, isRequest, helpers); 30 | if (token == null) { 31 | return; 32 | } 33 | 34 | String tokenWithoutPrefix = lal(token.getToken()); 35 | 36 | IScanIssue[] currentIssues = callbacks.getScanIssues(null); 37 | for (IScanIssue currentIssue : currentIssues) { 38 | if (currentIssue.getIssueDetail() != null && currentIssue.getIssueDetail().contains(tokenWithoutPrefix)) { 39 | // messageInfo.setHighlight("blue"); 40 | return; 41 | } 42 | } 43 | 44 | String curAlgo = new CustomJWToken(tokenWithoutPrefix).getAlgorithm(); 45 | for (String key : JwtKeyProvider.getKeys()) { 46 | try { 47 | JWTVerifier verifier = JWT.require(AlgorithmLinker.getVerifierAlgorithm(curAlgo, key)).build(); 48 | verifier.verify(tokenWithoutPrefix); 49 | 50 | // messageInfo.setComment(String.format("JWT Key: %s", key)); 51 | // messageInfo.setHighlight("blue"); 52 | 53 | JwtTokenKeyScannerIssue jwtTokenKeyScannerIssue = new JwtTokenKeyScannerIssue() 54 | .setUrl(new URL("https://url")) 55 | .setIssueName("Found public JWT secret") 56 | .setIssueType(0x00200200) 57 | .setSeverity("High") 58 | .setConfidence("Certain") 59 | .setIssueBackground(null) 60 | .setRemediationBackground(null) 61 | .setIssueDetail(String.format("Token: %s%nKey: %s", tokenWithoutPrefix, key)) 62 | .setRemediationDetail("Change JWT sing key") 63 | .setHttpMessages(new IHttpRequestResponse[]{messageInfo}) 64 | .setHttpService(messageInfo.getHttpService()); 65 | callbacks.addScanIssue(jwtTokenKeyScannerIssue); 66 | return; 67 | } catch (UnsupportedEncodingException | MalformedURLException e) { 68 | Output.output("Verification failed (" + e.getMessage() + ")"); 69 | } catch (JWTVerificationException e) { 70 | // do nothing 71 | } 72 | } 73 | } 74 | 75 | private String lal(String jwts) { 76 | jwts = jwts.replace("Authorization:", ""); 77 | jwts = jwts.replace("Bearer", ""); 78 | jwts = jwts.replace("Set-Cookie: ", ""); 79 | jwts = jwts.replace("Cookie: ", ""); 80 | jwts = jwts.replaceAll("\\s", ""); 81 | 82 | return jwts; 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /src/main/java/pingvin/JwtPublicSecretsTab.java: -------------------------------------------------------------------------------- 1 | package pingvin; 2 | 3 | import burp.IBurpExtenderCallbacks; 4 | import burp.ITab; 5 | import lombok.SneakyThrows; 6 | import org.apache.commons.lang.StringUtils; 7 | import pingvin.tokenposition.Config; 8 | 9 | import javax.swing.*; 10 | import javax.swing.event.TableModelEvent; 11 | import javax.swing.table.DefaultTableModel; 12 | import java.awt.*; 13 | import java.awt.event.ActionEvent; 14 | import java.net.URI; 15 | import java.net.URL; 16 | import java.util.ArrayList; 17 | import java.util.List; 18 | import java.util.Map; 19 | 20 | public class JwtPublicSecretsTab implements ITab { 21 | 22 | final JPanel panel; 23 | final JTable urlsTable; 24 | final DefaultTableModel urlsTableModel; 25 | 26 | @SneakyThrows 27 | public JwtPublicSecretsTab(IBurpExtenderCallbacks callbacks) { 28 | panel = new JPanel(); 29 | panel.setLayout(new BorderLayout()); 30 | 31 | urlsTableModel = new DefaultTableModel(new String[]{"URL", "Count"}, 0) { 32 | @Override 33 | public boolean isCellEditable(int row, int column) { 34 | if (column == 1) { 35 | return false; 36 | } 37 | 38 | return super.isCellEditable(row, column); 39 | } 40 | }; 41 | final Map keys = JwtKeyProvider.getSecrets(); 42 | for (Map.Entry key : keys.entrySet()) { 43 | urlsTableModel.addRow(new Object[]{key.getKey().toString(), key.getValue()}); 44 | } 45 | urlsTableModel.addRow(new String[]{null, null}); 46 | 47 | urlsTable = new JTable(urlsTableModel); 48 | urlsTableModel.addTableModelListener(e -> { 49 | if (e.getType() == TableModelEvent.UPDATE && e.getColumn() == 0) { 50 | Object valueAt = urlsTableModel.getValueAt(e.getFirstRow(), 0); 51 | if (valueAt == null || StringUtils.isBlank((String) valueAt)) { 52 | urlsTableModel.removeRow(e.getFirstRow()); 53 | } 54 | 55 | Object valueAt1 = urlsTableModel.getValueAt(urlsTableModel.getRowCount() - 1, 0); 56 | if (valueAt1 != null && StringUtils.isNotBlank((String) valueAt1)) { 57 | urlsTableModel.addRow(new String[]{null, null}); 58 | } 59 | } 60 | }); 61 | 62 | final JScrollPane tableScrollPane = new JScrollPane(urlsTable); 63 | panel.add(tableScrollPane, BorderLayout.CENTER); 64 | 65 | final JPanel updateAndCount = new JPanel(new BorderLayout()); 66 | final JButton updateButton = new JButton(); 67 | updateButton.setText("Update"); 68 | updateButton.addActionListener(this::update); 69 | updateAndCount.add(updateButton, BorderLayout.CENTER); 70 | 71 | final JPanel linksPanel = new JPanel(new FlowLayout()); 72 | final JButton sourceButton = new JButton(); 73 | sourceButton.setText("Source Code"); 74 | final URI sourceUri = new URI("https://github.com/Wallarm/jwt-heartbreaker"); 75 | sourceButton.addActionListener(e -> openLink(sourceUri)); 76 | linksPanel.add(sourceButton); 77 | 78 | final JButton releaseNotesButton = new JButton(); 79 | releaseNotesButton.setText("Release Notes"); 80 | final URI releaseNotesUri = new URI("https://lab.wallarm.com/jwt-heartbreaker/"); 81 | releaseNotesButton.addActionListener(e -> openLink(releaseNotesUri)); 82 | linksPanel.add(releaseNotesButton); 83 | updateAndCount.add(linksPanel, BorderLayout.EAST); 84 | panel.add(updateAndCount, BorderLayout.SOUTH); 85 | 86 | callbacks.customizeUiComponent(panel); 87 | } 88 | 89 | @SneakyThrows 90 | private void openLink(final URI uri) { 91 | if (Desktop.isDesktopSupported()) { 92 | Desktop.getDesktop().browse(uri); 93 | } 94 | } 95 | 96 | @SneakyThrows 97 | private void update(ActionEvent e) { 98 | int lastRow = urlsTableModel.getRowCount(); 99 | final List secrets = new ArrayList<>(); 100 | for (int i = 0; i < lastRow; i++) { 101 | Object valueAt = urlsTableModel.getValueAt(i, 0); 102 | if (valueAt != null && StringUtils.isNotBlank((String) valueAt)) { 103 | try { 104 | new URL((String) valueAt); 105 | } catch (Exception ex) { 106 | continue; 107 | } 108 | secrets.add((String) valueAt); 109 | } 110 | } 111 | 112 | Config.updateSecrets(secrets); 113 | Config.loadConfig(); 114 | JwtKeyProvider.loadKeys(); 115 | 116 | urlsTableModel.getDataVector().clear(); 117 | urlsTableModel.fireTableRowsDeleted(0, lastRow - 1); 118 | 119 | final Map keys = JwtKeyProvider.getSecrets(); 120 | for (Map.Entry key : keys.entrySet()) { 121 | urlsTableModel.addRow(new Object[]{key.getKey().toString(), key.getValue()}); 122 | } 123 | urlsTableModel.addRow(new String[]{null, null}); 124 | } 125 | 126 | @Override 127 | public String getTabCaption() { 128 | return "JWT heartbreaker"; 129 | } 130 | 131 | @Override 132 | public Component getUiComponent() { 133 | return panel; 134 | } 135 | 136 | } 137 | -------------------------------------------------------------------------------- /src/main/java/pingvin/JwtScannerCheck.java: -------------------------------------------------------------------------------- 1 | package pingvin; 2 | 3 | import burp.*; 4 | import com.auth0.jwt.JWT; 5 | import com.auth0.jwt.JWTVerifier; 6 | import com.auth0.jwt.exceptions.JWTVerificationException; 7 | import pingvin.tokenposition.CustomJWToken; 8 | import pingvin.tokenposition.ITokenPosition; 9 | import pingvin.tokenposition.Output; 10 | import pingvin.tokenposition.algorithm.AlgorithmLinker; 11 | 12 | import java.io.UnsupportedEncodingException; 13 | import java.util.Collections; 14 | import java.util.List; 15 | import java.util.Set; 16 | import java.util.concurrent.ConcurrentHashMap; 17 | 18 | public class JwtScannerCheck implements IScannerCheck { 19 | 20 | private final IExtensionHelpers helpers; 21 | private final Set checkedTokens; 22 | 23 | public JwtScannerCheck(IBurpExtenderCallbacks callbacks) { 24 | this.helpers = callbacks.getHelpers(); 25 | this.checkedTokens = ConcurrentHashMap.newKeySet(); 26 | } 27 | 28 | private String lal(String jwts) { 29 | jwts = jwts.replace("Authorization:", ""); 30 | jwts = jwts.replace("Bearer", ""); 31 | jwts = jwts.replace("Set-Cookie: ", ""); 32 | jwts = jwts.replace("Cookie: ", ""); 33 | jwts = jwts.replaceAll("\\s", ""); 34 | 35 | return jwts; 36 | } 37 | 38 | @Override 39 | public List doPassiveScan(IHttpRequestResponse baseRequestResponse) { 40 | JwtTokenKeyScannerIssue jwtTokenKeyScannerIssues = lal2(baseRequestResponse, true); 41 | if (jwtTokenKeyScannerIssues != null) { 42 | return Collections.singletonList(jwtTokenKeyScannerIssues); 43 | } 44 | JwtTokenKeyScannerIssue jwtTokenKeyScannerIssue = lal2(baseRequestResponse, false); 45 | if (jwtTokenKeyScannerIssue != null) { 46 | return Collections.singletonList(jwtTokenKeyScannerIssue); 47 | } 48 | 49 | return null; 50 | } 51 | 52 | private JwtTokenKeyScannerIssue lal2(IHttpRequestResponse baseRequestResponse, boolean isRequest) { 53 | final ITokenPosition token = ITokenPosition.findTokenPositionImplementation(isRequest ? baseRequestResponse.getRequest() : baseRequestResponse.getResponse(), isRequest, helpers); 54 | if (token == null) { 55 | return null; 56 | } 57 | 58 | String tokenWithoutPrefix = lal(token.getToken()); 59 | 60 | if (checkedTokens.contains(tokenWithoutPrefix)) { 61 | return null; 62 | } 63 | /* IScanIssue[] currentIssues = callbacks.getScanIssues(null); 64 | for (IScanIssue currentIssue : currentIssues) { 65 | if (currentIssue.getIssueDetail() != null && currentIssue.getIssueDetail().contains(tokenWithoutPrefix)) { 66 | return null; 67 | } 68 | }*/ 69 | 70 | String curAlgo = new CustomJWToken(tokenWithoutPrefix).getAlgorithm(); 71 | for (String key : JwtKeyProvider.getKeys()) { 72 | try { 73 | JWTVerifier verifier = JWT.require(AlgorithmLinker.getVerifierAlgorithm(curAlgo, key)).build(); 74 | verifier.verify(tokenWithoutPrefix); 75 | 76 | JwtTokenKeyScannerIssue jwtTokenKeyScannerIssue = new JwtTokenKeyScannerIssue() 77 | .setUrl(helpers.analyzeRequest(baseRequestResponse).getUrl()) 78 | .setIssueName("Found public JWT secret") 79 | .setIssueType(0x00200200) 80 | .setSeverity("High") 81 | .setConfidence("Certain") 82 | .setIssueBackground(null) 83 | .setRemediationBackground(null) 84 | .setIssueDetail(String.format("Token: %s%nKey: %s", tokenWithoutPrefix, key)) 85 | .setRemediationDetail("Change JWT sing key") 86 | .setHttpMessages(new IHttpRequestResponse[]{baseRequestResponse}) 87 | .setHttpService(baseRequestResponse.getHttpService()); 88 | if (checkedTokens.contains(tokenWithoutPrefix)) { 89 | return null; 90 | } 91 | checkedTokens.add(tokenWithoutPrefix); 92 | return jwtTokenKeyScannerIssue; 93 | } catch (UnsupportedEncodingException e) { 94 | Output.output("Verification failed (" + e.getMessage() + ")"); 95 | } catch (JWTVerificationException e) { 96 | // do nothing 97 | } 98 | } 99 | 100 | return null; 101 | } 102 | 103 | @Override 104 | public List doActiveScan(IHttpRequestResponse baseRequestResponse, IScannerInsertionPoint insertionPoint) { 105 | return null; 106 | } 107 | 108 | @Override 109 | public int consolidateDuplicateIssues(IScanIssue existingIssue, IScanIssue newIssue) { 110 | return 0; 111 | } 112 | } 113 | -------------------------------------------------------------------------------- /src/main/java/pingvin/JwtTokenKeyScannerIssue.java: -------------------------------------------------------------------------------- 1 | package pingvin; 2 | 3 | import burp.IHttpRequestResponse; 4 | import burp.IHttpService; 5 | import burp.IScanIssue; 6 | import lombok.Data; 7 | import lombok.experimental.Accessors; 8 | 9 | import java.net.URL; 10 | 11 | @Data 12 | @Accessors(chain = true) 13 | public class JwtTokenKeyScannerIssue implements IScanIssue { 14 | 15 | private URL url; 16 | private String issueName; 17 | private int issueType; 18 | private String severity; 19 | private String confidence; 20 | private String issueBackground; 21 | private String remediationBackground; 22 | private String issueDetail; 23 | private String remediationDetail; 24 | private IHttpRequestResponse[] httpMessages; 25 | private IHttpService httpService; 26 | 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/pingvin/tokenposition/AuthorizationBearerHeader.java: -------------------------------------------------------------------------------- 1 | package pingvin.tokenposition; 2 | 3 | import java.util.List; 4 | 5 | // finds and replaces JWT's in authorization headers 6 | public class AuthorizationBearerHeader extends ITokenPosition { 7 | private String selectedKeyword; 8 | private Integer headerIndex; 9 | private final List headers; 10 | 11 | public AuthorizationBearerHeader(List headers, String bodyP) { 12 | this.headers = headers; 13 | } 14 | 15 | public boolean positionFound() { 16 | for (int counter = 0; counter < headers.size(); counter++) { 17 | if (headerContainsaKeyWordAndIsJWT(headers.get(counter), Config.jwtKeywords)) { 18 | this.headerIndex = counter; 19 | return true; 20 | } 21 | } 22 | return false; 23 | } 24 | 25 | private boolean headerContainsaKeyWordAndIsJWT(String header, List jwtKeywords) { 26 | for (String keyword : jwtKeywords) { 27 | if (header.startsWith(keyword)) { 28 | String jwt = header.replace(keyword, "").trim(); 29 | if (CustomJWToken.isValidJWT(jwt)) { 30 | this.selectedKeyword = keyword; 31 | return true; 32 | } 33 | } 34 | } 35 | return false; 36 | } 37 | 38 | public String getToken() { 39 | if (this.headerIndex == null) { 40 | return ""; 41 | } 42 | return headers.get(this.headerIndex).substring(this.selectedKeyword.length() + 1); 43 | } 44 | 45 | } 46 | -------------------------------------------------------------------------------- /src/main/java/pingvin/tokenposition/Body.java: -------------------------------------------------------------------------------- 1 | package pingvin.tokenposition; 2 | 3 | import com.eclipsesource.json.Json; 4 | import com.eclipsesource.json.JsonObject; 5 | import org.apache.commons.lang.StringUtils; 6 | 7 | import java.util.List; 8 | import java.util.regex.Pattern; 9 | 10 | //finds and replaces JWT's in HTTP bodies 11 | public class Body extends ITokenPosition { 12 | private String token; 13 | private boolean found = false; 14 | private String body; 15 | 16 | public Body(List headersP, String bodyP) { 17 | body = bodyP; 18 | } 19 | 20 | @Override 21 | public boolean positionFound() { 22 | KeyValuePair postJWT = getJWTFromBody(); 23 | if (postJWT != null) { 24 | found = true; 25 | token = postJWT.getValue(); 26 | return true; 27 | } 28 | return false; 29 | } 30 | 31 | public KeyValuePair getJWTFromBody() { 32 | KeyValuePair ret; 33 | if ((ret = getJWTFromBodyWithParameters()) != null) { 34 | return ret; 35 | } else if ((ret = getJWTFromBodyWithJson()) != null) { 36 | return ret; 37 | } else { 38 | return getJWTFromBodyWithoutParametersOrJSON(); 39 | } 40 | } 41 | 42 | private KeyValuePair getJWTFromBodyWithoutParametersOrJSON() { 43 | String[] split = StringUtils.split(body); 44 | for (String strg : split) { 45 | if (TokenCheck.isValidJWT(strg)) { 46 | return new KeyValuePair("", strg); 47 | } 48 | } 49 | return null; 50 | } 51 | 52 | private KeyValuePair getJWTFromBodyWithJson() { 53 | JsonObject obj; 54 | try { 55 | if (body.length() < 2) { 56 | return null; 57 | } 58 | obj = Json.parse(body).asObject(); 59 | } catch (Exception e) { 60 | return null; 61 | } 62 | return lookForJwtInJsonObject(obj); 63 | } 64 | 65 | private KeyValuePair lookForJwtInJsonObject(JsonObject object) { 66 | KeyValuePair rec; 67 | for (String name : object.names()) { 68 | if (object.get(name).isString()) { 69 | if (TokenCheck.isValidJWT(object.get(name).asString())) { 70 | return new KeyValuePair(name, object.get(name).asString().trim()); 71 | } 72 | } else if (object.get(name).isObject()) { 73 | if ((rec = lookForJwtInJsonObject(object.get(name).asObject())) != null) { 74 | return rec; 75 | } 76 | } 77 | } 78 | return null; 79 | } 80 | 81 | 82 | private KeyValuePair getJWTFromBodyWithParameters() { 83 | int from = 0; 84 | int index = body.indexOf("&") == -1 ? body.length() : body.indexOf("&"); 85 | int parameterCount = StringUtils.countMatches(body, "&") + 1; 86 | 87 | for (int i = 0; i < parameterCount; i++) { 88 | String parameter = body.substring(from, index); 89 | parameter = parameter.replace("&", ""); 90 | 91 | String[] parameterSplit = parameter.split(Pattern.quote("=")); 92 | if (parameterSplit.length > 1) { 93 | String name = parameterSplit[0]; 94 | String value = parameterSplit[1]; 95 | if (TokenCheck.isValidJWT(value)) { 96 | return new KeyValuePair(name, value); 97 | } 98 | 99 | from = index; 100 | index = body.indexOf("&", index + 1); 101 | if (index == -1) { 102 | index = body.length(); 103 | } 104 | } 105 | } 106 | return null; 107 | } 108 | 109 | @Override 110 | public String getToken() { 111 | return found ? token : ""; 112 | } 113 | 114 | } -------------------------------------------------------------------------------- /src/main/java/pingvin/tokenposition/Config.java: -------------------------------------------------------------------------------- 1 | package pingvin.tokenposition; 2 | 3 | import com.eclipsesource.json.*; 4 | 5 | import java.io.File; 6 | import java.io.IOException; 7 | import java.io.PrintWriter; 8 | import java.nio.file.Files; 9 | import java.nio.file.Paths; 10 | import java.util.ArrayList; 11 | import java.util.Arrays; 12 | import java.util.List; 13 | 14 | public class Config { 15 | 16 | public static PrintWriter stdout; 17 | public static PrintWriter stderr; 18 | 19 | private static JsonObject configJO; 20 | 21 | public static List jwtKeywords = Arrays.asList("Authorization: Bearer", "Authorization: bearer", "authorization: Bearer", "authorization: bearer"); 22 | public static List tokenKeywords = Arrays.asList("id_token", "ID_TOKEN", "access_token", "token"); 23 | public static List secrets = Arrays.asList("https://raw.githubusercontent.com/wallarm/jwt-secrets/master/jwt.secrets.list"); 24 | 25 | public static String configName = "config.json"; 26 | public static String configFolderName = ".JWTheartbreaker"; 27 | public static String configPath = System.getProperty("user.home") + File.separator + configFolderName + File.separator + configName; 28 | 29 | public static void loadConfig() { 30 | File configFile = new File(configPath); 31 | 32 | if (!configFile.getParentFile().exists()) { 33 | Output.output("Config file directory '" + configFolderName + "' does not exist - creating it"); 34 | configFile.getParentFile().mkdir(); 35 | } 36 | 37 | if (!configFile.exists()) { 38 | Output.output("Config file '" + configPath + "' does not exist - creating it"); 39 | try { 40 | configFile.createNewFile(); 41 | } catch (IOException e) { 42 | Output.outputError("Error creating config file '" + configPath + "' - message:" + e.getMessage() + " - cause:" + e.getCause().toString()); 43 | return; 44 | } 45 | String defaultConfigJSONRaw = generateDefaultConfigFile(); 46 | try { 47 | Files.write(Paths.get(configPath), defaultConfigJSONRaw.getBytes()); 48 | } catch (IOException e) { 49 | Output.outputError("Error writing config file '" + configPath + "' - message:" + e.getMessage() + " - cause:" + e.getCause().toString()); 50 | } 51 | } 52 | 53 | try { 54 | String configRaw = new String(Files.readAllBytes(Paths.get(configPath))); 55 | configJO = Json.parse(configRaw).asObject(); 56 | 57 | JsonArray secretsJA = configJO.get("secrets").asArray(); 58 | secrets = new ArrayList<>(); 59 | for (JsonValue jsonValue : secretsJA) { 60 | secrets.add(jsonValue.asString()); 61 | } 62 | 63 | JsonArray jwtKeywordsJA = configJO.get("jwtKeywords").asArray(); 64 | jwtKeywords = new ArrayList(); 65 | for (JsonValue jwtKeyword : jwtKeywordsJA) { 66 | jwtKeywords.add(jwtKeyword.asString()); 67 | } 68 | 69 | JsonArray tokenKeywordsJA = configJO.get("tokenKeywords").asArray(); 70 | tokenKeywords = new ArrayList(); 71 | for (JsonValue tokenKeyword : tokenKeywordsJA) { 72 | tokenKeywords.add(tokenKeyword.asString()); 73 | } 74 | 75 | } catch (IOException e) { 76 | Output.outputError("Error loading config file '" + configPath + "' - message:" + e.getMessage() + " - cause:" + e.getCause().toString()); 77 | } 78 | } 79 | 80 | private static String generateDefaultConfigFile() { 81 | configJO = new JsonObject(); 82 | 83 | JsonArray secretsJA = new JsonArray(); 84 | for (String secret : secrets) { 85 | secretsJA.add(secret); 86 | } 87 | 88 | JsonArray jwtKeywordsJA = new JsonArray(); 89 | for (String jwtKeyword : jwtKeywords) { 90 | jwtKeywordsJA.add(jwtKeyword); 91 | } 92 | 93 | JsonArray tokenKeywordsJA = new JsonArray(); 94 | for (String tokenKeyword : tokenKeywords) { 95 | tokenKeywordsJA.add(tokenKeyword); 96 | } 97 | 98 | configJO.add("secrets", secretsJA); 99 | configJO.add("jwtKeywords", jwtKeywordsJA); 100 | configJO.add("tokenKeywords", tokenKeywordsJA); 101 | 102 | return configJO.toString(WriterConfig.PRETTY_PRINT); 103 | } 104 | 105 | public static void updateSecrets(List secrets) { 106 | JsonArray secretsJA = new JsonArray(); 107 | for (String secret : secrets) { 108 | secretsJA.add(secret); 109 | } 110 | 111 | configJO.set("secrets", secretsJA); 112 | 113 | try { 114 | Files.write(Paths.get(configPath), configJO.toString(WriterConfig.PRETTY_PRINT).getBytes()); 115 | } catch (IOException e) { 116 | Output.outputError("Error writing config file '" + configPath + "' - message:" + e.getMessage() + " - cause:" + e.getCause().toString()); 117 | } 118 | } 119 | } 120 | -------------------------------------------------------------------------------- /src/main/java/pingvin/tokenposition/Cookie.java: -------------------------------------------------------------------------------- 1 | package pingvin.tokenposition; 2 | 3 | import org.apache.commons.lang.StringUtils; 4 | 5 | import java.util.List; 6 | import java.util.regex.Pattern; 7 | 8 | //finds and replaces JWT's in cookies 9 | public class Cookie extends ITokenPosition { 10 | 11 | private boolean found; 12 | private String token; 13 | private List headers; 14 | 15 | public Cookie(List headersP, String bodyP) { 16 | headers = headersP; 17 | } 18 | 19 | @Override 20 | public boolean positionFound() { 21 | String jwt = findJWTInHeaders(headers); 22 | if (jwt != null) { 23 | found = true; 24 | token = jwt; 25 | return true; 26 | } 27 | return false; 28 | } 29 | 30 | // finds the first jwt in the set-cookie or cookie header(s) 31 | public String findJWTInHeaders(List headers) { 32 | for (String header : headers) { 33 | if (header.startsWith("Set-Cookie: ")) { 34 | String cookie = header.replace("Set-Cookie: ", ""); 35 | if (cookie.length() > 1 && cookie.contains("=")) { 36 | String value = cookie.split(Pattern.quote("="))[1]; 37 | int flagMarker = value.indexOf(";"); 38 | if (flagMarker != -1) { 39 | value = value.substring(0, flagMarker); 40 | } 41 | TokenCheck.isValidJWT(value); 42 | if (TokenCheck.isValidJWT(value)) { 43 | found = true; 44 | token = value; 45 | return value; 46 | } 47 | } 48 | } 49 | if (header.startsWith("Cookie: ")) { 50 | String cookieHeader = header.replace("Cookie: ", ""); 51 | cookieHeader = cookieHeader.endsWith(";") ? cookieHeader : cookieHeader + ";"; 52 | int from = 0; 53 | int index = cookieHeader.indexOf(";"); 54 | int cookieCount = StringUtils.countMatches(cookieHeader, ";"); 55 | for (int i = 0; i < cookieCount; i++) { 56 | String cookie = cookieHeader.substring(from, index); 57 | cookie = cookie.replace(";", ""); 58 | String[] cvp = cookie.split(Pattern.quote("=")); 59 | String value = cvp.length == 2 ? cvp[1] : ""; 60 | if (TokenCheck.isValidJWT(value)) { 61 | found = true; 62 | token = value; 63 | return value; 64 | } 65 | from = index; 66 | index = cookieHeader.indexOf(";", index + 1); 67 | if (index == -1) { 68 | index = cookieHeader.length(); 69 | } 70 | } 71 | } 72 | } 73 | return null; 74 | } 75 | 76 | @Override 77 | public String getToken() { 78 | return found ? token : ""; 79 | } 80 | 81 | } 82 | -------------------------------------------------------------------------------- /src/main/java/pingvin/tokenposition/CookieFlagWrapper.java: -------------------------------------------------------------------------------- 1 | package pingvin.tokenposition; 2 | 3 | public class CookieFlagWrapper { 4 | private final boolean secureFlag; 5 | private final boolean httpOnlyFlag; 6 | private final boolean isCookie; 7 | 8 | public CookieFlagWrapper(boolean isCookie, boolean secureFlag, boolean httpOnlyFlag) { 9 | this.isCookie = isCookie; 10 | this.secureFlag = secureFlag; 11 | this.httpOnlyFlag = httpOnlyFlag; 12 | } 13 | 14 | public boolean isCookie(){ 15 | return isCookie; 16 | } 17 | 18 | public boolean hasHttpOnlyFlag() { 19 | if(isCookie){ 20 | return httpOnlyFlag; 21 | } 22 | return false; 23 | } 24 | 25 | public boolean hasSecureFlag() { 26 | if(isCookie){ 27 | return secureFlag; 28 | } 29 | return false; 30 | } 31 | 32 | public String toHTMLString(){ 33 | if(!isCookie){ 34 | return ""; 35 | } 36 | String returnString="
"; 37 | if(!hasSecureFlag()){ 38 | returnString+="No secure flag set. Token may be transmitted by HTTP.
"; 39 | }else{ 40 | returnString+="Secure Flag set.
"; 41 | } 42 | if(!hasHttpOnlyFlag()){ 43 | returnString+="No HttpOnly flag set. Token may accessed by JavaScript (XSS)."; 44 | }else{ 45 | returnString+="HttpOnly Flag set."; 46 | } 47 | returnString+="
"; 48 | return returnString; 49 | } 50 | 51 | } 52 | -------------------------------------------------------------------------------- /src/main/java/pingvin/tokenposition/CustomJWToken.java: -------------------------------------------------------------------------------- 1 | package pingvin.tokenposition; 2 | 3 | import com.auth0.jwt.JWT; 4 | import com.auth0.jwt.exceptions.JWTDecodeException; 5 | import com.auth0.jwt.interfaces.Claim; 6 | import com.fasterxml.jackson.databind.JsonNode; 7 | import com.fasterxml.jackson.databind.ObjectMapper; 8 | import org.apache.commons.codec.binary.Base64; 9 | import org.apache.commons.codec.binary.StringUtils; 10 | 11 | import java.io.IOException; 12 | import java.nio.charset.StandardCharsets; 13 | import java.util.Date; 14 | import java.util.List; 15 | import java.util.Map; 16 | 17 | /* 18 | * This Class is implemented separately to get raw access to the content of the Tokens. 19 | * The JWTDecoder class cannot be extended because it is final 20 | */ 21 | 22 | public class CustomJWToken extends JWT { 23 | private String headerJson; 24 | private String payloadJson; 25 | private byte[] signature; 26 | 27 | public CustomJWToken(String token) { 28 | if (token != null) { 29 | final String[] parts = splitToken(token); 30 | try { 31 | headerJson = StringUtils.newStringUtf8(Base64.decodeBase64(parts[0])); 32 | payloadJson = StringUtils.newStringUtf8(Base64.decodeBase64(parts[1])); 33 | } catch (NullPointerException e) { 34 | Output.outputError("The UTF-8 Charset isn't initialized (" + e.getMessage() + ")"); 35 | } 36 | signature = Base64.decodeBase64(parts[2]); 37 | } 38 | } 39 | 40 | public String getHeaderJson() { 41 | return headerJson; 42 | } 43 | 44 | public String getPayloadJson() { 45 | return payloadJson; 46 | } 47 | 48 | public JsonNode getHeaderJsonNode() { 49 | ObjectMapper objectMapper = new ObjectMapper(); 50 | try { 51 | return objectMapper.readTree(getHeaderJson()); 52 | } catch (IOException e) { 53 | Output.outputError("IO exception reading json tree (" + e.getMessage() + ")"); 54 | return null; 55 | } 56 | } 57 | 58 | private String jsonMinify(String json) { 59 | try { 60 | String jsonMinify = new Minify().minify(json); 61 | return jsonMinify; 62 | } catch (Exception e) { 63 | Output.outputError("Could not minify json: " + e.getMessage()); 64 | return null; 65 | } 66 | } 67 | 68 | @Override 69 | public String getToken() { 70 | if (jsonMinify(getHeaderJson()) != null && jsonMinify(getPayloadJson()) != null) { 71 | String content = String.format("%s.%s", b64(jsonMinify(getHeaderJson())), b64(jsonMinify((getPayloadJson())))); 72 | String signatureEncoded = Base64.encodeBase64URLSafeString(this.signature); 73 | return String.format("%s.%s", content, signatureEncoded); 74 | } 75 | return null; 76 | } 77 | 78 | private String b64(String input) { 79 | return Base64.encodeBase64URLSafeString(input.getBytes(StandardCharsets.UTF_8)); 80 | } 81 | 82 | public static boolean isValidJWT(String token) { 83 | if (org.apache.commons.lang.StringUtils.countMatches(token, ".") != 2) { 84 | return false; 85 | } 86 | try { 87 | JWT.decode(token); 88 | return true; 89 | } catch (JWTDecodeException exception) { 90 | } 91 | return false; 92 | } 93 | 94 | // Method copied from: 95 | // https://github.com/auth0/java-jwt/blob/9148ca20adf679721591e1d012b7c6b8c4913d75/lib/src/main/java/com/auth0/jwt/TokenUtils.java#L14 96 | // Cannot be reused, it's visibility is protected. 97 | static String[] splitToken(String token) throws JWTDecodeException { 98 | String[] parts = token.split("\\."); 99 | if (parts.length == 2 && token.endsWith(".")) { 100 | // Tokens with alg='none' have empty String as Signature. 101 | parts = new String[]{parts[0], parts[1], ""}; 102 | } 103 | if (parts.length != 3) { 104 | throw new JWTDecodeException(String.format("The token was expected to have 3 parts, but got %s.", parts.length)); 105 | } 106 | return parts; 107 | } 108 | 109 | @Override 110 | public List getAudience() { 111 | throw new UnsupportedOperationException(); 112 | } 113 | 114 | @Override 115 | public Claim getClaim(String arg0) { 116 | throw new UnsupportedOperationException(); 117 | } 118 | 119 | @Override 120 | public Map getClaims() { 121 | throw new UnsupportedOperationException(); 122 | } 123 | 124 | @Override 125 | public Date getExpiresAt() { 126 | throw new UnsupportedOperationException(); 127 | } 128 | 129 | @Override 130 | public String getId() { 131 | throw new UnsupportedOperationException(); 132 | } 133 | 134 | @Override 135 | public Date getIssuedAt() { 136 | throw new UnsupportedOperationException(); 137 | } 138 | 139 | @Override 140 | public String getIssuer() { 141 | throw new UnsupportedOperationException(); 142 | } 143 | 144 | @Override 145 | public Date getNotBefore() { 146 | throw new UnsupportedOperationException(); 147 | } 148 | 149 | @Override 150 | public String getSubject() { 151 | throw new UnsupportedOperationException(); 152 | } 153 | 154 | @Override 155 | public String getAlgorithm() { 156 | String algorithm = ""; 157 | try { 158 | algorithm = getHeaderJsonNode().get("alg").asText(); 159 | } catch (Exception e) { 160 | } 161 | return algorithm; 162 | } 163 | 164 | @Override 165 | public String getContentType() { 166 | return getHeaderJsonNode().get("typ").asText(); 167 | } 168 | 169 | @Override 170 | public Claim getHeaderClaim(String arg0) { 171 | throw new UnsupportedOperationException(); 172 | } 173 | 174 | @Override 175 | public String getKeyId() { 176 | throw new UnsupportedOperationException(); 177 | } 178 | 179 | @Override 180 | public String getType() { 181 | throw new UnsupportedOperationException(); 182 | } 183 | 184 | @Override 185 | public String getSignature() { 186 | return Base64.encodeBase64URLSafeString(this.signature); 187 | } 188 | 189 | } 190 | -------------------------------------------------------------------------------- /src/main/java/pingvin/tokenposition/Dummy.java: -------------------------------------------------------------------------------- 1 | package pingvin.tokenposition; 2 | 3 | public class Dummy extends ITokenPosition { 4 | 5 | @Override 6 | public boolean positionFound() { 7 | return false; 8 | } 9 | 10 | @Override 11 | public String getToken() { 12 | return "e30=.e30=."; 13 | } 14 | 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/pingvin/tokenposition/ITokenPosition.java: -------------------------------------------------------------------------------- 1 | package pingvin.tokenposition; 2 | 3 | import burp.IExtensionHelpers; 4 | import burp.IRequestInfo; 5 | import burp.IResponseInfo; 6 | 7 | import java.util.Arrays; 8 | import java.util.List; 9 | 10 | public abstract class ITokenPosition { 11 | 12 | protected IExtensionHelpers helpers; 13 | protected byte[] message; 14 | protected boolean isRequest; 15 | 16 | public abstract boolean positionFound(); 17 | 18 | public abstract String getToken(); 19 | 20 | public void setMessage(byte[] message, boolean isRequest) { 21 | this.message = message; 22 | this.isRequest = isRequest; 23 | } 24 | 25 | public void setHelpers(IExtensionHelpers helpers) { 26 | this.helpers = helpers; 27 | } 28 | 29 | public static ITokenPosition findTokenPositionImplementation(byte[] content, boolean isRequest, IExtensionHelpers helpers) { 30 | List> implementations = Arrays.asList(AuthorizationBearerHeader.class, PostBody.class, Cookie.class, Body.class); 31 | if (content == null) { 32 | return new Dummy(); 33 | } 34 | for (Class implClass : implementations) { 35 | try { 36 | List headers; 37 | int bodyOffset; 38 | if (isRequest) { 39 | IRequestInfo requestInfo = helpers.analyzeRequest(content); 40 | headers = requestInfo.getHeaders(); 41 | bodyOffset = requestInfo.getBodyOffset(); 42 | } else { 43 | IResponseInfo responseInfo = helpers.analyzeResponse(content); 44 | headers = responseInfo.getHeaders(); 45 | bodyOffset = responseInfo.getBodyOffset(); 46 | } 47 | String body = new String(Arrays.copyOfRange(content, bodyOffset, content.length)); 48 | ITokenPosition impl = (ITokenPosition) implClass.getConstructors()[0].newInstance(headers, body); 49 | 50 | impl.setHelpers(helpers); 51 | impl.setMessage(content, isRequest); 52 | if (impl.positionFound()) { 53 | return impl; 54 | } 55 | } catch (Exception e) { 56 | // sometimes 'isEnabled' is called in order to build the views 57 | // before an actual request / response passes through - in that case 58 | // it is not worth reporting 59 | if (!e.getMessage().equals("Request cannot be null") && !e.getMessage().equals("1")) { 60 | Output.outputError(e.getMessage()); 61 | } 62 | return null; 63 | } 64 | } 65 | return null; 66 | } 67 | 68 | } 69 | -------------------------------------------------------------------------------- /src/main/java/pingvin/tokenposition/KeyValuePair.java: -------------------------------------------------------------------------------- 1 | package pingvin.tokenposition; 2 | 3 | public class KeyValuePair { 4 | private String name; 5 | private String value; 6 | 7 | public KeyValuePair(String name, String value) { 8 | this.setName(name); 9 | this.setValue(value); 10 | } 11 | 12 | public String getName() { 13 | return name; 14 | } 15 | 16 | public void setName(String name) { 17 | this.name = name; 18 | } 19 | 20 | public String getValue() { 21 | return value; 22 | } 23 | 24 | public void setValue(String value) { 25 | this.value = value; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/pingvin/tokenposition/Minify.java: -------------------------------------------------------------------------------- 1 | package pingvin.tokenposition; 2 | 3 | import java.io.*; 4 | import java.nio.charset.StandardCharsets; 5 | 6 | /** 7 | * @author Andrea Di Cesare 8 | *

9 | * ---------------------- Minify.java 2015-10-04 ---------------------- 10 | *

11 | * Copyright (c) 2015 Charles Bihis (www.whoischarles.com) 12 | *

13 | * This work is an adaptation of JSMin.java published by John Reilly which is a 14 | * translation from C to Java of jsmin.c published by Douglas Crockford. 15 | * Permission is hereby granted to use this Java version under the same 16 | * conditions as the original jsmin.c on which all of these derivatives are 17 | * based. 18 | *

19 | *

20 | *

21 | * --------------------- JSMin.java 2006-02-13 --------------------- 22 | *

23 | * Copyright (c) 2006 John Reilly (www.inconspicuous.org) 24 | *

25 | * This work is a translation from C to Java of jsmin.c published by Douglas 26 | * Crockford. Permission is hereby granted to use the Java version under the 27 | * same conditions as the jsmin.c on which it is based. 28 | *

29 | *

30 | *

31 | * ------------------ jsmin.c 2003-04-21 ------------------ 32 | *

33 | * Copyright (c) 2002 Douglas Crockford (www.crockford.com) 34 | *

35 | * Permission is hereby granted, free of charge, to any person obtaining a copy 36 | * of this software and associated documentation files (the "Software"), to deal 37 | * in the Software without restriction, including without limitation the rights 38 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 39 | * copies of the Software, and to permit persons to whom the Software is 40 | * furnished to do so, subject to the following conditions: 41 | *

42 | * The above copyright notice and this permission notice shall be included in 43 | * all copies or substantial portions of the Software. 44 | *

45 | * The Software shall be used for Good, not Evil. 46 | *

47 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 48 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 49 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 50 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 51 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 52 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 53 | * SOFTWARE. 54 | */ 55 | /** 56 | * ---------------------- Minify.java 2015-10-04 ---------------------- 57 | * 58 | * Copyright (c) 2015 Charles Bihis (www.whoischarles.com) 59 | * 60 | * This work is an adaptation of JSMin.java published by John Reilly which is a 61 | * translation from C to Java of jsmin.c published by Douglas Crockford. 62 | * Permission is hereby granted to use this Java version under the same 63 | * conditions as the original jsmin.c on which all of these derivatives are 64 | * based. 65 | * 66 | * 67 | * 68 | * --------------------- JSMin.java 2006-02-13 --------------------- 69 | * 70 | * Copyright (c) 2006 John Reilly (www.inconspicuous.org) 71 | * 72 | * This work is a translation from C to Java of jsmin.c published by Douglas 73 | * Crockford. Permission is hereby granted to use the Java version under the 74 | * same conditions as the jsmin.c on which it is based. 75 | * 76 | * 77 | * 78 | * ------------------ jsmin.c 2003-04-21 ------------------ 79 | * 80 | * Copyright (c) 2002 Douglas Crockford (www.crockford.com) 81 | * 82 | * Permission is hereby granted, free of charge, to any person obtaining a copy 83 | * of this software and associated documentation files (the "Software"), to deal 84 | * in the Software without restriction, including without limitation the rights 85 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 86 | * copies of the Software, and to permit persons to whom the Software is 87 | * furnished to do so, subject to the following conditions: 88 | * 89 | * The above copyright notice and this permission notice shall be included in 90 | * all copies or substantial portions of the Software. 91 | * 92 | * The Software shall be used for Good, not Evil. 93 | * 94 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 95 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 96 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 97 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 98 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 99 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 100 | * SOFTWARE. 101 | */ 102 | 103 | /** 104 | * Minify.java is written by Charles Bihis (www.whoischarles.com) and is adapted 105 | * from JSMin.java written by John Reilly (www.inconspicuous.org) which is 106 | * itself a translation of jsmin.c written by Douglas Crockford 107 | * (www.crockford.com). 108 | * 109 | * @see http://www.unl.edu/ucomm/templatedependents/JSMin.java 111 | * @see http://www.crockford.com/javascript/jsmin.c 113 | */ 114 | 115 | public class Minify { 116 | 117 | private static final int EOF = -1; 118 | 119 | private PushbackInputStream in; 120 | private OutputStream out; 121 | private int currChar; 122 | private int nextChar; 123 | private int line; 124 | private int column; 125 | 126 | public enum Action { 127 | OUTPUT_CURR, DELETE_CURR, DELETE_NEXT 128 | } 129 | 130 | public Minify() { 131 | this.in = null; 132 | this.out = null; 133 | } 134 | 135 | /** 136 | * Minifies the input JSON string. 137 | * 138 | * Takes the input JSON string and deletes the characters which are 139 | * insignificant to JavaScipt. Comments will be removed, tabs will be replaced 140 | * with spaces, carriage returns will be replaced with line feeds, and most 141 | * spaces and line feeds will be removed. The result will be returned. 142 | * 143 | * @param json The JSON string for which to minify 144 | * @return A minified, yet functionally identical, version of the input JSON 145 | * string 146 | */ 147 | public String minify(String json) { 148 | InputStream in = new ByteArrayInputStream(json.getBytes(StandardCharsets.UTF_8)); 149 | ByteArrayOutputStream out = new ByteArrayOutputStream(); 150 | 151 | try { 152 | minify(in, out); 153 | } catch (Exception e) { 154 | return null; 155 | } 156 | 157 | return out.toString().trim(); 158 | } 159 | 160 | /** 161 | * Takes an input stream to a JSON string and outputs minified JSON to the 162 | * output stream. 163 | * 164 | * Takes the input JSON via the input stream and deletes the characters which 165 | * are insignificant to JavaScript. Comments will be removed, tabs will be 166 | * replaced with spaaces, carriage returns will be replaced with line feeds, and 167 | * most spaces and line feeds will be removed. The result is streamed to the 168 | * output stream. 169 | * 170 | * @param in The InputStream from which to get the un-minified 171 | * JSON 172 | * @param out The OutputStream where the resulting minified JSON 173 | * will be streamed to 174 | * @throws IOException 175 | * @throws UnterminatedRegExpLiteralException 176 | * @throws UnterminatedCommentException 177 | * @throws UnterminatedStringLiteralException 178 | */ 179 | public void minify(InputStream in, OutputStream out) throws IOException, UnterminatedRegExpLiteralException, 180 | UnterminatedCommentException, UnterminatedStringLiteralException { 181 | 182 | // Initialize 183 | this.in = new PushbackInputStream(in); 184 | this.out = out; 185 | this.line = 0; 186 | this.column = 0; 187 | currChar = '\n'; 188 | action(Action.DELETE_NEXT); 189 | 190 | // Process input 191 | while (currChar != EOF) { 192 | switch (currChar) { 193 | 194 | case ' ': 195 | if (isAlphanum(nextChar)) { 196 | action(Action.OUTPUT_CURR); 197 | } else { 198 | action(Action.DELETE_CURR); 199 | } 200 | break; 201 | 202 | case '\n': 203 | switch (nextChar) { 204 | case '{': 205 | case '[': 206 | case '(': 207 | case '+': 208 | case '-': 209 | action(Action.OUTPUT_CURR); 210 | break; 211 | case ' ': 212 | action(Action.DELETE_NEXT); 213 | break; 214 | default: 215 | if (isAlphanum(nextChar)) { 216 | action(Action.OUTPUT_CURR); 217 | } else { 218 | action(Action.DELETE_CURR); 219 | } 220 | } 221 | break; 222 | 223 | default: 224 | switch (nextChar) { 225 | case ' ': 226 | if (isAlphanum(currChar)) { 227 | action(Action.OUTPUT_CURR); 228 | break; 229 | } 230 | action(Action.DELETE_NEXT); 231 | break; 232 | case '\n': 233 | switch (currChar) { 234 | case '}': 235 | case ']': 236 | case ')': 237 | case '+': 238 | case '-': 239 | case '"': 240 | case '\'': 241 | action(Action.OUTPUT_CURR); 242 | break; 243 | default: 244 | if (isAlphanum(currChar)) { 245 | action(Action.OUTPUT_CURR); 246 | } else { 247 | action(Action.DELETE_NEXT); 248 | } 249 | } 250 | break; 251 | default: 252 | action(Action.OUTPUT_CURR); 253 | break; 254 | } 255 | } 256 | } 257 | out.flush(); 258 | } 259 | 260 | /** 261 | * Process the current character with an appropriate action. 262 | * 263 | * The action that occurs is determined by the current character. The options 264 | * are: 265 | * 266 | * 1. Output currChar: output currChar, copy nextChar to currChar, get the next 267 | * character and save it to nextChar 2. Delete currChar: copy nextChar to 268 | * currChar, get the next character and save it to nextChar 3. Delete nextChar: 269 | * get the next character and save it to nextChar 270 | * 271 | * This method essentially treats a string as a single character. Also 272 | * recognizes regular expressions if they are preceded by '(', ',', or '='. 273 | * 274 | * @param action The action to perform 275 | * @throws IOException 276 | * @throws UnterminatedRegExpLiteralException 277 | * @throws UnterminatedCommentException 278 | * @throws UnterminatedStringLiteralException 279 | */ 280 | private void action(Action action) throws IOException, UnterminatedRegExpLiteralException, 281 | UnterminatedCommentException, UnterminatedStringLiteralException { 282 | 283 | // Process action 284 | switch (action) { 285 | 286 | case OUTPUT_CURR: 287 | out.write(currChar); 288 | 289 | case DELETE_CURR: 290 | currChar = nextChar; 291 | 292 | if (currChar == '\'' || currChar == '"') { 293 | for (; ; ) { 294 | out.write(currChar); 295 | currChar = get(); 296 | if (currChar == nextChar) { 297 | break; 298 | } 299 | if (currChar <= '\n') { 300 | throw new UnterminatedStringLiteralException(line, column); 301 | } 302 | if (currChar == '\\') { 303 | out.write(currChar); 304 | currChar = get(); 305 | } 306 | } 307 | } 308 | 309 | case DELETE_NEXT: 310 | nextChar = next(); 311 | if (nextChar == '/' && (currChar == '(' || currChar == ',' || currChar == '=' || currChar == ':')) { 312 | out.write(currChar); 313 | out.write(nextChar); 314 | for (; ; ) { 315 | currChar = get(); 316 | if (currChar == '/') { 317 | break; 318 | } else if (currChar == '\\') { 319 | out.write(currChar); 320 | currChar = get(); 321 | } else if (currChar <= '\n') { 322 | throw new UnterminatedRegExpLiteralException(line, column); 323 | } 324 | out.write(currChar); 325 | } 326 | nextChar = next(); 327 | } 328 | } 329 | } 330 | 331 | /** 332 | * Determines whether a given character is a letter, digit, underscore, dollar 333 | * sign, or non-ASCII character. 334 | * 335 | * @param c The character to compare 336 | * @return True if the character is a letter, digit, underscore, dollar sign, or 337 | * non-ASCII character. False otherwise. 338 | */ 339 | private boolean isAlphanum(int c) { 340 | return ((c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || c == '_' || c == '$' 341 | || c == '\\' || c > 126); 342 | } 343 | 344 | /** 345 | * Returns the next character from the input stream. 346 | * 347 | * Will pop the next character from the input stack. If the character is a 348 | * control character, translate it to a space or line feed. 349 | * 350 | * @return The next character from the input stream 351 | * @throws IOException 352 | */ 353 | private int get() throws IOException { 354 | int c = in.read(); 355 | 356 | if (c == '\n') { 357 | line++; 358 | column = 0; 359 | } else { 360 | column++; 361 | } 362 | 363 | if (c >= ' ' || c == '\n' || c == EOF) { 364 | return c; 365 | } 366 | 367 | if (c == '\r') { 368 | column = 0; 369 | return '\n'; 370 | } 371 | 372 | return ' '; 373 | } 374 | 375 | /** 376 | * Returns the next character from the input stream without popping it from the 377 | * stack. 378 | * 379 | * @return The next character from the input stream 380 | * @throws IOException 381 | */ 382 | private int peek() throws IOException { 383 | int lookaheadChar = in.read(); 384 | in.unread(lookaheadChar); 385 | return lookaheadChar; 386 | } 387 | 388 | /** 389 | * Get the next character from the input stream, excluding comments. 390 | * 391 | * Will read from the input stream via the get() method. Will 392 | * exclude characters that are part of comments. peek() is used to 393 | * se if a '/' is followed by a '/' or a '*' for the purpose of identifying 394 | * comments. 395 | * 396 | * @return The next character from the input stream, excluding characters from 397 | * comments 398 | * @throws IOException 399 | * @throws UnterminatedCommentException 400 | */ 401 | private int next() throws IOException, UnterminatedCommentException { 402 | int c = get(); 403 | 404 | if (c == '/') { 405 | switch (peek()) { 406 | 407 | case '/': 408 | for (; ; ) { 409 | c = get(); 410 | if (c <= '\n') { 411 | return c; 412 | } 413 | } 414 | 415 | case '*': 416 | get(); 417 | for (; ; ) { 418 | switch (get()) { 419 | case '*': 420 | if (peek() == '/') { 421 | get(); 422 | return ' '; 423 | } 424 | break; 425 | case EOF: 426 | throw new UnterminatedCommentException(line, column); 427 | } 428 | } 429 | 430 | default: 431 | return c; 432 | } 433 | 434 | } 435 | return c; 436 | } 437 | 438 | /** 439 | * Exception to be thrown when an unterminated comment appears in the input. 440 | */ 441 | public static class UnterminatedCommentException extends Exception { 442 | private static final long serialVersionUID = 3L; 443 | 444 | public UnterminatedCommentException(int line, int column) { 445 | super("Unterminated comment at line " + line + " and column " + column); 446 | } 447 | } 448 | 449 | /** 450 | * Exception to be thrown when an unterminated string literal appears in the 451 | * input. 452 | */ 453 | public static class UnterminatedStringLiteralException extends Exception { 454 | private static final long serialVersionUID = 2L; 455 | 456 | public UnterminatedStringLiteralException(int line, int column) { 457 | super("Unterminated string literal at line " + line + " and column " + column); 458 | } 459 | } 460 | 461 | /** 462 | * Exception to be thrown when an unterminated regular expression literal 463 | * appears in the input. 464 | */ 465 | public static class UnterminatedRegExpLiteralException extends Exception { 466 | private static final long serialVersionUID = 1L; 467 | 468 | public UnterminatedRegExpLiteralException(int line, int column) { 469 | super("Unterminated regular expression at line " + line + " and column " + column); 470 | } 471 | } 472 | } 473 | -------------------------------------------------------------------------------- /src/main/java/pingvin/tokenposition/Output.java: -------------------------------------------------------------------------------- 1 | package pingvin.tokenposition; 2 | 3 | import java.text.SimpleDateFormat; 4 | import java.util.Calendar; 5 | import java.util.Date; 6 | import java.util.TimeZone; 7 | 8 | public class Output { 9 | 10 | private static final SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss.SSS"); 11 | 12 | public static void output(String string) { 13 | Date cal = Calendar.getInstance(TimeZone.getDefault()).getTime(); 14 | String msg = sdf.format(cal.getTime()) + " | " + string; 15 | if (Config.stdout == null) { 16 | System.out.println(msg); 17 | } else { 18 | Config.stdout.println(msg); 19 | } 20 | } 21 | 22 | public static void outputError(String string) { 23 | Date cal = Calendar.getInstance(TimeZone.getDefault()).getTime(); 24 | String msg = sdf.format(cal.getTime()) + " | " + string; 25 | if (Config.stderr == null) { 26 | System.err.println(msg); 27 | } else { 28 | Config.stderr.println(msg); 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/pingvin/tokenposition/PostBody.java: -------------------------------------------------------------------------------- 1 | package pingvin.tokenposition; 2 | 3 | import org.apache.commons.lang.StringUtils; 4 | 5 | import java.util.ArrayList; 6 | import java.util.List; 7 | import java.util.regex.Pattern; 8 | 9 | public class PostBody extends ITokenPosition { 10 | private String token; 11 | private boolean found = false; 12 | private String body; 13 | 14 | 15 | public PostBody(List headersP, String bodyP) { 16 | body = bodyP; 17 | } 18 | 19 | @Override 20 | public boolean positionFound() { 21 | if (isRequest) { 22 | KeyValuePair postJWT = getJWTFromPostBody(); 23 | if (postJWT != null) { 24 | found = true; 25 | token = postJWT.getValue(); 26 | return true; 27 | } 28 | } 29 | return false; 30 | } 31 | 32 | public KeyValuePair getJWTFromPostBody() { 33 | int from = 0; 34 | int index = body.indexOf("&") == -1 ? body.length() : body.indexOf("&"); 35 | int parameterCount = StringUtils.countMatches(body, "&") + 1; 36 | 37 | List postParameterList = new ArrayList(); 38 | for (int i = 0; i < parameterCount; i++) { 39 | String parameter = body.substring(from, index); 40 | parameter = parameter.replace("&", ""); 41 | 42 | String[] parameterSplit = parameter.split(Pattern.quote("=")); 43 | if (parameterSplit.length > 1) { 44 | String name = parameterSplit[0]; 45 | String value = parameterSplit[1]; 46 | postParameterList.add(new KeyValuePair(name, value)); 47 | from = index; 48 | index = body.indexOf("&", index + 1); 49 | if (index == -1) { 50 | index = body.length(); 51 | } 52 | } 53 | } 54 | for (String keyword : Config.tokenKeywords) { 55 | for (KeyValuePair postParameter : postParameterList) { 56 | if (keyword.equals(postParameter.getName()) 57 | && TokenCheck.isValidJWT(postParameter.getValue())) { 58 | return postParameter; 59 | } 60 | } 61 | } 62 | return null; 63 | } 64 | 65 | @Override 66 | public String getToken() { 67 | return found ? token : ""; 68 | } 69 | 70 | } 71 | -------------------------------------------------------------------------------- /src/main/java/pingvin/tokenposition/PublicKeyBroker.java: -------------------------------------------------------------------------------- 1 | package pingvin.tokenposition; 2 | 3 | /** 4 | * Created by mvetsch on 24.04.2017. 5 | */ 6 | public class PublicKeyBroker { 7 | // This hack is used to get public Key from the Random Key generator to the controller. Just for logging 8 | public static String publicKey; 9 | } 10 | -------------------------------------------------------------------------------- /src/main/java/pingvin/tokenposition/TimeClaim.java: -------------------------------------------------------------------------------- 1 | package pingvin.tokenposition; 2 | 3 | import java.util.List; 4 | 5 | public class TimeClaim { 6 | private final String date; 7 | private final long unixTimestamp; 8 | private final boolean valid; 9 | private final String claim; 10 | private final boolean canBeValid; 11 | 12 | public TimeClaim(String claim, String date, long unixTimestamp, boolean valid) { 13 | this.claim = claim; 14 | this.date=date; 15 | this.unixTimestamp=unixTimestamp; 16 | this.valid=valid; 17 | this.canBeValid = true; 18 | } 19 | 20 | public TimeClaim(String claim, String date, long unixTimestamp) { 21 | this.claim = claim; 22 | this.date=date; 23 | this.unixTimestamp=unixTimestamp; 24 | this.valid = true; 25 | this.canBeValid = false; 26 | } 27 | 28 | public String getClaimName() { 29 | return claim; 30 | } 31 | 32 | public String getDate() { 33 | return date; 34 | } 35 | 36 | public long getUnixTimestamp() { 37 | return unixTimestamp; 38 | } 39 | 40 | public boolean canBeValid() { 41 | return canBeValid; 42 | } 43 | 44 | public boolean isValid() { 45 | return valid; 46 | } 47 | 48 | public static String getTimeClaimsAsText(List tcl){ 49 | String timeClaimString = ""; 50 | if(tcl != null && tcl.size()>0){ 51 | for (TimeClaim timeClaim : tcl) { 52 | timeClaimString+=""+timeClaim.getClaimName()+ 53 | (timeClaim.canBeValid()?" check "+(timeClaim.isValid()?"passed":"failed"):"")+ 54 | " - "+timeClaim.getDate()+"
"; 55 | } 56 | } 57 | return timeClaimString+""; 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /src/main/java/pingvin/tokenposition/TokenCheck.java: -------------------------------------------------------------------------------- 1 | package pingvin.tokenposition; 2 | 3 | import com.auth0.jwt.JWT; 4 | import com.auth0.jwt.interfaces.DecodedJWT; 5 | import org.apache.commons.lang.StringUtils; 6 | 7 | public class TokenCheck { 8 | public static boolean isValidJWT(String jwt) { 9 | 10 | if (StringUtils.countMatches(jwt, ".") != 2) { 11 | return false; 12 | } 13 | 14 | jwt = jwt.trim(); 15 | if (StringUtils.contains(jwt, " ")) { 16 | return false; 17 | } 18 | 19 | String[] sArray = StringUtils.split(jwt, "."); 20 | if (sArray.length < 3) { 21 | return false; 22 | } 23 | for (String value : sArray) { 24 | if (!value.matches("[A-Za-z0-9+/=_-]+")) { 25 | return false; 26 | } 27 | } 28 | 29 | try { 30 | DecodedJWT decoded = JWT.decode(jwt); 31 | decoded.getAlgorithm(); 32 | return true; 33 | } catch (Exception exception) { 34 | } 35 | 36 | return false; 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/pingvin/tokenposition/algorithm/AlgorithmLinker.java: -------------------------------------------------------------------------------- 1 | package pingvin.tokenposition.algorithm; 2 | 3 | import com.auth0.jwt.algorithms.Algorithm; 4 | import org.apache.commons.lang.RandomStringUtils; 5 | import org.bouncycastle.util.encoders.Base64; 6 | import pingvin.tokenposition.Output; 7 | import pingvin.tokenposition.PublicKeyBroker; 8 | 9 | import java.io.UnsupportedEncodingException; 10 | import java.security.*; 11 | import java.security.interfaces.ECKey; 12 | import java.security.interfaces.RSAKey; 13 | import java.security.spec.EncodedKeySpec; 14 | import java.security.spec.PKCS8EncodedKeySpec; 15 | import java.security.spec.X509EncodedKeySpec; 16 | 17 | public class AlgorithmLinker { 18 | 19 | public static final String[] keyBeginMarkers = new String[]{"-----BEGIN PUBLIC KEY-----", "-----BEGIN CERTIFICATE-----"}; 20 | public static final String[] keyEndMarkers = new String[]{"-----END PUBLIC KEY-----", "-----END CERTIFICATE-----"}; 21 | 22 | public static final pingvin.tokenposition.algorithm.AlgorithmWrapper none = 23 | new pingvin.tokenposition.algorithm.AlgorithmWrapper("none", AlgorithmType.none); 24 | public static final pingvin.tokenposition.algorithm.AlgorithmWrapper HS256 = 25 | new pingvin.tokenposition.algorithm.AlgorithmWrapper("HS256", AlgorithmType.symmetric); 26 | public static final pingvin.tokenposition.algorithm.AlgorithmWrapper HS384 = 27 | new pingvin.tokenposition.algorithm.AlgorithmWrapper("HS384", AlgorithmType.symmetric); 28 | public static final pingvin.tokenposition.algorithm.AlgorithmWrapper HS512 = 29 | new pingvin.tokenposition.algorithm.AlgorithmWrapper("HS512", AlgorithmType.symmetric); 30 | public static final pingvin.tokenposition.algorithm.AlgorithmWrapper RS256 = 31 | new pingvin.tokenposition.algorithm.AlgorithmWrapper("RS256", AlgorithmType.asymmetric); 32 | public static final pingvin.tokenposition.algorithm.AlgorithmWrapper RS384 = 33 | new pingvin.tokenposition.algorithm.AlgorithmWrapper("RS384", AlgorithmType.asymmetric); 34 | public static final pingvin.tokenposition.algorithm.AlgorithmWrapper RS512 = 35 | new pingvin.tokenposition.algorithm.AlgorithmWrapper("RS512", AlgorithmType.asymmetric); 36 | public static final pingvin.tokenposition.algorithm.AlgorithmWrapper ES256 = 37 | new pingvin.tokenposition.algorithm.AlgorithmWrapper("ES256", AlgorithmType.asymmetric); 38 | public static final pingvin.tokenposition.algorithm.AlgorithmWrapper ES384 = 39 | new pingvin.tokenposition.algorithm.AlgorithmWrapper("ES384", AlgorithmType.asymmetric); 40 | public static final pingvin.tokenposition.algorithm.AlgorithmWrapper ES512 = 41 | new pingvin.tokenposition.algorithm.AlgorithmWrapper("ES512", AlgorithmType.asymmetric); 42 | 43 | private static final pingvin.tokenposition.algorithm.AlgorithmWrapper[] supportedAlgorithms = { 44 | none, HS256, HS384, HS512, RS256, RS384, RS512, ES256, ES384, ES512}; 45 | 46 | private static PublicKey generatePublicKeyFromString(String key, String algorithm) { 47 | PublicKey publicKey = null; 48 | if (key.length() > 1) { 49 | key = cleanKey(key); 50 | byte[] keyByteArray = java.util.Base64.getDecoder().decode(key); 51 | try { 52 | KeyFactory kf = KeyFactory.getInstance(algorithm); 53 | EncodedKeySpec keySpec = new X509EncodedKeySpec(keyByteArray); 54 | publicKey = kf.generatePublic(keySpec); 55 | } catch (Exception e) { 56 | Output.outputError(e.getMessage()); 57 | } 58 | } 59 | return publicKey; 60 | } 61 | 62 | public static String cleanKey(String key) { 63 | for (String keyBeginMarker : keyBeginMarkers) { 64 | key = key.replace(keyBeginMarker, ""); 65 | } 66 | for (String keyEndMarker : keyEndMarkers) { 67 | key = key.replace(keyEndMarker, ""); 68 | } 69 | key = key.replaceAll("\\s+", "").replaceAll("\\r+", "").replaceAll("\\n+", ""); 70 | 71 | return key; 72 | } 73 | 74 | private static PrivateKey generatePrivateKeyFromString(String key, String algorithm) { 75 | PrivateKey privateKey = null; 76 | if (key.length() > 1) { 77 | key = cleanKey(key); 78 | try { 79 | byte[] keyByteArray = Base64.decode(key); 80 | KeyFactory kf = KeyFactory.getInstance(algorithm); 81 | EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyByteArray); 82 | privateKey = kf.generatePrivate(keySpec); 83 | } catch (Exception e) { 84 | Output.outputError("Error generating private key with input string '" + key + "' and algorithm '" + algorithm + "' - " + e.getMessage() + " - "); 85 | } 86 | } 87 | return privateKey; 88 | } 89 | 90 | /** 91 | * @param algo 92 | * @param key - either the secret or the private key 93 | * @return the algorithm element from the library, if nothing matches the 94 | * none algorithm element is returned 95 | * @throws IllegalArgumentException 96 | * @throws UnsupportedEncodingException 97 | */ 98 | public static Algorithm getVerifierAlgorithm(String algo, String key) throws UnsupportedEncodingException { 99 | return getAlgorithm(algo, key, false); 100 | } 101 | 102 | public static Algorithm getSignerAlgorithm(String algo, String key) throws UnsupportedEncodingException { 103 | return getAlgorithm(algo, key, true); 104 | } 105 | 106 | private static Algorithm getAlgorithm(String algo, String key, boolean IsKeyASignerKey) 107 | throws IllegalArgumentException, UnsupportedEncodingException { 108 | if (algo.equals(HS256.getAlgorithm())) { 109 | return Algorithm.HMAC256(key); 110 | } 111 | if (algo.equals(HS384.getAlgorithm())) { 112 | return Algorithm.HMAC384(key); 113 | } 114 | if (algo.equals(HS512.getAlgorithm())) { 115 | return Algorithm.HMAC512(key); 116 | } 117 | if (algo.equals(ES256.getAlgorithm())) { 118 | return Algorithm.ECDSA256((ECKey) getKeyInstance(key, "EC", IsKeyASignerKey)); 119 | } 120 | if (algo.equals(ES384.getAlgorithm())) { 121 | return Algorithm.ECDSA384((ECKey) getKeyInstance(key, "EC", IsKeyASignerKey)); 122 | } 123 | if (algo.equals(ES512.getAlgorithm())) { 124 | return Algorithm.ECDSA512((ECKey) getKeyInstance(key, "EC", IsKeyASignerKey)); 125 | } 126 | if (algo.equals(RS256.getAlgorithm())) { 127 | return Algorithm.RSA256((RSAKey) getKeyInstance(key, "RSA", IsKeyASignerKey)); 128 | } 129 | if (algo.equals(RS384.getAlgorithm())) { 130 | return Algorithm.RSA384((RSAKey) getKeyInstance(key, "RSA", IsKeyASignerKey)); 131 | } 132 | if (algo.equals(RS512.getAlgorithm())) { 133 | return Algorithm.RSA512((RSAKey) getKeyInstance(key, "RSA", IsKeyASignerKey)); 134 | } 135 | 136 | return Algorithm.none(); 137 | } 138 | 139 | private static Key getKeyInstance(String key, String algorithm, boolean isPrivate) { 140 | return isPrivate ? generatePrivateKeyFromString(key, algorithm) : generatePublicKeyFromString(key, algorithm); 141 | } 142 | 143 | public static String getRandomKey(String algorithm) { 144 | String algorithmType = AlgorithmLinker.getTypeOf(algorithm); 145 | 146 | if (algorithmType.equals(AlgorithmType.symmetric)) { 147 | return RandomStringUtils.randomAlphanumeric(6); 148 | } 149 | if (algorithmType.equals(AlgorithmType.asymmetric) && algorithm.startsWith("RS")) { 150 | try { 151 | KeyPair keyPair = KeyPairGenerator.getInstance("RSA").generateKeyPair(); 152 | PublicKeyBroker.publicKey = Base64.toBase64String(keyPair.getPublic().getEncoded()); 153 | return Base64.toBase64String((keyPair.getPrivate().getEncoded())); 154 | } catch (NoSuchAlgorithmException e) { 155 | Output.outputError(e.getMessage()); 156 | } 157 | } 158 | if (algorithmType.equals(AlgorithmType.asymmetric) && algorithm.startsWith("ES")) { 159 | try { 160 | KeyPair keyPair = KeyPairGenerator.getInstance("EC").generateKeyPair(); 161 | return Base64.toBase64String(keyPair.getPrivate().getEncoded()); 162 | } catch (NoSuchAlgorithmException e) { 163 | Output.outputError(e.getMessage()); 164 | } 165 | } 166 | throw new RuntimeException("Cannot get random key of provided algorithm as it does not seem valid HS, RS or ES"); 167 | } 168 | 169 | /** 170 | * @return gets the type (asym, sym, none) of the provided @param algo 171 | */ 172 | public static String getTypeOf(String algorithm) { 173 | for (pingvin.tokenposition.algorithm.AlgorithmWrapper supportedAlgorithm : supportedAlgorithms) { 174 | if (algorithm.equals(supportedAlgorithm.getAlgorithm())) { 175 | return supportedAlgorithm.getType(); 176 | } 177 | } 178 | return AlgorithmType.none; 179 | } 180 | 181 | public static pingvin.tokenposition.algorithm.AlgorithmWrapper[] getSupportedAlgorithms() { 182 | return supportedAlgorithms; 183 | } 184 | } 185 | -------------------------------------------------------------------------------- /src/main/java/pingvin/tokenposition/algorithm/AlgorithmType.java: -------------------------------------------------------------------------------- 1 | package pingvin.tokenposition.algorithm; 2 | 3 | public class AlgorithmType { 4 | // dummy class that holds the different algorithm "types" 5 | public final static String none = "none"; 6 | public final static String symmetric = "symmetric"; 7 | public final static String asymmetric = "asymmetric"; 8 | } 9 | -------------------------------------------------------------------------------- /src/main/java/pingvin/tokenposition/algorithm/AlgorithmWrapper.java: -------------------------------------------------------------------------------- 1 | package pingvin.tokenposition.algorithm; 2 | 3 | public class AlgorithmWrapper { 4 | private final String algorithm; 5 | private final String type; 6 | 7 | public AlgorithmWrapper(String algorithm, String none) { 8 | this.algorithm = algorithm; 9 | this.type = none; 10 | } 11 | 12 | public String getAlgorithm() { 13 | return algorithm; 14 | } 15 | 16 | public String getType() { 17 | return type; 18 | } 19 | } 20 | --------------------------------------------------------------------------------