3 # Wrapper for Debian Security team
4 # Copyright (C) 2006 Anthony Towns <ajt@debian.org>
6 # This program is free software; you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 2 of the License, or
9 # (at your option) any later version.
11 # This program is distributed in the hope that it will be useful, but
12 # WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 # General Public License for more details.
16 # You should have received a copy of the GNU General Public License
17 # along with this program; if not, write to the Free Software
18 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
21 ################################################################################
23 from daklib import queue
24 from daklib import logging
25 from daklib import utils
26 from daklib import database
27 import apt_pkg, os, sys, pwd, time, re, commands
29 re_taint_free = re.compile(r"^['/;\-\+\.~\s\w]+$");
41 global Cnf, Upload, Options, Logger
43 Cnf = utils.get_conf()
44 Cnf["Dinstall::Options::No-Mail"] = "y"
45 Arguments = [('h', "help", "Security-Install::Options::Help"),
46 ('a', "automatic", "Security-Install::Options::Automatic"),
47 ('n', "no-action", "Security-Install::Options::No-Action"),
48 ('s', "sudo", "Security-Install::Options::Sudo"),
49 (' ', "no-upload", "Security-Install::Options::No-Upload"),
50 ('u', "fg-upload", "Security-Install::Options::Foreground-Upload"),
51 (' ', "drop-advisory", "Security-Install::Options::Drop-Advisory"),
52 ('A', "approve", "Security-Install::Options::Approve"),
53 ('R', "reject", "Security-Install::Options::Reject"),
54 ('D', "disembargo", "Security-Install::Options::Disembargo") ]
59 arguments = apt_pkg.ParseCommandLine(Cnf, Arguments, sys.argv)
61 Options = Cnf.SubTree("Security-Install::Options")
64 whoamifull = pwd.getpwuid(whoami)
65 username = whoamifull[0]
67 print "Non-dak user: %s" % username
74 if len(arguments) == 0:
75 utils.fubar("Process what?")
77 Upload = queue.Upload(Cnf)
78 if Options["No-Action"]:
80 if not Options["Sudo"] and not Options["No-Action"]:
81 Logger = Upload.Logger = logging.Logger(Cnf, "new-security-install")
90 def load_args(arguments):
91 global advisory, changes
94 if not arguments[0].endswith(".changes"):
95 adv_ids [arguments[0]] = 1
96 arguments = arguments[1:]
103 utils.fubar("can only deal with files in the current directory")
104 if not a.endswith(".changes"):
105 utils.fubar("not a .changes file: %s" % (a))
107 Upload.pkg.changes_file = a
109 if "adv id" in Upload.pkg.changes:
111 adv_ids[Upload.pkg.changes["adv id"]] = 1
113 null_adv_changes.append(a)
115 adv_ids = adv_ids.keys()
117 utils.fubar("multiple advisories selected: %s" % (", ".join(adv_ids)))
121 advisory = adv_ids[0]
123 changes = changesfiles.keys()
124 return null_adv_changes
126 def load_adv_changes():
127 global srcverarches, changes
129 for c in os.listdir("."):
130 if not c.endswith(".changes"): continue
132 Upload.pkg.changes_file = c
134 if "adv id" not in Upload.pkg.changes:
136 if Upload.pkg.changes["adv id"] != advisory:
139 if c not in changes: changes.append(c)
140 srcver = "%s %s" % (Upload.pkg.changes["source"],
141 Upload.pkg.changes["version"])
142 srcverarches.setdefault(srcver, {})
143 for arch in Upload.pkg.changes["architecture"].keys():
144 srcverarches[srcver][arch] = 1
148 print "Advisory: %s" % (advisory)
154 svs = srcverarches.keys()
157 as = srcverarches[sv].keys()
159 print " %s (%s)" % (sv, ", ".join(as))
161 def prompt(opts, default):
167 p += ", [%s]%s" % (o[0], o[1:])
173 if Options["Automatic"]:
177 a = utils.our_raw_input(p) + default
182 def add_changes(extras):
186 Upload.pkg.changes_file = c
188 srcver = "%s %s" % (Upload.pkg.changes["source"], Upload.pkg.changes["version"])
189 srcverarches.setdefault(srcver, {})
190 for arch in Upload.pkg.changes["architecture"].keys():
191 srcverarches[srcver][arch] = 1
192 Upload.pkg.changes["adv id"] = advisory
193 Upload.dump_vars(os.getcwd())
196 if Options["Automatic"]: return True
198 answer = utils.our_raw_input(prompt + " ").lower()
201 print "Invalid answer; please try again."
204 if Options["No-Upload"]:
205 print "Not uploading as requested"
206 elif Options["Foreground-Upload"]:
207 actually_upload(changes)
211 actually_upload(changes)
213 print "Uploading in the background"
215 def actually_upload(changes_files):
218 component_mapping = {}
219 for component in Cnf.SubTree("Security-Install::ComponentMappings").List():
220 component_mapping[component] = Cnf["Security-Install::ComponentMappings::%s" % (component)]
221 uploads = {}; # uploads[uri] = file_list
222 changesfiles = {}; # changesfiles[uri] = file_list
223 package_list = {} # package_list[source_name][version]
224 changes_files.sort(utils.changes_compare)
225 for changes_file in changes_files:
226 changes_file = utils.validate_changes_file_arg(changes_file)
232 # Parse the .dak file for the .changes file
233 Upload.pkg.changes_file = changes_file
235 files = Upload.pkg.files
236 changes = Upload.pkg.changes
238 # We have the changes, now return if its amd64, to not upload them to ftp-master
239 if changes["distribution"].has_key("oldstable-security") and changes["architecture"].has_key("amd64"):
240 print "Not uploading amd64 oldstable-security changes to ftp-master\n"
242 # Build the file list for this .changes file
243 for file in files.keys():
244 poolname = os.path.join(Cnf["Dir::Root"], Cnf["Dir::PoolRoot"],
245 utils.poolify(changes["source"], files[file]["component"]),
247 file_list.append(poolname)
248 orig_component = files[file].get("original component", files[file]["component"])
249 components[orig_component] = ""
250 # Determine the upload uri for this .changes file
251 for component in components.keys():
252 upload_uri = component_mapping.get(component)
254 upload_uris[upload_uri] = ""
255 num_upload_uris = len(upload_uris.keys())
256 if num_upload_uris == 0:
257 utils.fubar("%s: No valid upload URI found from components (%s)."
258 % (changes_file, ", ".join(components.keys())))
259 elif num_upload_uris > 1:
260 utils.fubar("%s: more than one upload URI (%s) from components (%s)."
261 % (changes_file, ", ".join(upload_uris.keys()),
262 ", ".join(components.keys())))
263 upload_uri = upload_uris.keys()[0]
264 # Update the file list for the upload uri
265 if not uploads.has_key(upload_uri):
266 uploads[upload_uri] = []
267 uploads[upload_uri].extend(file_list)
268 # Update the changes list for the upload uri
269 if not changesfiles.has_key(upload_uri):
270 changesfiles[upload_uri] = []
271 changesfiles[upload_uri].append(changes_file)
272 # Remember the suites and source name/version
273 for suite in changes["distribution"].keys():
275 # Remember the source name and version
276 if changes["architecture"].has_key("source") and \
277 changes["distribution"].has_key("testing"):
278 if not package_list.has_key(dsc["source"]):
279 package_list[dsc["source"]] = {}
280 package_list[dsc["source"]][dsc["version"]] = ""
282 for uri in uploads.keys():
283 uploads[uri].extend(changesfiles[uri])
284 (host, path) = uri.split(":")
285 file_list = " ".join(uploads[uri])
286 print "Uploading files to %s..." % (host)
287 spawn("lftp -c 'open %s; cd %s; put %s'" % (host, path, file_list))
289 if not Options["No-Action"]:
290 filename = "%s/testing-processed" % (Cnf["Dir::Log"])
291 file = utils.open_file(filename, 'a')
292 for source in package_list.keys():
293 for version in package_list[source].keys():
294 file.write(" ".join([source, version])+'\n')
297 def generate_advisory(template):
298 global changes, advisory
301 updated_pkgs = {}; # updated_pkgs[distro][arch][file] = {path,md5,size}
304 arg = utils.validate_changes_file_arg(arg)
305 Upload.pkg.changes_file = arg
309 src = Upload.pkg.changes["source"]
310 src_ver = "%s (%s)" % (src, Upload.pkg.changes["version"])
311 if src_ver not in adv_packages:
312 adv_packages.append(src_ver)
314 suites = Upload.pkg.changes["distribution"].keys()
316 if not updated_pkgs.has_key(suite):
317 updated_pkgs[suite] = {}
319 files = Upload.pkg.files
320 for file in files.keys():
321 arch = files[file]["architecture"]
322 md5 = files[file]["md5sum"]
323 size = files[file]["size"]
324 poolname = Cnf["Dir::PoolRoot"] + \
325 utils.poolify(src, files[file]["component"])
326 if arch == "source" and file.endswith(".dsc"):
327 dscpoolname = poolname
329 if not updated_pkgs[suite].has_key(arch):
330 updated_pkgs[suite][arch] = {}
331 updated_pkgs[suite][arch][file] = {
332 "md5": md5, "size": size, "poolname": poolname }
334 dsc_files = Upload.pkg.dsc_files
335 for file in dsc_files.keys():
337 if not dsc_files[file].has_key("files id"):
340 # otherwise, it's already in the pool and needs to be
342 md5 = dsc_files[file]["md5sum"]
343 size = dsc_files[file]["size"]
345 if not updated_pkgs[suite].has_key(arch):
346 updated_pkgs[suite][arch] = {}
347 updated_pkgs[suite][arch][file] = {
348 "md5": md5, "size": size, "poolname": dscpoolname }
350 if os.environ.has_key("SUDO_UID"):
351 whoami = long(os.environ["SUDO_UID"])
354 whoamifull = pwd.getpwuid(whoami)
355 username = whoamifull[4].split(",")[0]
358 "__ADVISORY__": advisory,
359 "__WHOAMI__": username,
360 "__DATE__": time.strftime("%B %d, %Y", time.gmtime(time.time())),
361 "__PACKAGE__": ", ".join(adv_packages),
362 "__DAK_ADDRESS__": Cnf["Dinstall::MyEmailAddress"]
365 if Cnf.has_key("Dinstall::Bcc"):
366 Subst["__BCC__"] = "Bcc: %s" % (Cnf["Dinstall::Bcc"])
369 archive = Cnf["Archive::%s::PrimaryMirror" % (utils.where_am_i())]
370 for suite in updated_pkgs.keys():
371 ver = Cnf["Suite::%s::Version" % suite]
372 if ver != "": ver += " "
373 suite_header = "%s %s(%s)" % (Cnf["Dinstall::MyDistribution"],
375 adv += "%s\n%s\n\n" % (suite_header, "-"*len(suite_header))
377 arches = Cnf.ValueList("Suite::%s::Architectures" % suite)
378 if "source" in arches:
379 arches.remove("source")
384 adv += "%s updates are available for %s.\n\n" % (
385 suite.capitalize(), utils.join_with_commas_and(arches))
387 for a in ["source", "all"] + arches:
388 if not updated_pkgs[suite].has_key(a):
392 adv += "Source archives:\n\n"
394 adv += "Architecture independent packages:\n\n"
396 adv += "%s architecture (%s)\n\n" % (a,
397 Cnf["Architectures::%s" % a])
399 for file in updated_pkgs[suite][a].keys():
400 adv += " http://%s/%s%s\n" % (
401 archive, updated_pkgs[suite][a][file]["poolname"], file)
402 adv += " Size/MD5 checksum: %8s %s\n" % (
403 updated_pkgs[suite][a][file]["size"],
404 updated_pkgs[suite][a][file]["md5"])
408 Subst["__ADVISORY_TEXT__"] = adv
410 adv = utils.TemplateSubst(Subst, template)
414 if not re_taint_free.match(command):
415 utils.fubar("Invalid character in \"%s\"." % (command))
417 if Options["No-Action"]:
418 print "[%s]" % (command)
420 (result, output) = commands.getstatusoutput(command)
422 utils.fubar("Invocation of '%s' failed:\n%s\n" % (command, output), result)
425 ##################### ! ! ! N O T E ! ! ! #####################
427 # These functions will be reinvoked by semi-priveleged users, be careful not
428 # to invoke external programs that will escalate privileges, etc.
430 ##################### ! ! ! N O T E ! ! ! #####################
432 def sudo(arg, fn, exit):
435 utils.fubar("Must set advisory name")
436 os.spawnl(os.P_WAIT, "/usr/bin/sudo", "/usr/bin/sudo", "-u", "dak", "-H",
437 "/usr/local/bin/dak", "new-security-install", "-"+arg, "--", advisory)
443 def do_Approve(): sudo("A", _do_Approve, True)
445 # 1. dump advisory in drafts
446 draft = "/org/security.debian.org/advisories/drafts/%s" % (advisory)
447 print "Advisory in %s" % (draft)
448 if not Options["No-Action"]:
449 adv_file = "./advisory.%s" % (advisory)
450 if not os.path.exists(adv_file):
451 adv_file = Cnf["Dir::Templates"]+"/security-install.advisory"
452 adv_fd = os.open(draft, os.O_RDWR|os.O_CREAT|os.O_EXCL, 0664)
453 os.write(adv_fd, generate_advisory(adv_file))
457 # 2. run dak process-accepted on changes
458 print "Accepting packages..."
459 spawn("dak process-accepted -pa %s" % (" ".join(changes)))
461 # 3. run dak make-suite-file-list / apt-ftparchve / dak generate-releases
462 print "Updating file lists for apt-ftparchive..."
463 spawn("dak make-suite-file-list")
464 print "Updating Packages and Sources files..."
465 spawn("apt-ftparchive generate %s" % (utils.which_apt_conf_file()))
466 print "Updating Release files..."
467 spawn("dak generate-releases")
468 print "Triggering security mirrors..."
469 spawn("sudo -u archvsync /home/archvsync/signal_security")
471 # 4. chdir to done - do upload
472 if not Options["No-Action"]:
473 os.chdir(Cnf["Dir::Queue::Done"])
476 def do_Disembargo(): sudo("D", _do_Disembargo, True)
477 def _do_Disembargo():
478 if os.getcwd() != Cnf["Dir::Queue::Embargoed"].rstrip("/"):
479 utils.fubar("Can only disembargo from %s" % Cnf["Dir::Queue::Embargoed"])
481 dest = Cnf["Dir::Queue::Unembargoed"]
482 emb_q = database.get_or_set_queue_id("embargoed")
483 une_q = database.get_or_set_queue_id("unembargoed")
486 print "Disembargoing %s" % (c)
489 Upload.pkg.changes_file = c
492 if "source" in Upload.pkg.changes["architecture"].keys():
493 print "Adding %s %s to disembargo table" % (Upload.pkg.changes["source"], Upload.pkg.changes["version"])
494 Upload.projectB.query("INSERT INTO disembargo (package, version) VALUES ('%s', '%s')" % (Upload.pkg.changes["source"], Upload.pkg.changes["version"]))
497 for suite in Upload.pkg.changes["distribution"].keys():
498 if suite not in Cnf.ValueList("Dinstall::QueueBuildSuites"):
500 dest_dir = Cnf["Dir::QueueBuild"]
501 if Cnf.FindB("Dinstall::SecurityQueueBuild"):
502 dest_dir = os.path.join(dest_dir, suite)
503 for file in Upload.pkg.files.keys():
504 files[os.path.join(dest_dir, file)] = 1
507 Upload.projectB.query("BEGIN WORK")
509 Upload.projectB.query("UPDATE queue_build SET queue = %s WHERE filename = '%s' AND queue = %s" % (une_q, f, emb_q))
510 Upload.projectB.query("COMMIT WORK")
512 for file in Upload.pkg.files.keys():
513 utils.copy(file, os.path.join(dest, file))
517 utils.copy(c, os.path.join(dest, c))
520 utils.copy(k, os.path.join(dest, k))
523 def do_Reject(): sudo("R", _do_Reject, True)
527 print "Rejecting %s..." % (c)
529 Upload.pkg.changes_file = c
532 for suite in Upload.pkg.changes["distribution"].keys():
533 if suite not in Cnf.ValueList("Dinstall::QueueBuildSuites"):
535 dest_dir = Cnf["Dir::QueueBuild"]
536 if Cnf.FindB("Dinstall::SecurityQueueBuild"):
537 dest_dir = os.path.join(dest_dir, suite)
538 for file in Upload.pkg.files.keys():
539 files[os.path.join(dest_dir, file)] = 1
543 aborted = Upload.do_reject()
545 os.unlink(c[:-8]+".dak")
547 Upload.projectB.query(
548 "DELETE FROM queue_build WHERE filename = '%s'" % (f))
551 print "Updating buildd information..."
552 spawn("/org/security.debian.org/dak/config/debian-security/cron.buildd")
554 adv_file = "./advisory.%s" % (advisory)
555 if os.path.exists(adv_file):
558 def do_DropAdvisory():
561 Upload.pkg.changes_file = c
563 del Upload.pkg.changes["adv id"]
564 Upload.dump_vars(os.getcwd())
568 adv_file = "./advisory.%s" % (advisory)
569 if not os.path.exists(adv_file):
570 utils.copy(Cnf["Dir::Templates"]+"/security-install.advisory", adv_file)
571 editor = os.environ.get("EDITOR", "vi")
572 result = os.system("%s %s" % (editor, adv_file))
574 utils.fubar("%s invocation failed for %s." % (editor, adv_file))
577 adv_file = "./advisory.%s" % (advisory)
578 if not os.path.exists(adv_file):
579 adv_file = Cnf["Dir::Templates"]+"/security-install.advisory"
580 print "====\n%s\n====" % (generate_advisory(adv_file))
589 extras = load_args(args)
596 if srcverarches == {}:
597 if not yes_no("Create new advisory %s?" % (advisory)):
598 print "Not doing anything, then"
604 if yes_no("Add %s to %s?" % (c, advisory)):
610 utils.fubar("Must specify an advisory id")
613 utils.fubar("No changes specified")
615 if Options["Approve"]:
618 elif Options["Reject"]:
621 elif Options["Disembargo"]:
624 elif Options["Drop-Advisory"]:
630 opts = ["Approve", "Edit advisory"]
631 if os.path.exists("./advisory.%s" % advisory):
635 if os.getcwd() == Cnf["Dir::Queue::Embargoed"].rstrip("/"):
636 opts.append("Disembargo")
637 opts += ["Show advisory", "Reject", "Quit"]
640 what = prompt(opts, default)
644 elif what == "Approve":
646 elif what == "Edit advisory":
648 elif what == "Show advisory":
650 elif what == "Disembargo":
652 elif what == "Reject":
655 utils.fubar("Impossible answer '%s', wtf?" % (what))
657 ################################################################################
659 if __name__ == '__main__':
662 ################################################################################