blob: 2bacacf7bfdf8002c24f706f4d463db3e08dc9ff [file] [log] [blame]
Mike Frysinger9f7e4ee2013-03-13 15:43:03 -04001#!/usr/bin/python
Jim Hebert91c052c2011-03-11 11:00:53 -08002# Copyright (c) 2010 The Chromium OS Authors. All rights reserved.
3# Use of this source code is governed by a BSD-style license that can be
4# found in the LICENSE file.
5
Don Garrett25f309a2014-03-19 14:02:12 -07006"""Command to extract the dependancy tree for a given package."""
7
Jim Hebert91c052c2011-03-11 11:00:53 -08008import json
Don Garrettf8bf7842014-03-20 17:03:42 -07009import portage # pylint: disable=F0401
10
Jim Hebert91c052c2011-03-11 11:00:53 -080011from parallel_emerge import DepGraphGenerator
Don Garrettf8bf7842014-03-20 17:03:42 -070012
Jim Hebertcf870d72013-06-12 15:33:34 -070013from chromite.lib import commandline
14from chromite.lib import cros_build_lib
Jim Hebert91c052c2011-03-11 11:00:53 -080015
Mike Frysingercc838832014-05-24 13:10:30 -040016
David James1b363582012-12-17 11:53:11 -080017def FlattenDepTree(deptree, pkgtable=None, parentcpv=None):
Don Garrett25f309a2014-03-19 14:02:12 -070018 """Simplify dependency json.
19
20Turn something like this (the parallel_emerge DepsTree format):
Jim Hebert91c052c2011-03-11 11:00:53 -080021{
22 "app-admin/eselect-1.2.9": {
23 "action": "merge",
24 "deps": {
25 "sys-apps/coreutils-7.5-r1": {
26 "action": "merge",
27 "deps": {},
28 "deptype": "runtime"
29 },
30 ...
31 }
32 }
33}
34 ...into something like this (the cros_extract_deps format):
35{
36 "app-admin/eselect-1.2.9": {
37 "deps": ["coreutils-7.5-r1"],
38 "rev_deps": [],
39 "name": "eselect",
40 "category": "app-admin",
41 "version": "1.2.9",
42 "full_name": "app-admin/eselect-1.2.9",
43 "action": "merge"
44 },
45 "sys-apps/coreutils-7.5-r1": {
46 "deps": [],
47 "rev_deps": ["app-admin/eselect-1.2.9"],
48 "name": "coreutils",
49 "category": "sys-apps",
50 "version": "7.5-r1",
51 "full_name": "sys-apps/coreutils-7.5-r1",
52 "action": "merge"
53 }
54}
55 """
David James1b363582012-12-17 11:53:11 -080056 if pkgtable is None:
57 pkgtable = {}
Jim Hebert91c052c2011-03-11 11:00:53 -080058 for cpv, record in deptree.items():
59 if cpv not in pkgtable:
David James1b363582012-12-17 11:53:11 -080060 cat, nam, ver, rev = portage.versions.catpkgsplit(cpv)
Jim Hebert91c052c2011-03-11 11:00:53 -080061 pkgtable[cpv] = {"deps": [],
62 "rev_deps": [],
63 "name": nam,
64 "category": cat,
65 "version": "%s-%s" % (ver, rev),
66 "full_name": cpv,
Jim Hebertcf870d72013-06-12 15:33:34 -070067 "cpes": GetCPEFromCPV(cat, nam, ver),
Jim Hebert91c052c2011-03-11 11:00:53 -080068 "action": record["action"]}
69 # If we have a parent, that is a rev_dep for the current package.
70 if parentcpv:
71 pkgtable[cpv]["rev_deps"].append(parentcpv)
72 # If current package has any deps, record those.
73 for childcpv in record["deps"]:
74 pkgtable[cpv]["deps"].append(childcpv)
75 # Visit the subtree recursively as well.
76 FlattenDepTree(record["deps"], pkgtable=pkgtable, parentcpv=cpv)
77 return pkgtable
78
79
Jim Hebertcf870d72013-06-12 15:33:34 -070080def GetCPEFromCPV(category, package, version):
81 """Look up the CPE for a specified Portage package.
Jim Hebert91c052c2011-03-11 11:00:53 -080082
Jim Hebertcf870d72013-06-12 15:33:34 -070083 Args:
84 category: The Portage package's category, e.g. "net-misc"
85 package: The Portage package's name, e.g. "curl"
86 version: The Portage version, e.g. "7.30.0"
87
Mike Frysinger02e1e072013-11-10 22:11:34 -050088 Returns:
89 A list of CPE Name strings, e.g.
90 ["cpe:/a:curl:curl:7.30.0", "cpe:/a:curl:libcurl:7.30.0"]
Jim Hebertcf870d72013-06-12 15:33:34 -070091 """
92 equery_cmd = ["equery", "m", "-U", "%s/%s" % (category, package)]
93 lines = cros_build_lib.RunCommand(equery_cmd, error_code_ok=True,
94 print_cmd=False,
95 redirect_stdout=True).output.splitlines()
96 # Look for lines like "Remote-ID: cpe:/a:kernel:linux-pam ID: cpe"
97 # and extract the cpe URI.
98 cpes = []
99 for line in lines:
100 if "ID: cpe" not in line:
101 continue
Jim Hebert96aff9c2013-07-16 15:43:17 -0700102 cpes.append("%s:%s" % (line.split()[1], version.replace("_", "")))
Jim Hebertcf870d72013-06-12 15:33:34 -0700103 # Note that we're assuming we can combine the root of the CPE, taken
104 # from metadata.xml, and tack on the version number as used by
105 # Portage, and come up with a legitimate CPE. This works so long as
106 # Portage and CPE agree on the precise formatting of the version
Jim Hebert96aff9c2013-07-16 15:43:17 -0700107 # number, which they almost always do. The major exception we've
108 # identified thus far is that our ebuilds have a pattern of inserting
109 # underscores prior to patchlevels, that neither upstream nor CPE
110 # use. For example, our code will decide we have
Jim Hebertcf870d72013-06-12 15:33:34 -0700111 # cpe:/a:todd_miller:sudo:1.8.6_p7 yet the advisories use a format
112 # like cpe:/a:todd_miller:sudo:1.8.6p7, without the underscore. (CPE
113 # is "right" in this example, in that it matches www.sudo.ws.)
114 #
Jim Hebert96aff9c2013-07-16 15:43:17 -0700115 # Removing underscores seems to improve our chances of correctly
116 # arriving at the CPE used by NVD. However, at the end of the day,
117 # ebuild version numbers are rev'd by people who don't have "try to
118 # match NVD" as one of their goals, and there is always going to be
119 # some risk of minor formatting disagreements at the version number
120 # level, if not from stray underscores then from something else.
121 #
Jim Hebertcf870d72013-06-12 15:33:34 -0700122 # This is livable so long as you do some fuzzy version number
123 # comparison in your vulnerability monitoring, between what-we-have
124 # and what-the-advisory-says-is-affected.
125 return cpes
126
127
128def ExtractCPEList(deps_list):
129 cpe_dump = []
130 for cpv, record in deps_list.items():
131 if record["cpes"]:
Jim Heberteef14932013-07-09 11:34:08 -0700132 cpe_dump.append({"Name": cpv, "Targets": sorted(record["cpes"]),
133 "Repository": "cros"})
Jim Hebertcf870d72013-06-12 15:33:34 -0700134 else:
135 cros_build_lib.Warning("No CPE entry for %s", cpv)
Jim Heberteef14932013-07-09 11:34:08 -0700136 return sorted(cpe_dump, key=lambda k: k["Name"])
Jim Hebert91c052c2011-03-11 11:00:53 -0800137
138
Brian Harring30675052012-02-29 12:18:22 -0800139def main(argv):
Jim Hebertcf870d72013-06-12 15:33:34 -0700140 parser = commandline.ArgumentParser(description="""
141This extracts the dependency tree for the specified package, and outputs it
142to stdout, in a serialized JSON format.""")
143 parser.add_argument("--board", required=True,
144 help="The board to use when computing deps.")
145 parser.add_argument("--format", default="deps",
146 choices=["deps", "cpe"],
147 help="Output either traditional deps or CPE-only JSON")
148 # Even though this is really just a pass-through to DepGraphGenerator,
149 # handling it as a known arg here allows us to specify a default more
150 # elegantly than testing for its presence in the unknown_args later.
151 parser.add_argument("--root-deps", default="rdeps",
152 help="Which deps to report (defaults to rdeps)")
153 known_args, unknown_args = parser.parse_known_args(argv)
Jim Hebert91c052c2011-03-11 11:00:53 -0800154
Jim Hebertcf870d72013-06-12 15:33:34 -0700155 lib_argv = ["--board=%s" % known_args.board,
156 "--root-deps=%s" % known_args.root_deps,
157 "--quiet", "--pretend", "--emptytree"]
158 lib_argv.extend(unknown_args)
Jim Hebert91c052c2011-03-11 11:00:53 -0800159
160 deps = DepGraphGenerator()
Jim Hebertcf870d72013-06-12 15:33:34 -0700161 deps.Initialize(lib_argv)
David James1b363582012-12-17 11:53:11 -0800162 deps_tree, _deps_info = deps.GenDependencyTree()
Jim Hebertcf870d72013-06-12 15:33:34 -0700163 deps_list = FlattenDepTree(deps_tree)
164 if known_args.format == "cpe":
165 deps_list = ExtractCPEList(deps_list)
166 print json.dumps(deps_list, sort_keys=True, indent=2)