Debian Codegraph @

in_toto/in_toto_verify.py

raw
1 #!/usr/bin/env python
2
3 # Copyright New York University and the in-toto contributors
4 # SPDX-License-Identifier: Apache-2.0
5
6 """
7 <Program Name>
8 in_toto_verify.py
9
10 <Author>
11 Lukas Puehringer <[email protected]>
12
13 <Started>
14 Oct 3, 2016
15
16 <Copyright>
17 See LICENSE for licensing information.
18
19 <Purpose>
20 Provides a command line interface for verifylib.in_toto_verify.
21
22 <Return Codes>
23 2 if an exception occurred during argument parsing
24 1 if an exception occurred (verification failed)
25 0 if no exception occurred (verification passed)
26
27 """
28 import argparse
29 import logging
30 import sys
31
32 from securesystemslib import interface
33 from securesystemslib.gpg import functions as gpg_interface
34
35 from in_toto import (
36 KEY_TYPE_ECDSA,
37 KEY_TYPE_ED25519,
38 KEY_TYPE_RSA,
39 SUPPORTED_KEY_TYPES,
40 __version__,
41 verifylib,
42 )
43 from in_toto.common_args import (
44 GPG_HOME_ARGS,
45 GPG_HOME_KWARGS,
46 OPTS_TITLE,
47 QUIET_ARGS,
48 QUIET_KWARGS,
49 VERBOSE_ARGS,
50 VERBOSE_KWARGS,
51 sort_action_groups,
52 title_case_action_groups,
53 )
54 from in_toto.models.metadata import Metadata
55
56 # Command line interfaces should use in_toto base logger (c.f. in_toto.log)
57 LOG = logging.getLogger("in_toto")
58
59
60 def create_parser():
61 """Create and return configured ArgumentParser instance."""
62 parser = argparse.ArgumentParser(
63 formatter_class=argparse.RawDescriptionHelpFormatter,
64 description="""
65 in-toto-verify is the main verification tool of the suite, and it is used to
66 verify that the software supply chain of the delivered product was carried out
67 as defined in the passed in-toto supply chain layout. Evidence for supply chain
68 steps must be available in the form of link metadata files named
69 '<step name>.<functionary keyid prefix>.link'.
70
71 Both 'in-toto-run' and 'in-toto-record' generate link metadata named in this
72 manner. If you require special handling of the in-toto link metadata files,
73 please take a look at the library api to modify this behavior.
74
75 The verification includes the following checks:
76 * the layout is signed with the passed keys,
77 * the layout has not expired,
78 * a threshold of link metadata files exists for each step of the layout,
79 * link files are signed by the authorized functionaries,
80 * the materials and products for each step, as reported by the corresponding
81 link files, adhere to the artifact rules specified by the step.
82
83 Additionally, inspection commands defined in the layout are executed
84 sequentially, followed by processing the inspections' artifact rules.
85
86 If the layout includes sublayouts, the verification routine will recurse into a
87 subdirectory named '<step name>.<keyid prefix>', where all the links relevant
88 to that sublayout must exist. The sublayout itself must be in the same
89 directory as the other links of the superlayout. (i.e. '<step name>.<keyid
90 prefix>.link')
91
92 The verification workflow is performed in isolation and does not rely on
93 information about keys that are available through external sources. For example,
94 in-toto does not rely on the creation time, revocation status, and usage flags
95 for PGP keys.
96
97 The command returns 2 if it is called with wrong arguments, 1 if in-toto
98 verification fails and 0 if verification passes. """,
99 )
100
101 parser.usage = "%(prog)s <named arguments> [{}]".format(OPTS_TITLE.lower())
102
103 parser.epilog = """EXAMPLE USAGE
104
105 Verify supply chain in 'root.layout', signed with private part of
106 'key_file.pub'.
107
108 {prog} --layout root.layout --layout-keys key_file.pub
109
110
111 Verify supply chain as above but load links corresponding to steps of
112 'root.layout' from 'link_dir'.
113
114 {prog} --layout root.layout --layout-keys key_file.pub \\
115 --link-dir link_dir
116
117
118 Verify supply chain in 'root.layout', signed with GPG key '...7E0C8A17',
119 for which the public part can be found in the GPG keyring at '~/.gnupg'.
120
121 {prog} --layout root.layout \\
122 --gpg 8465A1E2E0FB2B40ADB2478E18FB3F537E0C8A17 \\
123 --gpg-home ~/.gnupg
124
125
126 """.format(
127 prog=parser.prog
128 )
129
130 named_args = parser.add_argument_group("required named arguments")
131
132 named_args.add_argument(
133 "-l",
134 "--layout",
135 type=str,
136 required=True,
137 metavar="<path>",
138 help=(
139 "path to root layout specifying the software supply chain to be"
140 " verified."
141 ),
142 )
143
144 named_args.add_argument(
145 "-k",
146 "--layout-keys",
147 type=str,
148 metavar="<path>",
149 nargs="+",
150 help=(
151 "paths to public key files used to verify the passed root layout's"
152 " signatures. See '--key-types' for available formats. Passing at least"
153 " one key using '--layout-keys' and/or '--gpg' is required. For each"
154 " passed key the layout must carry a valid signature."
155 ),
156 )
157
158 parser.add_argument(
159 "-t",
160 "--key-types",
161 dest="key_types",
162 type=str,
163 choices=SUPPORTED_KEY_TYPES,
164 nargs="+",
165 help=(
166 "types of keys specified by the '--layout-keys' option. '{rsa}' keys are"
167 " expected in a 'PEM' format. '{ed25519}' and '{ecdsa}' are expected"
168 " in a custom 'securesystemslib/json' format. If multiple keys are"
169 " passed via '--layout-keys' the same amount of key types must be"
170 " passed. Key types are then associated with keys by index. If"
171 " '--key-types' is omitted, the default of '{rsa}' is used for all"
172 " keys.".format(
173 rsa=KEY_TYPE_RSA, ed25519=KEY_TYPE_ED25519, ecdsa=KEY_TYPE_ECDSA
174 )
175 ),
176 )
177
178 named_args.add_argument(
179 "-g",
180 "--gpg",
181 nargs="+",
182 metavar="<id>",
183 help=(
184 "GPG keyid, identifying a public key in the GPG keyring used to verify"
185 " the passed root layout's signatures."
186 " Passing at least one key using '--layout-keys' and/or '--gpg' is"
187 " required. For each passed key the layout must carry a valid"
188 " signature."
189 ),
190 )
191
192 parser.add_argument(
193 "--link-dir",
194 dest="link_dir",
195 type=str,
196 metavar="<path>",
197 default=".",
198 help=(
199 "path to directory from which link metadata files for steps defined"
200 " in the root layout should be loaded. If not passed, links are"
201 " loaded from the current working directory."
202 ),
203 )
204
205 parser.add_argument(*GPG_HOME_ARGS, **GPG_HOME_KWARGS)
206
207 verbosity_args = parser.add_mutually_exclusive_group(required=False)
208 verbosity_args.add_argument(*VERBOSE_ARGS, **VERBOSE_KWARGS)
209 verbosity_args.add_argument(*QUIET_ARGS, **QUIET_KWARGS)
210
211 parser.add_argument(
212 "--version",
213 action="version",
214 version="{} {}".format(parser.prog, __version__),
215 )
216
217 title_case_action_groups(parser)
218 sort_action_groups(parser)
219
220 return parser
221
222
223 def main():
224 """Parse arguments and call in_toto_verify."""
225 parser = create_parser()
226 args = parser.parse_args()
227
228 LOG.setLevelVerboseOrQuiet(args.verbose, args.quiet)
229
230 # For verifying at least one of --layout-keys or --gpg must be specified
231 # Note: Passing both at the same time is possible.
232 if (args.layout_keys is None) and (args.gpg is None):
233 parser.print_help()
234 parser.error(
235 "wrong arguments: specify at least one of"
236 " '--layout-keys path [path ...]' or '--gpg id [id ...]'"
237 )
238
239 try:
240 LOG.info("Loading layout...")
241 layout = Metadata.load(args.layout)
242
243 layout_key_dict = {}
244 if args.layout_keys is not None:
245 LOG.info("Loading layout key(s)...")
246 layout_key_dict.update(
247 interface.import_publickeys_from_file(
248 args.layout_keys, args.key_types
249 )
250 )
251
252 if args.gpg is not None:
253 LOG.info("Loading layout gpg key(s)...")
254 layout_key_dict.update(
255 gpg_interface.export_pubkeys(args.gpg, homedir=args.gpg_home)
256 )
257
258 verifylib.in_toto_verify(layout, layout_key_dict, args.link_dir)
259
260 except Exception as e:
261 LOG.error("(in-toto-verify) {0}: {1}".format(type(e).__name__, e))
262 sys.exit(1)
263
264 sys.exit(0)
265
266
267 if __name__ == "__main__":
268 main()