├── .github ├── CODEOWNERS └── workflows │ └── assign.yml ├── LICENSE ├── Logos ├── C Crypto.com (green).png ├── Lionhead Crypto.com (blue).png └── README.md ├── README.md ├── codeql-pack.lock.yml ├── qlpack.yml ├── queries.xml └── src ├── bech32-constants.ql ├── beginendblock-panic.ql ├── floating-point-ops.ql ├── goroutine.ql ├── map-iteration.ql ├── path-beginendblock-panic.ql ├── sensitive-import.ql └── system-time.ql /.github/CODEOWNERS: -------------------------------------------------------------------------------- 1 | * @crypto-com/codeql-maintainers -------------------------------------------------------------------------------- /.github/workflows/assign.yml: -------------------------------------------------------------------------------- 1 | name: Issue assignment 2 | 3 | on: 4 | issues: 5 | types: [opened] 6 | 7 | permissions: 8 | issues: write 9 | 10 | jobs: 11 | auto-assign: 12 | runs-on: ubuntu-latest 13 | steps: 14 | - name: 'Auto-assign issue' 15 | uses: pozil/auto-assign-issue@v1 16 | with: 17 | assignees: calvinaco 18 | numOfAssignee: 1 19 | allowSelfAssign: true 20 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2021 Crypto.com 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /Logos/C Crypto.com (green).png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/crypto-com/cosmos-sdk-codeql/95e3707788fe2b95c84b7bc8e5694977fdc95611/Logos/C Crypto.com (green).png -------------------------------------------------------------------------------- /Logos/Lionhead Crypto.com (blue).png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/crypto-com/cosmos-sdk-codeql/95e3707788fe2b95c84b7bc8e5694977fdc95611/Logos/Lionhead Crypto.com (blue).png -------------------------------------------------------------------------------- /Logos/README.md: -------------------------------------------------------------------------------- 1 | # Logos 2 | 3 | The logos are registered trademarks of Crypto.com and any unauthorised use of the logos or its elements may constitute a breach of such trademark. The name or logos of Crypto.com may not be used or reproduced without the specific, prior written permission of Crypto.com. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # cosmos-sdk-codeql 2 | A query suite for common bug patterns in Cosmos SDK-based applications. 3 | 4 | ## Passive Maintenance 5 | This repository is in a passive maintenance mode: it is not actively developed, but we will accept pull requests and issues. It may, however, take some time to respond. 6 | 7 | ## Usage 8 | In CodeQL CLI, you can download it using the following command: 9 | 10 | ```bash 11 | $ codeql pack download crypto-com/cosmos-sdk-codeql@0.0.7 12 | ``` 13 | 14 | [See more details in the CodeQL CLI documentation](https://codeql.github.com/docs/codeql-cli/publishing-and-using-codeql-packs/). 15 | 16 | In order to add the extra queries to the CI pipeline, you can use the `queries` or `packs` option in the CodeQL initialization: 17 | 18 | ```yaml 19 | #... 20 | # Initializes the CodeQL tools for scanning. 21 | - name: Initialize CodeQL 22 | uses: github/codeql-action/init@v2 23 | with: 24 | languages: 'go' 25 | queries: crypto-com/cosmos-sdk-codeql@v0.0.7, <...other queries...> 26 | #... 27 | ``` 28 | 29 | [See more details in the GitHub Code Scanning documentation](https://docs.github.com/en/code-security/code-scanning/automatically-scanning-your-code-for-vulnerabilities-and-errors/configuring-code-scanning#running-additional-queries). 30 | 31 | ## False Negatives 32 | The queries have heuristics based on the usage in the Cosmos SDK codebase to reduce false positives. 33 | They may, however, lead to false negatives: for example, if you used "client" package's code parts (that may be ignored by queries) 34 | in consensus-critical sections, related bugs from ignored packages may not be uncovered by queries. 35 | If you are worried about false negatives in particular queries, [you can open an issue to discuss the query change](https://github.com/crypto-com/cosmos-sdk-codeql/issues/new). 36 | Alternatively, you can tweak the query and either execute it manually from time to time, or add the tweaked query to your CI scanning action. 37 | 38 | ## False Positives 39 | The queries over-approximate and may lead to false positives. If you encounter a false positive, you can do the following: 40 | 41 | 1. [you can dismiss the false positive alerts in the Security tab on GitHub](https://docs.github.com/en/code-security/code-scanning/automatically-scanning-your-code-for-vulnerabilities-and-errors/managing-code-scanning-alerts-for-your-repository#dismissing--alerts); 42 | 2. if see a repeating pattern of false positives, [you can open an issue to discuss the query improvement](https://github.com/crypto-com/cosmos-sdk-codeql/issues/new); 43 | 3. alternatively, if you cannot dismiss alerts in the Security tab on GitHub, 44 | some of the queries will ignore findings that have an explicit comment (starting with "SAFE:") 45 | that explains why it is safe to ignore that bit of code. The comments can be placed either on the preceding line or on the enclosing function: 46 | 47 | ```go 48 | // SAFE: ...explanation why findings in this function are false positives... 49 | func myFun(...) { 50 | ... 51 | } 52 | 53 | func myFun2(...) { 54 | ... 55 | // SAFE: ...explanation why this particular finding is a false positive... 56 | myVar := ... 57 | ... 58 | } 59 | ``` -------------------------------------------------------------------------------- /codeql-pack.lock.yml: -------------------------------------------------------------------------------- 1 | --- 2 | dependencies: 3 | codeql/go-all: 4 | version: 0.3.6 5 | compiled: false 6 | lockVersion: 1.0.0 7 | -------------------------------------------------------------------------------- /qlpack.yml: -------------------------------------------------------------------------------- 1 | --- 2 | library: false 3 | name: crypto-com/cosmos-sdk-codeql 4 | extractor: go 5 | version: 0.0.8 6 | description: A query suite for common bug patterns in Cosmos SDK-based applications 7 | default-suite: 8 | - query: src/bech32-constants.ql 9 | - query: src/beginendblock-panic.ql 10 | - query: src/path-beginendblock-panic.ql 11 | - query: src/floating-point-ops.ql 12 | - query: src/goroutine.ql 13 | - query: src/map-iteration.ql 14 | - query: src/sensitive-import.ql 15 | - query: src/system-time.ql 16 | license: Apache 2 17 | dependencies: 18 | codeql/go-all: 0.3.6 19 | -------------------------------------------------------------------------------- /queries.xml: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/bech32-constants.ql: -------------------------------------------------------------------------------- 1 | /** 2 | * @name Directly using the bech32 constants 3 | * @description Bech32 constants are hardcoded to Gaia defaults; the external applications would need to use `GetConfig().GetBech32...` functions instead of constants 4 | * @kind problem 5 | * @problem.severity warning 6 | * @id crypto-com/cosmos-sdk-codeql/bech-32-constant 7 | * @tags correctness 8 | */ 9 | 10 | import go 11 | 12 | from ConstantName cn 13 | where 14 | cn.toString().matches("Bech32%") and 15 | cn.getLocation().getFile().getPackageName() != "types" and 16 | cn.getLocation().getFile().getPackageName() != "config" 17 | select cn, "Directly using the bech32 constants instead of the configuration values" 18 | -------------------------------------------------------------------------------- /src/beginendblock-panic.ql: -------------------------------------------------------------------------------- 1 | /** 2 | * @name Panic in BeginBock or EndBlock consensus methods 3 | * @description Panics in BeginBlocker and EndBlocker could cause a chain halt: https://docs.cosmos.network/master/building-modules/beginblock-endblock.html 4 | * @kind problem 5 | * @precision low 6 | * @problem.severity warning 7 | * @id crypto-com/cosmos-sdk-codeql/beginendblock-panic 8 | * @tags correctness 9 | */ 10 | 11 | import go 12 | 13 | predicate isBeginOrEndBlock(string funName) { 14 | // TODO: make it more precise to check if it's from Keeper or ABCI interface 15 | funName = "BeginBlock" or 16 | funName = "EndBlock" or 17 | funName = "BeginBlocker" or 18 | funName = "EndBlocker" 19 | } 20 | 21 | predicate isIrrelevantPackage(string packageName) { 22 | // for normal cases, panics to cause chain halts are desired in crisis or upgrade 23 | // (but there may be unwanted cases, i.e. false negatives) 24 | packageName = "crisis" or 25 | packageName = "upgrade" or 26 | packageName = "mocks" 27 | } 28 | 29 | class CallNodeWithFamily extends DataFlow::CallNode, DataFlow::Node { 30 | CallNodeWithFamily() { this instanceof DataFlow::CallNode } 31 | 32 | DataFlow::CallNode getParentCallNode() { result.getACallee() = this.getRoot() } 33 | } 34 | 35 | /* 36 | * This query looks for all calls to panic that originated from EndBlock or BeginBlock 37 | * (as defined by the isBeginOrEndBlock predicate). 38 | * It excludes potential false-positives (as defined by isLikelyFalsePositive predicate) 39 | * and those stemming from irrelevant packages (as defined by isIrrelevantPackage predicate). 40 | * It also exludes panics which are preceded by a comment containing the string "SAFE:". 41 | */ 42 | 43 | from CallNodeWithFamily panicCall, CallNodeWithFamily sourceCall 44 | where 45 | panicCall.getTarget().mustPanic() and 46 | sourceCall = panicCall.getParentCallNode*() and 47 | isBeginOrEndBlock(sourceCall.getEnclosingCallable().getName()) and 48 | not isIrrelevantPackage(panicCall.getFile().getPackageName()) and 49 | not panicCall.getArgument(0).getStringValue() = "not implemented" and 50 | // explicit comment explaining why it is safe 51 | // TODO: extract to a common predicate or a class 52 | not exists(CommentGroup c | 53 | panicCall.asExpr().getLocation().getStartLine() - 1 = c.getLocation().getStartLine() or 54 | panicCall.asExpr().getEnclosingFunction().getLocation().getStartLine() - 1 = 55 | c.getLocation().getStartLine() 56 | | 57 | c.getAComment().getText().matches("%SAFE:%") 58 | ) 59 | select panicCall, 60 | "Possible panics in BeginBock- or EndBlock-related consensus methods could cause a chain halt" 61 | -------------------------------------------------------------------------------- /src/floating-point-ops.ql: -------------------------------------------------------------------------------- 1 | /** 2 | * @name Floating point arithmetic 3 | * @kind problem 4 | * @description Floating point operations are not associative and may lead to surprising situations: https://en.wikipedia.org/wiki/Floating-point_arithmetic#Accuracy_problems 5 | * @problem.severity recommendation 6 | * @id crypto-com/cosmos-sdk-codeql/floating-point-arithmetic 7 | * @tags correctness 8 | */ 9 | 10 | import go 11 | 12 | from ArithmeticBinaryExpr e 13 | where 14 | ( 15 | e.getLeftOperand().getType() instanceof FloatType or 16 | e.getRightOperand().getType() instanceof FloatType 17 | ) and 18 | e.getLocation().getFile().getPackageName() != "simulation" and 19 | // explicit comment explaining why it is safe 20 | // TODO: extract to a common predicate or a class 21 | not exists(CommentGroup c | 22 | e.getLocation().getStartLine() - 1 = c.getLocation().getStartLine() or 23 | e.getEnclosingFunction().getLocation().getStartLine() - 1 = c.getLocation().getStartLine() 24 | | 25 | c.getAComment().getText().matches("%SAFE:%") 26 | ) 27 | select e, 28 | "Floating point arithmetic operations are not associative and a possible source of non-determinism" 29 | -------------------------------------------------------------------------------- /src/goroutine.ql: -------------------------------------------------------------------------------- 1 | /** 2 | * @name Spawning a Go routine 3 | * @kind problem 4 | * @description The execution order of Go routines may cause a non-deterministic behavior, so a caution should be taken when using Go routines in consensus-critical code sections. 5 | * @problem.severity recommendation 6 | * @id crypto-com/cosmos-sdk-codeql/goroutine 7 | * @tags correctness 8 | */ 9 | 10 | import go 11 | 12 | predicate isIrrelevantPackage(string packageName) { 13 | packageName = "testdata" or 14 | packageName = "testdata_pulsar" or 15 | packageName = "rosetta" or 16 | packageName = "simapp" or 17 | packageName = "simulation" or 18 | packageName = "testutil" or 19 | packageName = "client" or 20 | packageName = "cli" or 21 | packageName = "mocks" or 22 | packageName = "mock" or 23 | packageName = "version" or 24 | packageName = "genutil" or 25 | packageName = "memdb" or 26 | packageName = "db" or 27 | packageName = "server" or 28 | packageName = "snapshots" or 29 | packageName = "file" or 30 | packageName = "network" or 31 | packageName = "grpc" 32 | } 33 | 34 | from GoStmt goroutine 35 | where 36 | not goroutine.getFile().getBaseName().matches("%.pb.%") and 37 | not goroutine.getCall().getCalleeName().matches("%Snapshot%") and 38 | not isIrrelevantPackage(goroutine.getFile().getPackageName()) 39 | select goroutine, "Spawning a Go routine may be a possible source of non-determinism" 40 | -------------------------------------------------------------------------------- /src/map-iteration.ql: -------------------------------------------------------------------------------- 1 | /** 2 | * @name Iteration over map 3 | * @description Iteration over map is non-deterministic and could cause issues in consensus-critical code. 4 | * @kind problem 5 | * @problem.severity warning 6 | * @id crypto-com/cosmos-sdk-codeql/map-iteration 7 | * @tags correctness 8 | */ 9 | 10 | import go 11 | 12 | predicate isIrrelevantPackage(string packageName) { 13 | packageName = "testdata" or 14 | packageName = "testdata_pulsar" or 15 | packageName = "rosetta" or 16 | packageName = "simapp" or 17 | packageName = "simulation" or 18 | packageName = "testutil" or 19 | packageName = "client" or 20 | packageName = "cli" or 21 | packageName = "mocks" or 22 | packageName = "mock" or 23 | packageName = "version" or 24 | packageName = "genutil" 25 | } 26 | 27 | from RangeStmt loop 28 | where 29 | loop.getDomain().getType() instanceof MapType and 30 | // ignore iterations over maps where keys are subsequently sorted 31 | // TODO: make it more general to also ignore cases where keys are written to fields 32 | // in structs that are stored in arrays which are then sorted by those fields 33 | not exists( 34 | Assignment a, CallExpr sort, VariableName unsorted, VariableName sorted, VariableName key 35 | | 36 | loop.getBody().getAChild*() = a and 37 | sort.getTarget().getQualifiedName().prefix(4) = "sort" and 38 | a.getAnRhs().getAChild*() = key and 39 | key.getTarget() = loop.getKey().(VariableName).getTarget() and 40 | a.getAnLhs() = unsorted and 41 | sort.getAnArgument() = sorted and 42 | unsorted.getTarget() = sorted.getTarget() and 43 | loop.getParent*().getAChild*() = sort 44 | ) and 45 | not isIrrelevantPackage(loop.getFile().getPackageName()) and 46 | // explicit comment explaining why it is safe 47 | // TODO: extract to a common predicate or a class 48 | not exists(CommentGroup c | 49 | loop.getLocation().getStartLine() - 1 = c.getLocation().getStartLine() or 50 | loop.getEnclosingFunction().getLocation().getStartLine() - 1 = c.getLocation().getStartLine() 51 | | 52 | c.getAComment().getText().matches("%SAFE:%") 53 | ) 54 | select loop, "Iteration over map may be a possible source of non-determinism" 55 | -------------------------------------------------------------------------------- /src/path-beginendblock-panic.ql: -------------------------------------------------------------------------------- 1 | /** 2 | * @name Panic in BeginBock or EndBlock consensus methods 3 | * @description Panics in BeginBlocker and EndBlocker could cause a chain halt: https://docs.cosmos.network/master/building-modules/beginblock-endblock.html 4 | * @kind path-problem 5 | * @precision low 6 | * @problem.severity warning 7 | * @id crypto-com/cosmos-sdk-codeql/beginendblock-panic 8 | * @tags correctness 9 | */ 10 | 11 | import go 12 | 13 | predicate isBeginOrEndBlock(string funName) { 14 | // TODO: make it more precise to check if it's from Keeper or ABCI interface 15 | funName = "BeginBlock" or 16 | funName = "EndBlock" or 17 | funName = "BeginBlocker" or 18 | funName = "EndBlocker" 19 | } 20 | 21 | predicate isIrrelevantPackage(string packageName) { 22 | // for normal cases, panics to cause chain halts are desired in crisis or upgrade 23 | // (but there may be unwanted cases, i.e. false negatives) 24 | packageName = "crisis" or 25 | packageName = "upgrade" or 26 | packageName = "mocks" 27 | } 28 | 29 | class CallNodeWithFamily extends DataFlow::CallNode, DataFlow::Node { 30 | CallNodeWithFamily() { this instanceof DataFlow::CallNode } 31 | 32 | DataFlow::CallNode getChildCallNode() { this.getACallee() = result.getRoot() } 33 | } 34 | 35 | query predicate edges(CallNodeWithFamily a, CallNodeWithFamily b) { a.getChildCallNode() = b } 36 | 37 | /* 38 | * This query looks for all function call paths originating from EndBlock or BeginBlock 39 | * (as defined by the isBeginOrEndBlock predicate) and ending in a panic. 40 | * It excludes irrelevant packages (as defined by isIrrelevantPackage predicate). 41 | * It also exludes panics which are preceded by a comment containing the string "SAFE:". 42 | */ 43 | 44 | from CallNodeWithFamily panicCall, CallNodeWithFamily sourceCall 45 | where 46 | panicCall.getTarget().mustPanic() and 47 | edges*(sourceCall, panicCall) and 48 | isBeginOrEndBlock(sourceCall.getEnclosingCallable().getName()) and 49 | not isIrrelevantPackage(panicCall.getFile().getPackageName()) and 50 | not panicCall.getArgument(0).getStringValue() = "not implemented" and 51 | // explicit comment explaining why it is safe 52 | // TODO: extract to a common predicate or a class 53 | not exists(CommentGroup c | 54 | panicCall.asExpr().getLocation().getStartLine() - 1 = c.getLocation().getStartLine() or 55 | panicCall.asExpr().getEnclosingFunction().getLocation().getStartLine() - 1 = 56 | c.getLocation().getStartLine() 57 | | 58 | c.getAComment().getText().matches("%SAFE:%") 59 | ) 60 | select sourceCall, sourceCall, panicCall, "path flow from Begin/EndBlock to a panic call" 61 | -------------------------------------------------------------------------------- /src/sensitive-import.ql: -------------------------------------------------------------------------------- 1 | /** 2 | * @name Sensitive package import 3 | * @kind problem 4 | * @description Certain system packages (unsafe, rand, reflect, runtime...) may cause a non-deterministic behavior, so a caution should be taken when importing them. 5 | * @problem.severity recommendation 6 | * @id crypto-com/cosmos-sdk-codeql/sensitive-import 7 | * @tags correctness 8 | */ 9 | 10 | import go 11 | 12 | predicate isSensitiveImport(string packageName) { 13 | packageName = "unsafe" or 14 | packageName = "rand" or 15 | packageName = "reflect" or 16 | packageName = "runtime" 17 | } 18 | 19 | predicate isIrrelevantPackage(string packageName) { 20 | packageName = "testdata" or 21 | packageName = "testdata_pulsar" or 22 | packageName = "rosetta" or 23 | packageName = "simapp" or 24 | packageName = "simulation" or 25 | packageName = "testutil" or 26 | packageName = "client" or 27 | packageName = "cli" or 28 | packageName = "mocks" or 29 | packageName = "mock" or 30 | packageName = "version" or 31 | packageName = "genutil" 32 | } 33 | 34 | from ImportSpec imp 35 | where 36 | isSensitiveImport(imp.getPath()) and 37 | not isIrrelevantPackage(imp.getFile().getPackageName()) and 38 | // explicit comment explaining why it is safe 39 | // TODO: extract to a common predicate or a class 40 | not exists(CommentGroup c | 41 | imp.getLocation().getStartLine() - 1 = c.getLocation().getStartLine() 42 | | 43 | c.getAComment().getText().matches("%SAFE:%") 44 | ) 45 | select imp, 46 | "Certain system packages contain functions which may be a possible source of non-determinism" 47 | -------------------------------------------------------------------------------- /src/system-time.ql: -------------------------------------------------------------------------------- 1 | /** 2 | * @name Calling the system time 3 | * @description Calling the system time is non-deterministic and could cause issues in consensus-critical code. 4 | * @kind problem 5 | * @problem.severity warning 6 | * @id crypto-com/cosmos-sdk-codeql/system-time 7 | * @tags correctness 8 | */ 9 | 10 | import go 11 | 12 | predicate isIrrelevantPackage(string packageName) { 13 | packageName = "cli" or packageName = "main" or packageName = "testutil" 14 | } 15 | 16 | from CallExpr call 17 | where 18 | call.getTarget().getQualifiedName() = "time.Now" and 19 | // string formatting is usually a false positive (used in logging etc.), 20 | // so it's usually ok to ignore. 21 | // but there could be false negatives (if the string formatting output is written to a consensus state) 22 | not ( 23 | call.getParent().(CallExpr).getTarget().getQualifiedName() = 24 | "github.com/cosmos/cosmos-sdk/types.FormatTimeBytes" or 25 | call.getParent*().(CallExpr).getTarget().getQualifiedName().matches("fmt.Sprintf") 26 | ) and 27 | not call.getEnclosingFunction().getName().matches("Test%") and 28 | call.getLocation().getFile().getBaseName() != "test_helpers.go" and 29 | not isIrrelevantPackage(call.getLocation().getFile().getPackageName()) and 30 | // ignore cases where time is fed into telemetry calls 31 | not exists(DataFlow::CallNode telemetryCall | 32 | telemetryCall 33 | .getExpr() 34 | .(CallExpr) 35 | .getTarget() 36 | .getQualifiedName() 37 | .matches("github.com/cosmos/cosmos-sdk/telemetry%") 38 | | 39 | DataFlow::localFlow(DataFlow::exprNode(call), telemetryCall.getAnArgument()) 40 | ) and 41 | // explicit comment explaining why it is safe 42 | // TODO: extract to a common predicate or a class 43 | not exists(CommentGroup c | 44 | call.getLocation().getStartLine() - 1 = c.getLocation().getStartLine() or 45 | call.getEnclosingFunction().getLocation().getStartLine() - 1 = c.getLocation().getStartLine() 46 | | 47 | c.getAComment().getText().matches("%SAFE:%") 48 | ) 49 | select call, "Calling the system time may be a possible source of non-determinism" 50 | --------------------------------------------------------------------------------