├── .github ├── .codecov.yml ├── ISSUE_TEMPLATE │ ├── bug-or-issue.yaml │ ├── config.yml │ └── feature-request.yaml ├── PULL_REQUEST_TEMPLATE.md ├── dependabot.yml ├── licenserc.yml └── workflows │ ├── build.yml │ ├── codeql.yml │ └── license-checker.yml ├── .gitignore ├── CODEOWNERS ├── LICENSE ├── MAINTAINERS ├── Makefile ├── README.md ├── conformance_test.go ├── errors.go ├── errors_test.go ├── go.mod ├── http.go ├── http_test.go ├── internal ├── cms │ ├── cms.go │ ├── errors.go │ ├── errors_test.go │ ├── signed.go │ ├── signed_test.go │ └── testdata │ │ ├── GlobalSignRootCA.crt │ │ ├── Sha1SignedData.p7s │ │ ├── SignedDataWithoutSignedAttributes.p7s │ │ ├── TimeStampToken.p7s │ │ ├── TimeStampTokenInvalidSignedAttributeContentType.p7s │ │ ├── TimeStampTokenWithAnInvalidAndAValidSignerInfo.p7s │ │ ├── TimeStampTokenWithInvalidCertificates.p7s │ │ ├── TimeStampTokenWithInvalidContentType.p7s │ │ ├── TimeStampTokenWithInvalidSignature.p7s │ │ ├── TimeStampTokenWithInvalidSigningTime.p7s │ │ ├── TimeStampTokenWithSignedAttributeSHA1.p7s │ │ ├── TimeStampTokenWithSignerVersion2.p7s │ │ ├── TimeStampTokenWithSigningTime.p7s │ │ ├── TimeStampTokenWithSigningTimeBeforeExpected.p7s │ │ ├── TimeStampTokenWithUnknownSignerIssuer.p7s │ │ ├── TimeStampTokenWithoutCertificate.p7s │ │ ├── TimeStampTokenWithoutSignedAttributeContentType.p7s │ │ ├── TimeStampTokenWithoutSignedAttributeDigest.p7s │ │ ├── TimeStampTokenWithoutSignedAttributes.p7s │ │ └── TimeStampTokenWithoutSigner.p7s ├── encoding │ └── asn1 │ │ ├── asn1.go │ │ ├── asn1_test.go │ │ └── ber │ │ ├── ber.go │ │ ├── ber_test.go │ │ ├── common.go │ │ ├── common_test.go │ │ ├── constructed.go │ │ ├── constructed_test.go │ │ ├── primitive.go │ │ └── primitive_test.go ├── hashutil │ ├── hash.go │ └── hash_test.go └── oid │ ├── algorithm.go │ ├── algorithm_test.go │ ├── hash.go │ ├── hash_test.go │ └── oid.go ├── pki ├── errors.go ├── errors_test.go ├── pki.go └── pki_test.go ├── request.go ├── request_test.go ├── response.go ├── response_test.go ├── testdata ├── GlobalSignRootCA.crt ├── SHA1TimeStampToken.p7s ├── TimeStampToken.p7s ├── TimeStampTokenNoRoot.p7s ├── TimeStampTokenWithInvalidSignature.p7s ├── TimeStampTokenWithInvalidSigningCertificateV1.p7s ├── TimeStampTokenWithInvalidSigningCertificateV2.p7s ├── TimeStampTokenWithInvalidTSTInfo.p7s ├── TimeStampTokenWithInvalideContentType.p7s ├── TimeStampTokenWithMismatchCertHash.p7s ├── TimeStampTokenWithSHA1CertHash.p7s ├── TimeStampTokenWithSigningCertificateV1.p7s ├── TimeStampTokenWithSigningCertificateV1NoCert.p7s ├── TimeStampTokenWithSigningCertificateV2NoCert.p7s ├── TimeStampTokenWithTSTInfoVersion2.p7s ├── TimeStampTokenWithValidAndInvalidSignerInfos.p7s ├── TimeStampTokenWithWrongSigningCertificateV2IssuerChoiceTag.p7s ├── TimeStampTokenWithoutCertificate.p7s ├── TimeStampTokenWithoutSigningCertificate.p7s ├── TimeStampTokenWithoutSigningCertificateV2IssuerSerial.p7s ├── granted.tsq ├── malformed.tsq ├── rejection.tsq └── validResponseWithSigningCertificateV1.tsr ├── timestamp.go ├── timestamp_test.go ├── token.go ├── token_test.go └── tspclient.go /.github/.codecov.yml: -------------------------------------------------------------------------------- 1 | # Copyright The Notary Project Authors. 2 | # Licensed under the Apache License, Version 2.0 (the "License"); 3 | # you may not use this file except in compliance with the License. 4 | # You may obtain a copy of the License at 5 | # 6 | # http://www.apache.org/licenses/LICENSE-2.0 7 | # 8 | # Unless required by applicable law or agreed to in writing, software 9 | # distributed under the License is distributed on an "AS IS" BASIS, 10 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | # See the License for the specific language governing permissions and 12 | # limitations under the License. 13 | 14 | coverage: 15 | status: 16 | project: 17 | default: 18 | target: 80% 19 | patch: 20 | default: 21 | target: 80% -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug-or-issue.yaml: -------------------------------------------------------------------------------- 1 | # Copyright The Notary Project Authors. 2 | # Licensed under the Apache License, Version 2.0 (the "License"); 3 | # you may not use this file except in compliance with the License. 4 | # You may obtain a copy of the License at 5 | # 6 | # http://www.apache.org/licenses/LICENSE-2.0 7 | # 8 | # Unless required by applicable law or agreed to in writing, software 9 | # distributed under the License is distributed on an "AS IS" BASIS, 10 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | # See the License for the specific language governing permissions and 12 | # limitations under the License. 13 | 14 | name: 🐛 Bug or Issue 15 | description: Something is not working as expected or not working at all! Report it here! 16 | labels: [bug, triage] 17 | body: 18 | - type: markdown 19 | attributes: 20 | value: | 21 | Thank you for taking the time to fill out this issue report. 🛑 Please check existing issues first before continuing: https://github.com/notaryproject/tspclient-go/issues 22 | - type: textarea 23 | id: verbatim 24 | validations: 25 | required: true 26 | attributes: 27 | label: "What is not working as expected?" 28 | description: "In your own words, describe what the issue is." 29 | - type: textarea 30 | id: expect 31 | validations: 32 | required: true 33 | attributes: 34 | label: "What did you expect to happen?" 35 | description: "A clear and concise description of what you expected to happen." 36 | - type: textarea 37 | id: reproduce 38 | validations: 39 | required: true 40 | attributes: 41 | label: "How can we reproduce it?" 42 | description: "Detailed steps to reproduce the behavior, code snippets are welcome." 43 | - type: textarea 44 | id: environment 45 | validations: 46 | required: true 47 | attributes: 48 | label: Describe your environment 49 | description: "OS and Golang version" 50 | - type: textarea 51 | id: version 52 | validations: 53 | required: true 54 | attributes: 55 | label: What is the version of your tspclient-go Library? 56 | description: "Check the `go.mod` file for the library version." 57 | - type: markdown 58 | attributes: 59 | value: | 60 | If you want to contribute to this project, we will be happy to guide you through the contribution process especially when you already have a good proposal or understanding of how to fix this issue. Join us at https://slack.cncf.io/ and choose #notary-project channel. 61 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/config.yml: -------------------------------------------------------------------------------- 1 | # Copyright The Notary Project Authors. 2 | # Licensed under the Apache License, Version 2.0 (the "License"); 3 | # you may not use this file except in compliance with the License. 4 | # You may obtain a copy of the License at 5 | # 6 | # http://www.apache.org/licenses/LICENSE-2.0 7 | # 8 | # Unless required by applicable law or agreed to in writing, software 9 | # distributed under the License is distributed on an "AS IS" BASIS, 10 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | # See the License for the specific language governing permissions and 12 | # limitations under the License. 13 | 14 | blank_issues_enabled: false 15 | contact_links: 16 | - name: Ask a question 17 | url: https://slack.cncf.io/ 18 | about: "Join #notary-project channel on CNCF Slack" 19 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature-request.yaml: -------------------------------------------------------------------------------- 1 | # Copyright The Notary Project Authors. 2 | # Licensed under the Apache License, Version 2.0 (the "License"); 3 | # you may not use this file except in compliance with the License. 4 | # You may obtain a copy of the License at 5 | # 6 | # http://www.apache.org/licenses/LICENSE-2.0 7 | # 8 | # Unless required by applicable law or agreed to in writing, software 9 | # distributed under the License is distributed on an "AS IS" BASIS, 10 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | # See the License for the specific language governing permissions and 12 | # limitations under the License. 13 | 14 | name: 🚀 Feature Request 15 | description: Suggest an idea for this project. 16 | labels: [enhancement, triage] 17 | body: 18 | - type: markdown 19 | attributes: 20 | value: | 21 | Thank you for taking the time to suggest a useful feature for the project! 22 | - type: textarea 23 | id: problem 24 | validations: 25 | required: true 26 | attributes: 27 | label: "Is your feature request related to a problem?" 28 | description: "A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]" 29 | - type: textarea 30 | id: solution 31 | validations: 32 | required: true 33 | attributes: 34 | label: "What solution do you propose?" 35 | description: "A clear and concise description of what you want to happen." 36 | - type: textarea 37 | id: alternatives 38 | validations: 39 | required: true 40 | attributes: 41 | label: "What alternatives have you considered?" 42 | description: "A clear and concise description of any alternative solutions or features you've considered." 43 | - type: textarea 44 | id: context 45 | validations: 46 | required: false 47 | attributes: 48 | label: "Any additional context?" 49 | description: "Add any other context or screenshots about the feature request here." 50 | - type: markdown 51 | attributes: 52 | value: | 53 | If you want to contribute to this project, we will be happy to guide you through the contribution process especially when you already have a good proposal or understanding of how to improve the functionality. Join us at https://slack.cncf.io/ and choose #notary-project channel. 54 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | **What this PR does / why we need it**: 2 | 3 | **Which issue(s) this PR resolves** *(optional, in `resolves #(, resolves #, ...)` format, will close the issue(s) when PR gets merged)*: 4 | Resolves # 5 | 6 | **Please check the following list**: 7 | - [ ] Does the affected code have corresponding tests, e.g. unit test? 8 | - [ ] Does this introduce breaking changes that would require an announcement or bumping the major version? 9 | - [ ] Do all new files have an appropriate license header? 10 | 11 | 12 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | # Copyright The Notary Project Authors. 2 | # Licensed under the Apache License, Version 2.0 (the "License"); 3 | # you may not use this file except in compliance with the License. 4 | # You may obtain a copy of the License at 5 | # 6 | # http://www.apache.org/licenses/LICENSE-2.0 7 | # 8 | # Unless required by applicable law or agreed to in writing, software 9 | # distributed under the License is distributed on an "AS IS" BASIS, 10 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | # See the License for the specific language governing permissions and 12 | # limitations under the License. 13 | 14 | version: 2 15 | updates: 16 | - package-ecosystem: "gomod" 17 | directory: "/" 18 | schedule: 19 | interval: "weekly" 20 | - package-ecosystem: "github-actions" 21 | directory: "/" 22 | schedule: 23 | interval: "weekly" 24 | -------------------------------------------------------------------------------- /.github/licenserc.yml: -------------------------------------------------------------------------------- 1 | # Copyright The Notary Project Authors. 2 | # Licensed under the Apache License, Version 2.0 (the "License"); 3 | # you may not use this file except in compliance with the License. 4 | # You may obtain a copy of the License at 5 | # 6 | # http://www.apache.org/licenses/LICENSE-2.0 7 | # 8 | # Unless required by applicable law or agreed to in writing, software 9 | # distributed under the License is distributed on an "AS IS" BASIS, 10 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | # See the License for the specific language governing permissions and 12 | # limitations under the License. 13 | 14 | header: 15 | license: 16 | spdx-id: Apache-2.0 17 | content: | 18 | Copyright The Notary Project Authors. 19 | Licensed under the Apache License, Version 2.0 (the "License"); 20 | you may not use this file except in compliance with the License. 21 | You may obtain a copy of the License at 22 | 23 | http://www.apache.org/licenses/LICENSE-2.0 24 | 25 | Unless required by applicable law or agreed to in writing, software 26 | distributed under the License is distributed on an "AS IS" BASIS, 27 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 28 | See the License for the specific language governing permissions and 29 | limitations under the License. 30 | 31 | paths-ignore: 32 | - '**/*.md' 33 | - 'CODEOWNERS' 34 | - 'LICENSE' 35 | - 'MAINTAINERS' 36 | - 'go.mod' 37 | - 'go.sum' 38 | - '**/testdata/**' 39 | 40 | comment: on-failure 41 | 42 | dependency: 43 | files: 44 | - go.mod -------------------------------------------------------------------------------- /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | # Copyright The Notary Project Authors. 2 | # Licensed under the Apache License, Version 2.0 (the "License"); 3 | # you may not use this file except in compliance with the License. 4 | # You may obtain a copy of the License at 5 | # 6 | # http://www.apache.org/licenses/LICENSE-2.0 7 | # 8 | # Unless required by applicable law or agreed to in writing, software 9 | # distributed under the License is distributed on an "AS IS" BASIS, 10 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | # See the License for the specific language governing permissions and 12 | # limitations under the License. 13 | 14 | name: build 15 | 16 | on: 17 | push: 18 | branches: main 19 | pull_request: 20 | branches: main 21 | 22 | jobs: 23 | build: 24 | uses: notaryproject/notation-core-go/.github/workflows/reusable-build.yml@main 25 | secrets: 26 | CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }} 27 | -------------------------------------------------------------------------------- /.github/workflows/codeql.yml: -------------------------------------------------------------------------------- 1 | # Copyright The Notary Project Authors. 2 | # Licensed under the Apache License, Version 2.0 (the "License"); 3 | # you may not use this file except in compliance with the License. 4 | # You may obtain a copy of the License at 5 | # 6 | # http://www.apache.org/licenses/LICENSE-2.0 7 | # 8 | # Unless required by applicable law or agreed to in writing, software 9 | # distributed under the License is distributed on an "AS IS" BASIS, 10 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | # See the License for the specific language governing permissions and 12 | # limitations under the License. 13 | 14 | name: "CodeQL" 15 | 16 | on: 17 | push: 18 | branches: main 19 | pull_request: 20 | branches: main 21 | schedule: 22 | - cron: '35 13 * * 5' 23 | 24 | jobs: 25 | analyze: 26 | uses: notaryproject/notation-core-go/.github/workflows/reusable-codeql.yml@main -------------------------------------------------------------------------------- /.github/workflows/license-checker.yml: -------------------------------------------------------------------------------- 1 | # Copyright The Notary Project Authors. 2 | # Licensed under the Apache License, Version 2.0 (the "License"); 3 | # you may not use this file except in compliance with the License. 4 | # You may obtain a copy of the License at 5 | # 6 | # http://www.apache.org/licenses/LICENSE-2.0 7 | # 8 | # Unless required by applicable law or agreed to in writing, software 9 | # distributed under the License is distributed on an "AS IS" BASIS, 10 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | # See the License for the specific language governing permissions and 12 | # limitations under the License. 13 | 14 | name: License Checker 15 | 16 | on: 17 | push: 18 | branches: main 19 | pull_request: 20 | branches: main 21 | 22 | permissions: 23 | contents: write 24 | pull-requests: write 25 | 26 | jobs: 27 | check-license: 28 | uses: notaryproject/notation-core-go/.github/workflows/reusable-license-checker.yml@main -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Copyright The Notary Project Authors. 2 | # Licensed under the Apache License, Version 2.0 (the "License"); 3 | # you may not use this file except in compliance with the License. 4 | # You may obtain a copy of the License at 5 | # 6 | # http://www.apache.org/licenses/LICENSE-2.0 7 | # 8 | # Unless required by applicable law or agreed to in writing, software 9 | # distributed under the License is distributed on an "AS IS" BASIS, 10 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | # See the License for the specific language governing permissions and 12 | # limitations under the License. 13 | 14 | # Binaries for programs and plugins 15 | *.exe 16 | *.exe~ 17 | *.dll 18 | *.so 19 | *.dylib 20 | 21 | # Test binary, built with `go test -c` 22 | *.test 23 | 24 | # Output of the go coverage tool, specifically when used with LiteIDE 25 | *.out 26 | 27 | # Dependency directories (remove the comment below to include it) 28 | # vendor/ 29 | 30 | # Go workspace file 31 | go.work 32 | 33 | # Code Editors 34 | .vscode 35 | .idea 36 | *.sublime-project 37 | *.sublime-workspace 38 | 39 | # Custom 40 | coverage.txt -------------------------------------------------------------------------------- /CODEOWNERS: -------------------------------------------------------------------------------- 1 | # Repo-Level Owners (in alphabetical order) 2 | # Note: This is only for the notaryproject/tspclient-go repo 3 | * @gokarnm @JeyJeyGao @niazfk @priteshbandi @shizhMSFT @toddysm @Two-Hearts @vaninrao10 @yizha1 4 | -------------------------------------------------------------------------------- /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 [yyyy] [name of copyright owner] 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 | -------------------------------------------------------------------------------- /MAINTAINERS: -------------------------------------------------------------------------------- 1 | # Org-Level Maintainers (in alphabetical order) 2 | # Pattern: [First Name] [Last Name] <[Email Address]> ([GitHub Handle]) 3 | Niaz Khan (@niazfk) 4 | Pritesh Bandi (@priteshbandi) 5 | Shiwei Zhang (@shizhMSFT) 6 | Toddy Mladenov (@toddysm) 7 | Vani Rao (@vaninrao10) 8 | Yi Zha (@yizha1) 9 | 10 | # Repo-Level Maintainers (in alphabetical order) 11 | # Pattern: [First Name] [Last Name] <[Email Address]> ([GitHub Handle]) 12 | # Note: This is for the notaryproject/tspclient-go repo 13 | Junjie Gao (@JeyJeyGao) 14 | Patrick Zheng (@Two-Hearts) 15 | Shiwei Zhang (@shizhMSFT) 16 | 17 | # Emeritus Org Maintainers (in alphabetical order) 18 | Justin Cormack (@justincormack) 19 | Steve Lasker (@stevelasker) -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | # Copyright The Notary Project Authors. 2 | # Licensed under the Apache License, Version 2.0 (the "License"); 3 | # you may not use this file except in compliance with the License. 4 | # You may obtain a copy of the License at 5 | # 6 | # http://www.apache.org/licenses/LICENSE-2.0 7 | # 8 | # Unless required by applicable law or agreed to in writing, software 9 | # distributed under the License is distributed on an "AS IS" BASIS, 10 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | # See the License for the specific language governing permissions and 12 | # limitations under the License. 13 | 14 | .PHONY: help 15 | help: 16 | @grep -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | sort | awk 'BEGIN {FS = ":.*?## "}; {printf "\033[36m%-25s\033[0m %s\n", $$1, $$2}' 17 | 18 | .PHONY: all 19 | all: test 20 | 21 | .PHONY: test 22 | test: check-line-endings ## run unit tests 23 | go test -race -v -coverprofile=coverage.txt -covermode=atomic ./... 24 | 25 | .PHONY: clean 26 | clean: 27 | git status --ignored --short | grep '^!! ' | sed 's/!! //' | xargs rm -rf 28 | 29 | .PHONY: check-line-endings 30 | check-line-endings: ## check line endings 31 | ! find . -name "*.go" -type f -exec file "{}" ";" | grep CRLF 32 | ! find scripts -name "*.sh" -type f -exec file "{}" ";" | grep CRLF 33 | 34 | .PHONY: fix-line-endings 35 | fix-line-endings: ## fix line endings 36 | find . -type f -name "*.go" -exec sed -i -e "s/\r//g" {} + 37 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # tspclient-go 2 | 3 | [![Build Status](https://github.com/notaryproject/tspclient-go/actions/workflows/build.yml/badge.svg?event=push&branch=main)](https://github.com/notaryproject/tspclient-go/actions/workflows/build.yml?query=workflow%3Abuild+event%3Apush+branch%3Amain) 4 | [![codecov](https://codecov.io/gh/notaryproject/tspclient-go/branch/main/graph/badge.svg)](https://codecov.io/gh/notaryproject/tspclient-go) 5 | [![Go Reference](https://pkg.go.dev/badge/github.com/notaryproject/tspclient-go.svg)](https://pkg.go.dev/github.com/notaryproject/tspclient-go@main) 6 | 7 | tspclient-go provides implementation of the Time-Stamp Protocol (TSP) client as specified in RFC 3161. 8 | 9 | ## Table of Contents 10 | - [Documentation](#documentation) 11 | - [Code of Conduct](#code-of-conduct) 12 | - [License](#license) 13 | 14 | ## Documentation 15 | 16 | Library documentation is available at [Go Reference](https://pkg.go.dev/github.com/notaryproject/tspclient-go). 17 | 18 | ## Code of Conduct 19 | 20 | This project has adopted the [CNCF Code of Conduct](https://github.com/cncf/foundation/blob/master/code-of-conduct.md). 21 | 22 | ## License 23 | 24 | This project is covered under the Apache 2.0 license. You can read the license [here](LICENSE). -------------------------------------------------------------------------------- /errors.go: -------------------------------------------------------------------------------- 1 | // Copyright The Notary Project Authors. 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // 6 | // http://www.apache.org/licenses/LICENSE-2.0 7 | // 8 | // Unless required by applicable law or agreed to in writing, software 9 | // distributed under the License is distributed on an "AS IS" BASIS, 10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | // See the License for the specific language governing permissions and 12 | // limitations under the License. 13 | 14 | package tspclient 15 | 16 | // CertificateNotFoundError is used when identified certificate is not found 17 | // in the timestampe token 18 | type CertificateNotFoundError error 19 | 20 | // MalformedRequestError is used when timestamping request is malformed. 21 | type MalformedRequestError struct { 22 | Msg string 23 | Detail error 24 | } 25 | 26 | // Error returns error message. 27 | func (e *MalformedRequestError) Error() string { 28 | msg := "malformed timestamping request" 29 | if e.Msg != "" { 30 | msg += ": " + e.Msg 31 | } 32 | if e.Detail != nil { 33 | msg += ": " + e.Detail.Error() 34 | } 35 | return msg 36 | } 37 | 38 | // Unwrap returns the internal error. 39 | func (e *MalformedRequestError) Unwrap() error { 40 | return e.Detail 41 | } 42 | 43 | // InvalidResponseError is used when timestamping response is invalid. 44 | type InvalidResponseError struct { 45 | Msg string 46 | Detail error 47 | } 48 | 49 | // Error returns error message. 50 | func (e *InvalidResponseError) Error() string { 51 | msg := "invalid timestamping response" 52 | if e.Msg != "" { 53 | msg += ": " + e.Msg 54 | } 55 | if e.Detail != nil { 56 | msg += ": " + e.Detail.Error() 57 | } 58 | return msg 59 | } 60 | 61 | // Unwrap returns the internal error. 62 | func (e *InvalidResponseError) Unwrap() error { 63 | return e.Detail 64 | } 65 | 66 | // SignedTokenVerificationError is used when fail to verify signed token. 67 | type SignedTokenVerificationError struct { 68 | Msg string 69 | Detail error 70 | } 71 | 72 | // Error returns error message. 73 | func (e *SignedTokenVerificationError) Error() string { 74 | msg := "failed to verify signed token" 75 | if e.Msg != "" { 76 | msg += ": " + e.Msg 77 | } 78 | if e.Detail != nil { 79 | msg += ": " + e.Detail.Error() 80 | } 81 | return msg 82 | } 83 | 84 | // Unwrap returns the internal error. 85 | func (e *SignedTokenVerificationError) Unwrap() error { 86 | return e.Detail 87 | } 88 | 89 | // TSTInfoError is used when fail a TSTInfo is invalid. 90 | type TSTInfoError struct { 91 | Msg string 92 | Detail error 93 | } 94 | 95 | // Error returns error message. 96 | func (e *TSTInfoError) Error() string { 97 | msg := "invalid TSTInfo" 98 | if e.Msg != "" { 99 | msg += ": " + e.Msg 100 | } 101 | if e.Detail != nil { 102 | msg += ": " + e.Detail.Error() 103 | } 104 | return msg 105 | } 106 | 107 | // Unwrap returns the internal error. 108 | func (e *TSTInfoError) Unwrap() error { 109 | return e.Detail 110 | } 111 | -------------------------------------------------------------------------------- /errors_test.go: -------------------------------------------------------------------------------- 1 | // Copyright The Notary Project Authors. 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // 6 | // http://www.apache.org/licenses/LICENSE-2.0 7 | // 8 | // Unless required by applicable law or agreed to in writing, software 9 | // distributed under the License is distributed on an "AS IS" BASIS, 10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | // See the License for the specific language governing permissions and 12 | // limitations under the License. 13 | 14 | package tspclient 15 | 16 | import ( 17 | "errors" 18 | "testing" 19 | ) 20 | 21 | var errTestInner = errors.New("test inner error") 22 | 23 | func TestMalformedRequestError(t *testing.T) { 24 | newErr := MalformedRequestError{} 25 | expectedErrMsg := "malformed timestamping request" 26 | if newErr.Error() != expectedErrMsg { 27 | t.Fatalf("expected error %s, but got %v", expectedErrMsg, newErr) 28 | } 29 | 30 | newErr = MalformedRequestError{ 31 | Detail: errTestInner, 32 | } 33 | expectedErrMsg = "malformed timestamping request: test inner error" 34 | if newErr.Error() != expectedErrMsg { 35 | t.Fatalf("expected error %s, but got %v", expectedErrMsg, newErr) 36 | } 37 | innerErr := newErr.Unwrap() 38 | expectedErrMsg = "test inner error" 39 | if innerErr.Error() != expectedErrMsg { 40 | t.Fatalf("expected error %s, but got %v", expectedErrMsg, innerErr) 41 | } 42 | } 43 | 44 | func TestInvalidResponseError(t *testing.T) { 45 | newErr := InvalidResponseError{} 46 | expectedErrMsg := "invalid timestamping response" 47 | if newErr.Error() != expectedErrMsg { 48 | t.Fatalf("expected error %s, but got %v", expectedErrMsg, newErr) 49 | } 50 | 51 | newErr = InvalidResponseError{ 52 | Detail: errTestInner, 53 | } 54 | expectedErrMsg = "invalid timestamping response: test inner error" 55 | if newErr.Error() != expectedErrMsg { 56 | t.Fatalf("expected error %s, but got %v", expectedErrMsg, newErr) 57 | } 58 | innerErr := newErr.Unwrap() 59 | expectedErrMsg = "test inner error" 60 | if innerErr.Error() != expectedErrMsg { 61 | t.Fatalf("expected error %s, but got %v", expectedErrMsg, innerErr) 62 | } 63 | } 64 | 65 | func TestSignedTokenVerificationError(t *testing.T) { 66 | newErr := SignedTokenVerificationError{Msg: "test error msg"} 67 | expectedErrMsg := "failed to verify signed token: test error msg" 68 | if newErr.Error() != expectedErrMsg { 69 | t.Fatalf("expected error %s, but got %v", expectedErrMsg, newErr) 70 | } 71 | 72 | newErr = SignedTokenVerificationError{ 73 | Detail: errTestInner, 74 | } 75 | expectedErrMsg = "failed to verify signed token: test inner error" 76 | if newErr.Error() != expectedErrMsg { 77 | t.Fatalf("expected error %s, but got %v", expectedErrMsg, newErr) 78 | } 79 | innerErr := newErr.Unwrap() 80 | expectedErrMsg = "test inner error" 81 | if innerErr.Error() != expectedErrMsg { 82 | t.Fatalf("expected error %s, but got %v", expectedErrMsg, newErr) 83 | } 84 | } 85 | 86 | func TestTSTInfoError(t *testing.T) { 87 | newErr := TSTInfoError{} 88 | expectedErrMsg := "invalid TSTInfo" 89 | if newErr.Error() != expectedErrMsg { 90 | t.Fatalf("expected error %s, but got %v", expectedErrMsg, newErr) 91 | } 92 | 93 | newErr = TSTInfoError{ 94 | Detail: errTestInner, 95 | } 96 | expectedErrMsg = "invalid TSTInfo: test inner error" 97 | if newErr.Error() != expectedErrMsg { 98 | t.Fatalf("expected error %s, but got %v", expectedErrMsg, newErr) 99 | } 100 | innerErr := newErr.Unwrap() 101 | expectedErrMsg = "test inner error" 102 | if innerErr.Error() != expectedErrMsg { 103 | t.Fatalf("expected error %s, but got %v", expectedErrMsg, innerErr) 104 | } 105 | } 106 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/notaryproject/tspclient-go 2 | 3 | go 1.23.0 4 | -------------------------------------------------------------------------------- /http.go: -------------------------------------------------------------------------------- 1 | // Copyright The Notary Project Authors. 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // 6 | // http://www.apache.org/licenses/LICENSE-2.0 7 | // 8 | // Unless required by applicable law or agreed to in writing, software 9 | // distributed under the License is distributed on an "AS IS" BASIS, 10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | // See the License for the specific language governing permissions and 12 | // limitations under the License. 13 | 14 | package tspclient 15 | 16 | import ( 17 | "bytes" 18 | "context" 19 | "fmt" 20 | "io" 21 | "net/http" 22 | "net/url" 23 | "time" 24 | ) 25 | 26 | // maxBodyLength specifies the max content can be received from the remote 27 | // server. 28 | // The legnth of a regular TSA response with certificates is usually less than 29 | // 10 KiB. 30 | var maxBodyLength = 1 * 1024 * 1024 // 1 MiB 31 | 32 | // const for MediaTypes defined in RFC 3161 3.4 33 | const ( 34 | // MediaTypeTimestampQuery is the content-type of timestamp query. 35 | // RFC 3161 3.4 36 | MediaTypeTimestampQuery = "application/timestamp-query" 37 | 38 | // MediaTypeTimestampReply is the content-type of timestamp reply 39 | // RFC 3161 3.4 40 | MediaTypeTimestampReply = "application/timestamp-reply" 41 | ) 42 | 43 | // httpTimestamper is a HTTP-based timestamper. 44 | type httpTimestamper struct { 45 | httpClient *http.Client 46 | endpoint string 47 | } 48 | 49 | // NewHTTPTimestamper creates a HTTP-based timestamper with the endpoint 50 | // provided by the TSA. 51 | // http.DefaultTransport is used if nil RoundTripper is passed. 52 | func NewHTTPTimestamper(httpClient *http.Client, endpoint string) (Timestamper, error) { 53 | if httpClient == nil { 54 | httpClient = &http.Client{Timeout: 5 * time.Second} 55 | } 56 | tsaURL, err := url.Parse(endpoint) 57 | if err != nil { 58 | return nil, err 59 | } 60 | if tsaURL.Scheme != "http" && tsaURL.Scheme != "https" { 61 | return nil, fmt.Errorf("endpoint %q: scheme must be http or https, but got %q", endpoint, tsaURL.Scheme) 62 | } 63 | if tsaURL.Host == "" { 64 | return nil, fmt.Errorf("endpoint %q: host cannot be empty", endpoint) 65 | } 66 | return &httpTimestamper{ 67 | httpClient: httpClient, 68 | endpoint: endpoint, 69 | }, nil 70 | } 71 | 72 | // Timestamp sends the request to the remote TSA server for timestamping. 73 | // 74 | // Reference: RFC 3161 3.4 Time-Stamp Protocol via HTTP 75 | func (ts *httpTimestamper) Timestamp(ctx context.Context, req *Request) (*Response, error) { 76 | // sanity check 77 | if err := req.Validate(); err != nil { 78 | return nil, err 79 | } 80 | 81 | // prepare for http request 82 | reqBytes, err := req.MarshalBinary() 83 | if err != nil { 84 | return nil, err 85 | } 86 | hReq, err := http.NewRequestWithContext(ctx, http.MethodPost, ts.endpoint, bytes.NewReader(reqBytes)) 87 | if err != nil { 88 | return nil, err 89 | } 90 | hReq.Header.Set("Content-Type", MediaTypeTimestampQuery) 91 | 92 | // send the request to the remote TSA server 93 | hResp, err := ts.httpClient.Do(hReq) 94 | if err != nil { 95 | return nil, err 96 | } 97 | defer hResp.Body.Close() 98 | 99 | // verify HTTP response 100 | if hResp.StatusCode != http.StatusOK { 101 | return nil, fmt.Errorf("%s %q: https response bad status: %s", http.MethodPost, ts.endpoint, hResp.Status) 102 | } 103 | if contentType := hResp.Header.Get("Content-Type"); contentType != MediaTypeTimestampReply { 104 | return nil, fmt.Errorf("%s %q: unexpected response content type: %s", http.MethodPost, ts.endpoint, contentType) 105 | } 106 | 107 | // read TSA response 108 | lr := &io.LimitedReader{ 109 | R: hResp.Body, 110 | N: int64(maxBodyLength), 111 | } 112 | respBytes, err := io.ReadAll(lr) 113 | if err != nil { 114 | return nil, err 115 | } 116 | if lr.N == 0 { 117 | return nil, fmt.Errorf("%s %q: unexpected large http response, max response body size allowed is %d MiB", hResp.Request.Method, hResp.Request.URL, maxBodyLength/1024/1024) 118 | } 119 | var resp Response 120 | if err := resp.UnmarshalBinary(respBytes); err != nil { 121 | return nil, err 122 | } 123 | // validate response against RFC 3161 124 | if err := resp.Validate(req); err != nil { 125 | return nil, err 126 | } 127 | return &resp, nil 128 | } 129 | -------------------------------------------------------------------------------- /internal/cms/cms.go: -------------------------------------------------------------------------------- 1 | // Copyright The Notary Project Authors. 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // 6 | // http://www.apache.org/licenses/LICENSE-2.0 7 | // 8 | // Unless required by applicable law or agreed to in writing, software 9 | // distributed under the License is distributed on an "AS IS" BASIS, 10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | // See the License for the specific language governing permissions and 12 | // limitations under the License. 13 | 14 | // Package cms verifies Signed-Data defined in RFC 5652 Cryptographic Message 15 | // Syntax (CMS) / PKCS7 16 | // 17 | // References: 18 | // - RFC 5652 Cryptographic Message Syntax (CMS) 19 | package cms 20 | 21 | import ( 22 | "crypto/x509" 23 | "crypto/x509/pkix" 24 | "encoding/asn1" 25 | "math/big" 26 | ) 27 | 28 | // ContentInfo struct is used to represent the content of a CMS message, 29 | // which can be encrypted, signed, or both. 30 | // 31 | // References: RFC 5652 3 ContentInfo Type 32 | // 33 | // ContentInfo ::= SEQUENCE { 34 | // contentType ContentType, 35 | // content [0] EXPLICIT ANY DEFINED BY contentType } 36 | type ContentInfo struct { 37 | // ContentType field specifies the type of the content, which can be one of 38 | // several predefined types, such as data, signedData, envelopedData, or 39 | // encryptedData. Only signedData is supported currently. 40 | ContentType asn1.ObjectIdentifier 41 | 42 | // Content field contains the actual content of the message. 43 | Content asn1.RawValue `asn1:"explicit,tag:0"` 44 | } 45 | 46 | // SignedData struct is used to represent a signed CMS message, which contains 47 | // one or more signatures that are used to verify the authenticity and integrity 48 | // of the message. 49 | // 50 | // Reference: RFC 5652 5.1 SignedData 51 | // 52 | // SignedData ::= SEQUENCE { 53 | // version CMSVersion, 54 | // digestAlgorithms DigestAlgorithmIdentifiers, 55 | // encapContentInfo EncapsulatedContentInfo, 56 | // certificates [0] IMPLICIT CertificateSet OPTIONAL, 57 | // crls [1] IMPLICIT CertificateRevocationLists OPTIONAL, 58 | // signerInfos SignerInfos } 59 | type SignedData struct { 60 | // Version field specifies the syntax version number of the SignedData. 61 | Version int 62 | 63 | // DigestAlgorithmIdentifiers field specifies the digest algorithms used 64 | // by one or more signatures in SignerInfos. 65 | DigestAlgorithmIdentifiers []pkix.AlgorithmIdentifier `asn1:"set"` 66 | 67 | // EncapsulatedContentInfo field specifies the content that is signed. 68 | EncapsulatedContentInfo EncapsulatedContentInfo 69 | 70 | // Certificates field contains the certificates that are used to verify the 71 | // signatures in SignerInfos. 72 | Certificates asn1.RawValue `asn1:"optional,tag:0"` 73 | 74 | // CRLs field contains the Certificate Revocation Lists that are used to 75 | // verify the signatures in SignerInfos. 76 | CRLs []x509.RevocationList `asn1:"optional,tag:1"` 77 | 78 | // SignerInfos field contains one or more signatures. 79 | SignerInfos []SignerInfo `asn1:"set"` 80 | } 81 | 82 | // EncapsulatedContentInfo struct is used to represent the content of a CMS 83 | // message. 84 | // 85 | // References: RFC 5652 5.2 EncapsulatedContentInfo 86 | // 87 | // EncapsulatedContentInfo ::= SEQUENCE { 88 | // eContentType ContentType, 89 | // eContent [0] EXPLICIT OCTET STRING OPTIONAL } 90 | type EncapsulatedContentInfo struct { 91 | // ContentType is an object identifier. The object identifier uniquely 92 | // specifies the content type. 93 | ContentType asn1.ObjectIdentifier 94 | 95 | // Content field contains the actual content of the message. 96 | Content []byte `asn1:"explicit,optional,tag:0"` 97 | } 98 | 99 | // SignerInfo struct is used to represent a signature and related information 100 | // that is needed to verify the signature. 101 | // 102 | // Reference: RFC 5652 5.3 SignerInfo 103 | // 104 | // SignerInfo ::= SEQUENCE { 105 | // version CMSVersion, 106 | // sid SignerIdentifier, 107 | // digestAlgorithm DigestAlgorithmIdentifier, 108 | // signedAttrs [0] IMPLICIT SignedAttributes OPTIONAL, 109 | // signatureAlgorithm SignatureAlgorithmIdentifier, 110 | // signature SignatureValue, 111 | // unsignedAttrs [1] IMPLICIT UnsignedAttributes OPTIONAL } 112 | // 113 | // Only version 1 is supported. As defined in RFC 5652 5.3, SignerIdentifier 114 | // is IssuerAndSerialNumber when version is 1. 115 | type SignerInfo struct { 116 | // Version field specifies the syntax version number of the SignerInfo. 117 | Version int 118 | 119 | // SignerIdentifier field specifies the signer's certificate. Only IssuerAndSerialNumber 120 | // is supported currently. 121 | SignerIdentifier IssuerAndSerialNumber 122 | 123 | // DigestAlgorithm field specifies the digest algorithm used by the signer. 124 | DigestAlgorithm pkix.AlgorithmIdentifier 125 | 126 | // SignedAttributes field contains a collection of attributes that are 127 | // signed. 128 | SignedAttributes Attributes `asn1:"optional,tag:0"` 129 | 130 | // SignatureAlgorithm field specifies the signature algorithm used by the 131 | // signer. 132 | SignatureAlgorithm pkix.AlgorithmIdentifier 133 | 134 | // Signature field contains the actual signature. 135 | Signature []byte 136 | 137 | // UnsignedAttributes field contains a collection of attributes that are 138 | // not signed. 139 | UnsignedAttributes Attributes `asn1:"optional,tag:1"` 140 | } 141 | 142 | // IssuerAndSerialNumber struct is used to identify a certificate. 143 | // 144 | // Reference: RFC 5652 5.3 SignerIdentifier 145 | // 146 | // IssuerAndSerialNumber ::= SEQUENCE { 147 | // issuer Name, 148 | // serialNumber CertificateSerialNumber } 149 | type IssuerAndSerialNumber struct { 150 | // Issuer field identifies the certificate issuer. 151 | Issuer asn1.RawValue 152 | 153 | // SerialNumber field identifies the certificate. 154 | SerialNumber *big.Int 155 | } 156 | 157 | // Attribute struct is used to represent a attribute with type and values. 158 | // 159 | // Reference: RFC 5652 5.3 SignerInfo 160 | // 161 | // Attribute ::= SEQUENCE { 162 | // attrType OBJECT IDENTIFIER, 163 | // attrValues SET OF AttributeValue } 164 | type Attribute struct { 165 | // Type field specifies the type of the attribute. 166 | Type asn1.ObjectIdentifier 167 | 168 | // Values field contains the actual value of the attribute. 169 | Values asn1.RawValue `asn1:"set"` 170 | } 171 | 172 | // Attributes ::= SET SIZE (0..MAX) OF Attribute 173 | type Attributes []Attribute 174 | 175 | // Get tries to find the attribute by the given identifier, parse and store 176 | // the result in the value pointed to by out. 177 | func (a Attributes) Get(identifier asn1.ObjectIdentifier, out any) error { 178 | for _, attribute := range a { 179 | if identifier.Equal(attribute.Type) { 180 | _, err := asn1.Unmarshal(attribute.Values.Bytes, out) 181 | return err 182 | } 183 | } 184 | return ErrAttributeNotFound 185 | } 186 | -------------------------------------------------------------------------------- /internal/cms/errors.go: -------------------------------------------------------------------------------- 1 | // Copyright The Notary Project Authors. 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // 6 | // http://www.apache.org/licenses/LICENSE-2.0 7 | // 8 | // Unless required by applicable law or agreed to in writing, software 9 | // distributed under the License is distributed on an "AS IS" BASIS, 10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | // See the License for the specific language governing permissions and 12 | // limitations under the License. 13 | 14 | package cms 15 | 16 | import "errors" 17 | 18 | // ErrNotSignedData is returned if wrong content is provided when signed 19 | // data is expected. 20 | var ErrNotSignedData = errors.New("cms: content type is not signed-data") 21 | 22 | // ErrAttributeNotFound is returned if attribute is not found in a given set. 23 | var ErrAttributeNotFound = errors.New("attribute not found") 24 | 25 | // Verification errors 26 | var ( 27 | ErrSignerInfoNotFound = VerificationError{Message: "signerInfo not found"} 28 | ErrCertificateNotFound = VerificationError{Message: "certificate not found"} 29 | ) 30 | 31 | // SyntaxError indicates that the ASN.1 data is invalid. 32 | type SyntaxError struct { 33 | Message string 34 | Detail error 35 | } 36 | 37 | // Error returns error message. 38 | func (e SyntaxError) Error() string { 39 | msg := "cms: syntax error" 40 | if e.Message != "" { 41 | msg += ": " + e.Message 42 | } 43 | if e.Detail != nil { 44 | msg += ": " + e.Detail.Error() 45 | } 46 | return msg 47 | } 48 | 49 | // Unwrap returns the internal error. 50 | func (e SyntaxError) Unwrap() error { 51 | return e.Detail 52 | } 53 | 54 | // VerificationError indicates verification failures. 55 | type VerificationError struct { 56 | Message string 57 | Detail error 58 | } 59 | 60 | // Error returns error message. 61 | func (e VerificationError) Error() string { 62 | msg := "cms verification failure" 63 | if e.Message != "" { 64 | msg += ": " + e.Message 65 | } 66 | if e.Detail != nil { 67 | msg += ": " + e.Detail.Error() 68 | } 69 | return msg 70 | } 71 | 72 | // Unwrap returns the internal error. 73 | func (e VerificationError) Unwrap() error { 74 | return e.Detail 75 | } 76 | -------------------------------------------------------------------------------- /internal/cms/errors_test.go: -------------------------------------------------------------------------------- 1 | // Copyright The Notary Project Authors. 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // 6 | // http://www.apache.org/licenses/LICENSE-2.0 7 | // 8 | // Unless required by applicable law or agreed to in writing, software 9 | // distributed under the License is distributed on an "AS IS" BASIS, 10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | // See the License for the specific language governing permissions and 12 | // limitations under the License. 13 | 14 | package cms 15 | 16 | import ( 17 | "errors" 18 | "testing" 19 | ) 20 | 21 | func TestSyntaxError(t *testing.T) { 22 | tests := []struct { 23 | name string 24 | err SyntaxError 25 | wantMsg string 26 | }{ 27 | {"No detail", SyntaxError{Message: "test"}, "cms: syntax error: test"}, 28 | {"With detail", SyntaxError{Message: "test", Detail: errors.New("detail")}, "cms: syntax error: test: detail"}, 29 | } 30 | 31 | for _, tt := range tests { 32 | t.Run(tt.name, func(t *testing.T) { 33 | if gotMsg := tt.err.Error(); gotMsg != tt.wantMsg { 34 | t.Errorf("SyntaxError.Error() = %v, want %v", gotMsg, tt.wantMsg) 35 | } 36 | if gotDetail := tt.err.Unwrap(); gotDetail != tt.err.Detail { 37 | t.Errorf("SyntaxError.Unwrap() = %v, want %v", gotDetail, tt.err.Detail) 38 | } 39 | }) 40 | } 41 | } 42 | 43 | func TestVerificationError(t *testing.T) { 44 | tests := []struct { 45 | name string 46 | err VerificationError 47 | wantMsg string 48 | }{ 49 | {"No detail", VerificationError{Message: "test"}, "cms verification failure: test"}, 50 | {"With detail", VerificationError{Message: "test", Detail: errors.New("detail")}, "cms verification failure: test: detail"}, 51 | } 52 | 53 | for _, tt := range tests { 54 | t.Run(tt.name, func(t *testing.T) { 55 | if gotMsg := tt.err.Error(); gotMsg != tt.wantMsg { 56 | t.Errorf("VerificationError.Error() = %v, want %v", gotMsg, tt.wantMsg) 57 | } 58 | if gotDetail := tt.err.Unwrap(); gotDetail != tt.err.Detail { 59 | t.Errorf("VerificationError.Unwrap() = %v, want %v", gotDetail, tt.err.Detail) 60 | } 61 | }) 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /internal/cms/signed.go: -------------------------------------------------------------------------------- 1 | // Copyright The Notary Project Authors. 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // 6 | // http://www.apache.org/licenses/LICENSE-2.0 7 | // 8 | // Unless required by applicable law or agreed to in writing, software 9 | // distributed under the License is distributed on an "AS IS" BASIS, 10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | // See the License for the specific language governing permissions and 12 | // limitations under the License. 13 | 14 | package cms 15 | 16 | import ( 17 | "bytes" 18 | "context" 19 | "crypto" 20 | "crypto/x509" 21 | "encoding/asn1" 22 | "encoding/hex" 23 | "errors" 24 | "fmt" 25 | "time" 26 | 27 | "github.com/notaryproject/tspclient-go/internal/encoding/asn1/ber" 28 | "github.com/notaryproject/tspclient-go/internal/hashutil" 29 | "github.com/notaryproject/tspclient-go/internal/oid" 30 | ) 31 | 32 | // ParsedSignedData is a parsed SignedData structure for golang friendly types. 33 | type ParsedSignedData struct { 34 | // Content is the content of the EncapsulatedContentInfo. 35 | Content []byte 36 | 37 | // ContentType is the content type of the EncapsulatedContentInfo. 38 | ContentType asn1.ObjectIdentifier 39 | 40 | // Certificates is the list of certificates in the SignedData. 41 | Certificates []*x509.Certificate 42 | 43 | // CRLs is the list of certificate revocation lists in the SignedData. 44 | CRLs []x509.RevocationList 45 | 46 | // SignerInfos is the list of signer information in the SignedData. 47 | SignerInfos []SignerInfo 48 | } 49 | 50 | // ParseSignedData parses ASN.1 BER-encoded SignedData structure to golang 51 | // friendly types. 52 | // 53 | // Only supported SignedData version is 3. 54 | func ParseSignedData(berData []byte) (*ParsedSignedData, error) { 55 | data, err := ber.ConvertToDER(berData) 56 | if err != nil { 57 | return nil, SyntaxError{Message: "invalid signed data: failed to convert from BER to DER", Detail: err} 58 | } 59 | var contentInfo ContentInfo 60 | if _, err := asn1.Unmarshal(data, &contentInfo); err != nil { 61 | return nil, SyntaxError{Message: "invalid content info: failed to unmarshal DER to ContentInfo", Detail: err} 62 | } 63 | if !oid.SignedData.Equal(contentInfo.ContentType) { 64 | return nil, ErrNotSignedData 65 | } 66 | 67 | var signedData SignedData 68 | if _, err := asn1.Unmarshal(contentInfo.Content.Bytes, &signedData); err != nil { 69 | return nil, SyntaxError{Message: "invalid signed data", Detail: err} 70 | } 71 | 72 | if signedData.Version != 3 { 73 | return nil, SyntaxError{Message: fmt.Sprintf("unsupported signed data version: got %d, want 3", signedData.Version)} 74 | } 75 | 76 | certs, err := x509.ParseCertificates(signedData.Certificates.Bytes) 77 | if err != nil { 78 | return nil, SyntaxError{Message: "failed to parse X.509 certificates from signed data. Only X.509 certificates are supported", Detail: err} 79 | } 80 | 81 | return &ParsedSignedData{ 82 | Content: signedData.EncapsulatedContentInfo.Content, 83 | ContentType: signedData.EncapsulatedContentInfo.ContentType, 84 | Certificates: certs, 85 | CRLs: signedData.CRLs, 86 | SignerInfos: signedData.SignerInfos, 87 | }, nil 88 | } 89 | 90 | // Verify attempts to verify the content in the parsed signed data against the signer 91 | // information. The `Intermediates` in the verify options will be ignored and 92 | // re-contrusted using the certificates in the parsed signed data. 93 | // If more than one signature is present, the successful validation of any signature 94 | // implies that the content in the parsed signed data is valid. 95 | // On successful verification, the list of signing certificates that successfully 96 | // verify is returned. 97 | // If all signatures fail to verify, the last error is returned. 98 | // 99 | // References: 100 | // - RFC 5652 5 Signed-data Content Type 101 | // - RFC 5652 5.4 Message Digest Calculation Process 102 | // - RFC 5652 5.6 Signature Verification Process 103 | // 104 | // WARNING: this function doesn't do any revocation checking. 105 | func (d *ParsedSignedData) Verify(ctx context.Context, opts x509.VerifyOptions) ([][]*x509.Certificate, error) { 106 | if len(d.SignerInfos) == 0 { 107 | return nil, ErrSignerInfoNotFound 108 | } 109 | if len(d.Certificates) == 0 { 110 | return nil, ErrCertificateNotFound 111 | } 112 | 113 | intermediates := x509.NewCertPool() 114 | for _, cert := range d.Certificates { 115 | intermediates.AddCert(cert) 116 | } 117 | opts.Intermediates = intermediates 118 | verifiedSignerMap := map[string][]*x509.Certificate{} 119 | var lastErr error 120 | for _, signerInfo := range d.SignerInfos { 121 | signingCertificate := d.GetCertificate(signerInfo.SignerIdentifier) 122 | if signingCertificate == nil { 123 | lastErr = ErrCertificateNotFound 124 | continue 125 | } 126 | 127 | certChain, err := d.VerifySigner(ctx, &signerInfo, signingCertificate, opts) 128 | if err != nil { 129 | lastErr = err 130 | continue 131 | } 132 | 133 | thumbprint, err := hashutil.ComputeHash(crypto.SHA256, signingCertificate.Raw) 134 | if err != nil { 135 | lastErr = err 136 | continue 137 | } 138 | verifiedSignerMap[hex.EncodeToString(thumbprint)] = certChain 139 | } 140 | if len(verifiedSignerMap) == 0 { 141 | return nil, lastErr 142 | } 143 | 144 | verifiedSigningCertChains := make([][]*x509.Certificate, 0, len(verifiedSignerMap)) 145 | for _, certChain := range verifiedSignerMap { 146 | verifiedSigningCertChains = append(verifiedSigningCertChains, certChain) 147 | } 148 | return verifiedSigningCertChains, nil 149 | } 150 | 151 | // VerifySigner verifies the signerInfo against the user specified signingCertificate. 152 | // 153 | // This function should be used when: 154 | // 155 | // 1. The certificates field of d is missing. This function allows the caller to provide 156 | // a signing certificate to verify the signerInfo. 157 | // 158 | // 2. The caller doesn't trust the signer identifier (unsigned field) of signerInfo 159 | // to identify signing certificate. This function allows such caller to use their trusted 160 | // signing certificate. 161 | // 162 | // Note: the intermediate certificates (if any) and root certificates in the verify 163 | // options MUST be set by the caller. The certificates field of d is not used in this function. 164 | // 165 | // References: 166 | // - RFC 5652 5 Signed-data Content Type 167 | // - RFC 5652 5.4 Message Digest Calculation Process 168 | // - RFC 5652 5.6 Signature Verification Process 169 | // 170 | // WARNING: this function doesn't do any revocation checking. 171 | func (d *ParsedSignedData) VerifySigner(ctx context.Context, signerInfo *SignerInfo, signingCertificate *x509.Certificate, opts x509.VerifyOptions) ([]*x509.Certificate, error) { 172 | if signerInfo == nil { 173 | return nil, VerificationError{Message: "VerifySigner failed: signer info is required"} 174 | } 175 | 176 | if signingCertificate == nil { 177 | return nil, VerificationError{Message: "VerifySigner failed: signing certificate is required"} 178 | } 179 | 180 | if signerInfo.Version != 1 { 181 | // Only IssuerAndSerialNumber is supported currently 182 | return nil, VerificationError{Message: fmt.Sprintf("invalid signer info version: only version 1 is supported; got %d", signerInfo.Version)} 183 | } 184 | 185 | return d.verify(signerInfo, signingCertificate, &opts) 186 | } 187 | 188 | // verify verifies the trust in a top-down manner. 189 | // 190 | // References: 191 | // - RFC 5652 5.4 Message Digest Calculation Process 192 | // - RFC 5652 5.6 Signature Verification Process 193 | func (d *ParsedSignedData) verify(signerInfo *SignerInfo, cert *x509.Certificate, opts *x509.VerifyOptions) ([]*x509.Certificate, error) { 194 | // verify signer certificate 195 | certChains, err := cert.Verify(*opts) 196 | if err != nil { 197 | return nil, VerificationError{Detail: err} 198 | } 199 | 200 | // verify signature 201 | if err := d.verifySignature(signerInfo, cert); err != nil { 202 | return nil, err 203 | } 204 | 205 | // verify attribute 206 | return d.verifySignedAttributes(signerInfo, certChains) 207 | } 208 | 209 | // verifySignature verifies the signature with a trusted certificate. 210 | // 211 | // References: 212 | // - RFC 5652 5.4 Message Digest Calculation Process 213 | // - RFC 5652 5.6 Signature Verification Process 214 | func (d *ParsedSignedData) verifySignature(signerInfo *SignerInfo, cert *x509.Certificate) error { 215 | // verify signature 216 | algorithm := oid.ToSignatureAlgorithm( 217 | signerInfo.DigestAlgorithm.Algorithm, 218 | signerInfo.SignatureAlgorithm.Algorithm, 219 | ) 220 | if algorithm == x509.UnknownSignatureAlgorithm { 221 | return VerificationError{Message: "unknown signature algorithm"} 222 | } 223 | 224 | signed := d.Content 225 | if len(signerInfo.SignedAttributes) > 0 { 226 | encoded, err := asn1.MarshalWithParams(signerInfo.SignedAttributes, "set") 227 | if err != nil { 228 | return VerificationError{Message: "invalid signed attributes", Detail: err} 229 | } 230 | signed = encoded 231 | } 232 | 233 | if err := cert.CheckSignature(algorithm, signed, signerInfo.Signature); err != nil { 234 | return VerificationError{Detail: err} 235 | } 236 | return nil 237 | } 238 | 239 | // verifySignedAttributes verifies the signed attributes. 240 | // 241 | // References: 242 | // - RFC 5652 5.3 SignerInfo Type 243 | // - RFC 5652 5.6 Signature Verification Process 244 | func (d *ParsedSignedData) verifySignedAttributes(signerInfo *SignerInfo, chains [][]*x509.Certificate) ([]*x509.Certificate, error) { 245 | if len(chains) == 0 { 246 | return nil, VerificationError{Message: "Failed to verify signed attributes because the certificate chain is empty."} 247 | } 248 | 249 | // verify attributes if present 250 | if len(signerInfo.SignedAttributes) == 0 { 251 | // According to RFC 5652, if the Content Type is id-data, signed 252 | // attributes can be empty. However, this cms package is designed for 253 | // timestamp (RFC 3161) and the content type must be id-ct-TSTInfo, 254 | // so we require signed attributes to be present. 255 | return nil, VerificationError{Message: "missing signed attributes"} 256 | } 257 | 258 | // this CMS package is designed for timestamping (RFC 3161), so checking the 259 | // content type to be id-ct-TSTInfo is an optimization for tspclient to 260 | // fail fast. 261 | if !oid.TSTInfo.Equal(d.ContentType) { 262 | return nil, fmt.Errorf("unexpected content type: %v. Expected to be id-ct-TSTInfo (%v)", d.ContentType, oid.TSTInfo) 263 | } 264 | var contentType asn1.ObjectIdentifier 265 | if err := signerInfo.SignedAttributes.Get(oid.ContentType, &contentType); err != nil { 266 | return nil, VerificationError{Message: "invalid content type", Detail: err} 267 | } 268 | if !d.ContentType.Equal(contentType) { 269 | return nil, VerificationError{Message: fmt.Sprintf("mismatch content type: found %q in signer info, and %q in signed data", contentType, d.ContentType)} 270 | } 271 | 272 | var expectedDigest []byte 273 | if err := signerInfo.SignedAttributes.Get(oid.MessageDigest, &expectedDigest); err != nil { 274 | return nil, VerificationError{Message: "invalid message digest", Detail: err} 275 | } 276 | hash, ok := oid.ToHash(signerInfo.DigestAlgorithm.Algorithm) 277 | if !ok { 278 | return nil, VerificationError{Message: "unsupported digest algorithm"} 279 | } 280 | actualDigest, err := hashutil.ComputeHash(hash, d.Content) 281 | if err != nil { 282 | return nil, VerificationError{Message: "hash failure", Detail: err} 283 | } 284 | if !bytes.Equal(expectedDigest, actualDigest) { 285 | return nil, VerificationError{Message: "mismatch message digest"} 286 | } 287 | 288 | // sanity check on signing time 289 | var signingTime time.Time 290 | if err := signerInfo.SignedAttributes.Get(oid.SigningTime, &signingTime); err != nil { 291 | if errors.Is(err, ErrAttributeNotFound) { 292 | return chains[0], nil 293 | } 294 | return nil, VerificationError{Message: "invalid signing time", Detail: err} 295 | } 296 | 297 | // verify signing time is within the validity period of all certificates 298 | // in the chain. As long as one chain is valid, the signature is valid. 299 | for _, chain := range chains { 300 | if isSigningTimeValid(chain, signingTime) { 301 | return chain, nil 302 | } 303 | } 304 | 305 | return nil, VerificationError{Message: fmt.Sprintf("signing time, %s, is outside certificate's validity period", signingTime)} 306 | } 307 | 308 | // GetCertificate finds the certificate by issuer name and issuer-specific 309 | // serial number. 310 | // Reference: RFC 5652 5 Signed-data Content Type 311 | func (d *ParsedSignedData) GetCertificate(ref IssuerAndSerialNumber) *x509.Certificate { 312 | for _, cert := range d.Certificates { 313 | if bytes.Equal(cert.RawIssuer, ref.Issuer.FullBytes) && cert.SerialNumber.Cmp(ref.SerialNumber) == 0 { 314 | return cert 315 | } 316 | } 317 | return nil 318 | } 319 | 320 | // isSigningTimeValid helpes to check if signingTime is within the validity 321 | // period of all certificates in the chain 322 | func isSigningTimeValid(chain []*x509.Certificate, signingTime time.Time) bool { 323 | for _, cert := range chain { 324 | if signingTime.Before(cert.NotBefore) || signingTime.After(cert.NotAfter) { 325 | return false 326 | } 327 | } 328 | return true 329 | } 330 | -------------------------------------------------------------------------------- /internal/cms/testdata/GlobalSignRootCA.crt: -------------------------------------------------------------------------------- 1 | -----BEGIN CERTIFICATE----- 2 | MIIDXzCCAkegAwIBAgILBAAAAAABIVhTCKIwDQYJKoZIhvcNAQELBQAwTDEgMB4G 3 | A1UECxMXR2xvYmFsU2lnbiBSb290IENBIC0gUjMxEzARBgNVBAoTCkdsb2JhbFNp 4 | Z24xEzARBgNVBAMTCkdsb2JhbFNpZ24wHhcNMDkwMzE4MTAwMDAwWhcNMjkwMzE4 5 | MTAwMDAwWjBMMSAwHgYDVQQLExdHbG9iYWxTaWduIFJvb3QgQ0EgLSBSMzETMBEG 6 | A1UEChMKR2xvYmFsU2lnbjETMBEGA1UEAxMKR2xvYmFsU2lnbjCCASIwDQYJKoZI 7 | hvcNAQEBBQADggEPADCCAQoCggEBAMwldpB5BngiFvXAg7aEyiie/QV2EcWtiHL8 8 | RgJDx7KKnQRfJMsuS+FggkbhUqsMgUdwbN1k0ev1LKMPgj0MK66X17YUhhB5uzsT 9 | gHeMCOFJ0mpiLx9e+pZo34knlTifBtc+ycsmWQ1z3rDI6SYOgxXG71uL0gRgykmm 10 | KPZpO/bLyCiR5Z2KYVc3rHQU3HTgOu5yLy6c+9C7v/U9AOEGM+iCK65TpjoWc4zd 11 | QQ4gOsC0p6Hpsk+QLjJg6VfLuQSSaGjlOCZgdbKfd/+RFO+uIEn8rUAVSNECMWEZ 12 | XriX7613t2Saer9fwRPvm2L7DWzgVGkWqQPabumDk3F2xmmFghcCAwEAAaNCMEAw 13 | DgYDVR0PAQH/BAQDAgEGMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFI/wS3+o 14 | LkUkrk1Q+mOai97i3Ru8MA0GCSqGSIb3DQEBCwUAA4IBAQBLQNvAUKr+yAzv95ZU 15 | RUm7lgAJQayzE4aGKAczymvmdLm6AC2upArT9fHxD4q/c2dKg8dEe3jgr25sbwMp 16 | jjM5RcOO5LlXbKr8EpbsU8Yt5CRsuZRj+9xTaGdWPoO4zzUhw8lo/s7awlOqzJCK 17 | 6fBdRoyV3XpYKBovHd7NADdBj+1EbddTKJd+82cEHhXXipa0095MJ6RMG3NzdvQX 18 | mcIfeg7jLQitChws/zyrVQ4PkX4268NXSb7hLi18YIvDQVETI53O9zJrlAGomecs 19 | Mx86OyXShkDOOyyGeMlhLxS67ttVb9+E7gUJTb0o2HLO02JQZR7rkpeDMdmztcpH 20 | WD9f 21 | -----END CERTIFICATE----- 22 | -------------------------------------------------------------------------------- /internal/cms/testdata/Sha1SignedData.p7s: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/notaryproject/tspclient-go/4f55b14d9f01b9722bd4848117bc26486a8288c5/internal/cms/testdata/Sha1SignedData.p7s -------------------------------------------------------------------------------- /internal/cms/testdata/SignedDataWithoutSignedAttributes.p7s: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/notaryproject/tspclient-go/4f55b14d9f01b9722bd4848117bc26486a8288c5/internal/cms/testdata/SignedDataWithoutSignedAttributes.p7s -------------------------------------------------------------------------------- /internal/cms/testdata/TimeStampToken.p7s: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/notaryproject/tspclient-go/4f55b14d9f01b9722bd4848117bc26486a8288c5/internal/cms/testdata/TimeStampToken.p7s -------------------------------------------------------------------------------- /internal/cms/testdata/TimeStampTokenInvalidSignedAttributeContentType.p7s: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/notaryproject/tspclient-go/4f55b14d9f01b9722bd4848117bc26486a8288c5/internal/cms/testdata/TimeStampTokenInvalidSignedAttributeContentType.p7s -------------------------------------------------------------------------------- /internal/cms/testdata/TimeStampTokenWithAnInvalidAndAValidSignerInfo.p7s: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/notaryproject/tspclient-go/4f55b14d9f01b9722bd4848117bc26486a8288c5/internal/cms/testdata/TimeStampTokenWithAnInvalidAndAValidSignerInfo.p7s -------------------------------------------------------------------------------- /internal/cms/testdata/TimeStampTokenWithInvalidCertificates.p7s: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/notaryproject/tspclient-go/4f55b14d9f01b9722bd4848117bc26486a8288c5/internal/cms/testdata/TimeStampTokenWithInvalidCertificates.p7s -------------------------------------------------------------------------------- /internal/cms/testdata/TimeStampTokenWithInvalidContentType.p7s: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/notaryproject/tspclient-go/4f55b14d9f01b9722bd4848117bc26486a8288c5/internal/cms/testdata/TimeStampTokenWithInvalidContentType.p7s -------------------------------------------------------------------------------- /internal/cms/testdata/TimeStampTokenWithInvalidSignature.p7s: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/notaryproject/tspclient-go/4f55b14d9f01b9722bd4848117bc26486a8288c5/internal/cms/testdata/TimeStampTokenWithInvalidSignature.p7s -------------------------------------------------------------------------------- /internal/cms/testdata/TimeStampTokenWithInvalidSigningTime.p7s: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/notaryproject/tspclient-go/4f55b14d9f01b9722bd4848117bc26486a8288c5/internal/cms/testdata/TimeStampTokenWithInvalidSigningTime.p7s -------------------------------------------------------------------------------- /internal/cms/testdata/TimeStampTokenWithSignedAttributeSHA1.p7s: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/notaryproject/tspclient-go/4f55b14d9f01b9722bd4848117bc26486a8288c5/internal/cms/testdata/TimeStampTokenWithSignedAttributeSHA1.p7s -------------------------------------------------------------------------------- /internal/cms/testdata/TimeStampTokenWithSignerVersion2.p7s: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/notaryproject/tspclient-go/4f55b14d9f01b9722bd4848117bc26486a8288c5/internal/cms/testdata/TimeStampTokenWithSignerVersion2.p7s -------------------------------------------------------------------------------- /internal/cms/testdata/TimeStampTokenWithSigningTime.p7s: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/notaryproject/tspclient-go/4f55b14d9f01b9722bd4848117bc26486a8288c5/internal/cms/testdata/TimeStampTokenWithSigningTime.p7s -------------------------------------------------------------------------------- /internal/cms/testdata/TimeStampTokenWithSigningTimeBeforeExpected.p7s: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/notaryproject/tspclient-go/4f55b14d9f01b9722bd4848117bc26486a8288c5/internal/cms/testdata/TimeStampTokenWithSigningTimeBeforeExpected.p7s -------------------------------------------------------------------------------- /internal/cms/testdata/TimeStampTokenWithUnknownSignerIssuer.p7s: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/notaryproject/tspclient-go/4f55b14d9f01b9722bd4848117bc26486a8288c5/internal/cms/testdata/TimeStampTokenWithUnknownSignerIssuer.p7s -------------------------------------------------------------------------------- /internal/cms/testdata/TimeStampTokenWithoutCertificate.p7s: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/notaryproject/tspclient-go/4f55b14d9f01b9722bd4848117bc26486a8288c5/internal/cms/testdata/TimeStampTokenWithoutCertificate.p7s -------------------------------------------------------------------------------- /internal/cms/testdata/TimeStampTokenWithoutSignedAttributeContentType.p7s: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/notaryproject/tspclient-go/4f55b14d9f01b9722bd4848117bc26486a8288c5/internal/cms/testdata/TimeStampTokenWithoutSignedAttributeContentType.p7s -------------------------------------------------------------------------------- /internal/cms/testdata/TimeStampTokenWithoutSignedAttributeDigest.p7s: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/notaryproject/tspclient-go/4f55b14d9f01b9722bd4848117bc26486a8288c5/internal/cms/testdata/TimeStampTokenWithoutSignedAttributeDigest.p7s -------------------------------------------------------------------------------- /internal/cms/testdata/TimeStampTokenWithoutSignedAttributes.p7s: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/notaryproject/tspclient-go/4f55b14d9f01b9722bd4848117bc26486a8288c5/internal/cms/testdata/TimeStampTokenWithoutSignedAttributes.p7s -------------------------------------------------------------------------------- /internal/cms/testdata/TimeStampTokenWithoutSigner.p7s: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/notaryproject/tspclient-go/4f55b14d9f01b9722bd4848117bc26486a8288c5/internal/cms/testdata/TimeStampTokenWithoutSigner.p7s -------------------------------------------------------------------------------- /internal/encoding/asn1/asn1.go: -------------------------------------------------------------------------------- 1 | // Copyright The Notary Project Authors. 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // 6 | // http://www.apache.org/licenses/LICENSE-2.0 7 | // 8 | // Unless required by applicable law or agreed to in writing, software 9 | // distributed under the License is distributed on an "AS IS" BASIS, 10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | // See the License for the specific language governing permissions and 12 | // limitations under the License. 13 | 14 | package asn1 15 | 16 | import ( 17 | "bytes" 18 | "encoding/asn1" 19 | ) 20 | 21 | // EqualRawValue returns true if two asn1.RawValue are equal 22 | func EqualRawValue(m asn1.RawValue, n asn1.RawValue) bool { 23 | return m.Class == n.Class && 24 | m.Tag == n.Tag && 25 | m.IsCompound == n.IsCompound && 26 | bytes.Equal(m.Bytes, n.Bytes) && 27 | bytes.Equal(m.FullBytes, n.FullBytes) 28 | } 29 | -------------------------------------------------------------------------------- /internal/encoding/asn1/asn1_test.go: -------------------------------------------------------------------------------- 1 | // Copyright The Notary Project Authors. 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // 6 | // http://www.apache.org/licenses/LICENSE-2.0 7 | // 8 | // Unless required by applicable law or agreed to in writing, software 9 | // distributed under the License is distributed on an "AS IS" BASIS, 10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | // See the License for the specific language governing permissions and 12 | // limitations under the License. 13 | 14 | package asn1 15 | 16 | import ( 17 | "encoding/asn1" 18 | "testing" 19 | ) 20 | 21 | func TestEqual(t *testing.T) { 22 | m := asn1.RawValue{ 23 | Tag: asn1.TagNull, 24 | FullBytes: []byte{asn1.TagNull, 0}, 25 | } 26 | n := asn1.NullRawValue 27 | n.FullBytes = []byte{asn1.TagNull, 0} 28 | 29 | if !EqualRawValue(m, n) { 30 | t.Fatal("expected to be equal") 31 | } 32 | 33 | n = asn1.NullRawValue 34 | if EqualRawValue(m, n) { 35 | t.Fatal("expected to be unequal") 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /internal/encoding/asn1/ber/ber.go: -------------------------------------------------------------------------------- 1 | // Copyright The Notary Project Authors. 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // 6 | // http://www.apache.org/licenses/LICENSE-2.0 7 | // 8 | // Unless required by applicable law or agreed to in writing, software 9 | // distributed under the License is distributed on an "AS IS" BASIS, 10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | // See the License for the specific language governing permissions and 12 | // limitations under the License. 13 | 14 | // Package ber decodes BER-encoded ASN.1 data structures and encodes in DER. 15 | // Note: 16 | // - DER is a subset of BER. 17 | // - Indefinite length is not supported. 18 | // - The length of the encoded data must fit the memory space of the int type 19 | // (4 bytes). 20 | // 21 | // Reference: 22 | // - http://luca.ntop.org/Teaching/Appunti/asn1.html 23 | // - ISO/IEC 8825-1:2021 24 | // - https://learn.microsoft.com/windows/win32/seccertenroll/about-introduction-to-asn-1-syntax-and-encoding 25 | package ber 26 | 27 | import ( 28 | "bytes" 29 | "encoding/asn1" 30 | "fmt" 31 | ) 32 | 33 | // value is the interface for an ASN.1 value node. 34 | type value interface { 35 | // EncodeMetadata encodes the identifier and length in DER to the buffer. 36 | EncodeMetadata(writer) error 37 | 38 | // EncodedLen returns the length in bytes of the data when encoding in DER. 39 | EncodedLen() int 40 | 41 | // Content returns the content of the value. 42 | // For primitive values, it returns the content octets. 43 | // For constructed values, it returns nil because the content is 44 | // the data of all members. 45 | Content() []byte 46 | } 47 | 48 | // ConvertToDER converts BER-encoded ASN.1 data structures to DER-encoded. 49 | func ConvertToDER(ber []byte) ([]byte, error) { 50 | if len(ber) == 0 { 51 | return nil, asn1.SyntaxError{Msg: "BER-encoded ASN.1 data structures is empty"} 52 | } 53 | 54 | flatValues, err := decode(ber) 55 | if err != nil { 56 | return nil, err 57 | } 58 | 59 | // get the total length from the root value and allocate a buffer 60 | buf := bytes.NewBuffer(make([]byte, 0, flatValues[0].EncodedLen())) 61 | for _, v := range flatValues { 62 | if err = v.EncodeMetadata(buf); err != nil { 63 | return nil, err 64 | } 65 | 66 | if content := v.Content(); content != nil { 67 | // primitive value 68 | _, err = buf.Write(content) 69 | if err != nil { 70 | return nil, err 71 | } 72 | } 73 | } 74 | 75 | return buf.Bytes(), nil 76 | } 77 | 78 | // decode decodes BER-encoded ASN.1 data structures. 79 | // To get the DER of `r`, encode the values 80 | // in the returned slice in order. 81 | // 82 | // Parameters: 83 | // r - The input byte slice. 84 | // 85 | // Return: 86 | // []value - The returned value, which is the flat slice of ASN.1 values, 87 | // contains the nodes from a depth-first traversal. 88 | // error - An error that can occur during the decoding process. 89 | // 90 | // Reference: ISO/IEC 8825-1: 8.1.1.3 91 | func decode(r []byte) ([]value, error) { 92 | // prepare the first value 93 | identifier, contentLen, r, err := decodeMetadata(r) 94 | if err != nil { 95 | return nil, err 96 | } 97 | if len(r) != contentLen { 98 | return nil, asn1.SyntaxError{Msg: fmt.Sprintf("decoding BER: length octets value %d does not match with content length %d", contentLen, len(r))} 99 | } 100 | 101 | // primitive value 102 | if isPrimitive(identifier) { 103 | return []value{&primitive{ 104 | identifier: identifier, 105 | content: r, 106 | }}, nil 107 | } 108 | 109 | // constructed value 110 | rootConstructed := &constructed{ 111 | identifier: identifier, 112 | rawContent: r, 113 | } 114 | flatValues := []value{rootConstructed} 115 | 116 | // start depth-first decoding with stack 117 | contructedStack := []*constructed{rootConstructed} 118 | for { 119 | stackLen := len(contructedStack) 120 | if stackLen == 0 { 121 | break 122 | } 123 | 124 | // top 125 | node := contructedStack[stackLen-1] 126 | 127 | // check that the constructed value is fully decoded 128 | if len(node.rawContent) == 0 { 129 | // calculate the length of the members 130 | for _, m := range node.members { 131 | node.length += m.EncodedLen() 132 | } 133 | // pop 134 | contructedStack = contructedStack[:stackLen-1] 135 | continue 136 | } 137 | 138 | // decode the next member of the constructed value 139 | nextNodeIdentifier, nextNodeContentLen, remainingContent, err := decodeMetadata(node.rawContent) 140 | if err != nil { 141 | return nil, err 142 | } 143 | nextNodeContent := remainingContent[:nextNodeContentLen] 144 | node.rawContent = remainingContent[nextNodeContentLen:] 145 | 146 | if isPrimitive(nextNodeIdentifier) { 147 | // primitive value 148 | primitiveNode := &primitive{ 149 | identifier: nextNodeIdentifier, 150 | content: nextNodeContent, 151 | } 152 | node.members = append(node.members, primitiveNode) 153 | flatValues = append(flatValues, primitiveNode) 154 | } else { 155 | // constructed value 156 | constructedNode := &constructed{ 157 | identifier: nextNodeIdentifier, 158 | rawContent: nextNodeContent, 159 | } 160 | node.members = append(node.members, constructedNode) 161 | 162 | // add a new constructed node to the stack 163 | contructedStack = append(contructedStack, constructedNode) 164 | flatValues = append(flatValues, constructedNode) 165 | } 166 | } 167 | return flatValues, nil 168 | } 169 | 170 | // decodeMetadata decodes the metadata of a BER-encoded ASN.1 value. 171 | // 172 | // Parameters: 173 | // r - The input byte slice. 174 | // 175 | // Return: 176 | // []byte - The identifier octets. 177 | // int - The length octets value. 178 | // []byte - The subsequent octets after the length octets. 179 | // error - An error that can occur during the decoding process. 180 | // 181 | // Reference: ISO/IEC 8825-1: 8.1.1.3 182 | func decodeMetadata(r []byte) ([]byte, int, []byte, error) { 183 | // structure of an encoding (primitive or constructed) 184 | // +----------------+----------------+----------------+ 185 | // | identifier | length | content | 186 | // +----------------+----------------+----------------+ 187 | identifier, r, err := decodeIdentifier(r) 188 | if err != nil { 189 | return nil, 0, nil, err 190 | } 191 | 192 | contentLen, r, err := decodeLength(r) 193 | if err != nil { 194 | return nil, 0, nil, err 195 | } 196 | 197 | return identifier, contentLen, r, nil 198 | } 199 | 200 | // decodeIdentifier decodes decodeIdentifier octets. 201 | // 202 | // Parameters: 203 | // r - The input byte slice from which the identifier octets are to be decoded. 204 | // 205 | // Returns: 206 | // []byte - The identifier octets decoded from the input byte slice. 207 | // []byte - The remaining part of the input byte slice after the identifier octets. 208 | // error - An error that can occur during the decoding process. 209 | // 210 | // Reference: ISO/IEC 8825-1: 8.1.2 211 | func decodeIdentifier(r []byte) ([]byte, []byte, error) { 212 | if len(r) < 1 { 213 | return nil, nil, asn1.SyntaxError{Msg: "decoding BER identifier octets: identifier octets is empty"} 214 | } 215 | offset := 0 216 | b := r[offset] 217 | offset++ 218 | 219 | // high-tag-number form 220 | // Reference: ISO/IEC 8825-1: 8.1.2.4 221 | if b&0x1f == 0x1f { 222 | for offset < len(r) && r[offset]&0x80 == 0x80 { 223 | offset++ 224 | } 225 | if offset >= len(r) { 226 | return nil, nil, asn1.SyntaxError{Msg: "decoding BER identifier octets: high-tag-number form with early EOF"} 227 | } 228 | offset++ 229 | } 230 | 231 | if offset >= len(r) { 232 | return nil, nil, asn1.SyntaxError{Msg: "decoding BER identifier octets: early EOF due to missing length and content octets"} 233 | } 234 | return r[:offset], r[offset:], nil 235 | } 236 | 237 | // decodeLength decodes length octets. 238 | // Indefinite length is not supported 239 | // 240 | // Parameters: 241 | // r - The input byte slice from which the length octets are to be decoded. 242 | // 243 | // Returns: 244 | // int - The length decoded from the input byte slice. 245 | // []byte - The remaining part of the input byte slice after the length octets. 246 | // error - An error that can occur during the decoding process. 247 | // 248 | // Reference: ISO/IEC 8825-1: 8.1.3 249 | func decodeLength(r []byte) (int, []byte, error) { 250 | if len(r) < 1 { 251 | return 0, nil, asn1.SyntaxError{Msg: "decoding BER length octets: length octets is empty"} 252 | } 253 | offset := 0 254 | b := r[offset] 255 | offset++ 256 | 257 | if b < 0x80 { 258 | // short form 259 | // Reference: ISO/IEC 8825-1: 8.1.3.4 260 | contentLen := int(b) 261 | subsequentOctets := r[offset:] 262 | if contentLen > len(subsequentOctets) { 263 | return 0, nil, asn1.SyntaxError{Msg: "decoding BER length octets: short form length octets value should be less or equal to the subsequent octets length"} 264 | } 265 | return contentLen, subsequentOctets, nil 266 | } 267 | 268 | if b == 0x80 { 269 | // Indefinite-length method is not supported. 270 | // Reference: ISO/IEC 8825-1: 8.1.3.6.1 271 | return 0, nil, asn1.StructuralError{Msg: "decoding BER length octets: indefinite length not supported"} 272 | } 273 | 274 | // long form 275 | // Reference: ISO/IEC 8825-1: 8.1.3.5 276 | n := int(b & 0x7f) 277 | if n > 4 { 278 | // length must fit the memory space of the int type (4 bytes). 279 | return 0, nil, asn1.StructuralError{Msg: fmt.Sprintf("decoding BER length octets: length of encoded data (%d bytes) cannot exceed 4 bytes", n)} 280 | } 281 | if offset+n >= len(r) { 282 | return 0, nil, asn1.SyntaxError{Msg: "decoding BER length octets: long form length octets with early EOF"} 283 | } 284 | var length uint64 285 | for i := 0; i < n; i++ { 286 | length = (length << 8) | uint64(r[offset]) 287 | offset++ 288 | } 289 | 290 | // length must fit the memory space of the int32. 291 | if (length >> 31) > 0 { 292 | return 0, nil, asn1.StructuralError{Msg: fmt.Sprintf("decoding BER length octets: length %d does not fit the memory space of int32", length)} 293 | } 294 | 295 | contentLen := int(length) 296 | subsequentOctets := r[offset:] 297 | if contentLen > len(subsequentOctets) { 298 | return 0, nil, asn1.SyntaxError{Msg: "decoding BER length octets: long form length octets value should be less or equal to the subsequent octets length"} 299 | } 300 | return contentLen, subsequentOctets, nil 301 | } 302 | 303 | // isPrimitive returns true if the first identifier octet is marked 304 | // as primitive. 305 | // Reference: ISO/IEC 8825-1: 8.1.2.5 306 | func isPrimitive(identifier []byte) bool { 307 | return identifier[0]&0x20 == 0 308 | } 309 | -------------------------------------------------------------------------------- /internal/encoding/asn1/ber/ber_test.go: -------------------------------------------------------------------------------- 1 | // Copyright The Notary Project Authors. 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // 6 | // http://www.apache.org/licenses/LICENSE-2.0 7 | // 8 | // Unless required by applicable law or agreed to in writing, software 9 | // distributed under the License is distributed on an "AS IS" BASIS, 10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | // See the License for the specific language governing permissions and 12 | // limitations under the License. 13 | 14 | package ber 15 | 16 | import ( 17 | "reflect" 18 | "testing" 19 | ) 20 | 21 | func TestConvertToDER(t *testing.T) { 22 | var testBytes = make([]byte, 0x7FFFFFFF) 23 | // primitive identifier 24 | testBytes[0] = 0x1f 25 | testBytes[1] = 0xa0 26 | testBytes[2] = 0x20 27 | // length 28 | testBytes[3] = 0x84 29 | testBytes[4] = 0xFF 30 | testBytes[5] = 0xFF 31 | testBytes[6] = 0xFF 32 | testBytes[7] = 0xFF 33 | 34 | type data struct { 35 | name string 36 | ber []byte 37 | der []byte 38 | expectError bool 39 | } 40 | testData := []data{ 41 | { 42 | name: "Constructed value", 43 | ber: []byte{ 44 | // Constructed value 45 | 0x30, 46 | // Constructed value length 47 | 0x2e, 48 | 49 | // Type identifier 50 | 0x06, 51 | // Type length 52 | 0x09, 53 | // Type content 54 | 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 55 | 56 | // Value identifier 57 | 0x04, 58 | // Value length in BER 59 | 0x81, 0x20, 60 | // Value content 61 | 0xe3, 0xb0, 0xc4, 0x42, 0x98, 0xfc, 0x1c, 0x14, 62 | 0x9a, 0xfb, 0xf4, 0xc8, 0x99, 0x6f, 0xb9, 0x24, 63 | 0x27, 0xae, 0x41, 0xe4, 0x64, 0x9b, 0x93, 0x4c, 64 | 0xa4, 0x95, 0x99, 0x1b, 0x78, 0x52, 0xb8, 0x55, 65 | }, 66 | der: []byte{ 67 | // Constructed value 68 | 0x30, 69 | // Constructed value length 70 | 0x2d, 71 | 72 | // Type identifier 73 | 0x06, 74 | // Type length 75 | 0x09, 76 | // Type content 77 | 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 78 | 79 | // Value identifier 80 | 0x04, 81 | // Value length in BER 82 | 0x20, 83 | // Value content 84 | 0xe3, 0xb0, 0xc4, 0x42, 0x98, 0xfc, 0x1c, 0x14, 85 | 0x9a, 0xfb, 0xf4, 0xc8, 0x99, 0x6f, 0xb9, 0x24, 86 | 0x27, 0xae, 0x41, 0xe4, 0x64, 0x9b, 0x93, 0x4c, 87 | 0xa4, 0x95, 0x99, 0x1b, 0x78, 0x52, 0xb8, 0x55, 88 | }, 89 | expectError: false, 90 | }, 91 | { 92 | name: "Primitive value", 93 | ber: []byte{ 94 | // Primitive value 95 | // identifier 96 | 0x1f, 0x20, 97 | // length 98 | 0x81, 0x01, 99 | // content 100 | 0x01, 101 | }, 102 | der: []byte{ 103 | // Primitive value 104 | // identifier 105 | 0x1f, 0x20, 106 | // length 107 | 0x01, 108 | // content 109 | 0x01, 110 | }, 111 | expectError: false, 112 | }, 113 | { 114 | name: "Constructed value in constructed value", 115 | ber: []byte{ 116 | // Constructed value 117 | 0x30, 118 | // Constructed value length 119 | 0x2d, 120 | 121 | // Constructed value identifier 122 | 0x26, 123 | // Type length 124 | 0x2b, 125 | 126 | // Value identifier 127 | 0x04, 128 | // Value length in BER 129 | 0x81, 0x28, 130 | // Value content 131 | 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 132 | 0xe3, 0xb0, 0xc4, 0x42, 0x98, 0xfc, 0x1c, 0x14, 133 | 0x9a, 0xfb, 0xf4, 0xc8, 0x99, 0x6f, 0xb9, 0x24, 134 | 0x27, 0xae, 0x41, 0xe4, 0x64, 0x9b, 0x93, 0x4c, 135 | 0xa4, 0x95, 0x99, 0x1b, 0x78, 0x52, 0xb8, 0x55, 136 | }, 137 | der: []byte{ 138 | // Constructed value 139 | 0x30, 140 | // Constructed value length 141 | 0x2c, 142 | 143 | // Constructed value identifier 144 | 0x26, 145 | // Type length 146 | 0x2a, 147 | 148 | // Value identifier 149 | 0x04, 150 | // Value length in BER 151 | 0x28, 152 | // Value content 153 | 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 154 | 0xe3, 0xb0, 0xc4, 0x42, 0x98, 0xfc, 0x1c, 0x14, 155 | 0x9a, 0xfb, 0xf4, 0xc8, 0x99, 0x6f, 0xb9, 0x24, 156 | 0x27, 0xae, 0x41, 0xe4, 0x64, 0x9b, 0x93, 0x4c, 157 | 0xa4, 0x95, 0x99, 0x1b, 0x78, 0x52, 0xb8, 0x55, 158 | }, 159 | expectError: false, 160 | }, 161 | { 162 | name: "empty", 163 | ber: []byte{}, 164 | der: []byte{}, 165 | expectError: true, 166 | }, 167 | { 168 | name: "identifier high tag number form", 169 | ber: []byte{ 170 | // Primitive value 171 | // identifier 172 | 0x1f, 0xa0, 0x20, 173 | // length 174 | 0x81, 0x01, 175 | // content 176 | 0x01, 177 | }, 178 | der: []byte{ 179 | // Primitive value 180 | // identifier 181 | 0x1f, 0xa0, 0x20, 182 | // length 183 | 0x01, 184 | // content 185 | 0x01, 186 | }, 187 | expectError: false, 188 | }, 189 | { 190 | name: "EarlyEOF for identifier high tag number form", 191 | ber: []byte{ 192 | // Primitive value 193 | // identifier 194 | 0x1f, 0xa0, 195 | }, 196 | der: []byte{}, 197 | expectError: true, 198 | }, 199 | { 200 | name: "EarlyEOF for length", 201 | ber: []byte{ 202 | // Primitive value 203 | // identifier 204 | 0x1f, 0xa0, 0x20, 205 | }, 206 | der: []byte{}, 207 | expectError: true, 208 | }, 209 | { 210 | name: "Unsupport indefinite-length", 211 | ber: []byte{ 212 | // Primitive value 213 | // identifier 214 | 0x1f, 0xa0, 0x20, 215 | // length 216 | 0x80, 217 | }, 218 | der: []byte{}, 219 | expectError: true, 220 | }, 221 | { 222 | name: "length greater than 4 bytes", 223 | ber: []byte{ 224 | // Primitive value 225 | // identifier 226 | 0x1f, 0xa0, 0x20, 227 | // length 228 | 0x85, 229 | }, 230 | der: []byte{}, 231 | expectError: true, 232 | }, 233 | { 234 | name: "long form length EarlyEOF ", 235 | ber: []byte{ 236 | // Primitive value 237 | // identifier 238 | 0x1f, 0xa0, 0x20, 239 | // length 240 | 0x84, 241 | }, 242 | der: []byte{}, 243 | expectError: true, 244 | }, 245 | { 246 | name: "length greater than content", 247 | ber: []byte{ 248 | // Primitive value 249 | // identifier 250 | 0x1f, 0xa0, 0x20, 251 | // length 252 | 0x02, 253 | }, 254 | der: []byte{}, 255 | expectError: true, 256 | }, 257 | { 258 | name: "trailing data", 259 | ber: []byte{ 260 | // Primitive value 261 | // identifier 262 | 0x1f, 0xa0, 0x20, 263 | // length 264 | 0x02, 265 | // content 266 | 0x01, 0x02, 0x03, 267 | }, 268 | der: []byte{}, 269 | expectError: true, 270 | }, 271 | { 272 | name: "EarlyEOF in constructed value", 273 | ber: []byte{ 274 | // Constructed value 275 | 0x30, 276 | // Constructed value length 277 | 0x2c, 278 | 279 | // Constructed value identifier 280 | 0x26, 281 | // Type length 282 | 0x2b, 283 | 284 | // Value identifier 285 | 0x04, 286 | // Value length in BER 287 | 0x81, 0x28, 288 | // Value content 289 | 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 290 | 0xe3, 0xb0, 0xc4, 0x42, 0x98, 0xfc, 0x1c, 0x14, 291 | 0x9a, 0xfb, 0xf4, 0xc8, 0x99, 0x6f, 0xb9, 0x24, 292 | 0x27, 0xae, 0x41, 0xe4, 0x64, 0x9b, 0x93, 0x4c, 293 | 0xa4, 0x95, 0x99, 0x1b, 0x78, 0x52, 0xb8, 294 | }, 295 | expectError: true, 296 | }, 297 | { 298 | name: "length greater > int32", 299 | ber: testBytes[:], 300 | der: []byte{}, 301 | expectError: true, 302 | }, 303 | { 304 | name: "long form length greather than subsequent octets length ", 305 | ber: []byte{ 306 | // Primitive value 307 | // identifier 308 | 0x1f, 0xa0, 0x20, 309 | // length 310 | 0x81, 0x09, 311 | // content 312 | 0x01, 313 | }, 314 | der: []byte{}, 315 | expectError: true, 316 | }, 317 | } 318 | 319 | for _, tt := range testData { 320 | der, err := ConvertToDER(tt.ber) 321 | if !tt.expectError && err != nil { 322 | t.Errorf("ConvertToDER() error = %v, but expect no error", err) 323 | return 324 | } 325 | if tt.expectError && err == nil { 326 | t.Errorf("ConvertToDER() error = nil, but expect error") 327 | } 328 | 329 | if !tt.expectError && !reflect.DeepEqual(der, tt.der) { 330 | t.Errorf("got = %v, want %v", der, tt.der) 331 | } 332 | } 333 | } 334 | 335 | func TestDecodeIdentifier(t *testing.T) { 336 | t.Run("identifier is empty", func(t *testing.T) { 337 | _, _, err := decodeIdentifier([]byte{}) 338 | if err == nil { 339 | t.Errorf("decodeIdentifier() error = nil, but expect error") 340 | } 341 | }) 342 | } 343 | 344 | func TestDecodeLength(t *testing.T) { 345 | t.Run("length is empty", func(t *testing.T) { 346 | _, _, err := decodeLength([]byte{}) 347 | if err == nil { 348 | t.Errorf("decodeLength() error = nil, but expect error") 349 | } 350 | }) 351 | } 352 | -------------------------------------------------------------------------------- /internal/encoding/asn1/ber/common.go: -------------------------------------------------------------------------------- 1 | // Copyright The Notary Project Authors. 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // 6 | // http://www.apache.org/licenses/LICENSE-2.0 7 | // 8 | // Unless required by applicable law or agreed to in writing, software 9 | // distributed under the License is distributed on an "AS IS" BASIS, 10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | // See the License for the specific language governing permissions and 12 | // limitations under the License. 13 | 14 | package ber 15 | 16 | import "io" 17 | 18 | // writer is the interface that wraps the basic Write and WriteByte methods. 19 | type writer interface { 20 | io.Writer 21 | io.ByteWriter 22 | } 23 | 24 | // encodeLength encodes length octets in DER. 25 | // Reference: 26 | // - ISO/IEC 8825-1: 10.1 27 | // - https://learn.microsoft.com/windows/win32/seccertenroll/about-encoded-length-and-value-bytes 28 | func encodeLength(w io.ByteWriter, length int) error { 29 | // DER restriction: short form must be used for length less than 128 30 | if length < 0x80 { 31 | return w.WriteByte(byte(length)) 32 | } 33 | 34 | // DER restriction: long form must be encoded in the minimum number of octets 35 | lengthSize := encodedLengthSize(length) 36 | err := w.WriteByte(0x80 | byte(lengthSize-1)) 37 | if err != nil { 38 | return err 39 | } 40 | for i := lengthSize - 1; i > 0; i-- { 41 | if err = w.WriteByte(byte(length >> (8 * (i - 1)))); err != nil { 42 | return err 43 | } 44 | } 45 | return nil 46 | } 47 | 48 | // encodedLengthSize gives the number of octets used for encoding the length 49 | // in DER. 50 | // Reference: 51 | // - ISO/IEC 8825-1: 10.1 52 | // - https://learn.microsoft.com/windows/win32/seccertenroll/about-encoded-length-and-value-bytes 53 | func encodedLengthSize(length int) int { 54 | if length < 0x80 { 55 | return 1 56 | } 57 | 58 | lengthSize := 1 59 | for length > 0 { 60 | length >>= 8 61 | lengthSize++ 62 | } 63 | return lengthSize 64 | } 65 | -------------------------------------------------------------------------------- /internal/encoding/asn1/ber/common_test.go: -------------------------------------------------------------------------------- 1 | // Copyright The Notary Project Authors. 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // 6 | // http://www.apache.org/licenses/LICENSE-2.0 7 | // 8 | // Unless required by applicable law or agreed to in writing, software 9 | // distributed under the License is distributed on an "AS IS" BASIS, 10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | // See the License for the specific language governing permissions and 12 | // limitations under the License. 13 | 14 | package ber 15 | 16 | import ( 17 | "bytes" 18 | "errors" 19 | "testing" 20 | ) 21 | 22 | func TestEncodeLength(t *testing.T) { 23 | tests := []struct { 24 | name string 25 | length int 26 | want []byte 27 | wantErr bool 28 | }{ 29 | { 30 | name: "Length less than 128", 31 | length: 127, 32 | want: []byte{127}, 33 | wantErr: false, 34 | }, 35 | { 36 | name: "Length equal to 128", 37 | length: 128, 38 | want: []byte{0x81, 128}, 39 | wantErr: false, 40 | }, 41 | { 42 | name: "Length greater than 128", 43 | length: 300, 44 | want: []byte{0x82, 0x01, 0x2C}, 45 | wantErr: false, 46 | }, 47 | } 48 | 49 | for _, tt := range tests { 50 | t.Run(tt.name, func(t *testing.T) { 51 | buf := &bytes.Buffer{} 52 | err := encodeLength(buf, tt.length) 53 | if (err != nil) != tt.wantErr { 54 | t.Errorf("encodeLength() error = %v, wantErr %v", err, tt.wantErr) 55 | return 56 | } 57 | if got := buf.Bytes(); !bytes.Equal(got, tt.want) { 58 | t.Errorf("encodeLength() = %v, want %v", got, tt.want) 59 | } 60 | }) 61 | } 62 | } 63 | 64 | func TestEncodedLengthSize(t *testing.T) { 65 | tests := []struct { 66 | name string 67 | length int 68 | want int 69 | }{ 70 | { 71 | name: "Length less than 128", 72 | length: 127, 73 | want: 1, 74 | }, 75 | { 76 | name: "Length equal to 128", 77 | length: 128, 78 | want: 2, 79 | }, 80 | { 81 | name: "Length greater than 128", 82 | length: 300, 83 | want: 3, 84 | }, 85 | } 86 | 87 | for _, tt := range tests { 88 | t.Run(tt.name, func(t *testing.T) { 89 | if got := encodedLengthSize(tt.length); got != tt.want { 90 | t.Errorf("encodedLengthSize() = %v, want %v", got, tt.want) 91 | } 92 | }) 93 | } 94 | } 95 | 96 | type secondErrorWriter struct { 97 | count int 98 | } 99 | 100 | func (ew *secondErrorWriter) WriteByte(p byte) (err error) { 101 | ew.count += 1 102 | if ew.count == 2 { 103 | return errors.New("write error") 104 | } 105 | return nil 106 | } 107 | 108 | func TestEncodeLengthFailed(t *testing.T) { 109 | t.Run("byte write error 1", func(t *testing.T) { 110 | buf := &errorWriter{} 111 | err := encodeLength(buf, 128) 112 | if err == nil { 113 | t.Error("encodeLength() error = nil, want Error") 114 | return 115 | } 116 | }) 117 | 118 | t.Run("byte write error 2", func(t *testing.T) { 119 | buf := &secondErrorWriter{} 120 | err := encodeLength(buf, 128) 121 | if err == nil { 122 | t.Error("encodeLength() error = nil, want Error") 123 | return 124 | } 125 | }) 126 | } 127 | -------------------------------------------------------------------------------- /internal/encoding/asn1/ber/constructed.go: -------------------------------------------------------------------------------- 1 | // Copyright The Notary Project Authors. 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // 6 | // http://www.apache.org/licenses/LICENSE-2.0 7 | // 8 | // Unless required by applicable law or agreed to in writing, software 9 | // distributed under the License is distributed on an "AS IS" BASIS, 10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | // See the License for the specific language governing permissions and 12 | // limitations under the License. 13 | 14 | package ber 15 | 16 | // constructed represents a value in constructed. 17 | type constructed struct { 18 | identifier []byte 19 | length int // length of this constructed value's memebers in bytes when encoded in DER 20 | members []value 21 | rawContent []byte // the raw content of BER 22 | } 23 | 24 | // EncodeMetadata encodes the identifier and length octets of constructed 25 | // to the value writer in DER. 26 | func (v *constructed) EncodeMetadata(w writer) error { 27 | _, err := w.Write(v.identifier) 28 | if err != nil { 29 | return err 30 | } 31 | return encodeLength(w, v.length) 32 | } 33 | 34 | // EncodedLen returns the length in bytes of the constructed when encoded 35 | // in DER. 36 | func (v *constructed) EncodedLen() int { 37 | return len(v.identifier) + encodedLengthSize(v.length) + v.length 38 | } 39 | 40 | // Content returns the content of the value. 41 | func (v *constructed) Content() []byte { 42 | return nil 43 | } 44 | -------------------------------------------------------------------------------- /internal/encoding/asn1/ber/constructed_test.go: -------------------------------------------------------------------------------- 1 | // Copyright The Notary Project Authors. 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // 6 | // http://www.apache.org/licenses/LICENSE-2.0 7 | // 8 | // Unless required by applicable law or agreed to in writing, software 9 | // distributed under the License is distributed on an "AS IS" BASIS, 10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | // See the License for the specific language governing permissions and 12 | // limitations under the License. 13 | 14 | package ber 15 | 16 | import ( 17 | "errors" 18 | "testing" 19 | ) 20 | 21 | type errorWriter struct{} 22 | 23 | func (ew *errorWriter) Write(p []byte) (n int, err error) { 24 | return 0, errors.New("write error") 25 | } 26 | 27 | func (ew *errorWriter) WriteByte(c byte) error { 28 | return errors.New("write error") 29 | } 30 | 31 | func TestConstructedEncodeMetadata(t *testing.T) { 32 | tests := []struct { 33 | name string 34 | v constructed 35 | wantError bool 36 | }{ 37 | { 38 | name: "Error case", 39 | v: constructed{ 40 | identifier: []byte{0x30}, 41 | length: 5, 42 | }, 43 | wantError: true, 44 | }, 45 | } 46 | 47 | for _, tt := range tests { 48 | t.Run(tt.name, func(t *testing.T) { 49 | w := &errorWriter{} 50 | err := tt.v.EncodeMetadata(w) 51 | if (err != nil) != tt.wantError { 52 | t.Errorf("EncodeMetadata() error = %v, wantError %v", err, tt.wantError) 53 | } 54 | }) 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /internal/encoding/asn1/ber/primitive.go: -------------------------------------------------------------------------------- 1 | // Copyright The Notary Project Authors. 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // 6 | // http://www.apache.org/licenses/LICENSE-2.0 7 | // 8 | // Unless required by applicable law or agreed to in writing, software 9 | // distributed under the License is distributed on an "AS IS" BASIS, 10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | // See the License for the specific language governing permissions and 12 | // limitations under the License. 13 | 14 | package ber 15 | 16 | // primitive represents a value in primitive encoding. 17 | type primitive struct { 18 | identifier []byte 19 | content []byte 20 | } 21 | 22 | // EncodeMetadata encodes the identifier and length octets of primitive to 23 | // the value writer in DER. 24 | func (v *primitive) EncodeMetadata(w writer) error { 25 | _, err := w.Write(v.identifier) 26 | if err != nil { 27 | return err 28 | } 29 | return encodeLength(w, len(v.content)) 30 | } 31 | 32 | // EncodedLen returns the length in bytes of the primitive when encoded in DER. 33 | func (v *primitive) EncodedLen() int { 34 | return len(v.identifier) + encodedLengthSize(len(v.content)) + len(v.content) 35 | } 36 | 37 | // Content returns the content of the value. 38 | func (v *primitive) Content() []byte { 39 | return v.content 40 | } 41 | -------------------------------------------------------------------------------- /internal/encoding/asn1/ber/primitive_test.go: -------------------------------------------------------------------------------- 1 | // Copyright The Notary Project Authors. 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // 6 | // http://www.apache.org/licenses/LICENSE-2.0 7 | // 8 | // Unless required by applicable law or agreed to in writing, software 9 | // distributed under the License is distributed on an "AS IS" BASIS, 10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | // See the License for the specific language governing permissions and 12 | // limitations under the License. 13 | 14 | package ber 15 | 16 | import ( 17 | "testing" 18 | ) 19 | 20 | func TestPrimitiveEncodeMetadata(t *testing.T) { 21 | tests := []struct { 22 | name string 23 | v primitive 24 | wantError bool 25 | }{ 26 | { 27 | name: "Error case", 28 | v: primitive{ 29 | identifier: []byte{0x30}, 30 | }, 31 | wantError: true, 32 | }, 33 | } 34 | 35 | for _, tt := range tests { 36 | t.Run(tt.name, func(t *testing.T) { 37 | w := &errorWriter{} 38 | err := tt.v.EncodeMetadata(w) 39 | if (err != nil) != tt.wantError { 40 | t.Errorf("EncodeMetadata() error = %v, wantError %v", err, tt.wantError) 41 | } 42 | }) 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /internal/hashutil/hash.go: -------------------------------------------------------------------------------- 1 | // Copyright The Notary Project Authors. 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // 6 | // http://www.apache.org/licenses/LICENSE-2.0 7 | // 8 | // Unless required by applicable law or agreed to in writing, software 9 | // distributed under the License is distributed on an "AS IS" BASIS, 10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | // See the License for the specific language governing permissions and 12 | // limitations under the License. 13 | 14 | // Package hashutil provides utilities for hash. 15 | package hashutil 16 | 17 | import "crypto" 18 | 19 | // ComputeHash computes the digest of the message with the given hash algorithm. 20 | // Callers should check the availability of the hash algorithm before invoking. 21 | func ComputeHash(hash crypto.Hash, message []byte) ([]byte, error) { 22 | h := hash.New() 23 | _, err := h.Write(message) 24 | if err != nil { 25 | return nil, err 26 | } 27 | return h.Sum(nil), nil 28 | } 29 | -------------------------------------------------------------------------------- /internal/hashutil/hash_test.go: -------------------------------------------------------------------------------- 1 | // Copyright The Notary Project Authors. 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // 6 | // http://www.apache.org/licenses/LICENSE-2.0 7 | // 8 | // Unless required by applicable law or agreed to in writing, software 9 | // distributed under the License is distributed on an "AS IS" BASIS, 10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | // See the License for the specific language governing permissions and 12 | // limitations under the License. 13 | 14 | // Package hashutil provides utilities for hash. 15 | package hashutil 16 | 17 | import ( 18 | "crypto" 19 | "crypto/sha256" 20 | "testing" 21 | ) 22 | 23 | func TestComputeHash(t *testing.T) { 24 | message := []byte("test message") 25 | expectedHash := sha256.Sum256(message) 26 | 27 | hash, err := ComputeHash(crypto.SHA256, message) 28 | if err != nil { 29 | t.Fatalf("ComputeHash returned an error: %v", err) 30 | } 31 | 32 | if string(hash) != string(expectedHash[:]) { 33 | t.Errorf("ComputeHash returned incorrect hash: got %x, want %x", hash, expectedHash) 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /internal/oid/algorithm.go: -------------------------------------------------------------------------------- 1 | // Copyright The Notary Project Authors. 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // 6 | // http://www.apache.org/licenses/LICENSE-2.0 7 | // 8 | // Unless required by applicable law or agreed to in writing, software 9 | // distributed under the License is distributed on an "AS IS" BASIS, 10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | // See the License for the specific language governing permissions and 12 | // limitations under the License. 13 | 14 | package oid 15 | 16 | import ( 17 | "crypto/x509" 18 | "encoding/asn1" 19 | ) 20 | 21 | // ToSignatureAlgorithm converts ASN.1 digest and signature algorithm 22 | // identifiers to golang signature algorithms. 23 | func ToSignatureAlgorithm(digestAlg, sigAlg asn1.ObjectIdentifier) x509.SignatureAlgorithm { 24 | switch { 25 | case RSA.Equal(sigAlg): 26 | switch { 27 | case SHA256.Equal(digestAlg): 28 | return x509.SHA256WithRSA 29 | case SHA384.Equal(digestAlg): 30 | return x509.SHA384WithRSA 31 | case SHA512.Equal(digestAlg): 32 | return x509.SHA512WithRSA 33 | } 34 | case RSAPSS.Equal(sigAlg): 35 | switch { 36 | case SHA256.Equal(digestAlg): 37 | return x509.SHA256WithRSAPSS 38 | case SHA384.Equal(digestAlg): 39 | return x509.SHA384WithRSAPSS 40 | case SHA512.Equal(digestAlg): 41 | return x509.SHA512WithRSAPSS 42 | } 43 | case SHA256WithRSA.Equal(sigAlg): 44 | return x509.SHA256WithRSA 45 | case SHA384WithRSA.Equal(sigAlg): 46 | return x509.SHA384WithRSA 47 | case SHA512WithRSA.Equal(sigAlg): 48 | return x509.SHA512WithRSA 49 | case ECDSAWithSHA256.Equal(sigAlg): 50 | return x509.ECDSAWithSHA256 51 | case ECDSAWithSHA384.Equal(sigAlg): 52 | return x509.ECDSAWithSHA384 53 | case ECDSAWithSHA512.Equal(sigAlg): 54 | return x509.ECDSAWithSHA512 55 | } 56 | return x509.UnknownSignatureAlgorithm 57 | } 58 | -------------------------------------------------------------------------------- /internal/oid/algorithm_test.go: -------------------------------------------------------------------------------- 1 | // Copyright The Notary Project Authors. 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // 6 | // http://www.apache.org/licenses/LICENSE-2.0 7 | // 8 | // Unless required by applicable law or agreed to in writing, software 9 | // distributed under the License is distributed on an "AS IS" BASIS, 10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | // See the License for the specific language governing permissions and 12 | // limitations under the License. 13 | 14 | package oid 15 | 16 | import ( 17 | "crypto/x509" 18 | "encoding/asn1" 19 | "testing" 20 | ) 21 | 22 | func TestToSignatureAlgorithm(t *testing.T) { 23 | tests := []struct { 24 | name string 25 | digestAlg asn1.ObjectIdentifier 26 | sigAlg asn1.ObjectIdentifier 27 | wantResult x509.SignatureAlgorithm 28 | }{ 29 | {"SHA256WithRSA", SHA256, RSA, x509.SHA256WithRSA}, 30 | {"SHA384WithRSA", SHA384, RSA, x509.SHA384WithRSA}, 31 | {"SHA512WithRSA", SHA512, RSA, x509.SHA512WithRSA}, 32 | {"SHA256WithRSAPSS", SHA256, RSAPSS, x509.SHA256WithRSAPSS}, 33 | {"SHA384WithRSAPSS", SHA384, RSAPSS, x509.SHA384WithRSAPSS}, 34 | {"SHA512WithRSAPSS", SHA512, RSAPSS, x509.SHA512WithRSAPSS}, 35 | {"SHA256WithRSA direct", SHA256WithRSA, SHA256WithRSA, x509.SHA256WithRSA}, 36 | {"SHA384WithRSA direct", SHA384WithRSA, SHA384WithRSA, x509.SHA384WithRSA}, 37 | {"SHA512WithRSA direct", SHA512WithRSA, SHA512WithRSA, x509.SHA512WithRSA}, 38 | {"ECDSAWithSHA256", ECDSAWithSHA256, ECDSAWithSHA256, x509.ECDSAWithSHA256}, 39 | {"ECDSAWithSHA384", ECDSAWithSHA384, ECDSAWithSHA384, x509.ECDSAWithSHA384}, 40 | {"ECDSAWithSHA512", ECDSAWithSHA512, ECDSAWithSHA512, x509.ECDSAWithSHA512}, 41 | {"UnknownSignatureAlgorithm", asn1.ObjectIdentifier{1, 2, 3}, asn1.ObjectIdentifier{4, 5, 6}, x509.UnknownSignatureAlgorithm}, 42 | } 43 | 44 | for _, tt := range tests { 45 | t.Run(tt.name, func(t *testing.T) { 46 | if gotResult := ToSignatureAlgorithm(tt.digestAlg, tt.sigAlg); gotResult != tt.wantResult { 47 | t.Errorf("ToSignatureAlgorithm() = %v, want %v", gotResult, tt.wantResult) 48 | } 49 | }) 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /internal/oid/hash.go: -------------------------------------------------------------------------------- 1 | // Copyright The Notary Project Authors. 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // 6 | // http://www.apache.org/licenses/LICENSE-2.0 7 | // 8 | // Unless required by applicable law or agreed to in writing, software 9 | // distributed under the License is distributed on an "AS IS" BASIS, 10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | // See the License for the specific language governing permissions and 12 | // limitations under the License. 13 | 14 | package oid 15 | 16 | import ( 17 | "crypto" 18 | "encoding/asn1" 19 | "fmt" 20 | ) 21 | 22 | // ToHash converts ASN.1 digest algorithm identifier to golang crypto hash 23 | // if it is available. 24 | func ToHash(alg asn1.ObjectIdentifier) (crypto.Hash, bool) { 25 | var hash crypto.Hash 26 | switch { 27 | case SHA256.Equal(alg): 28 | hash = crypto.SHA256 29 | case SHA384.Equal(alg): 30 | hash = crypto.SHA384 31 | case SHA512.Equal(alg): 32 | hash = crypto.SHA512 33 | default: 34 | return hash, false 35 | } 36 | return hash, hash.Available() 37 | } 38 | 39 | // FromHash returns corresponding ASN.1 OID for the given Hash algorithm. 40 | func FromHash(alg crypto.Hash) (asn1.ObjectIdentifier, error) { 41 | var id asn1.ObjectIdentifier 42 | switch alg { 43 | case crypto.SHA256: 44 | id = SHA256 45 | case crypto.SHA384: 46 | id = SHA384 47 | case crypto.SHA512: 48 | id = SHA512 49 | default: 50 | return nil, fmt.Errorf("unsupported hashing algorithm: %v", alg) 51 | } 52 | return id, nil 53 | } 54 | -------------------------------------------------------------------------------- /internal/oid/hash_test.go: -------------------------------------------------------------------------------- 1 | // Copyright The Notary Project Authors. 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // 6 | // http://www.apache.org/licenses/LICENSE-2.0 7 | // 8 | // Unless required by applicable law or agreed to in writing, software 9 | // distributed under the License is distributed on an "AS IS" BASIS, 10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | // See the License for the specific language governing permissions and 12 | // limitations under the License. 13 | 14 | package oid 15 | 16 | import ( 17 | "crypto" 18 | "encoding/asn1" 19 | "fmt" 20 | "testing" 21 | ) 22 | 23 | // sha1 (id-sha1) is defined in RFC 8017 B.1 Hash Functions. 24 | // for test purpose only 25 | var sha1 = asn1.ObjectIdentifier{1, 3, 14, 3, 2, 26} 26 | 27 | func TestToHash(t *testing.T) { 28 | tests := []struct { 29 | name string 30 | alg asn1.ObjectIdentifier 31 | wantHash crypto.Hash 32 | wantExists bool 33 | }{ 34 | {"SHA256", SHA256, crypto.SHA256, true}, 35 | {"SHA384", SHA384, crypto.SHA384, true}, 36 | {"SHA512", SHA512, crypto.SHA512, true}, 37 | {"Unknown", asn1.ObjectIdentifier{1, 2, 3}, crypto.Hash(0), false}, 38 | } 39 | 40 | for _, tt := range tests { 41 | t.Run(tt.name, func(t *testing.T) { 42 | gotHash, gotExists := ToHash(tt.alg) 43 | if gotHash != tt.wantHash { 44 | t.Errorf("ToHash() gotHash = %v, want %v", gotHash, tt.wantHash) 45 | } 46 | if gotExists != tt.wantExists { 47 | t.Errorf("ToHash() gotExists = %v, want %v", gotExists, tt.wantExists) 48 | } 49 | }) 50 | } 51 | } 52 | 53 | func TestFromHash(t *testing.T) { 54 | tests := []struct { 55 | name string 56 | alg crypto.Hash 57 | wantAlg asn1.ObjectIdentifier 58 | wantError error 59 | }{ 60 | {"SHA256", crypto.SHA256, SHA256, nil}, 61 | {"SHA384", crypto.SHA384, SHA384, nil}, 62 | {"SHA512", crypto.SHA512, SHA512, nil}, 63 | {"Unsupported", crypto.SHA1, sha1, fmt.Errorf("unsupported hashing algorithm: %s", crypto.SHA1)}, 64 | } 65 | 66 | for _, tt := range tests { 67 | t.Run(tt.name, func(t *testing.T) { 68 | gotAlg, err := FromHash(tt.alg) 69 | if err == nil && tt.wantError != nil { 70 | t.Fatalf("FromHash() expected %v, but got nil", tt.wantError) 71 | } 72 | if err != nil && (tt.wantError == nil || err.Error() != tt.wantError.Error()) { 73 | t.Fatalf("FromHash() expected %v, but got %v", tt.wantError, err) 74 | } 75 | if err == nil && !gotAlg.Equal(tt.wantAlg) { 76 | t.Errorf("FromHash() gotAlg = %v, want %v", gotAlg, tt.wantAlg) 77 | } 78 | }) 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /internal/oid/oid.go: -------------------------------------------------------------------------------- 1 | // Copyright The Notary Project Authors. 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // 6 | // http://www.apache.org/licenses/LICENSE-2.0 7 | // 8 | // Unless required by applicable law or agreed to in writing, software 9 | // distributed under the License is distributed on an "AS IS" BASIS, 10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | // See the License for the specific language governing permissions and 12 | // limitations under the License. 13 | 14 | // Package oid collects object identifiers for crypto algorithms. 15 | package oid 16 | 17 | import "encoding/asn1" 18 | 19 | // OIDs for hash algorithms 20 | var ( 21 | // SHA256 (id-sha256) is defined in RFC 8017 B.1 Hash Functions 22 | SHA256 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 2, 1} 23 | 24 | // SHA384 (id-sha384) is defined in RFC 8017 B.1 Hash Functions 25 | SHA384 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 2, 2} 26 | 27 | // SHA512 (id-sha512) is defined in RFC 8017 B.1 Hash Functions 28 | SHA512 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 2, 3} 29 | ) 30 | 31 | // OIDs for signature algorithms 32 | var ( 33 | // RSA is defined in RFC 8017 C ASN.1 Module 34 | RSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 1} 35 | 36 | // SHA256WithRSA is defined in RFC 8017 C ASN.1 Module 37 | SHA256WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 11} 38 | 39 | // SHA384WithRSA is defined in RFC 8017 C ASN.1 Module 40 | SHA384WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 12} 41 | 42 | // SHA512WithRSA is defined in RFC 8017 C ASN.1 Module 43 | SHA512WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 13} 44 | 45 | // RSAPSS is defined in RFC 8017 C ASN.1 Module 46 | RSAPSS = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 10} 47 | 48 | // ECDSAWithSHA256 is defined in RFC 5758 3.2 ECDSA Signature Algorithm 49 | ECDSAWithSHA256 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 3, 2} 50 | 51 | // ECDSAWithSHA384 is defined in RFC 5758 3.2 ECDSA Signature Algorithm 52 | ECDSAWithSHA384 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 3, 3} 53 | 54 | // ECDSAWithSHA512 is defined in RFC 5758 3.2 ECDSA Signature Algorithm 55 | ECDSAWithSHA512 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 3, 4} 56 | ) 57 | 58 | // OIDs defined in RFC 5652 Cryptographic Message Syntax (CMS) 59 | var ( 60 | // Data (id-data) is defined in RFC 5652 4 Data Content Type 61 | Data = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 7, 1} 62 | 63 | // SignedData (id-signedData) is defined in RFC 5652 5.1 SignedData Type 64 | SignedData = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 7, 2} 65 | 66 | // ContentType (id-ct-contentType) is defined in RFC 5652 3 General Syntax 67 | ContentType = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 9, 3} 68 | 69 | // MessageDigest (id-messageDigest) is defined in RFC 5652 11.2 Message Digest 70 | MessageDigest = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 9, 4} 71 | 72 | // SigningTime (id-signingTime) is defined in RFC 5652 11.3 Signing Time 73 | SigningTime = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 9, 5} 74 | ) 75 | 76 | // OIDs for RFC 3161 Timestamping 77 | var ( 78 | // TSTInfo (id-ct-TSTInfo) is defined in RFC 3161 2.4.2 Response Format 79 | TSTInfo = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 9, 16, 1, 4} 80 | 81 | // SigningCertificateV2 (id-aa-signingCertificate) is defined in RFC 2634 5.4 82 | // 83 | // Reference: https://datatracker.ietf.org/doc/html/rfc2634#section-5.4 84 | SigningCertificate = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 9, 16, 2, 12} 85 | 86 | // SigningCertificateV2 (id-aa-signingCertificateV2) is defined in RFC 5035 3 87 | // 88 | // Reference: https://datatracker.ietf.org/doc/html/rfc5035#section-3 89 | SigningCertificateV2 = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 9, 16, 2, 47} 90 | 91 | // ExtKeyUsage (id-ce-extKeyUsage) is defined in RFC 5280 92 | // 93 | // Reference: https://www.rfc-editor.org/rfc/rfc5280.html#section-4.2.1.12 94 | ExtKeyUsage = asn1.ObjectIdentifier{2, 5, 29, 37} 95 | 96 | // Timestamping (id-kp-timeStamping) is defined in RFC 3161 2.3 97 | // 98 | // Reference: https://datatracker.ietf.org/doc/html/rfc3161#section-2.3 99 | Timestamping = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 8} 100 | ) 101 | 102 | // OIDs for RFC 3628 Policy Requirements for Time-Stamping Authorities (TSAs) 103 | var ( 104 | // BaselineTimestampPolicy (baseline time-stamp policy) is defined in 105 | // RFC 3628 106 | // 107 | // Referene: https://datatracker.ietf.org/doc/html/rfc3628#section-5.2 108 | BaselineTimestampPolicy = asn1.ObjectIdentifier{0, 4, 0, 2023, 1, 1} 109 | ) 110 | -------------------------------------------------------------------------------- /pki/errors.go: -------------------------------------------------------------------------------- 1 | // Copyright The Notary Project Authors. 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // 6 | // http://www.apache.org/licenses/LICENSE-2.0 7 | // 8 | // Unless required by applicable law or agreed to in writing, software 9 | // distributed under the License is distributed on an "AS IS" BASIS, 10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | // See the License for the specific language governing permissions and 12 | // limitations under the License. 13 | 14 | // Package pki contains Status of a timestamping response defined in RFC 3161. 15 | package pki 16 | 17 | import "strings" 18 | 19 | // FailureInfoError is error of FailureInfo with a joined internal error 20 | type FailureInfoError struct { 21 | // Detail is the joined internal error 22 | Detail error 23 | } 24 | 25 | // Error prints out the internal error e.Detail split by '; ' 26 | func (e *FailureInfoError) Error() string { 27 | if e.Detail == nil { 28 | return "" 29 | } 30 | return strings.ReplaceAll(e.Detail.Error(), "\n", "; ") 31 | } 32 | 33 | // Unwrap returns the internal error 34 | func (e *FailureInfoError) Unwrap() error { 35 | return e.Detail 36 | } 37 | -------------------------------------------------------------------------------- /pki/errors_test.go: -------------------------------------------------------------------------------- 1 | // Copyright The Notary Project Authors. 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // 6 | // http://www.apache.org/licenses/LICENSE-2.0 7 | // 8 | // Unless required by applicable law or agreed to in writing, software 9 | // distributed under the License is distributed on an "AS IS" BASIS, 10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | // See the License for the specific language governing permissions and 12 | // limitations under the License. 13 | 14 | // Package pki contains Status of a timestamping response defined in RFC 3161. 15 | package pki 16 | 17 | import ( 18 | "errors" 19 | "testing" 20 | ) 21 | 22 | func TestFailureInfoError(t *testing.T) { 23 | testData := []string{ 24 | "unrecognized or unsupported Algorithm Identifier", 25 | "transaction not permitted or supported", 26 | "the data submitted has the wrong format", 27 | "the TSA's time source is not available", 28 | "the requested TSA policy is not supported by the TSA", 29 | "the requested extension is not supported by the TSA", 30 | "the additional information requested could not be understood or is not available", 31 | "the request cannot be handled due to system failure", 32 | } 33 | for idx, f := range failureInfos { 34 | if f.Error().Error() != testData[idx] { 35 | t.Fatalf("expected %s, but got %s", f.Error().Error(), testData[idx]) 36 | } 37 | } 38 | 39 | unknown := FailureInfo(1) 40 | if unknown.Error().Error() != "unknown PKIFailureInfo 1" { 41 | t.Fatalf("expected %s, but got %s", "unknown PKIFailureInfo", unknown.Error().Error()) 42 | } 43 | 44 | failureInfoErr := FailureInfoError{ 45 | Detail: errors.Join(FailureInfoBadRequest.Error(), FailureInfoBadDataFormat.Error()), 46 | } 47 | expectedErrMsg := "transaction not permitted or supported; the data submitted has the wrong format" 48 | if failureInfoErr.Error() != expectedErrMsg { 49 | t.Fatalf("expected %s, but got %s", expectedErrMsg, failureInfoErr.Error()) 50 | } 51 | innerErr := failureInfoErr.Unwrap() 52 | expectedErrMsg = "transaction not permitted or supported\nthe data submitted has the wrong format" 53 | if innerErr.Error() != expectedErrMsg { 54 | t.Fatalf("expected error %s, but got %v", expectedErrMsg, innerErr) 55 | } 56 | 57 | failureInfoErr = FailureInfoError{} 58 | expectedErrMsg = "" 59 | if failureInfoErr.Error() != expectedErrMsg { 60 | t.Fatalf("expected error %s, but got %v", expectedErrMsg, innerErr) 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /pki/pki.go: -------------------------------------------------------------------------------- 1 | // Copyright The Notary Project Authors. 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // 6 | // http://www.apache.org/licenses/LICENSE-2.0 7 | // 8 | // Unless required by applicable law or agreed to in writing, software 9 | // distributed under the License is distributed on an "AS IS" BASIS, 10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | // See the License for the specific language governing permissions and 12 | // limitations under the License. 13 | 14 | // Package pki contains Status of a timestamping response defined in RFC 3161. 15 | package pki 16 | 17 | import ( 18 | "encoding/asn1" 19 | "errors" 20 | "fmt" 21 | "strconv" 22 | ) 23 | 24 | // ErrUnknownStatus is used when PKIStatus is not supported 25 | var ErrUnknownStatus = errors.New("unknown PKIStatus") 26 | 27 | // ErrUnknownFailureInfo is used when PKIFailureInfo is not supported or does 28 | // not exists 29 | var ErrUnknownFailureInfo = errors.New("unknown PKIFailureInfo") 30 | 31 | // Status is PKIStatus defined in RFC 3161 2.4.2. 32 | type Status int 33 | 34 | const ( 35 | StatusGranted Status = 0 // you got exactly what you asked for 36 | StatusGrantedWithMods Status = 1 // you got something like what you asked for 37 | StatusRejection Status = 2 // you don't get it, more information elsewhere in the message 38 | StatusWaiting Status = 3 // the request body part has not yet been processed, expect to hear more later 39 | StatusRevocationWarning Status = 4 // this message contains a warning that a revocation is imminent 40 | StatusRevocationNotification Status = 5 // notification that a revocation has occurred 41 | ) 42 | 43 | // String converts Status to string 44 | func (s Status) String() string { 45 | switch s { 46 | case StatusGranted: 47 | return "granted" 48 | case StatusGrantedWithMods: 49 | return "granted with modifications" 50 | case StatusRejection: 51 | return "rejected" 52 | case StatusWaiting: 53 | return "the request body part has not yet been processed, expect to hear more later" 54 | case StatusRevocationWarning: 55 | return "warning: a revocation is imminent" 56 | case StatusRevocationNotification: 57 | return "a revocation has occurred" 58 | default: 59 | return "unknown PKIStatus " + strconv.Itoa(int(s)) 60 | } 61 | } 62 | 63 | // FailureInfo is PKIFailureInfo defined in RFC 3161 2.4.2. 64 | type FailureInfo int 65 | 66 | const ( 67 | FailureInfoBadAlg FailureInfo = 0 // unrecognized or unsupported Algorithm Identifier 68 | FailureInfoBadRequest FailureInfo = 2 // transaction not permitted or supported 69 | FailureInfoBadDataFormat FailureInfo = 5 // the data submitted has the wrong format 70 | FailureInfoTimeNotAvailable FailureInfo = 14 // the TSA's time source is not available 71 | FailureInfoUnacceptedPolicy FailureInfo = 15 // the requested TSA policy is not supported by the TSA. 72 | FailureInfoUnacceptedExtension FailureInfo = 16 // the requested extension is not supported by the TSA. 73 | FailureInfoAddInfoNotAvailable FailureInfo = 17 // the additional information requested could not be understood or is not available 74 | FailureInfoSystemFailure FailureInfo = 25 // the request cannot be handled due to system failure 75 | ) 76 | 77 | // failureInfos is an array of supported PKIFailureInfo 78 | var failureInfos = []FailureInfo{ 79 | FailureInfoBadAlg, 80 | FailureInfoBadRequest, 81 | FailureInfoBadDataFormat, 82 | FailureInfoTimeNotAvailable, 83 | FailureInfoUnacceptedPolicy, 84 | FailureInfoUnacceptedExtension, 85 | FailureInfoAddInfoNotAvailable, 86 | FailureInfoSystemFailure, 87 | } 88 | 89 | // Error converts a FailureInfo to an error 90 | func (fi FailureInfo) Error() error { 91 | switch fi { 92 | case FailureInfoBadAlg: 93 | return errors.New("unrecognized or unsupported Algorithm Identifier") 94 | case FailureInfoBadRequest: 95 | return errors.New("transaction not permitted or supported") 96 | case FailureInfoBadDataFormat: 97 | return errors.New("the data submitted has the wrong format") 98 | case FailureInfoTimeNotAvailable: 99 | return errors.New("the TSA's time source is not available") 100 | case FailureInfoUnacceptedPolicy: 101 | return errors.New("the requested TSA policy is not supported by the TSA") 102 | case FailureInfoUnacceptedExtension: 103 | return errors.New("the requested extension is not supported by the TSA") 104 | case FailureInfoAddInfoNotAvailable: 105 | return errors.New("the additional information requested could not be understood or is not available") 106 | case FailureInfoSystemFailure: 107 | return errors.New("the request cannot be handled due to system failure") 108 | default: 109 | return errors.New("unknown PKIFailureInfo " + strconv.Itoa(int(fi))) 110 | } 111 | } 112 | 113 | // StatusInfo contains status codes and failure information for PKI messages. 114 | // 115 | // PKIStatusInfo ::= SEQUENCE { 116 | // status PKIStatus, 117 | // statusString PKIFreeText OPTIONAL, 118 | // failInfo PKIFailureInfo OPTIONAL } 119 | // 120 | // PKIStatus ::= INTEGER 121 | // PKIFreeText ::= SEQUENCE SIZE (1..MAX) OF UTF8String 122 | // PKIFailureInfo ::= BIT STRING 123 | // 124 | // Reference: RFC 3161 2.4.2 125 | type StatusInfo struct { 126 | Status Status 127 | StatusString []string `asn1:"optional,utf8"` 128 | FailInfo asn1.BitString `asn1:"optional"` 129 | } 130 | 131 | // Err return nil when si Status is StatusGranted or StatusGrantedWithMods 132 | // 133 | // Otherwise, Err returns an error with FailInfo if any. 134 | func (si StatusInfo) Err() error { 135 | if si.Status != StatusGranted && si.Status != StatusGrantedWithMods { 136 | var errs []error 137 | for _, fi := range failureInfos { 138 | if si.FailInfo.At(int(fi)) != 0 { 139 | errs = append(errs, fi.Error()) 140 | } 141 | } 142 | if len(errs) != 0 { 143 | // there is FailInfo, wrap them into a FailureInfoError 144 | return fmt.Errorf("invalid response with status code %d: %s. Failure info: %w", si.Status, si.Status.String(), &FailureInfoError{Detail: errors.Join(errs...)}) 145 | } 146 | return fmt.Errorf("invalid response with status code %d: %s", si.Status, si.Status.String()) 147 | } 148 | return nil 149 | } 150 | -------------------------------------------------------------------------------- /pki/pki_test.go: -------------------------------------------------------------------------------- 1 | // Copyright The Notary Project Authors. 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // 6 | // http://www.apache.org/licenses/LICENSE-2.0 7 | // 8 | // Unless required by applicable law or agreed to in writing, software 9 | // distributed under the License is distributed on an "AS IS" BASIS, 10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | // See the License for the specific language governing permissions and 12 | // limitations under the License. 13 | 14 | package pki 15 | 16 | import ( 17 | "encoding/asn1" 18 | "testing" 19 | ) 20 | 21 | // statuses is an array of supported PKIStatus 22 | var statuses = []Status{ 23 | StatusGranted, 24 | StatusGrantedWithMods, 25 | StatusRejection, 26 | StatusWaiting, 27 | StatusRevocationWarning, 28 | StatusRevocationNotification, 29 | } 30 | 31 | func TestStatusInfo(t *testing.T) { 32 | statusInfo := StatusInfo{ 33 | Status: StatusGranted, 34 | } 35 | err := statusInfo.Err() 36 | if err != nil { 37 | t.Fatalf("expected nil error, but got %s", err) 38 | } 39 | 40 | statusInfo = StatusInfo{ 41 | Status: StatusRejection, 42 | FailInfo: asn1.BitString{ 43 | // unknown FailureInfo 44 | Bytes: []byte{0x01}, 45 | BitLength: 1, 46 | }, 47 | } 48 | err = statusInfo.Err() 49 | expectedErrMsg := "invalid response with status code 2: rejected" 50 | if err == nil || err.Error() != expectedErrMsg { 51 | t.Fatalf("expected %s, but got %s", expectedErrMsg, err) 52 | } 53 | 54 | statusInfo = StatusInfo{ 55 | Status: StatusRejection, 56 | FailInfo: asn1.BitString{ 57 | // FailureInfoBadAlg 58 | Bytes: []byte{0x80}, 59 | BitLength: 1, 60 | }, 61 | } 62 | err = statusInfo.Err() 63 | expectedErrMsg = "invalid response with status code 2: rejected. Failure info: unrecognized or unsupported Algorithm Identifier" 64 | if err == nil || err.Error() != expectedErrMsg { 65 | t.Fatalf("expected %s, but got %s", expectedErrMsg, err) 66 | } 67 | 68 | statusInfo = StatusInfo{ 69 | Status: StatusRejection, 70 | FailInfo: asn1.BitString{ 71 | // FailureInfoBadRequest and FailureInfoBadDataFormat 72 | Bytes: []byte{0x24}, 73 | BitLength: 8, 74 | }, 75 | } 76 | err = statusInfo.Err() 77 | expectedErrMsg = "invalid response with status code 2: rejected. Failure info: transaction not permitted or supported; the data submitted has the wrong format" 78 | if err == nil || err.Error() != expectedErrMsg { 79 | t.Fatalf("expected %s, but got %s", expectedErrMsg, err) 80 | } 81 | } 82 | 83 | func TestStatusString(t *testing.T) { 84 | testData := []string{ 85 | "granted", 86 | "granted with modifications", 87 | "rejected", 88 | "the request body part has not yet been processed, expect to hear more later", 89 | "warning: a revocation is imminent", 90 | "a revocation has occurred", 91 | } 92 | for idx, s := range statuses { 93 | if s.String() != testData[idx] { 94 | t.Fatalf("expected %s, but got %s", s.String(), testData[idx]) 95 | } 96 | } 97 | 98 | unknown := Status(6) 99 | if unknown.String() != "unknown PKIStatus 6" { 100 | t.Fatalf("expected %s, but got %s", "unknown PKIStatus", unknown.String()) 101 | } 102 | } 103 | -------------------------------------------------------------------------------- /request.go: -------------------------------------------------------------------------------- 1 | // Copyright The Notary Project Authors. 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // 6 | // http://www.apache.org/licenses/LICENSE-2.0 7 | // 8 | // Unless required by applicable law or agreed to in writing, software 9 | // distributed under the License is distributed on an "AS IS" BASIS, 10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | // See the License for the specific language governing permissions and 12 | // limitations under the License. 13 | 14 | package tspclient 15 | 16 | import ( 17 | "bytes" 18 | "crypto" 19 | "crypto/rand" 20 | "crypto/x509/pkix" 21 | "encoding/asn1" 22 | "errors" 23 | "fmt" 24 | "math/big" 25 | 26 | tspclientasn1 "github.com/notaryproject/tspclient-go/internal/encoding/asn1" 27 | "github.com/notaryproject/tspclient-go/internal/hashutil" 28 | "github.com/notaryproject/tspclient-go/internal/oid" 29 | ) 30 | 31 | // MessageImprint contains the hash of the datum to be time-stamped. 32 | // 33 | // MessageImprint ::= SEQUENCE { 34 | // hashAlgorithm AlgorithmIdentifier, 35 | // hashedMessage OCTET STRING } 36 | type MessageImprint struct { 37 | HashAlgorithm pkix.AlgorithmIdentifier 38 | HashedMessage []byte 39 | } 40 | 41 | // Equal compares if m and n are the same MessageImprint 42 | // 43 | // Reference: RFC 3161 2.4.2 44 | func (m MessageImprint) Equal(n MessageImprint) bool { 45 | return m.HashAlgorithm.Algorithm.Equal(n.HashAlgorithm.Algorithm) && 46 | tspclientasn1.EqualRawValue(m.HashAlgorithm.Parameters, n.HashAlgorithm.Parameters) && 47 | bytes.Equal(m.HashedMessage, n.HashedMessage) 48 | } 49 | 50 | // asn1NullRawValue is the full form of asn1.NullRawValue with its encoded self 51 | // in the `FullBytes` field. 52 | // 53 | // https://pkg.go.dev/encoding/asn1#NullRawValue 54 | var asn1NullRawValue = asn1.RawValue{ 55 | Tag: asn1.TagNull, 56 | FullBytes: []byte{asn1.TagNull, 0}, 57 | } 58 | 59 | // Request is a time-stamping request. 60 | // 61 | // TimeStampReq ::= SEQUENCE { 62 | // version INTEGER { v1(1) }, 63 | // messageImprint MessageImprint, 64 | // reqPolicy TSAPolicyID OPTIONAL, 65 | // nonce INTEGER OPTIONAL, 66 | // certReq BOOLEAN DEFAULT FALSE, 67 | // extensions [0] IMPLICIT Extensions OPTIONAL } 68 | type Request struct { 69 | Version int // fixed to 1 as defined in RFC 3161 2.4.1 Request Format 70 | MessageImprint MessageImprint 71 | ReqPolicy asn1.ObjectIdentifier `asn1:"optional"` 72 | Nonce *big.Int `asn1:"optional"` 73 | CertReq bool `asn1:"optional,default:false"` 74 | Extensions []pkix.Extension `asn1:"optional,tag:0"` 75 | } 76 | 77 | // RequestOptions provides options for caller to create a new timestamp request 78 | type RequestOptions struct { 79 | // Content is the datum to be time stamped. REQUIRED. 80 | Content []byte 81 | 82 | // HashAlgorithm is the hash algorithm to be used to hash the Content. 83 | // REQUIRED and MUST be an available hash algorithm. 84 | HashAlgorithm crypto.Hash 85 | 86 | // HashAlgorithmParameters is the parameters for the HashAlgorithm. 87 | // OPTIONAL. 88 | // 89 | // Reference: https://www.rfc-editor.org/rfc/rfc5280#section-4.1.1.2 90 | HashAlgorithmParameters asn1.RawValue 91 | 92 | // ReqPolicy specifies the TSA policy ID. OPTIONAL. 93 | // 94 | // Reference: https://datatracker.ietf.org/doc/html/rfc3161#section-2.4.1 95 | ReqPolicy asn1.ObjectIdentifier 96 | 97 | // NoCert tells the TSA to not include any signing certificate in its 98 | // response. By default, TSA signing certificate is included in the response. 99 | // OPTIONAL. 100 | NoCert bool 101 | 102 | // Extensions is a generic way to add additional information 103 | // to the request in the future. OPTIONAL. 104 | Extensions []pkix.Extension 105 | } 106 | 107 | // NewRequest creates a timestamp request based on caller provided options. 108 | func NewRequest(opts RequestOptions) (*Request, error) { 109 | if opts.Content == nil { 110 | return nil, &MalformedRequestError{Msg: "content to be time stamped cannot be empty"} 111 | } 112 | hashAlg, err := oid.FromHash(opts.HashAlgorithm) 113 | if err != nil { 114 | return nil, &MalformedRequestError{Msg: err.Error()} 115 | } 116 | digest, err := hashutil.ComputeHash(opts.HashAlgorithm, opts.Content) 117 | if err != nil { 118 | return nil, &MalformedRequestError{Msg: err.Error()} 119 | } 120 | hashAlgParameter := opts.HashAlgorithmParameters 121 | if tspclientasn1.EqualRawValue(hashAlgParameter, asn1.RawValue{}) || tspclientasn1.EqualRawValue(hashAlgParameter, asn1.NullRawValue) { 122 | hashAlgParameter = asn1NullRawValue 123 | } 124 | nonce, err := generateNonce() 125 | if err != nil { 126 | return nil, &MalformedRequestError{Msg: err.Error()} 127 | } 128 | return &Request{ 129 | Version: 1, 130 | MessageImprint: MessageImprint{ 131 | HashAlgorithm: pkix.AlgorithmIdentifier{ 132 | Algorithm: hashAlg, 133 | Parameters: hashAlgParameter, 134 | }, 135 | HashedMessage: digest, 136 | }, 137 | ReqPolicy: opts.ReqPolicy, 138 | Nonce: nonce, 139 | CertReq: !opts.NoCert, 140 | Extensions: opts.Extensions, 141 | }, nil 142 | } 143 | 144 | // MarshalBinary encodes the request to binary form. 145 | // This method implements encoding.BinaryMarshaler. 146 | // 147 | // Reference: https://pkg.go.dev/encoding#BinaryMarshaler 148 | func (r *Request) MarshalBinary() ([]byte, error) { 149 | if r == nil { 150 | return nil, errors.New("nil request") 151 | } 152 | return asn1.Marshal(*r) 153 | } 154 | 155 | // UnmarshalBinary decodes the request from binary form. 156 | // This method implements encoding.BinaryUnmarshaler. 157 | // 158 | // Reference: https://pkg.go.dev/encoding#BinaryUnmarshaler 159 | func (r *Request) UnmarshalBinary(data []byte) error { 160 | _, err := asn1.Unmarshal(data, r) 161 | return err 162 | } 163 | 164 | // Validate checks if req is a valid request against RFC 3161. 165 | // It is used before a timstamp requestor sending the request to TSA. 166 | func (r *Request) Validate() error { 167 | if r == nil { 168 | return &MalformedRequestError{Msg: "request cannot be nil"} 169 | } 170 | if r.Version != 1 { 171 | return &MalformedRequestError{Msg: fmt.Sprintf("request version must be 1, but got %d", r.Version)} 172 | } 173 | hashAlg := r.MessageImprint.HashAlgorithm.Algorithm 174 | hash, available := oid.ToHash(hashAlg) 175 | if !available { 176 | return &MalformedRequestError{Msg: fmt.Sprintf("hash algorithm %v is unavailable", hashAlg)} 177 | } 178 | if hash.Size() != len(r.MessageImprint.HashedMessage) { 179 | return &MalformedRequestError{Msg: fmt.Sprintf("hashed message is of incorrect size %d", len(r.MessageImprint.HashedMessage))} 180 | } 181 | return nil 182 | } 183 | 184 | // generateNonce generates a built-in Nonce for TSA request 185 | func generateNonce() (*big.Int, error) { 186 | // Pick a random number from 0 to 2^159 187 | nonce, err := rand.Int(rand.Reader, (&big.Int{}).Lsh(big.NewInt(1), 159)) 188 | if err != nil { 189 | return nil, errors.New("failed to generate nonce") 190 | } 191 | return nonce, nil 192 | } 193 | -------------------------------------------------------------------------------- /request_test.go: -------------------------------------------------------------------------------- 1 | // Copyright The Notary Project Authors. 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // 6 | // http://www.apache.org/licenses/LICENSE-2.0 7 | // 8 | // Unless required by applicable law or agreed to in writing, software 9 | // distributed under the License is distributed on an "AS IS" BASIS, 10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | // See the License for the specific language governing permissions and 12 | // limitations under the License. 13 | 14 | package tspclient 15 | 16 | import ( 17 | "crypto" 18 | "crypto/rand" 19 | "crypto/x509/pkix" 20 | "encoding/asn1" 21 | "errors" 22 | "fmt" 23 | "reflect" 24 | "testing" 25 | 26 | "github.com/notaryproject/tspclient-go/internal/hashutil" 27 | "github.com/notaryproject/tspclient-go/internal/oid" 28 | ) 29 | 30 | func TestNewRequest(t *testing.T) { 31 | message := []byte("test") 32 | var malformedRequest *MalformedRequestError 33 | 34 | opts := RequestOptions{} 35 | expectedErrMsg := "malformed timestamping request: content to be time stamped cannot be empty" 36 | _, err := NewRequest(opts) 37 | if err == nil || !errors.As(err, &malformedRequest) || err.Error() != expectedErrMsg { 38 | t.Fatalf("expected error %s, but got %v", expectedErrMsg, err) 39 | } 40 | 41 | opts = RequestOptions{ 42 | Content: message, 43 | HashAlgorithm: crypto.SHA1, 44 | } 45 | expectedErrMsg = fmt.Sprintf("malformed timestamping request: unsupported hashing algorithm: %s", crypto.SHA1) 46 | _, err = NewRequest(opts) 47 | if err == nil || !errors.As(err, &malformedRequest) || err.Error() != expectedErrMsg { 48 | t.Fatalf("expected error %s, but got %v", expectedErrMsg, err) 49 | } 50 | 51 | opts = RequestOptions{ 52 | Content: message, 53 | HashAlgorithm: crypto.SHA256, 54 | } 55 | req, err := NewRequest(opts) 56 | if err != nil { 57 | t.Fatalf("expected nil error, but got %v", err) 58 | } 59 | if !reflect.DeepEqual(req.MessageImprint.HashAlgorithm.Parameters, asn1NullRawValue) { 60 | t.Fatalf("expected %v, but got %v", asn1NullRawValue, req.MessageImprint.HashAlgorithm.Parameters) 61 | } 62 | 63 | opts = RequestOptions{ 64 | Content: message, 65 | HashAlgorithm: crypto.SHA256, 66 | HashAlgorithmParameters: asn1.NullRawValue, 67 | } 68 | req, err = NewRequest(opts) 69 | if err != nil { 70 | t.Fatalf("expected nil error, but got %v", err) 71 | } 72 | if !reflect.DeepEqual(req.MessageImprint.HashAlgorithm.Parameters, asn1NullRawValue) { 73 | t.Fatalf("expected %v, but got %v", asn1NullRawValue, req.MessageImprint.HashAlgorithm.Parameters) 74 | } 75 | 76 | defaultRandReader := rand.Reader 77 | rand.Reader = &dummyRandReader{} 78 | defer func() { 79 | rand.Reader = defaultRandReader 80 | }() 81 | opts = RequestOptions{ 82 | Content: message, 83 | HashAlgorithm: crypto.SHA256, 84 | } 85 | expectedErrMsg = "malformed timestamping request: failed to generate nonce" 86 | _, err = NewRequest(opts) 87 | if err == nil || !errors.As(err, &malformedRequest) || err.Error() != expectedErrMsg { 88 | t.Fatalf("expected error %s, but got %v", expectedErrMsg, err) 89 | } 90 | } 91 | 92 | func TestRequestMarshalBinary(t *testing.T) { 93 | var r *Request 94 | _, err := r.MarshalBinary() 95 | if err == nil || err.Error() != "nil request" { 96 | t.Fatalf("expected error 'nil request', but got %v", err) 97 | } 98 | 99 | opts := RequestOptions{ 100 | Content: []byte("test"), 101 | HashAlgorithm: crypto.SHA256, 102 | } 103 | req, err := NewRequest(opts) 104 | if err != nil { 105 | t.Fatalf("NewRequest() error = %v", err) 106 | } 107 | _, err = req.MarshalBinary() 108 | if err != nil { 109 | t.Fatal(err) 110 | } 111 | } 112 | 113 | func TestRequestUnmarshalBinary(t *testing.T) { 114 | var r *Request 115 | expectedErrMsg := "asn1: Unmarshal recipient value is nil *tspclient.Request" 116 | err := r.UnmarshalBinary([]byte("test")) 117 | if err == nil || err.Error() != expectedErrMsg { 118 | t.Fatalf("expected error %s, but got %v", expectedErrMsg, err) 119 | } 120 | } 121 | 122 | func TestValidateRequest(t *testing.T) { 123 | var r *Request 124 | var malformedRequest *MalformedRequestError 125 | 126 | expectedErrMsg := "malformed timestamping request: request cannot be nil" 127 | err := r.Validate() 128 | if err == nil || !errors.As(err, &malformedRequest) || err.Error() != expectedErrMsg { 129 | t.Fatalf("expected error %s, but got %v", expectedErrMsg, err) 130 | } 131 | 132 | r = &Request{ 133 | Version: 2, 134 | } 135 | expectedErrMsg = "malformed timestamping request: request version must be 1, but got 2" 136 | err = r.Validate() 137 | if err == nil || !errors.As(err, &malformedRequest) || err.Error() != expectedErrMsg { 138 | t.Fatalf("expected error %s, but got %v", expectedErrMsg, err) 139 | } 140 | 141 | r = &Request{ 142 | Version: 1, 143 | MessageImprint: MessageImprint{ 144 | HashAlgorithm: pkix.AlgorithmIdentifier{ 145 | Algorithm: asn1.ObjectIdentifier{1}, 146 | }, 147 | }, 148 | } 149 | expectedErrMsg = "malformed timestamping request: hash algorithm 1 is unavailable" 150 | err = r.Validate() 151 | if err == nil || !errors.As(err, &malformedRequest) || err.Error() != expectedErrMsg { 152 | t.Fatalf("expected error %s, but got %v", expectedErrMsg, err) 153 | } 154 | 155 | digest, err := hashutil.ComputeHash(crypto.SHA384, []byte("test")) 156 | if err != nil { 157 | t.Fatal(err) 158 | } 159 | r = &Request{ 160 | Version: 1, 161 | MessageImprint: MessageImprint{ 162 | HashAlgorithm: pkix.AlgorithmIdentifier{ 163 | Algorithm: oid.SHA256, 164 | }, 165 | HashedMessage: digest, 166 | }, 167 | } 168 | expectedErrMsg = "malformed timestamping request: hashed message is of incorrect size 48" 169 | err = r.Validate() 170 | if err == nil || !errors.As(err, &malformedRequest) || err.Error() != expectedErrMsg { 171 | t.Fatalf("expected error %s, but got %v", expectedErrMsg, err) 172 | } 173 | } 174 | 175 | type dummyRandReader struct{} 176 | 177 | func (r *dummyRandReader) Read(b []byte) (int, error) { 178 | return 0, errors.New("failed to read") 179 | } 180 | -------------------------------------------------------------------------------- /response.go: -------------------------------------------------------------------------------- 1 | // Copyright The Notary Project Authors. 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // 6 | // http://www.apache.org/licenses/LICENSE-2.0 7 | // 8 | // Unless required by applicable law or agreed to in writing, software 9 | // distributed under the License is distributed on an "AS IS" BASIS, 10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | // See the License for the specific language governing permissions and 12 | // limitations under the License. 13 | 14 | package tspclient 15 | 16 | import ( 17 | "crypto/x509/pkix" 18 | "encoding/asn1" 19 | "errors" 20 | "fmt" 21 | "math/big" 22 | "time" 23 | 24 | "github.com/notaryproject/tspclient-go/pki" 25 | ) 26 | 27 | // signingCertificateV2 contains certificate hash and identifier of the 28 | // TSA signing certificate. 29 | // 30 | // Reference: RFC 5035 3 signingCertificateV2 31 | // 32 | // signingCertificateV2 ::= SEQUENCE { 33 | // certs SEQUENCE OF ESSCertIDv2, 34 | // policies SEQUENCE OF PolicyInformation OPTIONAL } 35 | type signingCertificateV2 struct { 36 | // Certificates contains the list of certificates. The first certificate 37 | // MUST be the signing certificate used to verify the timestamp token. 38 | Certificates []eSSCertIDv2 39 | 40 | // Policies suggests policy values to be used in the certification path 41 | // validation. 42 | Policies asn1.RawValue `asn1:"optional"` 43 | } 44 | 45 | // eSSCertIDv2 uniquely identifies a certificate. 46 | // 47 | // Reference: RFC 5035 4 48 | // 49 | // eSSCertIDv2 ::= SEQUENCE { 50 | // hashAlgorithm AlgorithmIdentifier 51 | // DEFAULT {algorithm id-sha256}, 52 | // certHash Hash, 53 | // issuerSerial IssuerSerial OPTIONAL } 54 | type eSSCertIDv2 struct { 55 | // HashAlgorithm is the hashing algorithm used to hash certificate. 56 | // When it is not present, the default value is SHA256 (id-sha256). 57 | // Supported values are SHA256, SHA384, and SHA512 58 | HashAlgorithm pkix.AlgorithmIdentifier `asn1:"optional"` 59 | 60 | // CertHash is the certificate hash using algorithm specified 61 | // by HashAlgorithm. It is computed over the entire DER-encoded 62 | // certificate (including the signature) 63 | CertHash []byte 64 | 65 | // IssuerSerial holds the issuer and serialNumber of the certificate. 66 | // When it is not present, the SignerIdentifier field in the SignerInfo 67 | // will be used. 68 | IssuerSerial issuerAndSerial `asn1:"optional"` 69 | } 70 | 71 | // issuerAndSerial holds the issuer name and serialNumber of the certificate 72 | // 73 | // Reference: RFC 5035 4 74 | // 75 | // IssuerSerial ::= SEQUENCE { 76 | // issuer GeneralNames, 77 | // serialNumber CertificateSerialNumber } 78 | type issuerAndSerial struct { 79 | IssuerName generalNames 80 | SerialNumber *big.Int 81 | } 82 | 83 | // generalNames holds the issuer name of the certificate. 84 | // 85 | // Reference: RFC 3280 4.2.1.7 86 | // 87 | // GeneralNames ::= SEQUENCE SIZE (1..MAX) OF GeneralName 88 | // 89 | // GeneralName ::= CHOICE { 90 | // otherName [0] OtherName, 91 | // rfc822Name [1] IA5String, 92 | // dNSName [2] IA5String, 93 | // x400Address [3] ORAddress, 94 | // directoryName [4] Name, 95 | // ediPartyName [5] EDIPartyName, 96 | // uniformResourceIdentifier [6] IA5String, 97 | // iPAddress [7] OCTET STRING, 98 | // registeredID [8] OBJECT IDENTIFIER } 99 | type generalNames struct { 100 | Name asn1.RawValue `asn1:"optional,tag:4"` 101 | } 102 | 103 | // Response is a time-stamping response. 104 | // 105 | // TimeStampResp ::= SEQUENCE { 106 | // status PKIStatusInfo, 107 | // timeStampToken TimeStampToken OPTIONAL } 108 | type Response struct { 109 | Status pki.StatusInfo 110 | TimestampToken asn1.RawValue `asn1:"optional"` 111 | } 112 | 113 | // MarshalBinary encodes the response to binary form. 114 | // This method implements encoding.BinaryMarshaler. 115 | // 116 | // Reference: https://pkg.go.dev/encoding#BinaryMarshaler 117 | func (r *Response) MarshalBinary() ([]byte, error) { 118 | if r == nil { 119 | return nil, errors.New("nil response") 120 | } 121 | return asn1.Marshal(*r) 122 | } 123 | 124 | // UnmarshalBinary decodes the response from binary form. 125 | // This method implements encoding.BinaryUnmarshaler. 126 | // 127 | // Reference: https://pkg.go.dev/encoding#BinaryUnmarshaler 128 | func (r *Response) UnmarshalBinary(data []byte) error { 129 | _, err := asn1.Unmarshal(data, r) 130 | return err 131 | } 132 | 133 | // SignedToken returns the timestamp token with signatures. 134 | // 135 | // Callers should invoke SignedToken.Verify to verify the content before 136 | // comsumption. 137 | func (r *Response) SignedToken() (*SignedToken, error) { 138 | if err := r.validateStatus(); err != nil { 139 | return nil, err 140 | } 141 | return ParseSignedToken(r.TimestampToken.FullBytes) 142 | } 143 | 144 | // Validate checks if resp is a successful timestamp response against 145 | // its corresponding request based on RFC 3161. 146 | // It is used when a timestamp requestor receives the response from TSA. 147 | func (r *Response) Validate(req *Request) error { 148 | if req == nil { 149 | return &InvalidResponseError{Msg: "missing corresponding request"} 150 | } 151 | if r == nil { 152 | return &InvalidResponseError{Msg: "response cannot be nil"} 153 | } 154 | if err := r.validateStatus(); err != nil { 155 | return err 156 | } 157 | token, err := r.SignedToken() 158 | if err != nil { 159 | return &InvalidResponseError{Detail: err} 160 | } 161 | info, err := token.Info() 162 | if err != nil { 163 | return &InvalidResponseError{Detail: err} 164 | } 165 | if info.Version != 1 { 166 | return &InvalidResponseError{Msg: fmt.Sprintf("timestamp token info version must be 1, but got %d", info.Version)} 167 | } 168 | // check policy 169 | if req.ReqPolicy != nil && !req.ReqPolicy.Equal(info.Policy) { 170 | return &InvalidResponseError{Msg: fmt.Sprintf("policy in response %v does not match policy in request %v", info.Policy, req.ReqPolicy)} 171 | } 172 | // check MessageImprint 173 | if !info.MessageImprint.Equal(req.MessageImprint) { 174 | return &InvalidResponseError{Msg: fmt.Sprintf("message imprint in response %+v does not match with request %+v", info.MessageImprint, req.MessageImprint)} 175 | } 176 | // check gen time to be UTC 177 | // reference: https://datatracker.ietf.org/doc/html/rfc3161#section-2.4.2 178 | genTime := info.GenTime 179 | if genTime.Location() != time.UTC { 180 | return &InvalidResponseError{Msg: "TSTInfo genTime must be in UTC"} 181 | } 182 | // check nonce 183 | if req.Nonce != nil { 184 | responseNonce := info.Nonce 185 | if responseNonce == nil || responseNonce.Cmp(req.Nonce) != 0 { 186 | return &InvalidResponseError{Msg: fmt.Sprintf("nonce in response %s does not match nonce in request %s", responseNonce, req.Nonce)} 187 | } 188 | } 189 | // check certReq 190 | if req.CertReq { 191 | for _, signerInfo := range token.SignerInfos { 192 | if _, err := token.SigningCertificate(&signerInfo); err == nil { 193 | // found at least one signing certificate 194 | return nil 195 | } 196 | } 197 | // no signing certificate was found 198 | return &InvalidResponseError{Msg: "certReq is True in request, but did not find any TSA signing certificate in the response"} 199 | } 200 | if len(token.Certificates) != 0 { 201 | return &InvalidResponseError{Msg: "certReq is False in request, but certificates field is included in the response"} 202 | } 203 | return nil 204 | } 205 | 206 | // validateStatus validates the response.Status 207 | // 208 | // Reference: RFC 3161 2.4.2 209 | func (r *Response) validateStatus() error { 210 | if err := r.Status.Err(); err != nil { 211 | return &InvalidResponseError{Detail: err} 212 | } 213 | return nil 214 | } 215 | -------------------------------------------------------------------------------- /response_test.go: -------------------------------------------------------------------------------- 1 | // Copyright The Notary Project Authors. 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // 6 | // http://www.apache.org/licenses/LICENSE-2.0 7 | // 8 | // Unless required by applicable law or agreed to in writing, software 9 | // distributed under the License is distributed on an "AS IS" BASIS, 10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | // See the License for the specific language governing permissions and 12 | // limitations under the License. 13 | 14 | package tspclient 15 | 16 | import ( 17 | "context" 18 | "crypto" 19 | "crypto/x509/pkix" 20 | "encoding/asn1" 21 | "encoding/hex" 22 | "errors" 23 | "math/big" 24 | "os" 25 | "testing" 26 | "time" 27 | 28 | "github.com/notaryproject/tspclient-go/internal/oid" 29 | "github.com/notaryproject/tspclient-go/pki" 30 | ) 31 | 32 | func TestResponseMarshalBinary(t *testing.T) { 33 | var r *Response 34 | _, err := r.MarshalBinary() 35 | if err == nil || err.Error() != "nil response" { 36 | t.Fatalf("expected error nil response, but got %v", err) 37 | } 38 | 39 | testResponse := Response{ 40 | Status: pki.StatusInfo{ 41 | Status: pki.StatusGranted, 42 | }, 43 | } 44 | _, err = (&testResponse).MarshalBinary() 45 | if err != nil { 46 | t.Fatal(err) 47 | } 48 | } 49 | 50 | func TestResponseUnmarshalBinary(t *testing.T) { 51 | var r *Response 52 | expectedErrMsg := "asn1: Unmarshal recipient value is nil *tspclient.Response" 53 | err := r.UnmarshalBinary([]byte("test")) 54 | if err == nil || err.Error() != expectedErrMsg { 55 | t.Fatalf("expected error %s, but got %v", expectedErrMsg, err) 56 | } 57 | } 58 | 59 | func TestValidateStatus(t *testing.T) { 60 | badResponse := Response{ 61 | Status: pki.StatusInfo{ 62 | Status: pki.StatusRejection, 63 | }, 64 | } 65 | expectedErrMsg := "invalid timestamping response: invalid response with status code 2: rejected" 66 | err := (&badResponse).validateStatus() 67 | if err == nil || err.Error() != expectedErrMsg { 68 | t.Fatalf("expected error %s, but got %v", expectedErrMsg, err) 69 | } 70 | 71 | badResponse = Response{ 72 | Status: pki.StatusInfo{ 73 | Status: pki.StatusRejection, 74 | FailInfo: asn1.BitString{ 75 | Bytes: []byte{0x80}, 76 | BitLength: 1, 77 | }, 78 | }, 79 | } 80 | expectedErrMsg = "invalid timestamping response: invalid response with status code 2: rejected. Failure info: unrecognized or unsupported Algorithm Identifier" 81 | err = (&badResponse).validateStatus() 82 | if err == nil || err.Error() != expectedErrMsg { 83 | t.Fatalf("expected error %s, but got %v", expectedErrMsg, err) 84 | } 85 | 86 | validResponse := Response{ 87 | Status: pki.StatusInfo{ 88 | Status: pki.StatusGranted, 89 | }, 90 | } 91 | err = (&validResponse).validateStatus() 92 | if err != nil { 93 | t.Fatal(err) 94 | } 95 | } 96 | 97 | func TestSignedToken(t *testing.T) { 98 | badResponse := Response{ 99 | Status: pki.StatusInfo{ 100 | Status: pki.StatusRejection, 101 | }, 102 | } 103 | expectedErrMsg := "invalid timestamping response: invalid response with status code 2: rejected" 104 | _, err := (&badResponse).SignedToken() 105 | if err == nil || err.Error() != expectedErrMsg { 106 | t.Fatalf("expected error %s, but got %v", expectedErrMsg, err) 107 | } 108 | 109 | validResponse := Response{ 110 | Status: pki.StatusInfo{ 111 | Status: pki.StatusGranted, 112 | }, 113 | } 114 | expectedErrMsg = "cms: syntax error: invalid signed data: failed to convert from BER to DER: asn1: syntax error: BER-encoded ASN.1 data structures is empty" 115 | _, err = (&validResponse).SignedToken() 116 | if err == nil || err.Error() != expectedErrMsg { 117 | t.Fatalf("expected error %s, but got %v", expectedErrMsg, err) 118 | } 119 | } 120 | 121 | func TestValidateResponse(t *testing.T) { 122 | var invalidResponse *InvalidResponseError 123 | var req *Request 124 | var resp *Response 125 | 126 | expectedErrMsg := "invalid timestamping response: missing corresponding request" 127 | err := resp.Validate(req) 128 | if err == nil || !errors.As(err, &invalidResponse) || err.Error() != expectedErrMsg { 129 | t.Fatalf("expected error %s, but got %v", expectedErrMsg, err) 130 | } 131 | 132 | req = &Request{ 133 | Version: 1, 134 | } 135 | expectedErrMsg = "invalid timestamping response: response cannot be nil" 136 | err = resp.Validate(req) 137 | if err == nil || !errors.As(err, &invalidResponse) || err.Error() != expectedErrMsg { 138 | t.Fatalf("expected error %s, but got %v", expectedErrMsg, err) 139 | } 140 | 141 | resp = &Response{ 142 | Status: pki.StatusInfo{ 143 | Status: pki.StatusRejection, 144 | }, 145 | } 146 | expectedErrMsg = "invalid timestamping response: invalid response with status code 2: rejected" 147 | err = resp.Validate(req) 148 | if err == nil || !errors.As(err, &invalidResponse) || err.Error() != expectedErrMsg { 149 | t.Fatalf("expected error %s, but got %v", expectedErrMsg, err) 150 | } 151 | 152 | resp = &Response{ 153 | Status: pki.StatusInfo{ 154 | Status: pki.StatusGranted, 155 | }, 156 | } 157 | expectedErrMsg = "invalid timestamping response: cms: syntax error: invalid signed data: failed to convert from BER to DER: asn1: syntax error: BER-encoded ASN.1 data structures is empty" 158 | err = resp.Validate(req) 159 | if err == nil || !errors.As(err, &invalidResponse) || err.Error() != expectedErrMsg { 160 | t.Fatalf("expected error %s, but got %v", expectedErrMsg, err) 161 | } 162 | 163 | token, err := os.ReadFile("testdata/TimeStampTokenWithInvalidTSTInfo.p7s") 164 | if err != nil { 165 | t.Fatal("failed to read timestamp token from file:", err) 166 | } 167 | resp = &Response{ 168 | Status: pki.StatusInfo{ 169 | Status: pki.StatusGranted, 170 | }, 171 | TimestampToken: asn1.RawValue{ 172 | FullBytes: token, 173 | }, 174 | } 175 | expectedErrMsg = "invalid timestamping response: cannot unmarshal TSTInfo from timestamp token: asn1: structure error: tags don't match (23 vs {class:0 tag:16 length:3 isCompound:true}) {optional:false explicit:false application:false private:false defaultValue: tag: stringType:0 timeType:24 set:false omitEmpty:false} Time @89" 176 | err = resp.Validate(req) 177 | if err == nil || !errors.As(err, &invalidResponse) || err.Error() != expectedErrMsg { 178 | t.Fatalf("expected error %s, but got %v", expectedErrMsg, err) 179 | } 180 | 181 | req = &Request{} 182 | token, err = os.ReadFile("testdata/TimeStampTokenWithTSTInfoVersion2.p7s") 183 | if err != nil { 184 | t.Fatal("failed to read timestamp token from file:", err) 185 | } 186 | resp = &Response{ 187 | Status: pki.StatusInfo{ 188 | Status: pki.StatusGranted, 189 | }, 190 | TimestampToken: asn1.RawValue{ 191 | FullBytes: token, 192 | }, 193 | } 194 | expectedErrMsg = "invalid timestamping response: timestamp token info version must be 1, but got 2" 195 | err = resp.Validate(req) 196 | if err == nil || !errors.As(err, &invalidResponse) || err.Error() != expectedErrMsg { 197 | t.Fatalf("expected error %s, but got %v", expectedErrMsg, err) 198 | } 199 | 200 | req = &Request{ 201 | ReqPolicy: asn1.ObjectIdentifier{1}, 202 | } 203 | token, err = os.ReadFile("testdata/TimeStampToken.p7s") 204 | if err != nil { 205 | t.Fatal("failed to read timestamp token from file:", err) 206 | } 207 | resp = &Response{ 208 | Status: pki.StatusInfo{ 209 | Status: pki.StatusGranted, 210 | }, 211 | TimestampToken: asn1.RawValue{ 212 | FullBytes: token, 213 | }, 214 | } 215 | expectedErrMsg = "invalid timestamping response: policy in response 1.3.6.1.4.1.4146.2.3 does not match policy in request 1" 216 | err = resp.Validate(req) 217 | if err == nil || !errors.As(err, &invalidResponse) || err.Error() != expectedErrMsg { 218 | t.Fatalf("expected error %s, but got %v", expectedErrMsg, err) 219 | } 220 | 221 | req = &Request{} 222 | token, err = os.ReadFile("testdata/TimeStampToken.p7s") 223 | if err != nil { 224 | t.Fatal("failed to read timestamp token from file:", err) 225 | } 226 | resp = &Response{ 227 | Status: pki.StatusInfo{ 228 | Status: pki.StatusGranted, 229 | }, 230 | TimestampToken: asn1.RawValue{ 231 | FullBytes: token, 232 | }, 233 | } 234 | expectedErrMsg = "invalid timestamping response: message imprint in response {HashAlgorithm:{Algorithm:2.16.840.1.101.3.4.2.1 Parameters:{Class:0 Tag:5 IsCompound:false Bytes:[] FullBytes:[5 0]}} HashedMessage:[131 38 244 112 157 64 29 250 191 167 131 2 251 28 222 160 241 128 72 164 64 64 194 18 189 142 40 218 107 198 81 199]} does not match with request {HashAlgorithm:{Algorithm: Parameters:{Class:0 Tag:0 IsCompound:false Bytes:[] FullBytes:[]}} HashedMessage:[]}" 235 | err = resp.Validate(req) 236 | if err == nil || !errors.As(err, &invalidResponse) || err.Error() != expectedErrMsg { 237 | t.Fatalf("expected error %s, but got %v", expectedErrMsg, err) 238 | } 239 | 240 | digest, err := hex.DecodeString("8326f4709d401dfabfa78302fb1cdea0f18048a44040c212bd8e28da6bc651c7") 241 | if err != nil { 242 | t.Fatal(err) 243 | } 244 | messageImprint := MessageImprint{ 245 | HashAlgorithm: pkix.AlgorithmIdentifier{ 246 | Algorithm: oid.SHA256, 247 | Parameters: asn1.RawValue{ 248 | Class: 0, 249 | Tag: 5, 250 | FullBytes: []byte{5, 0}, 251 | }, 252 | }, 253 | HashedMessage: digest, 254 | } 255 | req = &Request{ 256 | MessageImprint: messageImprint, 257 | Nonce: big.NewInt(63456), 258 | } 259 | token, err = os.ReadFile("testdata/TimeStampToken.p7s") 260 | if err != nil { 261 | t.Fatal("failed to read timestamp token from file:", err) 262 | } 263 | resp = &Response{ 264 | Status: pki.StatusInfo{ 265 | Status: pki.StatusGranted, 266 | }, 267 | TimestampToken: asn1.RawValue{ 268 | FullBytes: token, 269 | }, 270 | } 271 | expectedErrMsg = "invalid timestamping response: nonce in response does not match nonce in request 63456" 272 | err = resp.Validate(req) 273 | if err == nil || !errors.As(err, &invalidResponse) || err.Error() != expectedErrMsg { 274 | t.Fatalf("expected error %s, but got %v", expectedErrMsg, err) 275 | } 276 | 277 | req = &Request{ 278 | MessageImprint: messageImprint, 279 | CertReq: true, 280 | } 281 | token, err = os.ReadFile("testdata/TimeStampTokenWithoutCertificate.p7s") 282 | if err != nil { 283 | t.Fatal("failed to read timestamp token from file:", err) 284 | } 285 | resp = &Response{ 286 | Status: pki.StatusInfo{ 287 | Status: pki.StatusGranted, 288 | }, 289 | TimestampToken: asn1.RawValue{ 290 | FullBytes: token, 291 | }, 292 | } 293 | expectedErrMsg = "invalid timestamping response: certReq is True in request, but did not find any TSA signing certificate in the response" 294 | err = resp.Validate(req) 295 | if err == nil || !errors.As(err, &invalidResponse) || err.Error() != expectedErrMsg { 296 | t.Fatalf("expected error %s, but got %v", expectedErrMsg, err) 297 | } 298 | 299 | req = &Request{ 300 | MessageImprint: messageImprint, 301 | CertReq: false, 302 | } 303 | token, err = os.ReadFile("testdata/TimeStampToken.p7s") 304 | if err != nil { 305 | t.Fatal("failed to read timestamp token from file:", err) 306 | } 307 | resp = &Response{ 308 | Status: pki.StatusInfo{ 309 | Status: pki.StatusGranted, 310 | }, 311 | TimestampToken: asn1.RawValue{ 312 | FullBytes: token, 313 | }, 314 | } 315 | expectedErrMsg = "invalid timestamping response: certReq is False in request, but certificates field is included in the response" 316 | err = resp.Validate(req) 317 | if err == nil || !errors.As(err, &invalidResponse) || err.Error() != expectedErrMsg { 318 | t.Fatalf("expected error %s, but got %v", expectedErrMsg, err) 319 | } 320 | 321 | req = &Request{ 322 | Version: 1, 323 | MessageImprint: messageImprint, 324 | ReqPolicy: asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 4146, 2, 3}, 325 | CertReq: true, 326 | } 327 | token, err = os.ReadFile("testdata/TimeStampToken.p7s") 328 | if err != nil { 329 | t.Fatal("failed to read timestamp token from file:", err) 330 | } 331 | resp = &Response{ 332 | Status: pki.StatusInfo{ 333 | Status: pki.StatusGranted, 334 | }, 335 | TimestampToken: asn1.RawValue{ 336 | FullBytes: token, 337 | }, 338 | } 339 | err = resp.Validate(req) 340 | if err != nil { 341 | t.Fatalf("expected nil error, but got %v", err) 342 | } 343 | 344 | req = &Request{ 345 | Version: 1, 346 | MessageImprint: messageImprint, 347 | ReqPolicy: asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 4146, 2, 3}, 348 | CertReq: false, 349 | } 350 | token, err = os.ReadFile("testdata/TimeStampTokenWithoutCertificate.p7s") 351 | if err != nil { 352 | t.Fatal("failed to read timestamp token from file:", err) 353 | } 354 | resp = &Response{ 355 | Status: pki.StatusInfo{ 356 | Status: pki.StatusGranted, 357 | }, 358 | TimestampToken: asn1.RawValue{ 359 | FullBytes: token, 360 | }, 361 | } 362 | err = resp.Validate(req) 363 | if err != nil { 364 | t.Fatalf("expected nil error, but got %v", err) 365 | } 366 | } 367 | 368 | func TestTSAWithGenTimeNotUTC(t *testing.T) { 369 | // prepare TSA 370 | loc := time.FixedZone("UTC+8", 8*60*60) 371 | now := time.Date(2021, 9, 18, 11, 54, 34, 0, loc) 372 | tsa, err := newTestTSA(false, true) 373 | if err != nil { 374 | t.Fatalf("NewTSA() error = %v", err) 375 | } 376 | tsa.nowFunc = func() time.Time { 377 | return now 378 | } 379 | tsa.malformedTimeZone = true 380 | 381 | // do timestamp 382 | requestOpts := RequestOptions{ 383 | Content: []byte("notation"), 384 | HashAlgorithm: crypto.SHA256, 385 | } 386 | req, err := NewRequest(requestOpts) 387 | if err != nil { 388 | t.Fatalf("NewRequest() error = %v", err) 389 | } 390 | ctx := context.Background() 391 | resp, err := tsa.Timestamp(ctx, req) 392 | if err != nil { 393 | t.Fatalf("TSA.Timestamp() error = %v", err) 394 | } 395 | wantStatus := pki.StatusGranted 396 | if got := resp.Status.Status; got != wantStatus { 397 | t.Fatalf("Response.Status = %v, want %v", got, wantStatus) 398 | } 399 | 400 | expectedErrMsg := "invalid timestamping response: TSTInfo genTime must be in UTC" 401 | var invalidResponse *InvalidResponseError 402 | err = resp.Validate(req) 403 | if err == nil || !errors.As(err, &invalidResponse) || err.Error() != expectedErrMsg { 404 | t.Fatalf("expected error %s, but got %v", expectedErrMsg, err) 405 | } 406 | } 407 | -------------------------------------------------------------------------------- /testdata/GlobalSignRootCA.crt: -------------------------------------------------------------------------------- 1 | -----BEGIN CERTIFICATE----- 2 | MIIDXzCCAkegAwIBAgILBAAAAAABIVhTCKIwDQYJKoZIhvcNAQELBQAwTDEgMB4G 3 | A1UECxMXR2xvYmFsU2lnbiBSb290IENBIC0gUjMxEzARBgNVBAoTCkdsb2JhbFNp 4 | Z24xEzARBgNVBAMTCkdsb2JhbFNpZ24wHhcNMDkwMzE4MTAwMDAwWhcNMjkwMzE4 5 | MTAwMDAwWjBMMSAwHgYDVQQLExdHbG9iYWxTaWduIFJvb3QgQ0EgLSBSMzETMBEG 6 | A1UEChMKR2xvYmFsU2lnbjETMBEGA1UEAxMKR2xvYmFsU2lnbjCCASIwDQYJKoZI 7 | hvcNAQEBBQADggEPADCCAQoCggEBAMwldpB5BngiFvXAg7aEyiie/QV2EcWtiHL8 8 | RgJDx7KKnQRfJMsuS+FggkbhUqsMgUdwbN1k0ev1LKMPgj0MK66X17YUhhB5uzsT 9 | gHeMCOFJ0mpiLx9e+pZo34knlTifBtc+ycsmWQ1z3rDI6SYOgxXG71uL0gRgykmm 10 | KPZpO/bLyCiR5Z2KYVc3rHQU3HTgOu5yLy6c+9C7v/U9AOEGM+iCK65TpjoWc4zd 11 | QQ4gOsC0p6Hpsk+QLjJg6VfLuQSSaGjlOCZgdbKfd/+RFO+uIEn8rUAVSNECMWEZ 12 | XriX7613t2Saer9fwRPvm2L7DWzgVGkWqQPabumDk3F2xmmFghcCAwEAAaNCMEAw 13 | DgYDVR0PAQH/BAQDAgEGMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFI/wS3+o 14 | LkUkrk1Q+mOai97i3Ru8MA0GCSqGSIb3DQEBCwUAA4IBAQBLQNvAUKr+yAzv95ZU 15 | RUm7lgAJQayzE4aGKAczymvmdLm6AC2upArT9fHxD4q/c2dKg8dEe3jgr25sbwMp 16 | jjM5RcOO5LlXbKr8EpbsU8Yt5CRsuZRj+9xTaGdWPoO4zzUhw8lo/s7awlOqzJCK 17 | 6fBdRoyV3XpYKBovHd7NADdBj+1EbddTKJd+82cEHhXXipa0095MJ6RMG3NzdvQX 18 | mcIfeg7jLQitChws/zyrVQ4PkX4268NXSb7hLi18YIvDQVETI53O9zJrlAGomecs 19 | Mx86OyXShkDOOyyGeMlhLxS67ttVb9+E7gUJTb0o2HLO02JQZR7rkpeDMdmztcpH 20 | WD9f 21 | -----END CERTIFICATE----- 22 | -------------------------------------------------------------------------------- /testdata/SHA1TimeStampToken.p7s: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/notaryproject/tspclient-go/4f55b14d9f01b9722bd4848117bc26486a8288c5/testdata/SHA1TimeStampToken.p7s -------------------------------------------------------------------------------- /testdata/TimeStampToken.p7s: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/notaryproject/tspclient-go/4f55b14d9f01b9722bd4848117bc26486a8288c5/testdata/TimeStampToken.p7s -------------------------------------------------------------------------------- /testdata/TimeStampTokenNoRoot.p7s: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/notaryproject/tspclient-go/4f55b14d9f01b9722bd4848117bc26486a8288c5/testdata/TimeStampTokenNoRoot.p7s -------------------------------------------------------------------------------- /testdata/TimeStampTokenWithInvalidSignature.p7s: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/notaryproject/tspclient-go/4f55b14d9f01b9722bd4848117bc26486a8288c5/testdata/TimeStampTokenWithInvalidSignature.p7s -------------------------------------------------------------------------------- /testdata/TimeStampTokenWithInvalidSigningCertificateV1.p7s: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/notaryproject/tspclient-go/4f55b14d9f01b9722bd4848117bc26486a8288c5/testdata/TimeStampTokenWithInvalidSigningCertificateV1.p7s -------------------------------------------------------------------------------- /testdata/TimeStampTokenWithInvalidSigningCertificateV2.p7s: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/notaryproject/tspclient-go/4f55b14d9f01b9722bd4848117bc26486a8288c5/testdata/TimeStampTokenWithInvalidSigningCertificateV2.p7s -------------------------------------------------------------------------------- /testdata/TimeStampTokenWithInvalidTSTInfo.p7s: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/notaryproject/tspclient-go/4f55b14d9f01b9722bd4848117bc26486a8288c5/testdata/TimeStampTokenWithInvalidTSTInfo.p7s -------------------------------------------------------------------------------- /testdata/TimeStampTokenWithInvalideContentType.p7s: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/notaryproject/tspclient-go/4f55b14d9f01b9722bd4848117bc26486a8288c5/testdata/TimeStampTokenWithInvalideContentType.p7s -------------------------------------------------------------------------------- /testdata/TimeStampTokenWithMismatchCertHash.p7s: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/notaryproject/tspclient-go/4f55b14d9f01b9722bd4848117bc26486a8288c5/testdata/TimeStampTokenWithMismatchCertHash.p7s -------------------------------------------------------------------------------- /testdata/TimeStampTokenWithSHA1CertHash.p7s: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/notaryproject/tspclient-go/4f55b14d9f01b9722bd4848117bc26486a8288c5/testdata/TimeStampTokenWithSHA1CertHash.p7s -------------------------------------------------------------------------------- /testdata/TimeStampTokenWithSigningCertificateV1.p7s: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/notaryproject/tspclient-go/4f55b14d9f01b9722bd4848117bc26486a8288c5/testdata/TimeStampTokenWithSigningCertificateV1.p7s -------------------------------------------------------------------------------- /testdata/TimeStampTokenWithSigningCertificateV1NoCert.p7s: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/notaryproject/tspclient-go/4f55b14d9f01b9722bd4848117bc26486a8288c5/testdata/TimeStampTokenWithSigningCertificateV1NoCert.p7s -------------------------------------------------------------------------------- /testdata/TimeStampTokenWithSigningCertificateV2NoCert.p7s: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/notaryproject/tspclient-go/4f55b14d9f01b9722bd4848117bc26486a8288c5/testdata/TimeStampTokenWithSigningCertificateV2NoCert.p7s -------------------------------------------------------------------------------- /testdata/TimeStampTokenWithTSTInfoVersion2.p7s: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/notaryproject/tspclient-go/4f55b14d9f01b9722bd4848117bc26486a8288c5/testdata/TimeStampTokenWithTSTInfoVersion2.p7s -------------------------------------------------------------------------------- /testdata/TimeStampTokenWithValidAndInvalidSignerInfos.p7s: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/notaryproject/tspclient-go/4f55b14d9f01b9722bd4848117bc26486a8288c5/testdata/TimeStampTokenWithValidAndInvalidSignerInfos.p7s -------------------------------------------------------------------------------- /testdata/TimeStampTokenWithWrongSigningCertificateV2IssuerChoiceTag.p7s: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/notaryproject/tspclient-go/4f55b14d9f01b9722bd4848117bc26486a8288c5/testdata/TimeStampTokenWithWrongSigningCertificateV2IssuerChoiceTag.p7s -------------------------------------------------------------------------------- /testdata/TimeStampTokenWithoutCertificate.p7s: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/notaryproject/tspclient-go/4f55b14d9f01b9722bd4848117bc26486a8288c5/testdata/TimeStampTokenWithoutCertificate.p7s -------------------------------------------------------------------------------- /testdata/TimeStampTokenWithoutSigningCertificate.p7s: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/notaryproject/tspclient-go/4f55b14d9f01b9722bd4848117bc26486a8288c5/testdata/TimeStampTokenWithoutSigningCertificate.p7s -------------------------------------------------------------------------------- /testdata/TimeStampTokenWithoutSigningCertificateV2IssuerSerial.p7s: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/notaryproject/tspclient-go/4f55b14d9f01b9722bd4848117bc26486a8288c5/testdata/TimeStampTokenWithoutSigningCertificateV2IssuerSerial.p7s -------------------------------------------------------------------------------- /testdata/granted.tsq: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/notaryproject/tspclient-go/4f55b14d9f01b9722bd4848117bc26486a8288c5/testdata/granted.tsq -------------------------------------------------------------------------------- /testdata/malformed.tsq: -------------------------------------------------------------------------------- 1 | 0��00�� *�H�� 2 | ���0��10 3 |  `�He0�� *�H�� 4 |  �����0�� +�2010 5 |  `�He �&�p�@�����ޠ�H�@@���(�k�Q�6_�#`)Ƕt�e!r��LY�20210918115434Z0�W�U0S1 0 UBE10U 6 | GlobalSign nv-sa1)0'U Globalsign TSA for Advanced - G4��d0�U0�=�FiP���p��MA�0 7 |  *�H�� 8 |  0[1 0 UBE10U 9 | GlobalSign nv-sa110/U(GlobalSign Timestamping CA - SHA384 - G40 10 | 210527095523Z 11 | 320628095522Z0S1 0 UBE10U 12 | GlobalSign nv-sa1)0'U Globalsign TSA for Advanced - G40��0 13 |  *�H�� 14 | ~p�x )��x�Y�̦$�0LU E0C0A +�20402+&https://www.globalsign.com/repository/0 U00��+��0��09+0�-http://ocsp.globalsign.com/ca/gstsacasha384g40C+0�7http://secure.globalsign.com/cacert/gstsacasha384g4.crt0U#0���i���WE93��@��ýe�0AU:0806�4�2�0http://crl.globalsign.com/ca/gstsacasha384g4.crl0 15 |  *�H�� 16 |  �b���w/Bok��EY<�uz��o#m-3BrOD�����L��]ͷ�$���h 17 | Z�EaӰ,�}��]�������2(6�� F-�~�@"yag����Of,.T*X��N�u�T& 18 | h��'�<�m0�&L�,�s܏���dJ{GLڢԷ��Qz�9�!����qp}��4��1� 19 | ��>6+f��Aղ#I"Ӿ_�6�Z��P�?NT �� 20 | ��q؟6<4������fJ�7��]z�>��=����gK붲�o��E]L�YZ�fsaE6J��cCn: F9�t�s ^B��/"l$'�Q���]����Au�d����鷇 �� 21 | 07bY�)rwiux���:\j�r��2�Yx�N��f��+���u�� 22 | 7�Au��?:����B�ٜQ��z�+�L%�m���OH���[���\r`��7q��\I�L)m�W;W���.Ba������|U��bd���UJo3���X���$g&��� 39 | ������{�g��X���A�U�n�Ż�LK��Bo�6�d������f�!��#��4D���Ig���Z��f�3ޙ%�qn�]L`<���r���BM�&�w�W �a�&��ȲM�d�E���?T��v�lj��"\� �)�K��7t��f�4s�}|^��=���P�m�W�~7k���)0�%0U��0U�0�0U��i���WE93��@��ýe�0U#0��l����������gS�0>+2000.+0�"http://ocsp2.globalsign.com/rootr606U/0-0+�)�'�%http://crl.globalsign.com/root-r6.crl0GU @0>0<U 0402+&https://www.globalsign.com/repository/0 40 |  *�H�� 41 |  ���Wg+B_�� �Ļ(V�L��p�� �:`39�k@I%��֤ 42 | ����A�OἫ���#�ƅ�K$�D�¤�в���Ve��ނȷ�aӵFH��gz�J�b�г�4HEU���J�^�rqvp����7W���܍�8X©�~�n&��*��Hdi/Қ�r��$KtZ}r�5�W�����L���SL����IUOu��oJ�.j�ʈ�0N�s�^�֙��}K�,�k��Y7� ,�Eֲ�n�u�ڍ�[/�.=}��0��{|�Ŭ�Q��0�QV`�|�="�� 43 | $S'���H�',y�<�㪄��>�J�!�b�0����H'|�uBk��k�X4 44 | ��P��{���H�+Uٍ�% Q��c���lraJ��C��Wŝ�<����1���@l �-� ƍm��q�R!�>���9���/z �����-���j�<����SM�GY|��CA�%�,~�� 45 | ��}� ��`r@P� �CD����� Y�xƤj�"�0�G0�/� 46 | �@B@��"��lq�0 47 |  *�H�� 48 |  0L1 0U GlobalSign Root CA - R310U 49 |  50 | GlobalSign10U 51 | GlobalSign0 52 | 190220000000Z 53 | 290318100000Z0L1 0U GlobalSign Root CA - R610U 54 |  55 | GlobalSign10U 56 | GlobalSign0�"0 57 |  *�H�� 58 | �0� 59 | ���s�f���{<� 60 | �E ,��H��[<���A�3�o�*�ư�kŶ��Ʋ��Q!�J�Z�և�M:�df ���D�s�N�Oxc�PmBf/M�y(MR����~Ċ�dL!Ch�=<�ŲfՐ��1ž�m2���몣����cP�����y��*�p.{缓�mS�H|�8�f�wa~��<�����Jm�����Рaw�Xt��#:�]:ʢ۝ �]D-���W��~�Pc4�k��k6�9�$6���W��޲�ⅷs��5�E���6�oT��rVn.��QBD���8��NNZ G�6Iw0�q7��!u��a?w�ّ�� 61 | l�Mt���9���^�� ����n ��af j�:e�Y��5���(��p� 62 | ��u�:��ۀ�%���'YLv9[����؃���0���3H��md,zXO�KIŕdcy=����X��BEyn�\T�e������ 63 | o�.�gnɋ���p�y����'�72�c<(L���&0�"0U�0U�0�0U�l����������gS�0U#0���K�.E$�MP�c������0>+2000.+0�"http://ocsp2.globalsign.com/rootr306U/0-0+�)�'�%http://crl.globalsign.com/root-r3.crl0GU @0>0<U 0402+&https://www.globalsign.com/repository/0 64 |  *�H�� 65 |  �I�^Ń�Z�a*M�J)���� ��z�5� 66 | 3mr�"NA?m 67 | ����_���,�;���6Yy��t����h��eYB��U9���&�q8��!�N�[`jC�} �`aݪ�^N2�l�<�»�Ӑvji�ܨ��XO�‹2J�T�8�; u 68 | � |%'�&�S����a52��݃�:��h�r�$7+���$�N򶹷G� �a��3�-����<#� 4�0�_0�G� !XS�0 69 |  *�H�� 70 |  0L1 0U GlobalSign Root CA - R310U 71 |  72 | GlobalSign10U 73 | GlobalSign0 74 | 090318100000Z 75 | 290318100000Z0L1 0U GlobalSign Root CA - R310U 76 |  77 | GlobalSign10U 78 | GlobalSign0�"0 79 |  *�H�� 80 | �0� 81 | ��%v�yx"������(��vŭ�r�FCDz��_$�.K�`�F�R� �Gpl�d���,��= +��׶�y�;�w��I�jb/^��h߉'�8��>��&Y 82 | sް��&���[��`�I�(�i;���(�坊aW7�t�t�:�r/.��л��=�3�+�S�:s��A :�����O�.2`�W˹�hh�8&`u��w��� I��@H�1a^���w�d�z�_��b� 83 | l�Ti��n郓qv�i���B0@0U�0U�0�0U��K�.E$�MP�c������0 84 |  *�H�� 85 |  �K@��P��� ���TEI�� A����(3�k�t��-�� 86 | ������sgJ��D{x�nlo)�39EÎ�Wl����S�-�$l��c��ShgV>���5!��h����S�̐���]F���zX(/��7A��Dm�S(�~�g׊����L'�Lssv���z�-� 87 | ,�<�U�~6��WI��.-|`��AQ#���2k����,3:;%҆@�;,�x�a/���Uo߄� M�(�r��bPe뒗�1ٳ��GX?_1�M0�I0o0[1 0 UBE10U 88 | GlobalSign nv-sa110/U(GlobalSign Timestamping CA - SHA384 - G4FiP���p��MA�0 89 |  `�He��/0 *�H�� 90 |  1 91 |  *�H�� 92 |  0- *�H�� 93 |  41 00 94 |  `�He� 95 |  *�H�� 96 |  0/ *�H�� 97 |  1" �CwT�����~����#Xw�����}W��{G0�� *�H�� 98 |  /1��0��0��0�� ��� �mN'Tr�h�x�edgۚ�e������0s0_�]0[1 0 UBE10U 99 | GlobalSign nv-sa110/U(GlobalSign Timestamping CA - SHA384 - G4FiP���p��MA�0 100 |  *�H�� 101 |  ���~s�U�N������2a1By�pѦvm��} ��!�W��B���a������z��r���J/|s��b�P,'��ýٽ�#�}3,0m>�R�Hl�U&& ��ǜe���� Rp{v@ayJ�i�7ٗB��JǨR̲�z-�4�`'�����Y��Q~i��Ȓ�?:�ʊ���U�7-%�J���k9JH�nn����(K�����Q�^H�}t�3���Y�u����j u�w}�=��~AI>�s0�<�P�n���$���WE��z'���,r�hxEY:�>.6���WZ �����-i�/�����,�0l2� ���<����W�����c�'���H�����/��+*v}��Y6�_,eP��"�b��0��((q��/J -------------------------------------------------------------------------------- /testdata/rejection.tsq: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/notaryproject/tspclient-go/4f55b14d9f01b9722bd4848117bc26486a8288c5/testdata/rejection.tsq -------------------------------------------------------------------------------- /testdata/validResponseWithSigningCertificateV1.tsr: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/notaryproject/tspclient-go/4f55b14d9f01b9722bd4848117bc26486a8288c5/testdata/validResponseWithSigningCertificateV1.tsr -------------------------------------------------------------------------------- /timestamp.go: -------------------------------------------------------------------------------- 1 | // Copyright The Notary Project Authors. 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // 6 | // http://www.apache.org/licenses/LICENSE-2.0 7 | // 8 | // Unless required by applicable law or agreed to in writing, software 9 | // distributed under the License is distributed on an "AS IS" BASIS, 10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | // See the License for the specific language governing permissions and 12 | // limitations under the License. 13 | 14 | package tspclient 15 | 16 | import ( 17 | "fmt" 18 | "time" 19 | ) 20 | 21 | // Timestamp denotes the time at which the timestamp token was created by the TSA 22 | // 23 | // Reference: RFC 3161 2.4.2 24 | type Timestamp struct { 25 | // Value is the GenTime of TSTInfo 26 | Value time.Time 27 | 28 | // Accuracy is the Accuracy of TSTInfo 29 | Accuracy time.Duration 30 | } 31 | 32 | // BoundedBefore returns true if the upper limit of the time at which the 33 | // timestamp token was created is before or equal to u. 34 | // 35 | // Reference: RFC 3161 2.4.2 36 | func (t *Timestamp) BoundedBefore(u time.Time) bool { 37 | timestampUpperLimit := t.Value.Add(t.Accuracy) 38 | return timestampUpperLimit.Before(u) || timestampUpperLimit.Equal(u) 39 | } 40 | 41 | // BoundedAfter returns true if the lower limit of the time at which the 42 | // timestamp token was created is after or equal to u. 43 | // 44 | // Reference: RFC 3161 2.4.2 45 | func (t *Timestamp) BoundedAfter(u time.Time) bool { 46 | timestampLowerLimit := t.Value.Add(-t.Accuracy) 47 | return timestampLowerLimit.After(u) || timestampLowerLimit.Equal(u) 48 | } 49 | 50 | // Format returns a string of t in format layout. 51 | // The output is a timestamp range calculated with its accuracy. 52 | func (t *Timestamp) Format(layout string) string { 53 | lowerBound := t.Value.Add(-t.Accuracy) 54 | upperBound := t.Value.Add(t.Accuracy) 55 | return fmt.Sprintf("[%s, %s]", lowerBound.Format(layout), upperBound.Format(layout)) 56 | } 57 | -------------------------------------------------------------------------------- /timestamp_test.go: -------------------------------------------------------------------------------- 1 | // Copyright The Notary Project Authors. 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // 6 | // http://www.apache.org/licenses/LICENSE-2.0 7 | // 8 | // Unless required by applicable law or agreed to in writing, software 9 | // distributed under the License is distributed on an "AS IS" BASIS, 10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | // See the License for the specific language governing permissions and 12 | // limitations under the License. 13 | 14 | package tspclient 15 | 16 | import ( 17 | "testing" 18 | "time" 19 | ) 20 | 21 | func TestTimestamp(t *testing.T) { 22 | // timestamp range: 23 | // [time.Date(2021, time.September, 17, 14, 9, 8, 0, time.UTC), 24 | // time.Date(2021, time.September, 17, 14, 9, 12, 0, time.UTC)] 25 | timestamp := Timestamp{ 26 | Value: time.Date(2021, time.September, 17, 14, 9, 10, 0, time.UTC), 27 | Accuracy: 2 * time.Second, 28 | } 29 | u1 := time.Date(2021, time.September, 17, 14, 9, 7, 0, time.UTC) 30 | u2 := time.Date(2021, time.September, 17, 14, 9, 8, 0, time.UTC) 31 | u3 := time.Date(2021, time.September, 17, 14, 9, 9, 0, time.UTC) 32 | u4 := time.Date(2021, time.September, 17, 14, 9, 10, 0, time.UTC) 33 | u5 := time.Date(2021, time.September, 17, 14, 9, 11, 0, time.UTC) 34 | u6 := time.Date(2021, time.September, 17, 14, 9, 12, 0, time.UTC) 35 | u7 := time.Date(2021, time.September, 17, 14, 9, 13, 0, time.UTC) 36 | 37 | if timestamp.BoundedBefore(u1) { 38 | t.Fatal("timestamp.BoundedBefore expected false, but got true") 39 | } 40 | if !timestamp.BoundedAfter(u1) { 41 | t.Fatal("timestamp.BoundedAfter expected true, but got false") 42 | } 43 | 44 | if timestamp.BoundedBefore(u2) { 45 | t.Fatal("timestamp.BoundedBefore expected false, but got true") 46 | } 47 | if !timestamp.BoundedAfter(u2) { 48 | t.Fatal("timestamp.BoundedAfter expected true, but got false") 49 | } 50 | 51 | if timestamp.BoundedBefore(u3) { 52 | t.Fatal("timestamp.BoundedBefore expected false, but got true") 53 | } 54 | if timestamp.BoundedAfter(u3) { 55 | t.Fatal("timestamp.BoundedAfter expected false, but got true") 56 | } 57 | 58 | if timestamp.BoundedBefore(u4) { 59 | t.Fatal("timestamp.BoundedBefore expected false, but got true") 60 | } 61 | if timestamp.BoundedAfter(u4) { 62 | t.Fatal("timestamp.BoundedAfter expected false, but got true") 63 | } 64 | 65 | if timestamp.BoundedBefore(u5) { 66 | t.Fatal("timestamp.BoundedBefore expected false, but got true") 67 | } 68 | if timestamp.BoundedAfter(u5) { 69 | t.Fatal("timestamp.BoundedAfter expected false, but got true") 70 | } 71 | 72 | if !timestamp.BoundedBefore(u6) { 73 | t.Fatal("timestamp.BoundedBefore expected true, but got false") 74 | } 75 | if timestamp.BoundedAfter(u6) { 76 | t.Fatal("timestamp.BoundedAfter expected false, but got true") 77 | } 78 | 79 | if !timestamp.BoundedBefore(u7) { 80 | t.Fatal("timestamp.BoundedBefore expected true, but got false") 81 | } 82 | if timestamp.BoundedAfter(u7) { 83 | t.Fatal("timestamp.BoundedAfter expected false, but got true") 84 | } 85 | } 86 | 87 | func TestString(t *testing.T) { 88 | // timestamp range: 89 | // [time.Date(2021, time.September, 17, 14, 9, 8, 0, time.UTC), 90 | // time.Date(2021, time.September, 17, 14, 9, 12, 0, time.UTC)] 91 | timestamp := Timestamp{ 92 | Value: time.Date(2021, time.September, 17, 14, 9, 10, 0, time.UTC), 93 | Accuracy: 2 * time.Second, 94 | } 95 | 96 | expectedStr := "[2021-09-17T14:09:08Z, 2021-09-17T14:09:12Z]" 97 | if timestamp.Format(time.RFC3339) != expectedStr { 98 | t.Fatalf("expected %s, but got %s", expectedStr, timestamp.Format(time.RFC3339)) 99 | } 100 | } 101 | -------------------------------------------------------------------------------- /token.go: -------------------------------------------------------------------------------- 1 | // Copyright The Notary Project Authors. 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // 6 | // http://www.apache.org/licenses/LICENSE-2.0 7 | // 8 | // Unless required by applicable law or agreed to in writing, software 9 | // distributed under the License is distributed on an "AS IS" BASIS, 10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | // See the License for the specific language governing permissions and 12 | // limitations under the License. 13 | 14 | package tspclient 15 | 16 | import ( 17 | "bytes" 18 | "context" 19 | "crypto" 20 | "crypto/x509" 21 | "crypto/x509/pkix" 22 | "encoding/asn1" 23 | "errors" 24 | "fmt" 25 | "math/big" 26 | "time" 27 | 28 | "github.com/notaryproject/tspclient-go/internal/cms" 29 | "github.com/notaryproject/tspclient-go/internal/hashutil" 30 | "github.com/notaryproject/tspclient-go/internal/oid" 31 | ) 32 | 33 | // SignedToken is a parsed timestamp token with signatures. 34 | type SignedToken cms.ParsedSignedData 35 | 36 | // ParseSignedToken parses ASN.1 BER-encoded structure to SignedToken 37 | // without verification. berData is the full bytes of a TimestampToken defined 38 | // in RFC 3161 2.4.2. 39 | // 40 | // Callers should invoke SignedToken.Verify to verify the content before 41 | // comsumption. 42 | func ParseSignedToken(berData []byte) (*SignedToken, error) { 43 | signed, err := cms.ParseSignedData(berData) 44 | if err != nil { 45 | return nil, err 46 | } 47 | if !oid.TSTInfo.Equal(signed.ContentType) { 48 | return nil, fmt.Errorf("unexpected content type: %v. Expected to be id-ct-TSTInfo (%v)", signed.ContentType, oid.TSTInfo) 49 | } 50 | return (*SignedToken)(signed), nil 51 | } 52 | 53 | // Verify verifies the signed token as CMS SignedData. 54 | // An empty list of KeyUsages in VerifyOptions implies ExtKeyUsageTimeStamping. 55 | // The `Intermediates` in the verify options will be ignored and 56 | // re-contrusted using the certificates in the parsed signed token. 57 | // It returns success when the first signer info verification succeeds. 58 | func (t *SignedToken) Verify(ctx context.Context, opts x509.VerifyOptions) ([]*x509.Certificate, error) { 59 | if len(t.SignerInfos) == 0 { 60 | return nil, &SignedTokenVerificationError{Msg: "signerInfo not found"} 61 | } 62 | if len(opts.KeyUsages) == 0 { 63 | opts.KeyUsages = []x509.ExtKeyUsage{x509.ExtKeyUsageTimeStamping} 64 | } 65 | intermediates := x509.NewCertPool() 66 | for _, cert := range t.Certificates { 67 | intermediates.AddCert(cert) 68 | } 69 | opts.Intermediates = intermediates 70 | if opts.Roots == nil { // fail on no user provided root cert pool 71 | return nil, &SignedTokenVerificationError{Msg: "tsa root certificate pool cannot be nil"} 72 | } 73 | signed := (*cms.ParsedSignedData)(t) 74 | var lastErr error 75 | for _, signerInfo := range t.SignerInfos { 76 | signingCertificate, err := t.SigningCertificate(&signerInfo) 77 | if err != nil { 78 | lastErr = &SignedTokenVerificationError{Detail: err} 79 | continue 80 | } 81 | certChain, err := signed.VerifySigner(ctx, &signerInfo, signingCertificate, opts) 82 | if err != nil { 83 | lastErr = &SignedTokenVerificationError{Detail: err} 84 | continue 85 | } 86 | // RFC 3161 2.3: The corresponding certificate MUST contain only one 87 | // instance of the extended key usage field extension. And it MUST be 88 | // marked as critical. 89 | if len(signingCertificate.ExtKeyUsage) == 1 && 90 | signingCertificate.ExtKeyUsage[0] == x509.ExtKeyUsageTimeStamping && 91 | len(signingCertificate.UnknownExtKeyUsage) == 0 { 92 | // check if marked as critical 93 | for _, ext := range signingCertificate.Extensions { 94 | if ext.Id.Equal(oid.ExtKeyUsage) { 95 | if ext.Critical { 96 | // success verification 97 | return certChain, nil 98 | } 99 | break 100 | } 101 | } 102 | lastErr = &SignedTokenVerificationError{Msg: "signing certificate extended key usage extension must be set as critical"} 103 | } else { 104 | lastErr = &SignedTokenVerificationError{Msg: "signing certificate must have and only have ExtKeyUsageTimeStamping as extended key usage"} 105 | } 106 | } 107 | return nil, lastErr 108 | } 109 | 110 | // SigningCertificate gets the signing certificate identified by SignedToken 111 | // SignerInfo's SigningCertificateV2 attribute. 112 | // If the IssuerSerial field of signing certificate is missing, 113 | // use signerInfo's sid instead. 114 | // The identified signing certificate MUST match the hash in SigningCertificateV2. 115 | // 116 | // References: RFC 3161 2.4.1 & 2.4.2; RFC 5816 117 | func (t *SignedToken) SigningCertificate(signerInfo *cms.SignerInfo) (*x509.Certificate, error) { 118 | var signingCertificateV2 signingCertificateV2 119 | if err := signerInfo.SignedAttributes.Get(oid.SigningCertificateV2, &signingCertificateV2); err != nil { 120 | return nil, fmt.Errorf("failed to get SigningCertificateV2 from signed attributes: %w", err) 121 | } 122 | // get candidate signing certificate 123 | if len(signingCertificateV2.Certificates) == 0 { 124 | return nil, errors.New("signingCertificateV2 does not contain any certificate") 125 | } 126 | issuerSerial := signingCertificateV2.Certificates[0].IssuerSerial 127 | var candidateSigningCert *x509.Certificate 128 | signed := (*cms.ParsedSignedData)(t) 129 | if issuerSerial.SerialNumber != nil { 130 | // use IssuerSerial from signed attribute 131 | if issuerSerial.IssuerName.Name.Bytes == nil { 132 | return nil, errors.New("issuer name is missing in IssuerSerial") 133 | } 134 | var issuer asn1.RawValue 135 | if _, err := asn1.Unmarshal(issuerSerial.IssuerName.Name.Bytes, &issuer); err != nil { 136 | return nil, fmt.Errorf("failed to unmarshal issuer name: %w", err) 137 | } 138 | ref := cms.IssuerAndSerialNumber{ 139 | Issuer: issuer, 140 | SerialNumber: issuerSerial.SerialNumber, 141 | } 142 | candidateSigningCert = signed.GetCertificate(ref) 143 | } else { 144 | // use sid (unsigned) as IssuerSerial 145 | candidateSigningCert = signed.GetCertificate(signerInfo.SignerIdentifier) 146 | } 147 | if candidateSigningCert == nil { 148 | return nil, CertificateNotFoundError(errors.New("signing certificate not found in the timestamp token")) 149 | } 150 | // validate hash of candidate signing certificate 151 | // Reference: https://datatracker.ietf.org/doc/html/rfc5035#section-4 152 | hashFunc := crypto.SHA256 // default hash algorithm for signingCertificateV2 is id-sha256 153 | if signingCertificateV2.Certificates[0].HashAlgorithm.Algorithm != nil { 154 | // use hash algorithm from SigningCertificateV2 signed attribute 155 | var ok bool 156 | hashFunc, ok = oid.ToHash(signingCertificateV2.Certificates[0].HashAlgorithm.Algorithm) 157 | if !ok { 158 | return nil, errors.New("unsupported certificate hash algorithm in SigningCertificateV2 attribute") 159 | } 160 | } 161 | expectedCertHash := signingCertificateV2.Certificates[0].CertHash 162 | certHash, err := hashutil.ComputeHash(hashFunc, candidateSigningCert.Raw) 163 | if err != nil { 164 | return nil, err 165 | } 166 | if !bytes.Equal(certHash, expectedCertHash) { 167 | return nil, errors.New("signing certificate hash does not match CertHash in signed attribute") 168 | } 169 | return candidateSigningCert, nil 170 | } 171 | 172 | // Info returns the TSTInfo as defined in RFC 3161 2.4.2. 173 | // 174 | // Caller should use TSTInfo.Timestamp for consumption. 175 | func (t *SignedToken) Info() (*TSTInfo, error) { 176 | var info TSTInfo 177 | if _, err := asn1.Unmarshal(t.Content, &info); err != nil { 178 | return nil, fmt.Errorf("cannot unmarshal TSTInfo from timestamp token: %w", err) 179 | } 180 | return &info, nil 181 | } 182 | 183 | // Accuracy ::= SEQUENCE { 184 | // seconds INTEGER OPTIONAL, 185 | // millis [0] INTEGER (1..999) OPTIONAL, 186 | // micros [1] INTEGER (1..999) OPTIONAL } 187 | type Accuracy struct { 188 | Seconds int `asn1:"optional"` 189 | Milliseconds int `asn1:"optional,tag:0"` 190 | Microseconds int `asn1:"optional,tag:1"` 191 | } 192 | 193 | // TSTInfo ::= SEQUENCE { 194 | // version INTEGER { v1(1) }, 195 | // policy TSAPolicyId, 196 | // messageImprint MessageImprint, 197 | // serialNumber INTEGER, 198 | // genTime GeneralizedTime, 199 | // accuracy Accuracy OPTIONAL, 200 | // ordering BOOLEAN DEFAULT FALSE, 201 | // nonce INTEGER OPTIONAL, 202 | // tsa [0] GeneralName OPTIONAL, 203 | // extensions [1] IMPLICIT Extensions OPTIONAL } 204 | type TSTInfo struct { 205 | Version int // fixed to 1 as defined in RFC 3161 2.4.2 206 | Policy asn1.ObjectIdentifier 207 | MessageImprint MessageImprint 208 | SerialNumber *big.Int 209 | GenTime time.Time `asn1:"generalized"` 210 | Accuracy Accuracy `asn1:"optional"` 211 | Ordering bool `asn1:"optional,default:false"` 212 | Nonce *big.Int `asn1:"optional"` 213 | TSA asn1.RawValue `asn1:"optional,tag:0"` 214 | Extensions []pkix.Extension `asn1:"optional,tag:1"` 215 | } 216 | 217 | // Validate validates tst and returns the Timestamp on success. 218 | // tst MUST be valid and the time stamped datum MUST match message. 219 | func (tst *TSTInfo) Validate(message []byte) (*Timestamp, error) { 220 | if err := tst.validate(message); err != nil { 221 | return nil, err 222 | } 223 | 224 | var accuracy time.Duration 225 | // References: 226 | // https://github.com/notaryproject/specifications/blob/main/specs/trust-store-trust-policy.md#steps 227 | if tst.Accuracy.Seconds == 0 && 228 | tst.Accuracy.Microseconds == 0 && 229 | tst.Accuracy.Milliseconds == 0 && 230 | oid.BaselineTimestampPolicy.Equal(tst.Policy) { 231 | accuracy = 1 * time.Second 232 | } else { 233 | accuracy = time.Duration(tst.Accuracy.Seconds)*time.Second + 234 | time.Duration(tst.Accuracy.Milliseconds)*time.Millisecond + 235 | time.Duration(tst.Accuracy.Microseconds)*time.Microsecond 236 | } 237 | 238 | return &Timestamp{ 239 | Value: tst.GenTime, 240 | Accuracy: accuracy, 241 | }, nil 242 | } 243 | 244 | // validate checks tst against RFC 3161. 245 | // message is verified against the timestamp token MessageImprint. 246 | func (tst *TSTInfo) validate(message []byte) error { 247 | if tst == nil { 248 | return &TSTInfoError{Msg: "timestamp token info cannot be nil"} 249 | } 250 | if tst.Version != 1 { 251 | return &TSTInfoError{Msg: fmt.Sprintf("timestamp token info version must be 1, but got %d", tst.Version)} 252 | } 253 | hashAlg := tst.MessageImprint.HashAlgorithm.Algorithm 254 | hash, ok := oid.ToHash(hashAlg) 255 | if !ok { 256 | return &TSTInfoError{Msg: fmt.Sprintf("unrecognized hash algorithm: %v", hashAlg)} 257 | } 258 | messageDigest, err := hashutil.ComputeHash(hash, message) 259 | if err != nil { 260 | return &TSTInfoError{Detail: err} 261 | } 262 | if !bytes.Equal(tst.MessageImprint.HashedMessage, messageDigest) { 263 | return &TSTInfoError{Msg: "mismatched message"} 264 | } 265 | return nil 266 | } 267 | -------------------------------------------------------------------------------- /token_test.go: -------------------------------------------------------------------------------- 1 | // Copyright The Notary Project Authors. 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // 6 | // http://www.apache.org/licenses/LICENSE-2.0 7 | // 8 | // Unless required by applicable law or agreed to in writing, software 9 | // distributed under the License is distributed on an "AS IS" BASIS, 10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | // See the License for the specific language governing permissions and 12 | // limitations under the License. 13 | 14 | package tspclient 15 | 16 | import ( 17 | "context" 18 | "crypto/x509" 19 | "errors" 20 | "fmt" 21 | "os" 22 | "testing" 23 | "time" 24 | 25 | "github.com/notaryproject/tspclient-go/internal/oid" 26 | ) 27 | 28 | func TestParseSignedToken(t *testing.T) { 29 | timestampToken, err := os.ReadFile("testdata/TimeStampTokenWithInvalideContentType.p7s") 30 | if err != nil { 31 | t.Fatal(err) 32 | } 33 | expectedErrMsg := fmt.Sprintf("unexpected content type: %v. Expected to be id-ct-TSTInfo (1.2.840.113549.1.9.16.1.4)", oid.Data) 34 | _, err = ParseSignedToken(timestampToken) 35 | if err == nil || err.Error() != expectedErrMsg { 36 | t.Fatalf("expected error %s, but got %v", expectedErrMsg, err) 37 | } 38 | } 39 | 40 | func TestVerify(t *testing.T) { 41 | timestampToken, err := getTimestampTokenFromPath("testdata/TimeStampToken.p7s") 42 | if err != nil { 43 | t.Fatal(err) 44 | } 45 | roots := x509.NewCertPool() 46 | rootCABytes, err := os.ReadFile("testdata/GlobalSignRootCA.crt") 47 | if err != nil { 48 | t.Fatal("failed to read root CA certificate:", err) 49 | } 50 | if ok := roots.AppendCertsFromPEM(rootCABytes); !ok { 51 | t.Fatal("failed to load root CA certificate") 52 | } 53 | opts := x509.VerifyOptions{ 54 | Roots: roots, 55 | } 56 | if _, err := timestampToken.Verify(context.Background(), opts); err != nil { 57 | t.Fatalf("expected nil error, but got %v", err) 58 | } 59 | 60 | timestampToken, err = getTimestampTokenFromPath("testdata/TimeStampTokenWithValidAndInvalidSignerInfos.p7s") 61 | if err != nil { 62 | t.Fatal(err) 63 | } 64 | if _, err := timestampToken.Verify(context.Background(), opts); err != nil { 65 | t.Fatalf("expected nil error, but got %v", err) 66 | } 67 | 68 | timestampToken = &SignedToken{} 69 | expectedErrMsg := "failed to verify signed token: signerInfo not found" 70 | if _, err := timestampToken.Verify(context.Background(), opts); err == nil || err.Error() != expectedErrMsg { 71 | t.Fatalf("expected error %s, but got %v", expectedErrMsg, err) 72 | } 73 | 74 | timestampToken, err = getTimestampTokenFromPath("testdata/TimeStampTokenWithoutCertificate.p7s") 75 | if err != nil { 76 | t.Fatal(err) 77 | } 78 | expectedErrMsg = "failed to verify signed token: signing certificate not found in the timestamp token" 79 | if _, err := timestampToken.Verify(context.Background(), opts); err == nil || err.Error() != expectedErrMsg { 80 | t.Fatalf("expected error %s, but got %v", expectedErrMsg, err) 81 | } 82 | 83 | timestampToken, err = getTimestampTokenFromPath("testdata/TimeStampTokenWithInvalidSignature.p7s") 84 | if err != nil { 85 | t.Fatal(err) 86 | } 87 | expectedErrMsg = "failed to verify signed token: cms verification failure: crypto/rsa: verification error" 88 | if _, err := timestampToken.Verify(context.Background(), opts); err == nil || err.Error() != expectedErrMsg { 89 | t.Fatalf("expected error %s, but got %v", expectedErrMsg, err) 90 | } 91 | 92 | timestampToken, err = getTimestampTokenFromPath("testdata/TimeStampToken.p7s") 93 | if err != nil { 94 | t.Fatal(err) 95 | } 96 | expectedErrMsg = "failed to verify signed token: tsa root certificate pool cannot be nil" 97 | if _, err := timestampToken.Verify(context.Background(), x509.VerifyOptions{}); err == nil || err.Error() != expectedErrMsg { 98 | t.Fatalf("expected %s, but got %s", expectedErrMsg, err) 99 | } 100 | } 101 | 102 | func TestInfo(t *testing.T) { 103 | timestampToken, err := getTimestampTokenFromPath("testdata/TimeStampTokenWithInvalidTSTInfo.p7s") 104 | if err != nil { 105 | t.Fatal(err) 106 | } 107 | expectedErrMsg := "cannot unmarshal TSTInfo from timestamp token: asn1: structure error: tags don't match (23 vs {class:0 tag:16 length:3 isCompound:true}) {optional:false explicit:false application:false private:false defaultValue: tag: stringType:0 timeType:24 set:false omitEmpty:false} Time @89" 108 | if _, err := timestampToken.Info(); err == nil || err.Error() != expectedErrMsg { 109 | t.Fatalf("expected error %s, but got %v", expectedErrMsg, err) 110 | } 111 | } 112 | 113 | func TestGetSigningCertificate(t *testing.T) { 114 | timestampToken, err := getTimestampTokenFromPath("testdata/TimeStampTokenWithoutSigningCertificate.p7s") 115 | if err != nil { 116 | t.Fatal(err) 117 | } 118 | expectedErrMsg := "failed to get SigningCertificateV2 from signed attributes: attribute not found" 119 | if _, err := timestampToken.SigningCertificate(×tampToken.SignerInfos[0]); err == nil || err.Error() != expectedErrMsg { 120 | t.Fatalf("expected error %s, but got %v", expectedErrMsg, err) 121 | } 122 | 123 | timestampToken, err = getTimestampTokenFromPath("testdata/TimeStampTokenWithWrongSigningCertificateV2IssuerChoiceTag.p7s") 124 | if err != nil { 125 | t.Fatal(err) 126 | } 127 | expectedErrMsg = "issuer name is missing in IssuerSerial" 128 | if _, err := timestampToken.SigningCertificate(×tampToken.SignerInfos[0]); err == nil || err.Error() != expectedErrMsg { 129 | t.Fatalf("expected error %s, but got %v", expectedErrMsg, err) 130 | } 131 | 132 | timestampToken, err = getTimestampTokenFromPath("testdata/TimeStampTokenWithoutSigningCertificateV2IssuerSerial.p7s") 133 | if err != nil { 134 | t.Fatal(err) 135 | } 136 | if _, err := timestampToken.SigningCertificate(×tampToken.SignerInfos[0]); err != nil { 137 | t.Fatalf("expected nil error, but got %v", err) 138 | } 139 | 140 | timestampToken, err = getTimestampTokenFromPath("testdata/TimeStampTokenWithoutCertificate.p7s") 141 | if err != nil { 142 | t.Fatal(err) 143 | } 144 | expectedErrMsg = "signing certificate not found in the timestamp token" 145 | if _, err := timestampToken.SigningCertificate(×tampToken.SignerInfos[0]); err == nil || err.Error() != expectedErrMsg { 146 | t.Fatalf("expected error %s, but got %v", expectedErrMsg, err) 147 | } 148 | 149 | timestampToken, err = getTimestampTokenFromPath("testdata/TimeStampTokenWithSHA1CertHash.p7s") 150 | if err != nil { 151 | t.Fatal(err) 152 | } 153 | expectedErrMsg = "unsupported certificate hash algorithm in SigningCertificateV2 attribute" 154 | if _, err := timestampToken.SigningCertificate(×tampToken.SignerInfos[0]); err == nil || err.Error() != expectedErrMsg { 155 | t.Fatalf("expected error %s, but got %v", expectedErrMsg, err) 156 | } 157 | 158 | timestampToken, err = getTimestampTokenFromPath("testdata/TimeStampTokenWithMismatchCertHash.p7s") 159 | if err != nil { 160 | t.Fatal(err) 161 | } 162 | expectedErrMsg = "signing certificate hash does not match CertHash in signed attribute" 163 | if _, err := timestampToken.SigningCertificate(×tampToken.SignerInfos[0]); err == nil || err.Error() != expectedErrMsg { 164 | t.Fatalf("expected error %s, but got %v", expectedErrMsg, err) 165 | } 166 | 167 | timestampToken, err = getTimestampTokenFromPath("testdata/TimeStampTokenWithInvalidSigningCertificateV2.p7s") 168 | if err != nil { 169 | t.Fatal(err) 170 | } 171 | expectedErrMsg = "failed to get SigningCertificateV2 from signed attributes: asn1: syntax error: sequence truncated" 172 | if _, err := timestampToken.SigningCertificate(×tampToken.SignerInfos[0]); err == nil || err.Error() != expectedErrMsg { 173 | t.Fatalf("expected error %s, but got %v", expectedErrMsg, err) 174 | } 175 | 176 | timestampToken, err = getTimestampTokenFromPath("testdata/TimeStampTokenWithSigningCertificateV2NoCert.p7s") 177 | if err != nil { 178 | t.Fatal(err) 179 | } 180 | expectedErrMsg = "signingCertificateV2 does not contain any certificate" 181 | if _, err := timestampToken.SigningCertificate(×tampToken.SignerInfos[0]); err == nil || err.Error() != expectedErrMsg { 182 | t.Fatalf("expected error %s, but got %v", expectedErrMsg, err) 183 | } 184 | 185 | timestampToken, err = getTimestampTokenFromPath("testdata/TimeStampTokenWithSigningCertificateV1.p7s") 186 | if err != nil { 187 | t.Fatal(err) 188 | } 189 | expectedErrMsg = "failed to get SigningCertificateV2 from signed attributes: attribute not found" 190 | if _, err := timestampToken.SigningCertificate(×tampToken.SignerInfos[0]); err == nil || err.Error() != expectedErrMsg { 191 | t.Fatalf("expected error %s, but got %v", expectedErrMsg, err) 192 | } 193 | } 194 | 195 | func TestValidate(t *testing.T) { 196 | timestampToken, err := getTimestampTokenFromPath("testdata/TimeStampToken.p7s") 197 | if err != nil { 198 | t.Fatal(err) 199 | } 200 | tstInfo, err := timestampToken.Info() 201 | if err != nil { 202 | t.Fatal(err) 203 | } 204 | expectedErrMsg := "invalid TSTInfo: mismatched message" 205 | if _, err := tstInfo.Validate([]byte("invalid")); err == nil || err.Error() != expectedErrMsg { 206 | t.Fatalf("expected error %s, but got %v", expectedErrMsg, err) 207 | } 208 | 209 | timestampToken, err = getTimestampTokenFromPath("testdata/TimeStampToken.p7s") 210 | if err != nil { 211 | t.Fatal(err) 212 | } 213 | tstInfo, err = timestampToken.Info() 214 | if err != nil { 215 | t.Fatal(err) 216 | } 217 | timestamp, err := tstInfo.Validate([]byte("notation")) 218 | if err != nil { 219 | t.Fatalf("expected nil error, but got %v", err) 220 | } 221 | expectedTimestampValue := time.Date(2021, time.September, 17, 14, 9, 10, 0, time.UTC) 222 | expectedTimestampAccuracy := time.Second 223 | if timestamp.Value != expectedTimestampValue { 224 | t.Fatalf("expected timestamp value %s, but got %s", expectedTimestampValue, timestamp.Value) 225 | } 226 | if timestamp.Accuracy != expectedTimestampAccuracy { 227 | t.Fatalf("expected timestamp accuracy %s, but got %s", expectedTimestampAccuracy, timestamp.Accuracy) 228 | } 229 | 230 | timestampToken, err = getTimestampTokenFromPath("testdata/TimeStampToken.p7s") 231 | if err != nil { 232 | t.Fatal(err) 233 | } 234 | tstInfo, err = timestampToken.Info() 235 | if err != nil { 236 | t.Fatal(err) 237 | } 238 | tstInfo.Accuracy = Accuracy{} 239 | tstInfo.Policy = oid.BaselineTimestampPolicy 240 | timestamp, err = tstInfo.Validate([]byte("notation")) 241 | if err != nil { 242 | t.Fatalf("expected nil error, but got %v", err) 243 | } 244 | if timestamp.Value != expectedTimestampValue { 245 | t.Fatalf("expected timestamp value %s, but got %s", expectedTimestampValue, timestamp.Value) 246 | } 247 | if timestamp.Accuracy != expectedTimestampAccuracy { 248 | t.Fatalf("expected timestamp accuracy %s, but got %s", expectedTimestampAccuracy, timestamp.Accuracy) 249 | } 250 | } 251 | 252 | func TestValidateInfo(t *testing.T) { 253 | message := []byte("notation") 254 | var tstInfoErr *TSTInfoError 255 | 256 | var tstInfo *TSTInfo 257 | expectedErrMsg := "invalid TSTInfo: timestamp token info cannot be nil" 258 | err := tstInfo.validate(message) 259 | if err == nil || !errors.As(err, &tstInfoErr) || err.Error() != expectedErrMsg { 260 | t.Fatalf("expected error %s, but got %v", expectedErrMsg, err) 261 | } 262 | 263 | timestampToken, err := getTimestampTokenFromPath("testdata/TimeStampTokenWithTSTInfoVersion2.p7s") 264 | if err != nil { 265 | t.Fatal(err) 266 | } 267 | tstInfo, err = timestampToken.Info() 268 | if err != nil { 269 | t.Fatal(err) 270 | } 271 | expectedErrMsg = "invalid TSTInfo: timestamp token info version must be 1, but got 2" 272 | err = tstInfo.validate(message) 273 | if err == nil || !errors.As(err, &tstInfoErr) || err.Error() != expectedErrMsg { 274 | t.Fatalf("expected error %s, but got %v", expectedErrMsg, err) 275 | } 276 | 277 | timestampToken, err = getTimestampTokenFromPath("testdata/SHA1TimeStampToken.p7s") 278 | if err != nil { 279 | t.Fatal(err) 280 | } 281 | tstInfo, err = timestampToken.Info() 282 | if err != nil { 283 | t.Fatal(err) 284 | } 285 | expectedErrMsg = "invalid TSTInfo: unrecognized hash algorithm: 1.2.840.113549.1.1.5" 286 | if err := tstInfo.validate(message); err == nil || err.Error() != expectedErrMsg { 287 | t.Fatalf("expected error %s, but got %v", expectedErrMsg, err) 288 | } 289 | 290 | timestampToken, err = getTimestampTokenFromPath("testdata/TimeStampToken.p7s") 291 | if err != nil { 292 | t.Fatal(err) 293 | } 294 | tstInfo, err = timestampToken.Info() 295 | if err != nil { 296 | t.Fatal(err) 297 | } 298 | expectedErrMsg = "invalid TSTInfo: mismatched message" 299 | if err := tstInfo.validate([]byte("invalid")); err == nil || err.Error() != expectedErrMsg { 300 | t.Fatalf("expected error %s, but got %v", expectedErrMsg, err) 301 | } 302 | 303 | timestampToken, err = getTimestampTokenFromPath("testdata/TimeStampToken.p7s") 304 | if err != nil { 305 | t.Fatal(err) 306 | } 307 | tstInfo, err = timestampToken.Info() 308 | if err != nil { 309 | t.Fatal(err) 310 | } 311 | if err := tstInfo.validate(message); err != nil { 312 | t.Fatalf("expected nil error, but got %v", err) 313 | } 314 | } 315 | 316 | func getTimestampTokenFromPath(path string) (*SignedToken, error) { 317 | timestampToken, err := os.ReadFile(path) 318 | if err != nil { 319 | return nil, err 320 | } 321 | return ParseSignedToken(timestampToken) 322 | } 323 | -------------------------------------------------------------------------------- /tspclient.go: -------------------------------------------------------------------------------- 1 | // Copyright The Notary Project Authors. 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // 6 | // http://www.apache.org/licenses/LICENSE-2.0 7 | // 8 | // Unless required by applicable law or agreed to in writing, software 9 | // distributed under the License is distributed on an "AS IS" BASIS, 10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | // See the License for the specific language governing permissions and 12 | // limitations under the License. 13 | 14 | // Package tspclient generates timestamping requests to TSA servers, 15 | // fetches and verifies the responses according to RFC 3161 and RFC 5816 16 | package tspclient 17 | 18 | import "context" 19 | 20 | // Timestamper stamps the time. 21 | type Timestamper interface { 22 | // Timestamp stamps the time with the given request. 23 | Timestamp(context.Context, *Request) (*Response, error) 24 | } 25 | --------------------------------------------------------------------------------