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 import apt_pkg, os, sys, pwd, time, commands
25 from daklib import queue
26 from daklib import daklog
27 from daklib import utils
28 from daklib import database
29 from daklib.regexes import re_taint_free
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 = daklog.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 # Build the file list for this .changes file
239 for file in files.keys():
240 poolname = os.path.join(Cnf["Dir::Root"], Cnf["Dir::PoolRoot"],
241 utils.poolify(changes["source"], files[file]["component"]),
243 file_list.append(poolname)
244 orig_component = files[file].get("original component", files[file]["component"])
245 components[orig_component] = ""
246 # Determine the upload uri for this .changes file
247 for component in components.keys():
248 upload_uri = component_mapping.get(component)
250 upload_uris[upload_uri] = ""
251 num_upload_uris = len(upload_uris.keys())
252 if num_upload_uris == 0:
253 utils.fubar("%s: No valid upload URI found from components (%s)."
254 % (changes_file, ", ".join(components.keys())))
255 elif num_upload_uris > 1:
256 utils.fubar("%s: more than one upload URI (%s) from components (%s)."
257 % (changes_file, ", ".join(upload_uris.keys()),
258 ", ".join(components.keys())))
259 upload_uri = upload_uris.keys()[0]
260 # Update the file list for the upload uri
261 if not uploads.has_key(upload_uri):
262 uploads[upload_uri] = []
263 uploads[upload_uri].extend(file_list)
264 # Update the changes list for the upload uri
265 if not changesfiles.has_key(upload_uri):
266 changesfiles[upload_uri] = []
267 changesfiles[upload_uri].append(changes_file)
268 # Remember the suites and source name/version
269 for suite in changes["distribution"].keys():
271 # Remember the source name and version
272 if changes["architecture"].has_key("source") and \
273 changes["distribution"].has_key("testing"):
274 if not package_list.has_key(dsc["source"]):
275 package_list[dsc["source"]] = {}
276 package_list[dsc["source"]][dsc["version"]] = ""
278 for uri in uploads.keys():
279 uploads[uri].extend(changesfiles[uri])
280 (host, path) = uri.split(":")
281 # file_list = " ".join(uploads[uri])
282 print "Moving files to UploadQueue"
283 for filename in uploads[uri]:
284 utils.copy(filename, Cnf["Dir::Upload"])
285 # .changes files have already been moved to queue/done by p-a
286 if not filename.endswith('.changes'):
287 remove_from_buildd(suites, filename)
288 #spawn("lftp -c 'open %s; cd %s; put %s'" % (host, path, file_list))
290 if not Options["No-Action"]:
291 filename = "%s/testing-processed" % (Cnf["Dir::Log"])
292 file = utils.open_file(filename, 'a')
293 for source in package_list.keys():
294 for version in package_list[source].keys():
295 file.write(" ".join([source, version])+'\n')
298 def remove_from_buildd(suites, filename):
299 """Check the buildd dir for each suite and remove the file if needed"""
300 builddbase = Cnf["Dir::QueueBuild"]
301 filebase = os.path.basename(filename)
304 os.unlink(os.path.join(builddbase, s, filebase))
307 # About no value printing this warning - it only confuses the security team,
308 # yet makes no difference otherwise.
309 #utils.warn("Problem removing %s from buildd queue %s [%s]" % (filebase, s, str(e)))
312 def generate_advisory(template):
313 global changes, advisory
316 updated_pkgs = {}; # updated_pkgs[distro][arch][file] = {path,md5,size}
319 arg = utils.validate_changes_file_arg(arg)
320 Upload.pkg.changes_file = arg
324 src = Upload.pkg.changes["source"]
325 src_ver = "%s (%s)" % (src, Upload.pkg.changes["version"])
326 if src_ver not in adv_packages:
327 adv_packages.append(src_ver)
329 suites = Upload.pkg.changes["distribution"].keys()
331 if not updated_pkgs.has_key(suite):
332 updated_pkgs[suite] = {}
334 files = Upload.pkg.files
335 for file in files.keys():
336 arch = files[file]["architecture"]
337 md5 = files[file]["md5sum"]
338 size = files[file]["size"]
339 poolname = Cnf["Dir::PoolRoot"] + \
340 utils.poolify(src, files[file]["component"])
341 if arch == "source" and file.endswith(".dsc"):
342 dscpoolname = poolname
344 if not updated_pkgs[suite].has_key(arch):
345 updated_pkgs[suite][arch] = {}
346 updated_pkgs[suite][arch][file] = {
347 "md5": md5, "size": size, "poolname": poolname }
349 dsc_files = Upload.pkg.dsc_files
350 for file in dsc_files.keys():
352 if not dsc_files[file].has_key("files id"):
355 # otherwise, it's already in the pool and needs to be
357 md5 = dsc_files[file]["md5sum"]
358 size = dsc_files[file]["size"]
360 if not updated_pkgs[suite].has_key(arch):
361 updated_pkgs[suite][arch] = {}
362 updated_pkgs[suite][arch][file] = {
363 "md5": md5, "size": size, "poolname": dscpoolname }
365 if os.environ.has_key("SUDO_UID"):
366 whoami = long(os.environ["SUDO_UID"])
369 whoamifull = pwd.getpwuid(whoami)
370 username = whoamifull[4].split(",")[0]
373 "__ADVISORY__": advisory,
374 "__WHOAMI__": username,
375 "__DATE__": time.strftime("%B %d, %Y", time.gmtime(time.time())),
376 "__PACKAGE__": ", ".join(adv_packages),
377 "__DAK_ADDRESS__": Cnf["Dinstall::MyEmailAddress"]
380 if Cnf.has_key("Dinstall::Bcc"):
381 Subst["__BCC__"] = "Bcc: %s" % (Cnf["Dinstall::Bcc"])
384 archive = Cnf["Archive::%s::PrimaryMirror" % (utils.where_am_i())]
385 for suite in updated_pkgs.keys():
386 ver = Cnf["Suite::%s::Version" % suite]
387 if ver != "": ver += " "
388 suite_header = "%s %s(%s)" % (Cnf["Dinstall::MyDistribution"],
390 adv += "%s\n%s\n\n" % (suite_header, "-"*len(suite_header))
392 arches = database.get_suite_architectures(suite)
393 if "source" in arches:
394 arches.remove("source")
399 adv += "%s updates are available for %s.\n\n" % (
400 suite.capitalize(), utils.join_with_commas_and(arches))
402 for a in ["source", "all"] + arches:
403 if not updated_pkgs[suite].has_key(a):
407 adv += "Source archives:\n\n"
409 adv += "Architecture independent packages:\n\n"
411 adv += "%s architecture (%s)\n\n" % (a,
412 Cnf["Architectures::%s" % a])
414 for file in updated_pkgs[suite][a].keys():
415 adv += " http://%s/%s%s\n" % (
416 archive, updated_pkgs[suite][a][file]["poolname"], file)
417 adv += " Size/MD5 checksum: %8s %s\n" % (
418 updated_pkgs[suite][a][file]["size"],
419 updated_pkgs[suite][a][file]["md5"])
423 Subst["__ADVISORY_TEXT__"] = adv
425 adv = utils.TemplateSubst(Subst, template)
429 if not re_taint_free.match(command):
430 utils.fubar("Invalid character in \"%s\"." % (command))
432 if Options["No-Action"]:
433 print "[%s]" % (command)
435 (result, output) = commands.getstatusoutput(command)
437 utils.fubar("Invocation of '%s' failed:\n%s\n" % (command, output), result)
440 ##################### ! ! ! N O T E ! ! ! #####################
442 # These functions will be reinvoked by semi-priveleged users, be careful not
443 # to invoke external programs that will escalate privileges, etc.
445 ##################### ! ! ! N O T E ! ! ! #####################
447 def sudo(arg, fn, exit):
450 utils.fubar("Must set advisory name")
451 os.spawnl(os.P_WAIT, "/usr/bin/sudo", "/usr/bin/sudo", "-u", "dak", "-H",
452 "/usr/local/bin/dak", "new-security-install", "-"+arg, "--", advisory)
458 def do_Approve(): sudo("A", _do_Approve, True)
460 # 1. dump advisory in drafts
461 draft = "/org/security.debian.org/advisories/drafts/%s" % (advisory)
462 print "Advisory in %s" % (draft)
463 if not Options["No-Action"]:
464 adv_file = "./advisory.%s" % (advisory)
465 if not os.path.exists(adv_file):
466 adv_file = Cnf["Dir::Templates"]+"/security-install.advisory"
467 adv_fd = os.open(draft, os.O_RDWR|os.O_CREAT|os.O_EXCL, 0664)
468 os.write(adv_fd, generate_advisory(adv_file))
472 # 2. run dak process-accepted on changes
473 print "Accepting packages..."
474 spawn("dak process-accepted -pa %s" % (" ".join(changes)))
476 # 3. run dak make-suite-file-list / apt-ftparchve / dak generate-releases
477 print "Updating file lists for apt-ftparchive..."
478 spawn("dak make-suite-file-list")
479 print "Updating Packages and Sources files..."
480 spawn("/org/security.debian.org/dak/config/debian-security/map.sh")
481 spawn("apt-ftparchive generate %s" % (utils.which_apt_conf_file()))
482 print "Updating Release files..."
483 spawn("dak generate-releases")
484 print "Triggering security mirrors..."
485 spawn("sudo -u archvsync -H /home/archvsync/signal_security")
487 # 4. chdir to done - do upload
488 if not Options["No-Action"]:
489 os.chdir(Cnf["Dir::Queue::Done"])
492 def do_Disembargo(): sudo("D", _do_Disembargo, True)
493 def _do_Disembargo():
494 if os.getcwd() != Cnf["Dir::Queue::Embargoed"].rstrip("/"):
495 utils.fubar("Can only disembargo from %s" % Cnf["Dir::Queue::Embargoed"])
497 dest = Cnf["Dir::Queue::Unembargoed"]
498 emb_q = database.get_or_set_queue_id("embargoed")
499 une_q = database.get_or_set_queue_id("unembargoed")
502 print "Disembargoing %s" % (c)
505 Upload.pkg.changes_file = c
508 if "source" in Upload.pkg.changes["architecture"].keys():
509 print "Adding %s %s to disembargo table" % (Upload.pkg.changes["source"], Upload.pkg.changes["version"])
510 Upload.projectB.query("INSERT INTO disembargo (package, version) VALUES ('%s', '%s')" % (Upload.pkg.changes["source"], Upload.pkg.changes["version"]))
513 for suite in Upload.pkg.changes["distribution"].keys():
514 if suite not in Cnf.ValueList("Dinstall::QueueBuildSuites"):
516 dest_dir = Cnf["Dir::QueueBuild"]
517 if Cnf.FindB("Dinstall::SecurityQueueBuild"):
518 dest_dir = os.path.join(dest_dir, suite)
519 for file in Upload.pkg.files.keys():
520 files[os.path.join(dest_dir, file)] = 1
523 Upload.projectB.query("BEGIN WORK")
525 Upload.projectB.query("UPDATE queue_build SET queue = %s WHERE filename = '%s' AND queue = %s" % (une_q, f, emb_q))
526 Upload.projectB.query("COMMIT WORK")
528 for file in Upload.pkg.files.keys():
529 utils.copy(file, os.path.join(dest, file))
533 utils.copy(c, os.path.join(dest, c))
536 utils.copy(k, os.path.join(dest, k))
539 def do_Reject(): sudo("R", _do_Reject, True)
543 print "Rejecting %s..." % (c)
545 Upload.pkg.changes_file = c
548 for suite in Upload.pkg.changes["distribution"].keys():
549 if suite not in Cnf.ValueList("Dinstall::QueueBuildSuites"):
551 dest_dir = Cnf["Dir::QueueBuild"]
552 if Cnf.FindB("Dinstall::SecurityQueueBuild"):
553 dest_dir = os.path.join(dest_dir, suite)
554 for file in Upload.pkg.files.keys():
555 files[os.path.join(dest_dir, file)] = 1
559 aborted = Upload.do_reject()
561 os.unlink(c[:-8]+".dak")
563 Upload.projectB.query(
564 "DELETE FROM queue_build WHERE filename = '%s'" % (f))
567 print "Updating buildd information..."
568 spawn("/org/security.debian.org/dak/config/debian-security/cron.buildd")
570 adv_file = "./advisory.%s" % (advisory)
571 if os.path.exists(adv_file):
574 def do_DropAdvisory():
577 Upload.pkg.changes_file = c
579 del Upload.pkg.changes["adv id"]
580 Upload.dump_vars(os.getcwd())
584 adv_file = "./advisory.%s" % (advisory)
585 if not os.path.exists(adv_file):
586 utils.copy(Cnf["Dir::Templates"]+"/security-install.advisory", adv_file)
587 editor = os.environ.get("EDITOR", "vi")
588 result = os.system("%s %s" % (editor, adv_file))
590 utils.fubar("%s invocation failed for %s." % (editor, adv_file))
593 adv_file = "./advisory.%s" % (advisory)
594 if not os.path.exists(adv_file):
595 adv_file = Cnf["Dir::Templates"]+"/security-install.advisory"
596 print "====\n%s\n====" % (generate_advisory(adv_file))
605 extras = load_args(args)
612 if srcverarches == {}:
613 if not yes_no("Create new advisory %s?" % (advisory)):
614 print "Not doing anything, then"
620 if yes_no("Add %s to %s?" % (c, advisory)):
626 utils.fubar("Must specify an advisory id")
629 utils.fubar("No changes specified")
631 if Options["Approve"]:
634 elif Options["Reject"]:
637 elif Options["Disembargo"]:
640 elif Options["Drop-Advisory"]:
646 opts = ["Approve", "Edit advisory"]
647 if os.path.exists("./advisory.%s" % advisory):
651 if os.getcwd() == Cnf["Dir::Queue::Embargoed"].rstrip("/"):
652 opts.append("Disembargo")
653 opts += ["Show advisory", "Reject", "Quit"]
656 what = prompt(opts, default)
660 elif what == "Approve":
662 elif what == "Edit advisory":
664 elif what == "Show advisory":
666 elif what == "Disembargo":
668 elif what == "Reject":
671 utils.fubar("Impossible answer '%s', wtf?" % (what))
673 ################################################################################
675 if __name__ == '__main__':
678 ################################################################################