command.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  1. """module to handle command files
  2. @contact: Debian FTP Master <ftpmaster@debian.org>
  3. @copyright: 2012, Ansgar Burchardt <ansgar@debian.org>
  4. @license: GPL-2+
  5. """
  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.
  10. #
  11. # This program is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. # GNU General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU General Public License along
  17. # with this program; if not, write to the Free Software Foundation, Inc.,
  18. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  19. import apt_pkg
  20. import os
  21. import tempfile
  22. from daklib.config import Config
  23. from daklib.dbconn import *
  24. from daklib.gpg import SignedFile
  25. from daklib.regexes import re_field_package
  26. from daklib.textutils import fix_maintainer
  27. from daklib.utils import gpg_get_key_addresses, send_mail, TemplateSubst
  28. class CommandError(Exception):
  29. pass
  30. class CommandFile(object):
  31. def __init__(self, filename, data, log=None):
  32. if log is None:
  33. from daklib.daklog import Logger
  34. log = Logger()
  35. self.cc = []
  36. self.result = []
  37. self.log = log
  38. self.filename = filename
  39. self.data = data
  40. def _check_replay(self, signed_file, session):
  41. """check for replays
  42. @note: Will commit changes to the database.
  43. @type signed_file: L{daklib.gpg.SignedFile}
  44. @param session: database session
  45. """
  46. # Mark commands file as seen to prevent replays.
  47. signature_history = SignatureHistory.from_signed_file(signed_file)
  48. session.add(signature_history)
  49. session.commit()
  50. def _quote_section(self, section):
  51. lines = []
  52. for l in str(section).splitlines():
  53. lines.append("> {0}".format(l))
  54. return "\n".join(lines)
  55. def _evaluate_sections(self, sections, session):
  56. session.rollback()
  57. try:
  58. while True:
  59. sections.next()
  60. section = sections.section
  61. self.result.append(self._quote_section(section))
  62. action = section.get('Action', None)
  63. if action is None:
  64. raise CommandError('Encountered section without Action field')
  65. if action == 'dm':
  66. self.action_dm(self.fingerprint, section, session)
  67. elif action == 'dm-remove':
  68. self.action_dm_remove(self.fingerprint, section, session)
  69. elif action == 'dm-migrate':
  70. self.action_dm_migrate(self.fingerprint, section, session)
  71. elif action == 'break-the-archive':
  72. self.action_break_the_archive(self.fingerprint, section, session)
  73. else:
  74. raise CommandError('Unknown action: {0}'.format(action))
  75. self.result.append('')
  76. except StopIteration:
  77. pass
  78. finally:
  79. session.rollback()
  80. def _notify_uploader(self):
  81. cnf = Config()
  82. bcc = 'X-DAK: dak process-command'
  83. if 'Dinstall::Bcc' in cnf:
  84. bcc = '{0}\nBcc: {1}'.format(bcc, cnf['Dinstall::Bcc'])
  85. cc = set(fix_maintainer(address)[1] for address in self.cc)
  86. subst = {
  87. '__DAK_ADDRESS__': cnf['Dinstall::MyEmailAddress'],
  88. '__MAINTAINER_TO__': fix_maintainer(self.uploader)[1],
  89. '__CC__': ", ".join(cc),
  90. '__BCC__': bcc,
  91. '__RESULTS__': "\n".join(self.result),
  92. '__FILENAME__': self.filename,
  93. }
  94. message = TemplateSubst(subst, os.path.join(cnf['Dir::Templates'], 'process-command.processed'))
  95. send_mail(message)
  96. def evaluate(self):
  97. """evaluate commands file
  98. @rtype: bool
  99. @returns: C{True} if the file was processed sucessfully,
  100. C{False} otherwise
  101. """
  102. result = True
  103. session = DBConn().session()
  104. keyrings = session.query(Keyring).filter_by(active=True).order_by(Keyring.priority)
  105. keyring_files = [k.keyring_name for k in keyrings]
  106. signed_file = SignedFile(self.data, keyring_files)
  107. if not signed_file.valid:
  108. self.log.log(['invalid signature', self.filename])
  109. return False
  110. self.fingerprint = session.query(Fingerprint).filter_by(fingerprint=signed_file.primary_fingerprint).one()
  111. if self.fingerprint.keyring is None:
  112. self.log.log(['singed by key in unknown keyring', self.filename])
  113. return False
  114. assert self.fingerprint.keyring.active
  115. self.log.log(['processing', self.filename, 'signed-by={0}'.format(self.fingerprint.fingerprint)])
  116. with tempfile.TemporaryFile() as fh:
  117. fh.write(signed_file.contents)
  118. fh.seek(0)
  119. sections = apt_pkg.TagFile(fh)
  120. self.uploader = None
  121. addresses = gpg_get_key_addresses(self.fingerprint.fingerprint)
  122. if len(addresses) > 0:
  123. self.uploader = addresses[0]
  124. try:
  125. sections.next()
  126. section = sections.section
  127. if 'Uploader' in section:
  128. self.uploader = section['Uploader']
  129. if 'Cc' in section:
  130. self.cc.append(section['Cc'])
  131. # TODO: Verify first section has valid Archive field
  132. if 'Archive' not in section:
  133. raise CommandError('No Archive field in first section.')
  134. # TODO: send mail when we detected a replay.
  135. self._check_replay(signed_file, session)
  136. self._evaluate_sections(sections, session)
  137. self.result.append('')
  138. except Exception as e:
  139. self.log.log(['ERROR', e])
  140. self.result.append("There was an error processing this section. No changes were committed.\nDetails:\n{0}".format(e))
  141. result = False
  142. self._notify_uploader()
  143. session.close()
  144. return result
  145. def _split_packages(self, value):
  146. names = value.split()
  147. for name in names:
  148. if not re_field_package.match(name):
  149. raise CommandError('Invalid package name "{0}"'.format(name))
  150. return names
  151. def action_dm(self, fingerprint, section, session):
  152. cnf = Config()
  153. if 'Command::DM::AdminKeyrings' not in cnf \
  154. or 'Command::DM::ACL' not in cnf \
  155. or 'Command::DM::Keyrings' not in cnf:
  156. raise CommandError('DM command is not configured for this archive.')
  157. allowed_keyrings = cnf.value_list('Command::DM::AdminKeyrings')
  158. if fingerprint.keyring.keyring_name not in allowed_keyrings:
  159. raise CommandError('Key {0} is not allowed to set DM'.format(fingerprint.fingerprint))
  160. acl_name = cnf.get('Command::DM::ACL', 'dm')
  161. acl = session.query(ACL).filter_by(name=acl_name).one()
  162. fpr_hash = section['Fingerprint'].translate(None, ' ')
  163. fpr = session.query(Fingerprint).filter_by(fingerprint=fpr_hash).first()
  164. if fpr is None:
  165. raise CommandError('Unknown fingerprint {0}'.format(fpr_hash))
  166. if fpr.keyring is None or fpr.keyring.keyring_name not in cnf.value_list('Command::DM::Keyrings'):
  167. raise CommandError('Key {0} is not in DM keyring.'.format(fpr.fingerprint))
  168. addresses = gpg_get_key_addresses(fpr.fingerprint)
  169. if len(addresses) > 0:
  170. self.cc.append(addresses[0])
  171. self.log.log(['dm', 'fingerprint', fpr.fingerprint])
  172. self.result.append('Fingerprint: {0}'.format(fpr.fingerprint))
  173. if len(addresses) > 0:
  174. self.log.log(['dm', 'uid', addresses[0]])
  175. self.result.append('Uid: {0}'.format(addresses[0]))
  176. for source in self._split_packages(section.get('Allow', '')):
  177. # Check for existance of source package to catch typos
  178. if session.query(DBSource).filter_by(source=source).first() is None:
  179. raise CommandError('Tried to grant permissions for unknown source package: {0}'.format(source))
  180. if session.query(ACLPerSource).filter_by(acl=acl, fingerprint=fpr, source=source).first() is None:
  181. aps = ACLPerSource()
  182. aps.acl = acl
  183. aps.fingerprint = fpr
  184. aps.source = source
  185. aps.created_by = fingerprint
  186. aps.reason = section.get('Reason')
  187. session.add(aps)
  188. self.log.log(['dm', 'allow', fpr.fingerprint, source])
  189. self.result.append('Allowed: {0}'.format(source))
  190. else:
  191. self.result.append('Already-Allowed: {0}'.format(source))
  192. session.flush()
  193. for source in self._split_packages(section.get('Deny', '')):
  194. count = session.query(ACLPerSource).filter_by(acl=acl, fingerprint=fpr, source=source).delete()
  195. if count == 0:
  196. raise CommandError('Tried to remove upload permissions for package {0}, '
  197. 'but no upload permissions were granted before.'.format(source))
  198. self.log.log(['dm', 'deny', fpr.fingerprint, source])
  199. self.result.append('Denied: {0}'.format(source))
  200. session.commit()
  201. def _action_dm_admin_common(self, fingerprint, section, session):
  202. cnf = Config()
  203. if 'Command::DM-Admin::AdminFingerprints' not in cnf \
  204. or 'Command::DM::ACL' not in cnf:
  205. raise CommandError('DM admin command is not configured for this archive.')
  206. allowed_fingerprints = cnf.value_list('Command::DM-Admin::AdminFingerprints')
  207. if fingerprint.fingerprint not in allowed_fingerprints:
  208. raise CommandError('Key {0} is not allowed to admin DM'.format(fingerprint.fingerprint))
  209. def action_dm_remove(self, fingerprint, section, session):
  210. self._action_dm_admin_common(fingerprint, section, session)
  211. cnf = Config()
  212. acl_name = cnf.get('Command::DM::ACL', 'dm')
  213. acl = session.query(ACL).filter_by(name=acl_name).one()
  214. fpr_hash = section['Fingerprint'].translate(None, ' ')
  215. fpr = session.query(Fingerprint).filter_by(fingerprint=fpr_hash).first()
  216. if fpr is None:
  217. self.result.append('Unknown fingerprint: {0}\nNo action taken.'.format(fpr_hash))
  218. return
  219. self.log.log(['dm-remove', fpr.fingerprint])
  220. count = 0
  221. for entry in session.query(ACLPerSource).filter_by(acl=acl, fingerprint=fpr):
  222. self.log.log(['dm-remove', fpr.fingerprint, 'source={0}'.format(entry.source)])
  223. count += 1
  224. session.delete(entry)
  225. self.result.append('Removed: {0}.\n{1} acl entries removed.'.format(fpr.fingerprint, count))
  226. session.commit()
  227. def action_dm_migrate(self, fingerprint, section, session):
  228. self._action_dm_admin_common(fingerprint, section, session)
  229. cnf = Config()
  230. acl_name = cnf.get('Command::DM::ACL', 'dm')
  231. acl = session.query(ACL).filter_by(name=acl_name).one()
  232. fpr_hash_from = section['From'].translate(None, ' ')
  233. fpr_from = session.query(Fingerprint).filter_by(fingerprint=fpr_hash_from).first()
  234. if fpr_from is None:
  235. self.result.append('Unknown fingerprint (From): {0}\nNo action taken.'.format(fpr_hash_from))
  236. return
  237. fpr_hash_to = section['To'].translate(None, ' ')
  238. fpr_to = session.query(Fingerprint).filter_by(fingerprint=fpr_hash_to).first()
  239. if fpr_to is None:
  240. self.result.append('Unknown fingerprint (To): {0}\nNo action taken.'.format(fpr_hash_to))
  241. return
  242. if fpr_to.keyring is None or fpr_to.keyring.keyring_name not in cnf.value_list('Command::DM::Keyrings'):
  243. self.result.append('Key (To) {0} is not in DM keyring.\nNo action taken.'.format(fpr_to.fingerprint))
  244. return
  245. self.log.log(['dm-migrate', 'from={0}'.format(fpr_hash_from), 'to={0}'.format(fpr_hash_to)])
  246. sources = []
  247. for entry in session.query(ACLPerSource).filter_by(acl=acl, fingerprint=fpr_from):
  248. self.log.log(['dm-migrate', 'from={0}'.format(fpr_hash_from), 'to={0}'.format(fpr_hash_to), 'source={0}'.format(entry.source)])
  249. entry.fingerprint = fpr_to
  250. sources.append(entry.source)
  251. self.result.append('Migrated {0} to {1}.\n{2} acl entries changed: {3}'.format(fpr_hash_from, fpr_hash_to, len(sources), ", ".join(sources)))
  252. session.commit()
  253. def action_break_the_archive(self, fingerprint, section, session):
  254. name = 'Dave'
  255. uid = fingerprint.uid
  256. if uid is not None and uid.name is not None:
  257. name = uid.name.split()[0]
  258. self.result.append("DAK9000: I'm sorry, {0}. I'm afraid I can't do that.".format(name))