command.py 13 KB

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