diff --git a/.solhint.json b/.solhint.json new file mode 100644 index 00000000..816d574c --- /dev/null +++ b/.solhint.json @@ -0,0 +1,7 @@ +{ + "extends": "solhint:recommended", + "rules": { + "compiler-version": ["off"], + "func-visibility": ["warn",{ "ignoreConstructors":true }] + } +} diff --git a/LICENSE b/LICENSE deleted file mode 100644 index be3f7b28..00000000 --- a/LICENSE +++ /dev/null @@ -1,661 +0,0 @@ - GNU AFFERO GENERAL PUBLIC LICENSE - Version 3, 19 November 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The GNU Affero General Public License is a free, copyleft license for -software and other kinds of works, specifically designed to ensure -cooperation with the community in the case of network server software. - - The licenses for most software and other practical works are designed -to take away your freedom to share and change the works. By contrast, -our General Public Licenses are intended to guarantee your freedom to -share and change all versions of a program--to make sure it remains free -software for all its users. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -them if you wish), that you receive source code or can get it if you -want it, that you can change the software or use pieces of it in new -free programs, and that you know you can do these things. - - Developers that use our General Public Licenses protect your rights -with two steps: (1) assert copyright on the software, and (2) offer -you this License which gives you legal permission to copy, distribute -and/or modify the software. - - A secondary benefit of defending all users' freedom is that -improvements made in alternate versions of the program, if they -receive widespread use, become available for other developers to -incorporate. Many developers of free software are heartened and -encouraged by the resulting cooperation. However, in the case of -software used on network servers, this result may fail to come about. -The GNU General Public License permits making a modified version and -letting the public access it on a server without ever releasing its -source code to the public. - - The GNU Affero General Public License is designed specifically to -ensure that, in such cases, the modified source code becomes available -to the community. It requires the operator of a network server to -provide the source code of the modified version running there to the -users of that server. Therefore, public use of a modified version, on -a publicly accessible server, gives the public access to the source -code of the modified version. - - An older license, called the Affero General Public License and -published by Affero, was designed to accomplish similar goals. This is -a different license, not a version of the Affero GPL, but Affero has -released a new version of the Affero GPL which permits relicensing under -this license. - - The precise terms and conditions for copying, distribution and -modification follow. - - TERMS AND CONDITIONS - - 0. Definitions. - - "This License" refers to version 3 of the GNU Affero General Public License. - - "Copyright" also means copyright-like laws that apply to other kinds of -works, such as semiconductor masks. - - "The Program" refers to any copyrightable work licensed under this -License. Each licensee is addressed as "you". "Licensees" and -"recipients" may be individuals or organizations. - - To "modify" a work means to copy from or adapt all or part of the work -in a fashion requiring copyright permission, other than the making of an -exact copy. The resulting work is called a "modified version" of the -earlier work or a work "based on" the earlier work. - - A "covered work" means either the unmodified Program or a work based -on the Program. - - To "propagate" a work means to do anything with it that, without -permission, would make you directly or secondarily liable for -infringement under applicable copyright law, except executing it on a -computer or modifying a private copy. Propagation includes copying, -distribution (with or without modification), making available to the -public, and in some countries other activities as well. - - To "convey" a work means any kind of propagation that enables other -parties to make or receive copies. Mere interaction with a user through -a computer network, with no transfer of a copy, is not conveying. - - An interactive user interface displays "Appropriate Legal Notices" -to the extent that it includes a convenient and prominently visible -feature that (1) displays an appropriate copyright notice, and (2) -tells the user that there is no warranty for the work (except to the -extent that warranties are provided), that licensees may convey the -work under this License, and how to view a copy of this License. If -the interface presents a list of user commands or options, such as a -menu, a prominent item in the list meets this criterion. - - 1. Source Code. - - The "source code" for a work means the preferred form of the work -for making modifications to it. "Object code" means any non-source -form of a work. - - A "Standard Interface" means an interface that either is an official -standard defined by a recognized standards body, or, in the case of -interfaces specified for a particular programming language, one that -is widely used among developers working in that language. - - The "System Libraries" of an executable work include anything, other -than the work as a whole, that (a) is included in the normal form of -packaging a Major Component, but which is not part of that Major -Component, and (b) serves only to enable use of the work with that -Major Component, or to implement a Standard Interface for which an -implementation is available to the public in source code form. A -"Major Component", in this context, means a major essential component -(kernel, window system, and so on) of the specific operating system -(if any) on which the executable work runs, or a compiler used to -produce the work, or an object code interpreter used to run it. - - The "Corresponding Source" for a work in object code form means all -the source code needed to generate, install, and (for an executable -work) run the object code and to modify the work, including scripts to -control those activities. However, it does not include the work's -System Libraries, or general-purpose tools or generally available free -programs which are used unmodified in performing those activities but -which are not part of the work. For example, Corresponding Source -includes interface definition files associated with source files for -the work, and the source code for shared libraries and dynamically -linked subprograms that the work is specifically designed to require, -such as by intimate data communication or control flow between those -subprograms and other parts of the work. - - The Corresponding Source need not include anything that users -can regenerate automatically from other parts of the Corresponding -Source. - - The Corresponding Source for a work in source code form is that -same work. - - 2. Basic Permissions. - - All rights granted under this License are granted for the term of -copyright on the Program, and are irrevocable provided the stated -conditions are met. This License explicitly affirms your unlimited -permission to run the unmodified Program. The output from running a -covered work is covered by this License only if the output, given its -content, constitutes a covered work. This License acknowledges your -rights of fair use or other equivalent, as provided by copyright law. - - You may make, run and propagate covered works that you do not -convey, without conditions so long as your license otherwise remains -in force. You may convey covered works to others for the sole purpose -of having them make modifications exclusively for you, or provide you -with facilities for running those works, provided that you comply with -the terms of this License in conveying all material for which you do -not control copyright. Those thus making or running the covered works -for you must do so exclusively on your behalf, under your direction -and control, on terms that prohibit them from making any copies of -your copyrighted material outside their relationship with you. - - Conveying under any other circumstances is permitted solely under -the conditions stated below. Sublicensing is not allowed; section 10 -makes it unnecessary. - - 3. Protecting Users' Legal Rights From Anti-Circumvention Law. - - No covered work shall be deemed part of an effective technological -measure under any applicable law fulfilling obligations under article -11 of the WIPO copyright treaty adopted on 20 December 1996, or -similar laws prohibiting or restricting circumvention of such -measures. - - When you convey a covered work, you waive any legal power to forbid -circumvention of technological measures to the extent such circumvention -is effected by exercising rights under this License with respect to -the covered work, and you disclaim any intention to limit operation or -modification of the work as a means of enforcing, against the work's -users, your or third parties' legal rights to forbid circumvention of -technological measures. - - 4. Conveying Verbatim Copies. - - You may convey verbatim copies of the Program's source code as you -receive it, in any medium, provided that you conspicuously and -appropriately publish on each copy an appropriate copyright notice; -keep intact all notices stating that this License and any -non-permissive terms added in accord with section 7 apply to the code; -keep intact all notices of the absence of any warranty; and give all -recipients a copy of this License along with the Program. - - You may charge any price or no price for each copy that you convey, -and you may offer support or warranty protection for a fee. - - 5. Conveying Modified Source Versions. - - You may convey a work based on the Program, or the modifications to -produce it from the Program, in the form of source code under the -terms of section 4, provided that you also meet all of these conditions: - - a) The work must carry prominent notices stating that you modified - it, and giving a relevant date. - - b) The work must carry prominent notices stating that it is - released under this License and any conditions added under section - 7. This requirement modifies the requirement in section 4 to - "keep intact all notices". - - c) You must license the entire work, as a whole, under this - License to anyone who comes into possession of a copy. This - License will therefore apply, along with any applicable section 7 - additional terms, to the whole of the work, and all its parts, - regardless of how they are packaged. This License gives no - permission to license the work in any other way, but it does not - invalidate such permission if you have separately received it. - - d) If the work has interactive user interfaces, each must display - Appropriate Legal Notices; however, if the Program has interactive - interfaces that do not display Appropriate Legal Notices, your - work need not make them do so. - - A compilation of a covered work with other separate and independent -works, which are not by their nature extensions of the covered work, -and which are not combined with it such as to form a larger program, -in or on a volume of a storage or distribution medium, is called an -"aggregate" if the compilation and its resulting copyright are not -used to limit the access or legal rights of the compilation's users -beyond what the individual works permit. Inclusion of a covered work -in an aggregate does not cause this License to apply to the other -parts of the aggregate. - - 6. Conveying Non-Source Forms. - - You may convey a covered work in object code form under the terms -of sections 4 and 5, provided that you also convey the -machine-readable Corresponding Source under the terms of this License, -in one of these ways: - - a) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by the - Corresponding Source fixed on a durable physical medium - customarily used for software interchange. - - b) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by a - written offer, valid for at least three years and valid for as - long as you offer spare parts or customer support for that product - model, to give anyone who possesses the object code either (1) a - copy of the Corresponding Source for all the software in the - product that is covered by this License, on a durable physical - medium customarily used for software interchange, for a price no - more than your reasonable cost of physically performing this - conveying of source, or (2) access to copy the - Corresponding Source from a network server at no charge. - - c) Convey individual copies of the object code with a copy of the - written offer to provide the Corresponding Source. This - alternative is allowed only occasionally and noncommercially, and - only if you received the object code with such an offer, in accord - with subsection 6b. - - d) Convey the object code by offering access from a designated - place (gratis or for a charge), and offer equivalent access to the - Corresponding Source in the same way through the same place at no - further charge. You need not require recipients to copy the - Corresponding Source along with the object code. If the place to - copy the object code is a network server, the Corresponding Source - may be on a different server (operated by you or a third party) - that supports equivalent copying facilities, provided you maintain - clear directions next to the object code saying where to find the - Corresponding Source. Regardless of what server hosts the - Corresponding Source, you remain obligated to ensure that it is - available for as long as needed to satisfy these requirements. - - e) Convey the object code using peer-to-peer transmission, provided - you inform other peers where the object code and Corresponding - Source of the work are being offered to the general public at no - charge under subsection 6d. - - A separable portion of the object code, whose source code is excluded -from the Corresponding Source as a System Library, need not be -included in conveying the object code work. - - A "User Product" is either (1) a "consumer product", which means any -tangible personal property which is normally used for personal, family, -or household purposes, or (2) anything designed or sold for incorporation -into a dwelling. In determining whether a product is a consumer product, -doubtful cases shall be resolved in favor of coverage. For a particular -product received by a particular user, "normally used" refers to a -typical or common use of that class of product, regardless of the status -of the particular user or of the way in which the particular user -actually uses, or expects or is expected to use, the product. A product -is a consumer product regardless of whether the product has substantial -commercial, industrial or non-consumer uses, unless such uses represent -the only significant mode of use of the product. - - "Installation Information" for a User Product means any methods, -procedures, authorization keys, or other information required to install -and execute modified versions of a covered work in that User Product from -a modified version of its Corresponding Source. The information must -suffice to ensure that the continued functioning of the modified object -code is in no case prevented or interfered with solely because -modification has been made. - - If you convey an object code work under this section in, or with, or -specifically for use in, a User Product, and the conveying occurs as -part of a transaction in which the right of possession and use of the -User Product is transferred to the recipient in perpetuity or for a -fixed term (regardless of how the transaction is characterized), the -Corresponding Source conveyed under this section must be accompanied -by the Installation Information. But this requirement does not apply -if neither you nor any third party retains the ability to install -modified object code on the User Product (for example, the work has -been installed in ROM). - - The requirement to provide Installation Information does not include a -requirement to continue to provide support service, warranty, or updates -for a work that has been modified or installed by the recipient, or for -the User Product in which it has been modified or installed. Access to a -network may be denied when the modification itself materially and -adversely affects the operation of the network or violates the rules and -protocols for communication across the network. - - Corresponding Source conveyed, and Installation Information provided, -in accord with this section must be in a format that is publicly -documented (and with an implementation available to the public in -source code form), and must require no special password or key for -unpacking, reading or copying. - - 7. Additional Terms. - - "Additional permissions" are terms that supplement the terms of this -License by making exceptions from one or more of its conditions. -Additional permissions that are applicable to the entire Program shall -be treated as though they were included in this License, to the extent -that they are valid under applicable law. If additional permissions -apply only to part of the Program, that part may be used separately -under those permissions, but the entire Program remains governed by -this License without regard to the additional permissions. - - When you convey a copy of a covered work, you may at your option -remove any additional permissions from that copy, or from any part of -it. (Additional permissions may be written to require their own -removal in certain cases when you modify the work.) You may place -additional permissions on material, added by you to a covered work, -for which you have or can give appropriate copyright permission. - - Notwithstanding any other provision of this License, for material you -add to a covered work, you may (if authorized by the copyright holders of -that material) supplement the terms of this License with terms: - - a) Disclaiming warranty or limiting liability differently from the - terms of sections 15 and 16 of this License; or - - b) Requiring preservation of specified reasonable legal notices or - author attributions in that material or in the Appropriate Legal - Notices displayed by works containing it; or - - c) Prohibiting misrepresentation of the origin of that material, or - requiring that modified versions of such material be marked in - reasonable ways as different from the original version; or - - d) Limiting the use for publicity purposes of names of licensors or - authors of the material; or - - e) Declining to grant rights under trademark law for use of some - trade names, trademarks, or service marks; or - - f) Requiring indemnification of licensors and authors of that - material by anyone who conveys the material (or modified versions of - it) with contractual assumptions of liability to the recipient, for - any liability that these contractual assumptions directly impose on - those licensors and authors. - - All other non-permissive additional terms are considered "further -restrictions" within the meaning of section 10. If the Program as you -received it, or any part of it, contains a notice stating that it is -governed by this License along with a term that is a further -restriction, you may remove that term. If a license document contains -a further restriction but permits relicensing or conveying under this -License, you may add to a covered work material governed by the terms -of that license document, provided that the further restriction does -not survive such relicensing or conveying. - - If you add terms to a covered work in accord with this section, you -must place, in the relevant source files, a statement of the -additional terms that apply to those files, or a notice indicating -where to find the applicable terms. - - Additional terms, permissive or non-permissive, may be stated in the -form of a separately written license, or stated as exceptions; -the above requirements apply either way. - - 8. Termination. - - You may not propagate or modify a covered work except as expressly -provided under this License. Any attempt otherwise to propagate or -modify it is void, and will automatically terminate your rights under -this License (including any patent licenses granted under the third -paragraph of section 11). - - However, if you cease all violation of this License, then your -license from a particular copyright holder is reinstated (a) -provisionally, unless and until the copyright holder explicitly and -finally terminates your license, and (b) permanently, if the copyright -holder fails to notify you of the violation by some reasonable means -prior to 60 days after the cessation. - - Moreover, your license from a particular copyright holder is -reinstated permanently if the copyright holder notifies you of the -violation by some reasonable means, this is the first time you have -received notice of violation of this License (for any work) from that -copyright holder, and you cure the violation prior to 30 days after -your receipt of the notice. - - Termination of your rights under this section does not terminate the -licenses of parties who have received copies or rights from you under -this License. If your rights have been terminated and not permanently -reinstated, you do not qualify to receive new licenses for the same -material under section 10. - - 9. Acceptance Not Required for Having Copies. - - You are not required to accept this License in order to receive or -run a copy of the Program. Ancillary propagation of a covered work -occurring solely as a consequence of using peer-to-peer transmission -to receive a copy likewise does not require acceptance. However, -nothing other than this License grants you permission to propagate or -modify any covered work. These actions infringe copyright if you do -not accept this License. Therefore, by modifying or propagating a -covered work, you indicate your acceptance of this License to do so. - - 10. Automatic Licensing of Downstream Recipients. - - Each time you convey a covered work, the recipient automatically -receives a license from the original licensors, to run, modify and -propagate that work, subject to this License. You are not responsible -for enforcing compliance by third parties with this License. - - An "entity transaction" is a transaction transferring control of an -organization, or substantially all assets of one, or subdividing an -organization, or merging organizations. If propagation of a covered -work results from an entity transaction, each party to that -transaction who receives a copy of the work also receives whatever -licenses to the work the party's predecessor in interest had or could -give under the previous paragraph, plus a right to possession of the -Corresponding Source of the work from the predecessor in interest, if -the predecessor has it or can get it with reasonable efforts. - - You may not impose any further restrictions on the exercise of the -rights granted or affirmed under this License. For example, you may -not impose a license fee, royalty, or other charge for exercise of -rights granted under this License, and you may not initiate litigation -(including a cross-claim or counterclaim in a lawsuit) alleging that -any patent claim is infringed by making, using, selling, offering for -sale, or importing the Program or any portion of it. - - 11. Patents. - - A "contributor" is a copyright holder who authorizes use under this -License of the Program or a work on which the Program is based. The -work thus licensed is called the contributor's "contributor version". - - A contributor's "essential patent claims" are all patent claims -owned or controlled by the contributor, whether already acquired or -hereafter acquired, that would be infringed by some manner, permitted -by this License, of making, using, or selling its contributor version, -but do not include claims that would be infringed only as a -consequence of further modification of the contributor version. For -purposes of this definition, "control" includes the right to grant -patent sublicenses in a manner consistent with the requirements of -this License. - - Each contributor grants you a non-exclusive, worldwide, royalty-free -patent license under the contributor's essential patent claims, to -make, use, sell, offer for sale, import and otherwise run, modify and -propagate the contents of its contributor version. - - In the following three paragraphs, a "patent license" is any express -agreement or commitment, however denominated, not to enforce a patent -(such as an express permission to practice a patent or covenant not to -sue for patent infringement). To "grant" such a patent license to a -party means to make such an agreement or commitment not to enforce a -patent against the party. - - If you convey a covered work, knowingly relying on a patent license, -and the Corresponding Source of the work is not available for anyone -to copy, free of charge and under the terms of this License, through a -publicly available network server or other readily accessible means, -then you must either (1) cause the Corresponding Source to be so -available, or (2) arrange to deprive yourself of the benefit of the -patent license for this particular work, or (3) arrange, in a manner -consistent with the requirements of this License, to extend the patent -license to downstream recipients. "Knowingly relying" means you have -actual knowledge that, but for the patent license, your conveying the -covered work in a country, or your recipient's use of the covered work -in a country, would infringe one or more identifiable patents in that -country that you have reason to believe are valid. - - If, pursuant to or in connection with a single transaction or -arrangement, you convey, or propagate by procuring conveyance of, a -covered work, and grant a patent license to some of the parties -receiving the covered work authorizing them to use, propagate, modify -or convey a specific copy of the covered work, then the patent license -you grant is automatically extended to all recipients of the covered -work and works based on it. - - A patent license is "discriminatory" if it does not include within -the scope of its coverage, prohibits the exercise of, or is -conditioned on the non-exercise of one or more of the rights that are -specifically granted under this License. You may not convey a covered -work if you are a party to an arrangement with a third party that is -in the business of distributing software, under which you make payment -to the third party based on the extent of your activity of conveying -the work, and under which the third party grants, to any of the -parties who would receive the covered work from you, a discriminatory -patent license (a) in connection with copies of the covered work -conveyed by you (or copies made from those copies), or (b) primarily -for and in connection with specific products or compilations that -contain the covered work, unless you entered into that arrangement, -or that patent license was granted, prior to 28 March 2007. - - Nothing in this License shall be construed as excluding or limiting -any implied license or other defenses to infringement that may -otherwise be available to you under applicable patent law. - - 12. No Surrender of Others' Freedom. - - If conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot convey a -covered work so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you may -not convey it at all. For example, if you agree to terms that obligate you -to collect a royalty for further conveying from those to whom you convey -the Program, the only way you could satisfy both those terms and this -License would be to refrain entirely from conveying the Program. - - 13. Remote Network Interaction; Use with the GNU General Public License. - - Notwithstanding any other provision of this License, if you modify the -Program, your modified version must prominently offer all users -interacting with it remotely through a computer network (if your version -supports such interaction) an opportunity to receive the Corresponding -Source of your version by providing access to the Corresponding Source -from a network server at no charge, through some standard or customary -means of facilitating copying of software. This Corresponding Source -shall include the Corresponding Source for any work covered by version 3 -of the GNU General Public License that is incorporated pursuant to the -following paragraph. - - Notwithstanding any other provision of this License, you have -permission to link or combine any covered work with a work licensed -under version 3 of the GNU General Public License into a single -combined work, and to convey the resulting work. The terms of this -License will continue to apply to the part which is the covered work, -but the work with which it is combined will remain governed by version -3 of the GNU General Public License. - - 14. Revised Versions of this License. - - The Free Software Foundation may publish revised and/or new versions of -the GNU Affero General Public License from time to time. Such new versions -will be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - - Each version is given a distinguishing version number. If the -Program specifies that a certain numbered version of the GNU Affero General -Public License "or any later version" applies to it, you have the -option of following the terms and conditions either of that numbered -version or of any later version published by the Free Software -Foundation. If the Program does not specify a version number of the -GNU Affero General Public License, you may choose any version ever published -by the Free Software Foundation. - - If the Program specifies that a proxy can decide which future -versions of the GNU Affero General Public License can be used, that proxy's -public statement of acceptance of a version permanently authorizes you -to choose that version for the Program. - - Later license versions may give you additional or different -permissions. However, no additional obligations are imposed on any -author or copyright holder as a result of your choosing to follow a -later version. - - 15. Disclaimer of Warranty. - - THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY -APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT -HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY -OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM -IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF -ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. Limitation of Liability. - - IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS -THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY -GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE -USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF -DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD -PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), -EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF -SUCH DAMAGES. - - 17. Interpretation of Sections 15 and 16. - - If the disclaimer of warranty and limitation of liability provided -above cannot be given local legal effect according to their terms, -reviewing courts shall apply local law that most closely approximates -an absolute waiver of all civil liability in connection with the -Program, unless a warranty or assumption of liability accompanies a -copy of the Program in return for a fee. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -state the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . - -Also add information on how to contact you by electronic and paper mail. - - If your software can interact with users remotely through a computer -network, you should also make sure that it provides a way for users to -get its source. For example, if your program is a web application, its -interface could display a "Source" link that leads users to an archive -of the code. There are many ways you could offer source, and different -solutions will be better for different programs; see section 13 for the -specific requirements. - - You should also get your employer (if you work as a programmer) or school, -if any, to sign a "copyright disclaimer" for the program, if necessary. -For more information on this, and how to apply and follow the GNU AGPL, see -. diff --git a/not-so-smart-contracts/solidity/README.md b/not-so-smart-contracts/solidity/README.md new file mode 100644 index 00000000..c446d283 --- /dev/null +++ b/not-so-smart-contracts/solidity/README.md @@ -0,0 +1,41 @@ + +# (Not So) Smart Solidity Contracts + +This repository contains examples of common Ethereum smart contract vulnerabilities, including code from real smart contracts. Use Not So Smart Contracts to +- learn about EVM and Solidity vulnerabilities +- as a reference when performing security reviews +- and as a benchmark for security and analysis tools. + +## Features + +Each _Not So Smart Contract_ includes a standard set of information: + +* Description of the unique vulnerability type +* Attack scenarios to exploit the vulnerability +* Recommendations to eliminate or mitigate the vulnerability +* Real-world contracts that exhibit the flaw +* References to third-party resources with more information + +## Vulnerabilities + +| Not So Smart Contract | Description | +| --- | --- | +| [Bad randomness](bad_randomness) | Contract attempts to get on-chain randomness, which can be manipulated by users | +| [Dangerous Strict Equalities](dangerous_strict_equalities) | Use of strict equalities that can be easily manipulated by an attacker. | +| [Denial of Service](denial_of_service) | Attacker stalls contract execution by failing in strategic way | +| [Forced Ether Reception](forced_ether_reception) | Contracts can be forced to receive Ether | +| [Honeypots](honeypots) | Adversarial contracts that use obscure edge cases in a wide selection of solidity compiler versions to steal money from you when you think you're taking money from them | +| [Integer Overflow](integer_overflow) | Arithmetic in Solidity (or EVM) is not safe by default | +| [Race Condition](race_condition) | Transactions can be frontrun on the blockchain | +| [Reentrancy](reentrancy) | Calling external contracts gives them control over execution | +| [rtlo](rtlo) | Usage of malicious unicode character. | +| [Tautology](tautology) | Usage of always boolean expressions that are always true. | +| [Unprotected Function](unprotected_function) | Failure to use function modifier allows attacker to manipulate contract | +| [Unused Return Value ](unused-return) | Return values from calls that is not used. | + + +## Credits + +These examples are developed and maintained by [Trail of Bits](https://www.trailofbits.com/). Contributions are encouraged and are covered under our [bounty program](https://github.com/trailofbits/not-so-smart-contracts/wiki#bounties). + +If you have questions, problems, or just want to learn more, then join the #ethereum channel on the [Empire Hacking Slack](https://empireslacking.herokuapp.com/) or [contact us](https://www.trailofbits.com/contact/) directly. diff --git a/not-so-smart-contracts/solidity/bad_randomness/README.md b/not-so-smart-contracts/solidity/bad_randomness/README.md new file mode 100644 index 00000000..4fdc07dc --- /dev/null +++ b/not-so-smart-contracts/solidity/bad_randomness/README.md @@ -0,0 +1,30 @@ +# Bad Randomness + +Pseudorandom number generation on the blockchain is generally unsafe. There are a number of reasons for this, including: + +- The blockchain does not provide any cryptographically secure source of randomness. Block hashes in isolation are cryptographically random, however, a malicious miner can modify block headers, introduce additional transactions, and choose not to publish blocks in order to influence the resulting hashes. Therefore, miner-influenced values like block hashes and timestamps should never be used as a source of randomness. +- Everything in a contract is publicly visible. Random numbers cannot be generated or stored in the contract until after all lottery entries have been stored. +- Computers will always be faster than the blockchain. Any number that the contract could generate can potentially be precalculated off-chain before the end of the block. + +A common workaround for the lack of on-chain randomness is using a commit and reveal scheme. Here, each user submits the hash of their secret number. When the time comes for the random number to be generated, each user sends their secret number to the contract which then verifies it matches the hash submitted earlier and XORs them together. Therefore no participant can observe how their contribution will affect the end result until after everyone has already committed to a value. However, this is also vulnerable to DoS attacks, since the last person to reveal can choose to never submit their secret. Even if the contract is allowed to move forward without everyone's secrets, this gives them influence over the end result. In general, we do not recommend commit and reveal schemes. + +## Attack Scenarios + +- A lottery where people bet on whether the hash of the current block is even or odd. A miner that bets on even can throw out blocks whose hash are odd. +- A commit-reveal scheme where users don't necessarily have to reveal their secret (to prevent DoS). A user has money riding on the outcome of the PRNG and submits a large number of commits, allowing them to choose the one they want to reveal at the end. + +## Mitigations + +There are not currently any guaranteed solutions for this issue. Do not build applications that require on-chain randomness. In the future, however, these approaches show promise + +- [Verifiable delay functions](https://eprint.iacr.org/2018/601.pdf): functions which produce a pseudorandom number and take a fixed amount of sequential time to evaluate +- [RANDAO](https://github.com/randao/randao): A commit reveal scheme where users must stake wei to participate + +## Examples + +- The `random` function in [TheRun](TheRun.sol) is vulnerable to this attack. It uses the blockhash, timestamp and block number to generate numbers in a range to determine winners of the lottery. To exploit this, an attacker could set up a smart contract that generates numbers in the same way and submits entries when it would win. As well, the miner of the block has some control over the blockhash and timestamp and would also be able to influence the lottery in their favor. + +## Sources + +- [StackExchange](https://ethereum.stackexchange.com/questions/191/how-can-i-securely-generate-a-random-number-in-my-smart-contract) +- [Blog Post](https://blog.positive.com/predicting-random-numbers-in-ethereum-smart-contracts-e5358c6b8620) diff --git a/not-so-smart-contracts/solidity/bad_randomness/theRun.sol b/not-so-smart-contracts/solidity/bad_randomness/theRun.sol new file mode 100644 index 00000000..c91c2224 --- /dev/null +++ b/not-so-smart-contracts/solidity/bad_randomness/theRun.sol @@ -0,0 +1,166 @@ +pragma solidity ^0.8.17; + +contract TheRun { + // solhint-disable-next-line not-rely-on-time + uint256 constant private SALT = block.timestamp; + + address private admin; + uint private balance = 0; + uint private payoutId = 0; + uint private lastPayout = 0; + uint private winningPot = 0; + uint private minMultiplier = 1100; //110% + + //Fees are necessary and set very low, the fees will decrease each time they are collected. + //Fees are just here to maintain the website at beginning, and will progressively go to 0% :) + uint private fees = 0; + uint private feeFrac = 20; //Fraction for fees in per"thousand", not percent, so 20 is 2% + + uint private potFrac = 30; //For the winningPot ,30=> 3% are collected. This is fixed. + + constructor() { + admin = msg.sender; + } + + modifier onlyowner {if (msg.sender == admin) _; } + + struct Player { + address addr; + uint payout; + bool paid; + } + + Player[] private players; + + //--Fallback function + fallback() payable { + init(); + } + + //--initiated function + function init() private { + uint deposit = msg.value; + if (msg.value < 500 finney) { // only participation with >1 ether accepted + msg.sender.transfer(msg.value); + return; + } + if (msg.value > 20 ether) { //only participation with <20 ether accepted + msg.sender.transfer(msg.value - (20 ether)); + deposit=20 ether; + } + participate(deposit); + } + + //------- Core of the game---------- + function participate(uint deposit) private { + //calculate the multiplier to apply to the future payout + + uint totalMultiplier = minMultiplier; //initiate totalMultiplier + if (balance < 1 ether && players.length > 1) { + totalMultiplier += 100; // + 10 % + } + if ((players.length % 10) == 0 && players.length > 1) { //Every 10th participant gets a 10% bonus + totalMultiplier += 100; // + 10 % + } + + //add new player in the queue ! + players.push(Player(msg.sender, (deposit * totalMultiplier) / 1000, false)); + + //--- UPDATING CONTRACT STATS ---- + winningPot += (deposit * potFrac) / 1000; // take some 3% to add for the winning pot ! + fees += (deposit * feeFrac) / 1000; // collect maintenance fees 2% + balance += (deposit * (1000 - ( feeFrac + potFrac ))) / 1000; // update balance + + //Classic payout for the participants + while (balance > players[payoutId].payout) { + lastPayout = players[payoutId].payout; + balance -= players[payoutId].payout; // update the balance + players[payoutId].paid=true; + players[payoutId].addr.transfer(lastPayout); // pay the man + // solhint-disable-next-line reentrancy + payoutId += 1; + } + + // Winning the Pot :) Condition : paying at least 1 people with deposit > 2 ether and having luck ! + if (( deposit > 1 ether ) && (deposit > players[payoutId].payout)) { + uint roll = random(100); // take a random number between 1 & 100 + if (roll % 10 == 0 ) { // if lucky : Chances : 1 out of 10 ! + // solhint-disable-next-line reentrancy + winningPot = 0; + msg.sender.transfer(winningPot); // Bravo ! + } + } + + } + + function random(uint max) private constant returns (uint256 result) { + //get the best seed for randomness + uint256 x = SALT * 100 / max; + uint256 y = SALT * block.number / (SALT % 5) ; + uint256 seed = block.number/3 + (SALT % 300) + lastPayout +y; + // solhint-disable-next-line not-rely-on-block-hash + uint256 h = uint256(block.blockhash(seed)); + return uint256((h / x)) % max + 1; //random number between 1 and max + } + + //---Contract management functions + function changeOwnership(address _owner) external onlyowner { + admin = _owner; + } + function watchBalance() external constant returns(uint totalBalance) { + totalBalance = balance / 1 wei; + } + + function watchBalanceInEther() external constant returns(uint totalBalanceInEther) { + totalBalanceInEther = balance / 1 ether; + } + + //Fee functions for creator + function collectAllFees() external onlyowner { + require(fees == 0, "No fees to collect"); + feeFrac -= 1; + fees = 0; + admin.transfer(fees); + } + + function getAndReduceFeesByFraction(uint p) external onlyowner { + if (fees == 0) feeFrac -= 1; // reduce fees. + fees -= fees / 1000 * p; + admin.transfer(fees / 1000 * p); // send a percent of fees + } + + + //---Contract informations + function nextPayout() external constant returns(uint next) { + next = players[payoutId].payout / 1 wei; + } + + function watchFees() external constant returns(uint collectedFees) { + collectedFees = fees / 1 wei; + } + + function watchWinningPot() external constant returns(uint winningPot) { + winningPot = winningPot / 1 wei; + } + + function watchLastPayout() external constant returns(uint payout) { + payout = lastPayout; + } + + function totalOfPlayers() external constant returns(uint numberOfPlayers) { + numberOfPlayers = players.length; + } + + function playerInfo(uint id) external constant returns(address player, uint payout, bool userPaid) { + if (id <= players.length) { + player = players[id].addr; + payout = players[id].payout / 1 wei; + userPaid=players[id].paid; + } + } + + function payoutQueueSize() external constant returns(uint queueSize) { + queueSize = players.length - payoutId; + } + +} diff --git a/not-so-smart-contracts/solidity/dangerous_strict_equalities/README.md b/not-so-smart-contracts/solidity/dangerous_strict_equalities/README.md new file mode 100644 index 00000000..5b17d2a9 --- /dev/null +++ b/not-so-smart-contracts/solidity/dangerous_strict_equalities/README.md @@ -0,0 +1,21 @@ +## Dangerous strict equalities + +### Description + +Use of strict equalities that can be easily manipulated by an attacker. + +### Exploit Scenario: + +```solidity +contract Crowdsale{ + function fund_reached() public returns(bool){ + return this.balance == 100 ether; + } +``` + +`Crowdsale` relies on `fund_reached` to know when to stop the sale of tokens. If `Crowdsale` reaches 100 ether and Bob sends 0.1 ether, `fund_reached` is always false and the crowdsale would never end. + +### Mitigations + +- Don't use strict equality to determine if an account has sufficient ethers or tokens. +- Use [slither](https://github.com/crytic/slither/) to detect this issue. diff --git a/not-so-smart-contracts/solidity/denial_of_service/README.md b/not-so-smart-contracts/solidity/denial_of_service/README.md new file mode 100644 index 00000000..a05d2056 --- /dev/null +++ b/not-so-smart-contracts/solidity/denial_of_service/README.md @@ -0,0 +1,20 @@ +# Denial of Service + +A malicious contract can permanently stall another contract that calls it by failing in a strategic way. In particular, contracts that bulk perform transactions or updates using a `for` loop can be DoS'd if a call to another contract or `transfer` fails during the loop. + +## Attack Scenarios + +- Auction contract where the previous winner must be reimbursed when they are outbid. If the call refunding the previous winner continuously fails, the auction is stalled and they become the de facto winner. It's better to use a pull-pattern that flags funds as eligible for withdrawal. See examples of an [insecure](auction.sol#L4) and [secure](auction#L24) version of this auction pattern. +- Contract iterates through an array to pay back its users. If one `transfer` fails in the middle of a `for` loop all reimbursements fail. See [this insecure example](list_dos.sol#L3) for an example of doing this wrong. +- Attacker spams contract, causing some array to become large. Then `for` loops iterating through the array might run out of gas and revert. See [this example](list_dos.sol#L26) that pauses & results list processing to prevent getting stuck due to out-of-gas errors. + +## Mitigations + +- Favor the pull-pattern: make funds available for users to withdraw rather than trying to send funds to users. +- If iterating over a dynamically sized data structure, be able to handle the case where the function takes multiple blocks to execute. One strategy for this is storing an iterator in a private variable and using `while` loop that stops when gas drops below certain threshold. + +## References + +- [Reddit conversation about stuck contract](https://www.reddit.com/r/ethereum/comments/4ghzhv/governmentals_1100_eth_jackpot_payout_is_stuck/) +- [ConsenSys re unexpected reverts](https://github.com/ConsenSys/smart-contract-best-practices#dos-with-unexpected-revert) +- [Griefing wallets](https://vessenes.com/ethereum-griefing-wallets-send-w-throw-considered-harmful/) diff --git a/not-so-smart-contracts/solidity/denial_of_service/auction.sol b/not-so-smart-contracts/solidity/denial_of_service/auction.sol new file mode 100644 index 00000000..62b61511 --- /dev/null +++ b/not-so-smart-contracts/solidity/denial_of_service/auction.sol @@ -0,0 +1,49 @@ +pragma solidity ^0.8.17; + +// Auction susceptible to DoS attack +contract InsecureAuction { + address public currentWinner = address(0); + uint public currentBid = 0; + + // Takes in bid, refunding the previous winner if they are outbid + function bid() public payable { + require(msg.value > currentBid, "Too little value to bid"); + // If the refund fails, the entire transaction reverts. + // Therefore a bidder who always fails will win + // E.g. if recipients fallback function is just revert() + if (currentWinner != 0) { + require(currentWinner.send(currentBid), "Send failure"); + } + currentWinner = msg.sender; // solhint-disable-line reentrancy + currentBid = msg.value; // solhint-disable-line reentrancy + } + +} + +// Auction that is NOT susceptible to DoS attack +contract SecureAuction { + address public currentWinner; + uint public currentBid; + + // Store refunds in mapping to avoid DoS + mapping(address => uint) public refunds; + + // Avoids "pushing" balance to users favoring "pull" architecture + function bid() external payable { + require(msg.value > currentBid, "Too little value to bid"); + if (currentWinner != 0) { + refunds[currentWinner] += currentBid; + } + currentWinner = msg.sender; + currentBid = msg.value; + } + + // Allows users to get their refund from auction + function withdraw() public { + // Do all state manipulation before external call to avoid reentrancy attack + uint refund = refunds[msg.sender]; + refunds[msg.sender] = 0; + msg.sender.transfer(refund); // even if this reverts, calls to bid() can still succeed + } + +} diff --git a/not-so-smart-contracts/solidity/denial_of_service/list_dos.sol b/not-so-smart-contracts/solidity/denial_of_service/list_dos.sol new file mode 100644 index 00000000..69a526f1 --- /dev/null +++ b/not-so-smart-contracts/solidity/denial_of_service/list_dos.sol @@ -0,0 +1,29 @@ +pragma solidity ^0.8.17; + +contract CrowdFundBad { + address[] private refundAddresses; + mapping(address => uint) public refundAmount; + function badRefund() public { + for(uint i; i < refundAddresses.length; i++) { + // If one of the following transfers reverts, they all revert + refundAddresses[i].transfer(refundAmount[refundAddresses[i]]); + } + } +} + +// This is safe against the list length causing out of gas issues +// This is NOT safe against the payee causing the execution to revert +contract CrowdFundSafer { + address[] private refundAddresses; + mapping(address => uint) public refundAmount; + uint256 public nextIdx; + function refundSafe() public { + uint256 i = nextIdx; + // Refunds are only processed as long as sufficient gas remains + while(i < refundAddresses.length && msg.gas > 200000) { + refundAddresses[i].transfer(refundAmount[i]); + i++; + } + nextIdx = i; // solhint-disable-line reentrancy + } +} diff --git a/not-so-smart-contracts/solidity/forced_ether_reception/README.md b/not-so-smart-contracts/solidity/forced_ether_reception/README.md new file mode 100644 index 00000000..25d30671 --- /dev/null +++ b/not-so-smart-contracts/solidity/forced_ether_reception/README.md @@ -0,0 +1,29 @@ +# Contracts can be forced to receive ether + +In certain circumstances, contracts can be forced to receive ether without triggering any code. This should be considered by the contract developers in order to avoid breaking important invariants in their code. + +## Attack Scenario + +An attacker can use a specially crafted contract to forceful send ether using `suicide` / `selfdestruct`: + +```solidity +contract Sender { + function receive_and_suicide(address target) payable { + suicide(target); + } +} +``` + +Alternatively, if a miner sets some contract as the block's `coinbase` then it's ether balance will be increased without executing any `fallback()` or `receive()` code that might be present. + +## Example + +- The MyAdvancedToken contract in [coin.sol](coin.sol#L145) is vulnerable to this attack. The owner will not be able to perform a migration of the contract if it receives ether outside of a call to `buy()`. + +## Mitigations + +There is no way to completely block the reception of ether. The only mitigation is to avoid assuming how the balance of the contract increases and implement checks to handle this type of edge cases. + +## References + +- [Solidity docs re sending & receiving ether](https://solidity.readthedocs.io/en/develop/security-considerations.html#sending-and-receiving-ether) diff --git a/not-so-smart-contracts/solidity/forced_ether_reception/coin.sol b/not-so-smart-contracts/solidity/forced_ether_reception/coin.sol new file mode 100644 index 00000000..eee5b4c4 --- /dev/null +++ b/not-so-smart-contracts/solidity/forced_ether_reception/coin.sol @@ -0,0 +1,129 @@ +pragma solidity ^0.8.17; + +contract Owned { + address public owner; + + constructor() { + owner = msg.sender; + } + + modifier onlyOwner { + require(msg.sender == owner, "permission denied"); + _; + } + + function transferOwnership(address newOwner) public onlyOwner { + owner = newOwner; + } +} + +interface TokenRecipient { + function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external; +} + +contract TokenERC20 { + string public name; + string public symbol; + uint8 public decimals = 18; // 18 decimals is the strongly suggested default, avoid changing it + uint256 public totalSupply; + + // This creates an array with all balances + mapping (address => uint256) public balanceOf; + mapping (address => mapping (address => uint256)) public allowance; + + // This generates a public event on the blockchain that will notify clients + event Transfer(address indexed from, address indexed to, uint256 value); + + // This generates a public event on the blockchain that will notify clients + event Approval(address indexed _owner, address indexed _spender, uint256 _value); + + constructor(string tokenName, string tokenSymbol) { + name = tokenName; + symbol = tokenSymbol; + } + + function transfer(address _to, uint256 _value) public returns (bool success) { + _transfer(msg.sender, _to, _value); + return true; + } + + function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { + require(_value <= allowance[_from][msg.sender], "Insuffient allowance"); + allowance[_from][msg.sender] -= _value; + _transfer(_from, _to, _value); + return true; + } + + function approve(address _spender, uint256 _value) public + returns (bool success) { + allowance[msg.sender][_spender] = _value; + emit Approval(msg.sender, _spender, _value); + return true; + } + + function _transfer(address _from, address _to, uint _value) internal { + // Prevent transfer to 0x0 address. + require(_to != 0x0, "Invalid address"); + // Check if the sender has enough + require(balanceOf[_from] >= _value, "Insufficient balance"); + // Check for overflows + require(balanceOf[_to] + _value > balanceOf[_to], "Overflow"); + // Save this for an assertion in the future + uint previousBalances = balanceOf[_from] + balanceOf[_to]; + // Subtract from the sender + balanceOf[_from] -= _value; + // Add the same to the recipient + balanceOf[_to] += _value; + emit Transfer(_from, _to, _value); + // Asserts are used to use static analysis to find bugs in your code. They should never fail + assert(balanceOf[_from] + balanceOf[_to] == previousBalances); + } + +} + +contract MyAdvancedToken is Owned, TokenERC20 { + mapping (address => bool) public frozenAccount; + + constructor(string tokenName, string tokenSymbol) { + TokenERC20(tokenName, tokenSymbol); + } + + // Internal transfer, only can be called by this contract + function _transfer(address _from, address _to, uint _value) internal { + require (_to != 0x0, "Invalid address"); + require (balanceOf[_from] >= _value, "Insufficient Balance"); + require (balanceOf[_to] + _value >= balanceOf[_to], "Overflow"); + require(!frozenAccount[_from], "Frozen sender"); + require(!frozenAccount[_to], "Frozen recipient"); + balanceOf[_from] -= _value; + balanceOf[_to] += _value; + emit Transfer(_from, _to, _value); + } + + // Buy tokens from contract by sending ether + function buy() public payable { + uint amount = msg.value; + balanceOf[msg.sender] += amount; + totalSupply += amount; // Increase total supply whenever new tokens are purchased + _transfer(address(0x0), msg.sender, amount); + } + + // Migration function + // NOTE: this function will fail if this contract receives ether outside of a call to buy() + function migrateAndDestroy() public onlyOwner { + assert(this.balance == totalSupply); // ERROR this can be DoS'd + selfdestruct(owner); + } + + // The following attempts to prevent anyone from sending ether to this contract + // BUT even with the following functions in place, this contract can still receive ether via: + // - a miner setting this address as it's beneficiary and then mining a block + // - a contract selfdestructs and sets this address as it's beneficiary + receive() public payable { + revert("Only send ether through buy()"); + } + fallback() public payable { + revert("Only send ether through buy()"); + } + +} diff --git a/not-so-smart-contracts/solidity/honeypots/GiftBox.sol b/not-so-smart-contracts/solidity/honeypots/GiftBox.sol new file mode 100644 index 00000000..dc1fdb49 --- /dev/null +++ b/not-so-smart-contracts/solidity/honeypots/GiftBox.sol @@ -0,0 +1,47 @@ +pragma solidity ^0.8.17; + +contract GiftBox { + string private message; + bool public passHasBeenSet = false; + address public sender; + bytes32 public passwordHash; + + function() public payable{} + + function setPassword(bytes32 newPassword) external payable { + if ((!passHasBeenSet && (msg.value > 1 ether)) || passwordHash == 0x0) { + passwordHash = getHash(newPassword); + sender = msg.sender; + } + } + + function setMessage(string _message) external { + if (msg.sender == sender) { + message = _message; + } + } + + function getGift(bytes password) external payable returns (string) { + if (passwordHash == getHash(password)) { + msg.sender.transfer(this.balance); + return message; + } + } + + function revoke() external payable { + if (msg.sender == sender) { + message = ""; + sender.transfer(this.balance); + } + } + + function getHash(bytes password) internal constant returns (bytes32) { + return keccak256(password); + } + + function passHasBeenSet(bytes32 currentPasswordHash) external { + if (msg.sender == sender && currentPasswordHash == passwordHash) { + passHasBeenSet = true; + } + } +} diff --git a/not-so-smart-contracts/solidity/honeypots/KingOfTheKill.sol b/not-so-smart-contracts/solidity/honeypots/KingOfTheKill.sol new file mode 100644 index 00000000..8d1ed373 --- /dev/null +++ b/not-so-smart-contracts/solidity/honeypots/KingOfTheKill.sol @@ -0,0 +1,40 @@ +pragma solidity ^0.5.17; + +// +//Live TEST ---- Please Do NOT use! Thanks! ---- +// +contract Ownable { + address public owner; + function Ownable() public { + owner = msg.sender; + } + modifier onlyOwner() { + require(msg.sender == owner, "Permission denied"); + _; + } +} + +// CEO Throne .. The CEO with the highest stake gets the control over the contract +// msg.value needs to be higher than largestStake when calling stake() + +contract KingOfTheKill is Ownable { + address public owner; + uint public largestStake; + + // stake() function being called with 0xde20bc92 and ETH :: recommended gas limit 35.000 + // The sent ETH is checked against largestStake + function stake() public payable { + // if you own the largest stake in a company, you own a company + if (msg.value > largestStake) { + owner = msg.sender; + largestStake = msg.value; + } + } + + // withdraw() function being called with 0x3ccfd60b :: recommened gas limit 30.000 + function withdraw() public onlyOwner { + // only owner can withdraw funds + msg.sender.transfer(this.balance); + } + +} diff --git a/not-so-smart-contracts/solidity/honeypots/Lottery.sol b/not-so-smart-contracts/solidity/honeypots/Lottery.sol new file mode 100644 index 00000000..2de58d52 --- /dev/null +++ b/not-so-smart-contracts/solidity/honeypots/Lottery.sol @@ -0,0 +1,107 @@ +pragma solidity ^0.4.26; + +/* + * This is a distributed lottery that chooses random addresses as lucky addresses. If these + * participate, they get the jackpot: 7 times the price of their bet. + * Of course one address can only win once. The owner regularly reseeds the secret + * seed of the contract (based on which the lucky addresses are chosen), so if you did not win, + * just wait for a reseed and try again! + * + * Jackpot chance: 1 in 8 + * Ticket price: Anything larger than (or equal to) 0.1 ETH + * Jackpot size: 7 times the ticket price + * + * HOW TO PARTICIPATE: Just send any amount greater than (or equal to) 0.1 ETH to the contract's address + * Keep in mind that your address can only win once + * + * If the contract doesn't have enough ETH to pay the jackpot, it sends the whole balance. +*/ + +contract OpenAddressLottery{ + struct SeedComponents{ + uint component1; + uint component2; + uint component3; + uint component4; + } + + address public owner; // address of the owner + uint private secretSeed; // seed used to calculate number of an address + uint private lastReseed; // last reseed - used to automatically reseed the contract every 1000 blocks + uint public luckyNumber = 7; // if the number of an address equals 7, it wins + + mapping (address => bool) public winner; // keeping track of addresses that have already won + + function OpenAddressLottery() { + owner = msg.sender; + reseed(SeedComponents( + (uint)(block.coinbase), + block.difficulty, + block.gaslimit, + block.timestamp // solhint-disable-line not-rely-on-time + )); + } + + function participate() public payable { + if (msg.value<0.1 ether) return; //verify ticket price + // make sure he hasn't won already + require(winner[msg.sender] == false, "Already won"); + if (luckyNumberOfAddress(msg.sender) == luckyNumber) { //check if it equals 7 + winner[msg.sender] = true; // every address can only win once + uint win=msg.value*7; //win = 7 times the ticket price + //if the balance isnt sufficient, send everything we've got + if (win>this.balance) win=this.balance; + msg.sender.transfer(win); + } + if (block.number-lastReseed>1000) { + //generate a quality random seed + reseed(SeedComponents( + (uint)(block.coinbase), + block.difficulty, + block.gaslimit, + block.timestamp // solhint-disable-line not-rely-on-time + )); + } + } + + function luckyNumberOfAddress(address addr) public constant returns(uint n){ + // calculate the number of current address - 1 in 8 chance + n = uint(keccak256(uint(addr), secretSeed)[0]) % 8; + } + + function reseed(SeedComponents components) internal { + secretSeed = uint256(keccak256( + components.component1, + components.component2, + components.component3, + components.component4 + )); //hash the incoming parameters and use the hash to (re)initialize the seed + lastReseed = block.number; + } + + function kill() public { + require(msg.sender==owner, "Permission denied"); + selfdestruct(msg.sender); + } + + function forceReseed() public { // reseed initiated by the owner - for testing purposes + require(msg.sender == owner, "Permission denied"); + SeedComponents s; + s.component1 = uint(msg.sender); + s.component2 = uint256( + block.blockhash(block.number - 1) // solhint-disable-line not-rely-on-block-hash + ); + s.component3 = block.difficulty*(uint)(block.coinbase); + s.component4 = tx.gasprice * 7; + reseed(s); //reseed + } + + // if someone sends money without any function call, just assume he wanted to participate + receive() public payable { + // owner can't participate, he can only fund the jackpot + if (msg.value >= 0.1 ether && msg.sender != owner) { + participate(); + } + } + +} diff --git a/not-so-smart-contracts/solidity/honeypots/Multiplicator.sol b/not-so-smart-contracts/solidity/honeypots/Multiplicator.sol new file mode 100644 index 00000000..044009de --- /dev/null +++ b/not-so-smart-contracts/solidity/honeypots/Multiplicator.sol @@ -0,0 +1,19 @@ +pragma solidity ^0.8.17; + +contract Multiplicator { + address public owner = msg.sender; + + fallback() payable {} + + function withdraw() external payable { + require(msg.sender == owner, "Permission Denied"); + owner.transfer(this.balance); + } + + function multiplicate(address adr) external payable { + if (msg.value >= this.balance) { + adr.transfer(this.balance + msg.value); + } + } + +} diff --git a/not-so-smart-contracts/solidity/honeypots/PrivateBank.sol b/not-so-smart-contracts/solidity/honeypots/PrivateBank.sol new file mode 100644 index 00000000..68a2b3c0 --- /dev/null +++ b/not-so-smart-contracts/solidity/honeypots/PrivateBank.sol @@ -0,0 +1,48 @@ +pragma solidity ^0.4.26; + +contract Log { + struct Message { + address sender; + string data; + uint val; + uint time; + } + Message[] public history; + Message public lastMsg; + function addMessage(address _adr,uint _val,string _data) public { + lastMsg.sender = _adr; + lastMsg.time = now; // solhint-disable-line not-rely-on-time + lastMsg.val = _val; + lastMsg.data = _data; + history.push(lastMsg); + } +} + +contract PrivateBank { + mapping (address => uint) public balances; + uint public minDeposit = 1 ether; + Log public transferLog; + + constructor(address _log) { + transferLog = Log(_log); + } + + function deposit() public payable { + if (msg.value >= minDeposit) { + balances[msg.sender]+=msg.value; + transferLog.addMessage(msg.sender, msg.value, "Deposit"); + } + } + + function cashOut(uint _am) public { + if (_am <= balances[msg.sender]) { + if (msg.sender.call{ value: _am}()) { // solhint-disable-line avoid-low-level-calls + balances[msg.sender] -= _am; + transferLog.addMessage(msg.sender, _am, "CashOut"); + } + } + } + + fallback() public payable {} + +} diff --git a/not-so-smart-contracts/solidity/honeypots/README.md b/not-so-smart-contracts/solidity/honeypots/README.md new file mode 100644 index 00000000..1a6ef7f6 --- /dev/null +++ b/not-so-smart-contracts/solidity/honeypots/README.md @@ -0,0 +1,71 @@ +# Honeypot Collection + +The Ethereum community has recently stumbled on a wide slew of honeypot smart contracts operating on the mainnet blockchain - something that we have been investigating for quite some time. They're designed to entice security researchers and developers to deposit Ethereum into the contract to obtain a chance to exploit 'easy vulnerabilities' in Solidity. However, once payment is deposited, the contracts will deploy subtle traps and quirks to lock out the user from successfully claiming the "prize." + +The traps vary in sophistication. Our blockchain security research has turned up six fundamental archetypes that construct most of these honeypots. Some of these contracts are weeks old. A few were released before September, 2017. Many seem to be moderately successful - trapping around 0.1 ether and containing approximately 5 transactions on average. Yet for every successful trap, a large minority of contracts had no interaction at all. These 'failed honeypots' most likely served the original developers as a testing environment. The existence of these contracts must be taken into account by academic researchers quantifying the effectiveness of tools and analysis methods for the Ethereum blockchain, given the potential to skew research results. + +Versions of the most recent compilers will emit warnings of most of these traps during compilation. However, some of the contracts rely on logic gaps in the solc compiler and the Solidity language itself. + +## [GiftBox](GiftBox.sol) + +Etherscan typically shows two transactions for a `GiftBox`-style honeypot. The first transaction is the contract creation, and the second is a call to a `setPassword` function that appears to set a "secret" `password` value. The secret can, of course, be easily observed on the blockchain, so the victim is tricked into submitting Ether with the correct value. + +
+ Trap Spoiler + Unbeknownst to the victim, the contract owner has already changed the stored hash of the secret, using an internal transaction with 0 value. Etherscan does not clearly display these 0 value internal transactions. The GiftBox owner might also be monitoring the mempool & would be prepared to front-run any withdrawals that submit the correct password. +
+ +## [King of the Hill](KingOfTheKill.sol) + +At first glance this contract appears to be your average King of the Hill ponzi scheme. Participants contribute ether to the contract via the `stake()` function that keeps track of the latest `owner` and ether deposit that allowed them to become to the current owner. The `withdraw()` function employs an `onlyOwner` modifier, seemingly allowing only the last person recently throned the ability to transfer all funds out of the contract. Stumbling upon this contract on etherscan and seeing an existing balance, one might think that there is a chance to gain some easy ether by taking advantage of a quick `stake()` claim and subsequent `withdraw()`. + +
+ Trap Spoiler + The heart of the honeypot lies in the fact that the owner variable qualifying the `onlyOwner` modifier is not the one being reassigned in the `stake()` function. This is a particularly nasty bug that is made even more insidious by the fact that solc compilers version <0.6.0 will throw no error or warning indicating that the owner address is in fact being shadowed by the inheriting `CEOThrone` contract. By re-declaring the variable in the child's scope, the contract ensures that owner in `Ownable` is actually never reassigned at all and allows the original creator to dump all funds at their leisure. +
+ +## [Lottery](Lottery.sol) + +This appears to be a straightforward lottery that gives users a 1/8 chance of paying out 7x the ticket price. You know that [a contract can't securely use random numbers on-chain](../bad_randomness) so you recognize an opportunity to game this lottery contract & score an easy win. But this lottery is not as simple as it appears. + +
+ Trap Spoiler + Uninitialized structs default to acting like storage pointers for solidity versions <0.5.0 allowing the owner to use the `SeedComponents` variable to overwrite private variables. +
+ +## [Multiplicator](Multiplicator.sol) + +Here is another ponzi-esque contract that promises to multiply your 'investment' by returning to you your initial deposit in addition to the current total balance of ether in the contract. The only condition is that the amount you send into the `multiplicate()` function must be greater than the current balance. + +
+ Trap Spoiler + The contract takes advantage of the fact that the global variable balance on the contract will always contain any ether sent to payable functions attached to `msg.value`. As a result, the condition `if(msg.value>=this.balance)` will always fail and the transfer will never occur. The `multiplicate()` function itself affirms the erroneous assumption by setting the transfer parameter as `this.balance + msg.value` (instead of only `this.balance`) +
+ +## [Private Bank](PrivateBank.sol) + +Someone familiar with smart contract security and some of the more technical vulnerabilities might recognize that this contract is susceptible to a [classic reentrancy attack](https://github.com/trailofbits/not-so-smart-contracts/tree/master/reentrancy). It takes advantage of the low-level call in the function `cashOut()` by `msg.sender.call.value(_am)())`. Since the user balance is only decremented afterwards, the caller's callback function can call back into the method, allowing an attacker to continuously call `cashOut()` beyond what their initial balance should allow for. The only main difference is the addition of a `Log` class that seems to keep track of transitions.. Should you deposit and then try to use this reentrancy bug to `cashOut` multiple times? + +
+ Trap Spoiler + + This honeypot takes advantage of the caller's assumptions, diverting attention away from the trap by seemingly including a reentrancy vulnerability. However, if you attempt to exploit this contract, you will find that your call to `cashOut` will fail every time. + + A closer inspection of the constructor will show that `TransferLog` is initialized from a user-supplied address. As long as the contract code at that location contains similar function signatures, the implementation of `AddMessage` can be completely different than the `Log` code contained in this source file. If this contract was deployed and only bytecode is available for the deployed `Log` contract, we can assume that it will revert or trap execution in a computationally expensive loop for everyone else but the owner. + +
+ +## [VarLoop](VarLoop.sol) + +The contract appears vulnerable to an old-fashioned constructor mismatch, allowing anyone to call the public method `Test1()` and double any ether they send to the function. The calculation involves a while loop which is strange, but the bounds conditions seem correct enough. + +
+ Trap Spoiler + + This contract takes advantage of different semantics between Solidity and JavaScript to create type confusion. The var keyword allows the compiler to infer the type of the assignment when declaring a variable. In this instance, `i1` and `i2` are resolved to fact be `uint8`. As such, their maximum value will be 255 after which they overflow (because the solidity version is <0.8.0) causing the loop condition `if (i1 < i2)` to fail, sending at most 255 wei to the caller before terminating. + + Fortunately the var keyword was deprecated by the Solidity authors for versions 0.7.0 or greater. + + Implicit conversion of `var` type variable into `uint8` causes payment loop to short-circuit. + +
diff --git a/not-so-smart-contracts/solidity/honeypots/VarLoop.sol b/not-so-smart-contracts/solidity/honeypots/VarLoop.sol new file mode 100644 index 00000000..4b9139b5 --- /dev/null +++ b/not-so-smart-contracts/solidity/honeypots/VarLoop.sol @@ -0,0 +1,31 @@ +pragma solidity ^0.4.26; + +contract Test1 { + address public owner = msg.sender; + + function withdraw() public payable { + require(msg.sender == owner, "Permission denied"); + owner.transfer(this.balance); + } + + fallback() payable {} + + // Old-school constructor + // solhint-disable-next-line func-name-mixedcase + function Test() public payable { + if (msg.value >= 1 ether) { + var i1 = 1; + var i2 = 0; + var amX2 = msg.value * 2; + + while(true) { + if (i1 < i2) break; + if (i1 > amX2) break; + i2 = i1; + i1++; + } + msg.sender.transfer(i2); + } + } + +} diff --git a/not-so-smart-contracts/solidity/integer_overflow/Overflow.sol b/not-so-smart-contracts/solidity/integer_overflow/Overflow.sol new file mode 100644 index 00000000..f16ec2aa --- /dev/null +++ b/not-so-smart-contracts/solidity/integer_overflow/Overflow.sol @@ -0,0 +1,16 @@ +pragma solidity ^0.7.6; + +contract Overflow { + uint private sellerBalance=0; + + function unsafeAdd(uint value) public returns (bool){ + sellerBalance += value; // possible overflow + // the following assertion will revert if the above overflows + // assert(sellerBalance >= value); + } + + function safeAdd(uint value) public returns (bool){ + require(value + sellerBalance >= sellerBalance, "Overflow"); + sellerBalance += value; + } +} diff --git a/not-so-smart-contracts/solidity/integer_overflow/README.md b/not-so-smart-contracts/solidity/integer_overflow/README.md new file mode 100644 index 00000000..0bfe3180 --- /dev/null +++ b/not-so-smart-contracts/solidity/integer_overflow/README.md @@ -0,0 +1,21 @@ +# Integer Overflow + +It is possible to cause solidity's native `+` and `-` operators to overflow (or underflow) on any type of integer in Solidity versions <0.8.0 or within `unchecked` blocks of solidity >=0.8.0 + +## Attack Scenarios + +- Attacker has 5 of some ERC20 token. They spend 6, but because the token doesn't check for underflows, they wind up with 2^256 tokens. + +- A contract contains a dynamic array and an unsafe `pop` method. An attacker can underflow the length of the array and alter other variables in the contract. + +## Mitigations + +- Use solidity >=0.8.0 and use `unchecked` blocks carefully and only where required. +- If using solidity <0.8.0, use OpenZeppelin's [SafeMath library](https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/math/SafeMath.sol) for arithmetic. +- Validate all arithmetic with both manual review and property-based fuzz testing. + +## Examples + +- In [Overflow](Overflow.sol), we give both unsafe and safe version of the `add` operation. + +- [A submission](https://github.com/Arachnid/uscc/tree/master/submissions-2017/doughoyte) to the Underhanded Solidity Coding Contest that exploits the unsafe dynamic array bug outlined above diff --git a/not-so-smart-contracts/solidity/race_condition/README.md b/not-so-smart-contracts/solidity/race_condition/README.md new file mode 100644 index 00000000..291fe672 --- /dev/null +++ b/not-so-smart-contracts/solidity/race_condition/README.md @@ -0,0 +1,14 @@ +# Race Condition + +There is a gap between the creation of a transaction and the moment it is accepted in the blockchain. Therefore, an attacker can take advantage of this gap to put a contract in a state that advantages them. + +## Attack Scenario + +- Bob creates `RaceCondition(100, token)`. Alice approves `RaceCondition` to spend all of her tokens. Alice calls `buy(150)` and Bob (or one of his bots) quickly sees the transaction and calls `changePrice(300)` with a high gas price. Bob's transaction is mined before Alice's and as a result, Bob received 300 tokens. See [the RaceCondition contract](RaceCondition.sol) for an example of this; + +- The ERC20 standard's `approve` and `transferFrom` functions are vulnerable to a race condition. Suppose Alice has approved Bob to spend 100 tokens on her behalf. She then decides to only approve him for 50 tokens and sends a second `approve` transaction. However, Bob sees that he's about to be downgraded and quickly submits a `transferFrom` for the original 100 tokens he was approved for. If this transaction gets mined before Alice's second `approve`, Bob will be able to spend an additional 50 of Alice's tokens (for a total of 150) after her new `approve` transaction is mined. + +## Mitigations + +- For the ERC20 bug, insist that Alice only be able to `approve` Bob when he is approved for 0 tokens. Or, Alice can reset Bob's allowance to zero before resetting it to ensure that he can't spend any more than her current allowance. +- Keep in mind that all transactions may be front-run. diff --git a/not-so-smart-contracts/solidity/race_condition/RaceCondition.sol b/not-so-smart-contracts/solidity/race_condition/RaceCondition.sol new file mode 100644 index 00000000..82cf2548 --- /dev/null +++ b/not-so-smart-contracts/solidity/race_condition/RaceCondition.sol @@ -0,0 +1,41 @@ +pragma solidity ^0.8.17; + +// https://github.com/ethereum/EIPs/issues/20 +interface IERC20 { + function totalSupply() public constant returns (uint totalSupply); + function balanceOf(address _owner) public constant returns (uint balance); + function transfer(address _to, uint _value) public returns (bool success); + function transferFrom(address _from, address _to, uint _value) public returns (bool success); + function approve(address _spender, uint _value) public returns (bool success); + function allowance(address _owner, address _spender) public constant returns (uint remaining); + event Transfer(address indexed _from, address indexed _to, uint _value); + event Approval(address indexed _owner, address indexed _spender, uint _value); +} + +contract RaceCondition{ + address private owner; + uint public price; + IERC20 public token; + + function RaceCondition(uint _price, IERC20 _token) public { + owner = msg.sender; + price = _price; + token = _token; + } + + // If the owner sees someone calls buy he can call changePrice to set a new price + // If his transaction is mined first, he can receive more tokens than expected by the new buyer + function buy(uint newPrice) external payable { + require(msg.value >= price, "Insufficient value"); + // we assume that the RaceCondition contract has enough allowance + token.transferFrom(msg.sender, owner, price); + price = newPrice; + owner = msg.sender; + } + + function changePrice(uint newPrice) external { + require(msg.sender == owner, "Permission denied"); + price = newPrice; + } + +} diff --git a/not-so-smart-contracts/solidity/reentrancy/README.md b/not-so-smart-contracts/solidity/reentrancy/README.md new file mode 100644 index 00000000..53829fdc --- /dev/null +++ b/not-so-smart-contracts/solidity/reentrancy/README.md @@ -0,0 +1,25 @@ +# Reentrancy + +[The DAO](https://en.wikipedia.org/wiki/The_DAO_(organization)) experienced the most famous [hack](http://hackingdistributed.com/2016/06/18/analysis-of-the-dao-exploit/) in Ethereum's history which ultimately led to a contentious hardfork as funds were recovered on Ethereum but not on Ethereum Classic. This hack was one of the first recorded reentrancy attacks: A state variable was changed after sending ether to an external contract. The attacker uses [a fallback function](ReentrancyExploit.sol#L26-L33) (which is automatically executed after ether is transferred from the targeted contract) to execute the vulnerable function again, *before* the state variable is changed. As a result, they could repeatedly withdraw funds that they did not own. + +Afterwards, solidity introduced `send` and `transfer` functions which only supply 2300 gas; enough to emit an Event but not enough to repeatedly call external contracts to perform the type of reentrancy that victimized The DAO. Reentrancy attacks triggered by simply sending ether are no longer feasible in the same way as it was for The DAO. + +However, reentrancy attacked lived on via more complicated function calls. For example, [SpankChain's state channels experienced a reentrancy attack](https://medium.com/spankchain/we-got-spanked-what-we-know-so-far-d5ed3a0f38fe) due to their support for user-supplied tokens. The attacker supplied a modified ERC20 token with a `transfer` function that called back into the SpankChain state channel manager to repeatedly withdraw funds. + +Notable, in both of these cases the exploited contract did not follow the [Check-Effects-Interaction pattern](https://docs.soliditylang.org/en/latest/security-considerations.html#use-the-checks-effects-interactions-pattern): +1. Check that the user-supplied parameters are valid eg that a withdrawing user has sufficient balance +2. Update accounting variables eg set the withdrawing user's balance to zero. +3. Send the user's withdrawal to their address. + +If SpankChain updated the user's balance to zero before calling `transfer` on the token contract, then there would be nothing to withdraw when the token called back into the withdrawal method. + +## Example + +See the four different withdraw functions of [Reenterable](Reenterable.sol). The first one is vulnerable to reentrancy attacks by the [ReentrancyExploiter](ReentrancyExploiter.sol) but the other three are fixed in the three different ways described below. + +## Mitigations + +- Use the check-effects-interaction pattern: update all bookkeeping state variables **before** allowing an external contracts to execute. +- Use `send` or `transfer` to move ether to an external account, these only supply 2300 gas which is not enough to call back into the calling contract. +- Use a reentrancy guard on sensitive external functions. This acts as a mutex to ensure that a function can't be called again until it completely finishes executing the current call. [OpenZeppelin's ReentrancyGuard](https://docs.openzeppelin.com/contracts/4.x/api/security#ReentrancyGuard) provides a ready-made function modifier for this. + diff --git a/not-so-smart-contracts/solidity/reentrancy/Reenterable.sol b/not-so-smart-contracts/solidity/reentrancy/Reenterable.sol new file mode 100644 index 00000000..0df36180 --- /dev/null +++ b/not-so-smart-contracts/solidity/reentrancy/Reenterable.sol @@ -0,0 +1,49 @@ +pragma solidity ^0.8.17; + +contract Reenterable { + mapping (address => uint) public balances; + bool public reentrancyGuard = true; + + function getBalance(address u) public constant returns(uint){ + return balances[u]; + } + + function deposit() public payable{ + balances[msg.sender] += msg.value; + } + + function withdraw() public { + // send balances[msg.sender] ethers to msg.sender + // if mgs.sender is a contract, it will call its fallback function + // solhint-disable-next-line avoid-low-level-calls + require(!(msg.sender.call{ value: balances[msg.sender] }()), "Call failed"); + balances[msg.sender] = 0; + } + + function checkEffectsInteractWithdraw() public { + // to protect against re-entrancy, the state variable is updated BEFORE the external call + uint amount = balances[msg.sender]; + balances[msg.sender] = 0; + // solhint-disable-next-line avoid-low-level-calls + require(!(msg.sender.call{ value: amount }()), "Call failed"); + } + + function transferWithdraw() public { + // send() and transfer() are safe against reentrancy + // they do not transfer all remaining gas, instead giving just enough gas to execute few instructions + msg.sender.transfer(balances[msg.sender]); + balances[msg.sender] = 0; // solhint-disable-line reentrancy + } + + function guardedWithdraw() public { + require(!reentrancyGuard, "Reentrant"); + reentrancyGuard = false; // Now, no external contracts can call this function + // send() and transfer() are safe against reentrancy + // they do not transfer all remaining gas, instead giving just enough gas to execute few instructions + // solhint-disable-next-line avoid-low-level-calls + require(!(msg.sender.call{ value: balances[msg.sender] }()), "Call failed"); + balances[msg.sender] = 0; + reentrancyGuard = true; // Now, external contracts can call this function again + } + +} diff --git a/not-so-smart-contracts/solidity/reentrancy/ReentrancyExploiter.sol b/not-so-smart-contracts/solidity/reentrancy/ReentrancyExploiter.sol new file mode 100644 index 00000000..2bcddbdc --- /dev/null +++ b/not-so-smart-contracts/solidity/reentrancy/ReentrancyExploiter.sol @@ -0,0 +1,51 @@ +pragma solidity ^0.8.17; + +contract ReentrancyExploiter { + bool public attackModeIsOn=false; + address public vulnerableContract; + address public owner; + + constructor() { + owner = msg.sender; + } + + function deposit(address _vulnerableContract) public payable{ + vulnerableContract = _vulnerableContract ; + // call addToBalance with msg.value ethers + require( + // solhint-disable-next-line avoid-low-level-calls + vulnerableContract.call{ value: msg.value }(bytes4(keccak256("addToBalance()"))), + "Call failed" + ); + } + + function launchAttack() public{ + attackModeIsOn = true; + // call withdrawBalance + // withdrawBalance calls the fallback of ReentranceExploit + require( + // solhint-disable-next-line avoid-low-level-calls + vulnerableContract.call(bytes4(keccak256("withdrawBalance()"))), + "Call failed" + ); + } + + // This function will be executed when Reenterable sends ether to this contract + fallback() payable { + // atackModeIsOn is used to execute the attack only once + // otherwise there is an infinite loop between withdrawBalance and the fallback function + if (attackModeIsOn){ + attackModeIsOn = false; + require( + // solhint-disable-next-line avoid-low-level-calls + vulnerableContract.call(bytes4(keccak256("withdrawBalance()"))), + "Call failed" + ); + } + } + + function getMoney() public { + selfdestruct(owner); + } + +} diff --git a/not-so-smart-contracts/solidity/rtlo/README.md b/not-so-smart-contracts/solidity/rtlo/README.md new file mode 100644 index 00000000..85e431c1 --- /dev/null +++ b/not-so-smart-contracts/solidity/rtlo/README.md @@ -0,0 +1,37 @@ +## Right-To-Left-Override character + +### Description + +An attacker can manipulate the logic of the contract by using a right-to-left-override character (U+202E) + +### Exploit Scenario: + +```solidity +contract Token +{ + + address payable o; // owner + mapping(address => uint) tokens; + + function withdraw() external returns(uint) + { + uint amount = tokens[msg.sender]; + address payable d = msg.sender; + tokens[msg.sender] = 0; + _withdraw(/*owner‮/*noitanitsed*/ d, o/*‭ + /*value */, amount); + } + + function _withdraw(address payable fee_receiver, address payable destination, uint value) internal + { + fee_receiver.transfer(1); + destination.transfer(value); + } +} +``` + +`Token` uses the right-to-left-override character when calling `_withdraw`. As a result, the fee is incorrectly sent to `msg.sender`, and the token balance is sent to the owner. + +### Mitigations +- Special control characters must not be allowed. +- Use [slither](https://github.com/crytic/slither/) to detect the right-to-left-override character. diff --git a/not-so-smart-contracts/solidity/tautology/README.md b/not-so-smart-contracts/solidity/tautology/README.md new file mode 100644 index 00000000..ee5e3283 --- /dev/null +++ b/not-so-smart-contracts/solidity/tautology/README.md @@ -0,0 +1,33 @@ +## Tautology or contradiction + +### Description + +Expressions that are tautologies or contradictions. + +### Exploit Scenario: + +```solidity +contract A { + function f(uint x) public { + // ... + if (x >= 0) { // bad -- always true + // ... + } + // ... + } + + function g(uint8 y) public returns (bool) { + // ... + return (y < 512); // bad! + // ... + } +} +``` + +`x` is an `uint256`, as a result `x >= 0` will be always true. + +`y` is an `uint8`, as a result `y <512` will be always true. + +### Mitigations +- Use [Slither](https://github.com/crytic/slither/) to detect tautologies. + diff --git a/not-so-smart-contracts/solidity/unprotected_function/README.md b/not-so-smart-contracts/solidity/unprotected_function/README.md new file mode 100644 index 00000000..ba3dbafd --- /dev/null +++ b/not-so-smart-contracts/solidity/unprotected_function/README.md @@ -0,0 +1,17 @@ +# Unprotected function + +Missing (or incorrectly used) modifier on a function allows an attacker to use sensitive functionality in the contract. + +## Attack Scenario + +An [unprotected contract](Unprotected.sol) with a `changeOwner` function does not label it as `private` nor does it specify the `onlyOwner` modifier, therefore anyone can call `changeOwner` to take control of the contract. + +## Mitigations + +Review all sensitive or administrative function and ensure that they have appropriate visibility & function modifiers. + +## Historical Examples +- April 2016: [Rubixi allows anyone to become owner](https://etherscan.io/address/0xe82719202e5965Cf5D9B6673B7503a3b92DE20be#code) +- July 2017: [Parity Wallet](https://blog.zeppelin.solutions/on-the-parity-wallet-multisig-hack-405a8c12e8f7). For code, see [initWallet](WalletLibrary_source_code/WalletLibrary.sol) +- BitGo Wallet v2 allows anyone to call tryInsertSequenceId. If you try close to MAXINT, no further transactions would be allowed. [Fix: make tryInsertSequenceId private.](https://github.com/BitGo/eth-multisig-v2/commit/8042188f08c879e06f097ae55c140e0aa7baaff8#diff-b498cc6fd64f83803c260abd8de0a8f5) +- Feb 2020: [Nexus Mutual's Oraclize callback was unprotected—allowing anyone to call it.](https://medium.com/nexus-mutual/responsible-vulnerability-disclosure-ece3fe3bcefa) Oraclize triggers a rebalance to occur via Uniswap. diff --git a/not-so-smart-contracts/solidity/unprotected_function/Unprotected.sol b/not-so-smart-contracts/solidity/unprotected_function/Unprotected.sol new file mode 100644 index 00000000..eebcd84e --- /dev/null +++ b/not-so-smart-contracts/solidity/unprotected_function/Unprotected.sol @@ -0,0 +1,23 @@ +pragma solidity ^0.8.17; + +contract Unprotected { + address private owner; + + modifier onlyOwner { + require(msg.sender==owner, "Permission denied"); + _; + } + + constructor() { + owner = msg.sender; + } + + // This function is missing the onlyOwner function modifier + function changeOwner(address _newOwner) public { + owner = _newOwner; + } + + function changeOwnerFixed(address _newOwner) public onlyOwner { + owner = _newOwner; + } +} diff --git a/not-so-smart-contracts/solidity/unprotected_function/WalletLibrary_source_code/WalletLibrary.sol b/not-so-smart-contracts/solidity/unprotected_function/WalletLibrary_source_code/WalletLibrary.sol new file mode 100644 index 00000000..d4f94d94 --- /dev/null +++ b/not-so-smart-contracts/solidity/unprotected_function/WalletLibrary_source_code/WalletLibrary.sol @@ -0,0 +1,462 @@ +// 0xa657491c1e7f16adb39b9b60e87bbb8d93988bc3#code +//sol Wallet +// Multi-sig, daily-limited account proxy/wallet. +// @authors: +// Gav Wood +// inheritable "property" contract that enables methods to be protected by requiring the acquiescence of either a +// single, or, crucially, each of a number of, designated owners. +// usage: +// use modifiers onlyowner (just own owned) or onlymanyowners(hash), whereby the same hash must be provided by +// some number (specified in constructor) of the set of owners (specified in the constructor, modifiable) before the +// interior is executed. + +pragma solidity ^0.4.9; + +contract WalletEvents { + // EVENTS + + // this contract only has six types of events: it can accept a confirmation, in which case + // we record owner and operation (hash) alongside it. + event Confirmation(address owner, bytes32 operation); + event Revoke(address owner, bytes32 operation); + + // some others are in the case of an owner changing. + event OwnerChanged(address oldOwner, address newOwner); + event OwnerAdded(address newOwner); + event OwnerRemoved(address oldOwner); + + // the last one is emitted if the required signatures change + event RequirementChanged(uint newRequirement); + + // Funds has arrived into the wallet (record how much). + event Deposit(address _from, uint value); + // Single transaction going out of the wallet (record who signed for it, how much, and to whom it's going). + event SingleTransact(address owner, uint value, address to, bytes data, address created); + // Multi-sig transaction going out of the wallet (record who signed for it last, the operation hash, how much, and to whom it's going). + event MultiTransact(address owner, bytes32 operation, uint value, address to, bytes data, address created); + // Confirmation still needed for a transaction. + event ConfirmationNeeded(bytes32 operation, address initiator, uint value, address to, bytes data); +} + +contract WalletAbi { + // Revokes a prior confirmation of the given operation + function revoke(bytes32 _operation) external; + + // Replaces an owner `_from` with another `_to`. + function changeOwner(address _from, address _to) external; + + function addOwner(address _owner) external; + + function removeOwner(address _owner) external; + + function changeRequirement(uint _newRequired) external; + + function isOwner(address _addr) constant returns (bool); + + function hasConfirmed(bytes32 _operation, address _owner) external constant returns (bool); + + // (re)sets the daily limit. needs many of the owners to confirm. doesn't alter the amount already spent today. + function setDailyLimit(uint _newLimit) external; + + function execute(address _to, uint _value, bytes _data) external returns (bytes32 o_hash); + function confirm(bytes32 _h) returns (bool o_success); +} + +contract WalletLibrary is WalletEvents { + // TYPES + + // struct for the status of a pending operation. + struct PendingState { + uint yetNeeded; + uint ownersDone; + uint index; + } + + // Transaction structure to remember details of transaction lest it need be saved for a later call. + struct Transaction { + address to; + uint value; + bytes data; + } + + // MODIFIERS + + // simple single-sig function modifier. + modifier onlyowner { + if (isOwner(msg.sender)) + _; + } + // multi-sig function modifier: the operation must have an intrinsic hash in order + // that later attempts can be realised as the same underlying operation and + // thus count as confirmations. + modifier onlymanyowners(bytes32 _operation) { + if (confirmAndCheck(_operation)) + _; + } + + // METHODS + + // gets called when no other function matches + function() payable { + // just being sent some cash? + if (msg.value > 0) + Deposit(msg.sender, msg.value); + } + + // constructor is given number of sigs required to do protected "onlymanyowners" transactions + // as well as the selection of addresses capable of confirming them. + function initMultiowned(address[] _owners, uint _required) { + m_numOwners = _owners.length + 1; + m_owners[1] = uint(msg.sender); + m_ownerIndex[uint(msg.sender)] = 1; + for (uint i = 0; i < _owners.length; ++i) + { + m_owners[2 + i] = uint(_owners[i]); + m_ownerIndex[uint(_owners[i])] = 2 + i; + } + m_required = _required; + } + + // Revokes a prior confirmation of the given operation + function revoke(bytes32 _operation) external { + uint ownerIndex = m_ownerIndex[uint(msg.sender)]; + // make sure they're an owner + if (ownerIndex == 0) return; + uint ownerIndexBit = 2**ownerIndex; + var pending = m_pending[_operation]; + if (pending.ownersDone & ownerIndexBit > 0) { + pending.yetNeeded++; + pending.ownersDone -= ownerIndexBit; + Revoke(msg.sender, _operation); + } + } + + // Replaces an owner `_from` with another `_to`. + function changeOwner(address _from, address _to) onlymanyowners(sha3(msg.data)) external { + if (isOwner(_to)) return; + uint ownerIndex = m_ownerIndex[uint(_from)]; + if (ownerIndex == 0) return; + + clearPending(); + m_owners[ownerIndex] = uint(_to); + m_ownerIndex[uint(_from)] = 0; + m_ownerIndex[uint(_to)] = ownerIndex; + OwnerChanged(_from, _to); + } + + function addOwner(address _owner) onlymanyowners(sha3(msg.data)) external { + if (isOwner(_owner)) return; + + clearPending(); + if (m_numOwners >= c_maxOwners) + reorganizeOwners(); + if (m_numOwners >= c_maxOwners) + return; + m_numOwners++; + m_owners[m_numOwners] = uint(_owner); + m_ownerIndex[uint(_owner)] = m_numOwners; + OwnerAdded(_owner); + } + + function removeOwner(address _owner) onlymanyowners(sha3(msg.data)) external { + uint ownerIndex = m_ownerIndex[uint(_owner)]; + if (ownerIndex == 0) return; + if (m_required > m_numOwners - 1) return; + + m_owners[ownerIndex] = 0; + m_ownerIndex[uint(_owner)] = 0; + clearPending(); + reorganizeOwners(); //make sure m_numOwner is equal to the number of owners and always points to the optimal free slot + OwnerRemoved(_owner); + } + + function changeRequirement(uint _newRequired) onlymanyowners(sha3(msg.data)) external { + if (_newRequired > m_numOwners) return; + m_required = _newRequired; + clearPending(); + RequirementChanged(_newRequired); + } + + // Gets an owner by 0-indexed position (using numOwners as the count) + function getOwner(uint ownerIndex) external constant returns (address) { + return address(m_owners[ownerIndex + 1]); + } + + function isOwner(address _addr) constant returns (bool) { + return m_ownerIndex[uint(_addr)] > 0; + } + + function hasConfirmed(bytes32 _operation, address _owner) external constant returns (bool) { + var pending = m_pending[_operation]; + uint ownerIndex = m_ownerIndex[uint(_owner)]; + + // make sure they're an owner + if (ownerIndex == 0) return false; + + // determine the bit to set for this owner. + uint ownerIndexBit = 2**ownerIndex; + return !(pending.ownersDone & ownerIndexBit == 0); + } + + // constructor - stores initial daily limit and records the present day's index. + function initDaylimit(uint _limit) { + m_dailyLimit = _limit; + m_lastDay = today(); + } + // (re)sets the daily limit. needs many of the owners to confirm. doesn't alter the amount already spent today. + function setDailyLimit(uint _newLimit) onlymanyowners(sha3(msg.data)) external { + m_dailyLimit = _newLimit; + } + // resets the amount already spent today. needs many of the owners to confirm. + function resetSpentToday() onlymanyowners(sha3(msg.data)) external { + m_spentToday = 0; + } + + // constructor - just pass on the owner array to the multiowned and + // the limit to daylimit + function initWallet(address[] _owners, uint _required, uint _daylimit) { + initDaylimit(_daylimit); + initMultiowned(_owners, _required); + } + + // kills the contract sending everything to `_to`. + function kill(address _to) onlymanyowners(sha3(msg.data)) external { + suicide(_to); + } + + // Outside-visible transact entry point. Executes transaction immediately if below daily spend limit. + // If not, goes into multisig process. We provide a hash on return to allow the sender to provide + // shortcuts for the other confirmations (allowing them to avoid replicating the _to, _value + // and _data arguments). They still get the option of using them if they want, anyways. + function execute(address _to, uint _value, bytes _data) external onlyowner returns (bytes32 o_hash) { + // first, take the opportunity to check that we're under the daily limit. + if ((_data.length == 0 && underLimit(_value)) || m_required == 1) { + // yes - just execute the call. + address created; + if (_to == 0) { + created = create(_value, _data); + } else { + if (!_to.call.value(_value)(_data)) + throw; + } + SingleTransact(msg.sender, _value, _to, _data, created); + } else { + // determine our operation hash. + o_hash = sha3(msg.data, block.number); + // store if it's new + if (m_txs[o_hash].to == 0 && m_txs[o_hash].value == 0 && m_txs[o_hash].data.length == 0) { + m_txs[o_hash].to = _to; + m_txs[o_hash].value = _value; + m_txs[o_hash].data = _data; + } + if (!confirm(o_hash)) { + ConfirmationNeeded(o_hash, msg.sender, _value, _to, _data); + } + } + } + + function create(uint _value, bytes _code) internal returns (address o_addr) { + assembly { + o_addr := create(_value, add(_code, 0x20), mload(_code)) + jumpi(invalidJumpLabel, iszero(extcodesize(o_addr))) + } + } + + // confirm a transaction through just the hash. we use the previous transactions map, m_txs, in order + // to determine the body of the transaction from the hash provided. + function confirm(bytes32 _h) onlymanyowners(_h) returns (bool o_success) { + if (m_txs[_h].to != 0 || m_txs[_h].value != 0 || m_txs[_h].data.length != 0) { + address created; + if (m_txs[_h].to == 0) { + created = create(m_txs[_h].value, m_txs[_h].data); + } else { + if (!m_txs[_h].to.call.value(m_txs[_h].value)(m_txs[_h].data)) + throw; + } + + MultiTransact(msg.sender, _h, m_txs[_h].value, m_txs[_h].to, m_txs[_h].data, created); + delete m_txs[_h]; + return true; + } + } + + // INTERNAL METHODS + + function confirmAndCheck(bytes32 _operation) internal returns (bool) { + // determine what index the present sender is: + uint ownerIndex = m_ownerIndex[uint(msg.sender)]; + // make sure they're an owner + if (ownerIndex == 0) return; + + var pending = m_pending[_operation]; + // if we're not yet working on this operation, switch over and reset the confirmation status. + if (pending.yetNeeded == 0) { + // reset count of confirmations needed. + pending.yetNeeded = m_required; + // reset which owners have confirmed (none) - set our bitmap to 0. + pending.ownersDone = 0; + pending.index = m_pendingIndex.length++; + m_pendingIndex[pending.index] = _operation; + } + // determine the bit to set for this owner. + uint ownerIndexBit = 2**ownerIndex; + // make sure we (the message sender) haven't confirmed this operation previously. + if (pending.ownersDone & ownerIndexBit == 0) { + Confirmation(msg.sender, _operation); + // ok - check if count is enough to go ahead. + if (pending.yetNeeded <= 1) { + // enough confirmations: reset and run interior. + delete m_pendingIndex[m_pending[_operation].index]; + delete m_pending[_operation]; + return true; + } + else + { + // not enough: record that this owner in particular confirmed. + pending.yetNeeded--; + pending.ownersDone |= ownerIndexBit; + } + } + } + + function reorganizeOwners() private { + uint free = 1; + while (free < m_numOwners) + { + while (free < m_numOwners && m_owners[free] != 0) free++; + while (m_numOwners > 1 && m_owners[m_numOwners] == 0) m_numOwners--; + if (free < m_numOwners && m_owners[m_numOwners] != 0 && m_owners[free] == 0) + { + m_owners[free] = m_owners[m_numOwners]; + m_ownerIndex[m_owners[free]] = free; + m_owners[m_numOwners] = 0; + } + } + } + + // checks to see if there is at least `_value` left from the daily limit today. if there is, subtracts it and + // returns true. otherwise just returns false. + function underLimit(uint _value) internal onlyowner returns (bool) { + // reset the spend limit if we're on a different day to last time. + if (today() > m_lastDay) { + m_spentToday = 0; + m_lastDay = today(); + } + // check to see if there's enough left - if so, subtract and return true. + // overflow protection // dailyLimit check + if (m_spentToday + _value >= m_spentToday && m_spentToday + _value <= m_dailyLimit) { + m_spentToday += _value; + return true; + } + return false; + } + + // determines today's index. + function today() private constant returns (uint) { return now / 1 days; } + + function clearPending() internal { + uint length = m_pendingIndex.length; + + for (uint i = 0; i < length; ++i) { + delete m_txs[m_pendingIndex[i]]; + + if (m_pendingIndex[i] != 0) + delete m_pending[m_pendingIndex[i]]; + } + + delete m_pendingIndex; + } + + // FIELDS + address constant _walletLibrary = 0xcafecafecafecafecafecafecafecafecafecafe; + + // the number of owners that must confirm the same operation before it is run. + uint public m_required; + // pointer used to find a free slot in m_owners + uint public m_numOwners; + + uint public m_dailyLimit; + uint public m_spentToday; + uint public m_lastDay; + + // list of owners + uint[256] m_owners; + + uint constant c_maxOwners = 250; + // index on the list of owners to allow reverse lookup + mapping(uint => uint) m_ownerIndex; + // the ongoing operations. + mapping(bytes32 => PendingState) m_pending; + bytes32[] m_pendingIndex; + + // pending transactions we have at present. + mapping (bytes32 => Transaction) m_txs; +} + +contract Wallet is WalletEvents { + + // WALLET CONSTRUCTOR + // calls the `initWallet` method of the Library in this context + function Wallet(address[] _owners, uint _required, uint _daylimit) { + // Signature of the Wallet Library's init function + bytes4 sig = bytes4(sha3("initWallet(address[],uint256,uint256)")); + address target = _walletLibrary; + + // Compute the size of the call data : arrays has 2 + // 32bytes for offset and length, plus 32bytes per element ; + // plus 2 32bytes for each uint + uint argarraysize = (2 + _owners.length); + uint argsize = (2 + argarraysize) * 32; + + assembly { + // Add the signature first to memory + mstore(0x0, sig) + // Add the call data, which is at the end of the + // code + codecopy(0x4, sub(codesize, argsize), argsize) + // Delegate call to the library + delegatecall(sub(gas, 10000), target, 0x0, add(argsize, 0x4), 0x0, 0x0) + } + } + + // METHODS + + // gets called when no other function matches + function() payable { + // just being sent some cash? + if (msg.value > 0) + Deposit(msg.sender, msg.value); + else if (msg.data.length > 0) + _walletLibrary.delegatecall(msg.data); + } + + // Gets an owner by 0-indexed position (using numOwners as the count) + function getOwner(uint ownerIndex) constant returns (address) { + return address(m_owners[ownerIndex + 1]); + } + + // As return statement unavailable in fallback, explicit the method here + + function hasConfirmed(bytes32 _operation, address _owner) external constant returns (bool) { + return _walletLibrary.delegatecall(msg.data); + } + + function isOwner(address _addr) constant returns (bool) { + return _walletLibrary.delegatecall(msg.data); + } + + // FIELDS + address constant _walletLibrary = 0xcafecafecafecafecafecafecafecafecafecafe; + + // the number of owners that must confirm the same operation before it is run. + uint public m_required; + // pointer used to find a free slot in m_owners + uint public m_numOwners; + + uint public m_dailyLimit; + uint public m_spentToday; + uint public m_lastDay; + + // list of owners + uint[256] m_owners; +} diff --git a/not-so-smart-contracts/solidity/unused_return/README.md b/not-so-smart-contracts/solidity/unused_return/README.md new file mode 100644 index 00000000..ded1b9b4 --- /dev/null +++ b/not-so-smart-contracts/solidity/unused_return/README.md @@ -0,0 +1,22 @@ +# Unused return + +## Description + +The return value of an external call is not checked. + +## Exploit Scenario: + +```solidity +contract MyConc{ + using SafeMath for uint; + function my_func(uint a, uint b) public{ + a.add(b); + } +} +``` + +`MyConc` calls `add` of SafeMath, but does not store the result in `a`. As a result, the computation has no effect. + +## Mitigations +- Ensure that all the return values of the function calls are used. +- Use [Slither](https://github.com/crytic/slither/) to detect function calls without any effect.