command.py 13 KB

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