sign.py revision 2405
3177N/A#!/usr/bin/python2.6
2026N/A#
2026N/A# CDDL HEADER START
2026N/A#
2026N/A# The contents of this file are subject to the terms of the
2026N/A# Common Development and Distribution License (the "License").
2026N/A# You may not use this file except in compliance with the License.
2026N/A#
2026N/A# You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
2026N/A# or http://www.opensolaris.org/os/licensing.
2026N/A# See the License for the specific language governing permissions
2026N/A# and limitations under the License.
2026N/A#
2026N/A# When distributing Covered Code, include this CDDL HEADER in each
2026N/A# file and include the License file at usr/src/OPENSOLARIS.LICENSE.
2026N/A# If applicable, add the following below this CDDL HEADER, with the
2026N/A# fields enclosed by brackets "[]" replaced with your own identifying
2026N/A# information: Portions Copyright [yyyy] [name of copyright owner]
2026N/A#
2026N/A# CDDL HEADER END
2026N/A#
2026N/A
2026N/A#
3321N/A# Copyright (c) 2010, 2011, Oracle and/or its affiliates. All rights reserved.
2026N/A#
2026N/A
2026N/Aimport getopt
2026N/Aimport gettext
2962N/Aimport locale
2026N/Aimport os
2026N/Aimport shutil
2026N/Aimport sys
2026N/Aimport tempfile
2026N/Aimport traceback
2026N/A
3339N/Aimport pkg
3339N/Aimport pkg.actions as actions
3339N/Aimport pkg.client.api_errors as api_errors
3339N/Aimport pkg.client.transport.transport as transport
3321N/Aimport pkg.fmri as fmri
3321N/Aimport pkg.manifest as manifest
3321N/Aimport pkg.misc as misc
3321N/Aimport pkg.publish.transaction as trans
3194N/Afrom pkg.client import global_settings
2026N/Afrom pkg.misc import emsg, msg, PipeError
2026N/A
2026N/APKG_CLIENT_NAME = "pkgsign"
2026N/A
2026N/A# pkg exit codes
2962N/AEXIT_OK = 0
2026N/AEXIT_OOPS = 1
2026N/AEXIT_BADOPT = 2
2026N/AEXIT_PARTIAL = 3
2026N/A
2026N/Arepo_cache = {}
2962N/A
2026N/Adef error(text, cmd=None):
2026N/A """Emit an error message prefixed by the command name """
2026N/A
2026N/A if cmd:
2026N/A text = "%s: %s" % (cmd, text)
2026N/A
2026N/A else:
2026N/A text = "%s: %s" % (PKG_CLIENT_NAME, text)
2026N/A
2026N/A
2026N/A # If the message starts with whitespace, assume that it should come
2026N/A # *before* the command-name prefix.
2026N/A text_nows = text.lstrip()
2026N/A ws = text[:len(text) - len(text_nows)]
2026N/A
2026N/A # This has to be a constant value as we can't reliably get our actual
3158N/A # program name on all platforms.
2962N/A emsg(ws + text_nows)
2026N/A
3158N/Adef usage(usage_error=None, cmd=None, retcode=EXIT_BADOPT):
2026N/A """Emit a usage message and optionally prefix it with a more specific
2026N/A error message. Causes program to exit."""
2026N/A
2026N/A if usage_error:
2026N/A error(usage_error, cmd=cmd)
2026N/A emsg (_("""\
2026N/AUsage:
2026N/A pkgsign -s path_or_uri [-acikn] [--no-index] [--no-catalog]
2026N/A (fmri|pattern) ...
2026N/A"""))
2026N/A
2026N/A sys.exit(retcode)
2026N/A
2026N/Adef fetch_catalog(src_pub, xport, temp_root):
2026N/A """Fetch the catalog from src_uri."""
2026N/A
2026N/A if not src_pub.meta_root:
2026N/A # Create a temporary directory for catalog.
2026N/A cat_dir = tempfile.mkdtemp(dir=temp_root)
2405N/A src_pub.meta_root = cat_dir
2405N/A
2026N/A src_pub.transport = xport
2026N/A src_pub.refresh(True, True)
2026N/A
2026N/A return src_pub.catalog
2405N/A
2026N/Adef main_func():
2026N/A misc.setlocale(locale.LC_ALL, "", error)
2026N/A gettext.install("pkg", "/usr/share/locale")
2026N/A global_settings.client_name = "pkgsign"
2026N/A
2026N/A try:
2026N/A opts, pargs = getopt.getopt(sys.argv[1:], "a:c:i:k:ns:",
2026N/A ["help", "no-index", "no-catalog"])
2026N/A except getopt.GetoptError, e:
2026N/A usage(_("illegal global option -- %s") % e.opt)
2405N/A
2026N/A show_usage = False
2414N/A sig_alg = "rsa-sha256"
2414N/A cert_path = None
3321N/A key_path = None
3321N/A chain_certs = []
3321N/A add_to_catalog = True
3321N/A set_alg = False
3158N/A dry_run = False
3158N/A
3158N/A repo_uri = os.getenv("PKG_REPO", None)
2414N/A for opt, arg in opts:
2414N/A if opt == "-a":
3321N/A sig_alg = arg
2414N/A set_alg = True
2414N/A elif opt == "-c":
2026N/A cert_path = os.path.abspath(arg)
2026N/A if not os.path.isfile(cert_path):
2026N/A usage(_("%s was expected to be a certificate "
2026N/A "but isn't a file.") % cert_path)
2962N/A elif opt == "-i":
2405N/A p = os.path.abspath(arg)
3171N/A if not os.path.isfile(p):
3158N/A usage(_("%s was expected to be a certificate "
2026N/A "but isn't a file.") % p)
2026N/A chain_certs.append(p)
2026N/A elif opt == "-k":
2026N/A key_path = os.path.abspath(arg)
2026N/A if not os.path.isfile(key_path):
2026N/A usage(_("%s was expected to be a key file "
2026N/A "but isn't a file.") % key_path)
2026N/A elif opt == "-n":
2405N/A dry_run = True
2026N/A elif opt == "-s":
2268N/A repo_uri = misc.parse_uri(arg)
2026N/A elif opt == "--help":
2026N/A show_usage = True
2026N/A elif opt == "--no-catalog":
2026N/A add_to_catalog = False
2026N/A
2026N/A if show_usage:
2026N/A usage(retcode=EXIT_OK)
3158N/A
3158N/A if not repo_uri:
2026N/A usage(_("a repository must be provided"))
2026N/A
2026N/A if key_path and not cert_path:
3158N/A usage(_("If a key is given to sign with, its associated "
3158N/A "certificate must be given."))
2026N/A
2026N/A if cert_path and not key_path:
2026N/A usage(_("If a certificate is given, its associated key must be "
2026N/A "given."))
3158N/A
3158N/A if chain_certs and not cert_path:
2405N/A usage(_("Intermediate certificates are only valid if a key "
2405N/A "and certificate are also provided."))
2026N/A
2268N/A if not pargs:
2026N/A usage(_("At least one fmri or pattern must be provided to "
2026N/A "sign."))
2026N/A
2026N/A if not set_alg and not key_path:
2962N/A sig_alg = "sha256"
2962N/A
2962N/A s, h = actions.signature.SignatureAction.decompose_sig_alg(sig_alg)
2962N/A if h is None:
2962N/A usage(_("%s is not a recognized signature algorithm.") %
3158N/A sig_alg)
3158N/A if s and not key_path:
3158N/A usage(_("Using %s as the signature algorithm requires that a "
2026N/A "key and certificate pair be presented using the -k and -c "
2026N/A "options.") % sig_alg)
2026N/A if not s and key_path:
2268N/A usage(_("The %s hash algorithm does not use a key or "
2268N/A "certificate. Do not use the -k or -c options with this "
2268N/A "algorithm.") % sig_alg)
2026N/A
2026N/A errors = []
2026N/A
2026N/A t = misc.config_temp_root()
2026N/A temp_root = tempfile.mkdtemp(dir=t)
2026N/A del t
2026N/A
2026N/A cache_dir = tempfile.mkdtemp(dir=temp_root)
2026N/A incoming_dir = tempfile.mkdtemp(dir=temp_root)
2026N/A chash_dir = tempfile.mkdtemp(dir=temp_root)
2026N/A
2026N/A try:
2405N/A xport, xport_cfg = transport.setup_transport()
2405N/A xport_cfg.add_cache(cache_dir, readonly=False)
2405N/A xport_cfg.incoming_root = incoming_dir
2026N/A
2026N/A # Configure publisher(s)
2026N/A transport.setup_publisher(repo_uri, "source", xport,
2026N/A xport_cfg, remote_prefix=True)
2026N/A pats = pargs
2026N/A successful_publish = False
3158N/A
3158N/A concrete_fmris = []
2026N/A unmatched_pats = set(pats)
3158N/A all_pats = frozenset(pats)
2026N/A get_all_pubs = False
3158N/A pub_prefs = set()
2026N/A matches = {}
3158N/A # Gather the publishers whose catalogs will be needed.
2026N/A for pat in pats:
3158N/A try:
2026N/A p_obj = fmri.MatchingPkgFmri(pat)
2962N/A except fmri.IllegalMatchingFmri, e:
2962N/A errors.append(e)
2962N/A continue
2026N/A pub_prefix = p_obj.get_publisher()
2026N/A if pub_prefix:
2026N/A pub_prefs.add(pub_prefix)
2026N/A else:
2026N/A get_all_pubs = True
2962N/A # Check each publisher for matches to our patterns.
2026N/A for p in xport_cfg.gen_publishers():
2026N/A if not get_all_pubs and p.prefix not in pub_prefs:
2286N/A continue
2414N/A cat = fetch_catalog(p, xport, temp_root)
2026N/A ms, tmp1, u = cat.get_matching_fmris(pats,
2026N/A raise_unmatched=False)
2414N/A # Find which patterns matched.
2414N/A matched_pats = all_pats - u
2414N/A # Remove those patterns from the unmatched set.
2414N/A unmatched_pats -= matched_pats
2414N/A for v_list in ms.values():
2414N/A concrete_fmris.extend([(v, p) for v in v_list])
2026N/A if unmatched_pats:
2073N/A raise api_errors.PackageMatchErrors(
2073N/A unmatched_fmris=unmatched_pats)
2026N/A
2405N/A for pfmri, src_pub in sorted(set(concrete_fmris)):
2405N/A try:
2026N/A # Get the existing manifest for the package to
2405N/A # be signed.
2028N/A m_str = xport.get_manifest(pfmri,
2026N/A content_only=True, pub=src_pub)
2405N/A m = manifest.Manifest()
2405N/A m.set_content(content=m_str)
2405N/A
2405N/A # Construct the base signature action.
2405N/A attrs = { "algorithm": sig_alg }
2405N/A a = actions.signature.SignatureAction(cert_path,
2405N/A **attrs)
2026N/A a.hash = cert_path
2405N/A
3171N/A # Add the action to the manifest to be signed
2405N/A # since the action signs itself.
2405N/A m.add_action(a, misc.EmptyI)
2405N/A
2405N/A # Set the signature value and certificate
2405N/A # information for the signature action.
2405N/A a.set_signature(m.gen_actions(),
2405N/A key_path=key_path, chain_paths=chain_certs,
2405N/A chash_dir=chash_dir)
2405N/A
2405N/A # The hash of 'a' is currently a path, we need
2405N/A # to find the hash of that file to allow
2405N/A # comparison to existing signatures.
2591N/A hsh = None
2405N/A if cert_path:
2405N/A hsh, _dummy = \
2405N/A misc.get_data_digest(cert_path)
2405N/A
2405N/A # Check whether the signature about to be added
2405N/A # is identical, or almost identical, to existing
2405N/A # signatures on the package. Because 'a' has
2405N/A # already been added to the manifest, it is
2405N/A # generated by gen_actions_by_type, so the cnt
2026N/A # must be 2 or higher to be an issue.
2405N/A cnt = 0
2405N/A almost_identical = False
2026N/A for a2 in m.gen_actions_by_type("signature"):
2405N/A try:
2026N/A if a.identical(a2, hsh):
2026N/A cnt += 1
2026N/A except api_errors.AlmostIdentical, e:
2073N/A e.pkg = pfmri
2026N/A errors.append(e)
2026N/A almost_identical = True
2026N/A if almost_identical:
2026N/A continue
2026N/A if cnt == 2:
2026N/A continue
2026N/A elif cnt > 2:
2026N/A raise api_errors.DuplicateSignaturesAlreadyExist(pfmri)
2026N/A assert cnt == 1, "Cnt was:%s" % cnt
2026N/A
2026N/A if not dry_run:
2026N/A # Append the finished signature action
2026N/A # to the published manifest.
2026N/A t = trans.Transaction(repo_uri,
2286N/A pkg_name=str(pfmri), xport=xport,
2286N/A pub=src_pub)
2286N/A try:
2286N/A t.append()
2286N/A t.add(a)
2286N/A for c in chain_certs:
2286N/A t.add_file(c)
2286N/A t.close(add_to_catalog=
2962N/A add_to_catalog)
2962N/A except:
2962N/A if t.trans_id:
2286N/A t.close(abandon=True)
2962N/A raise
2962N/A msg(_("Signed %s") % pfmri)
2286N/A successful_publish = True
2286N/A except (api_errors.ApiException, fmri.FmriError,
2286N/A trans.TransactionError), e:
2286N/A errors.append(e)
2286N/A if errors:
2286N/A error("\n".join([str(e) for e in errors]))
2286N/A if successful_publish:
2286N/A return EXIT_PARTIAL
2286N/A else:
2286N/A return EXIT_OOPS
2286N/A return EXIT_OK
2286N/A except api_errors.ApiException, e:
2286N/A error(e)
3171N/A return EXIT_OOPS
2286N/A finally:
2286N/A shutil.rmtree(temp_root)
2286N/A
2286N/A#
2286N/A# Establish a specific exit status which means: "python barfed an exception"
2286N/A# so that we can more easily detect these in testing of the CLI commands.
2286N/A#
2286N/Aif __name__ == "__main__":
2286N/A try:
3158N/A __ret = main_func()
2026N/A except (PipeError, KeyboardInterrupt):
2405N/A # We don't want to display any messages here to prevent
2405N/A # possible further broken pipe (EPIPE) errors.
2405N/A __ret = EXIT_OOPS
2405N/A except SystemExit, _e:
2405N/A raise _e
2405N/A except:
2405N/A traceback.print_exc()
2405N/A error(_("""\n
2405N/AThis is an internal error in pkg(5) version %(version)s. Please let the
2405N/Adevelopers know about this problem by including the information above (and
2405N/Athis message) when filing a bug at:
2405N/A
2405N/A%(bug_uri)s""") % { "version": pkg.VERSION, "bug_uri": misc.BUG_URI_CLI })
2405N/A __ret = 99
2405N/A sys.exit(__ret)
2405N/A