checks.py 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026
  1. # Copyright (C) 2012, Ansgar Burchardt <ansgar@debian.org>
  2. #
  3. # Parts based on code that is
  4. # Copyright (C) 2001-2006, James Troup <james@nocrew.org>
  5. # Copyright (C) 2009-2010, Joerg Jaspert <joerg@debian.org>
  6. #
  7. # This program is free software; you can redistribute it and/or modify
  8. # it under the terms of the GNU General Public License as published by
  9. # the Free Software Foundation; either version 2 of the License, or
  10. # (at your option) any later version.
  11. #
  12. # This program is distributed in the hope that it will be useful,
  13. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. # GNU General Public License for more details.
  16. #
  17. # You should have received a copy of the GNU General Public License along
  18. # with this program; if not, write to the Free Software Foundation, Inc.,
  19. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  20. """module provided pre-acceptance tests
  21. Please read the documentation for the :class:`Check` class for the interface.
  22. """
  23. from daklib.config import Config
  24. from daklib.dbconn import *
  25. import daklib.dbconn as dbconn
  26. from daklib.regexes import *
  27. from daklib.textutils import fix_maintainer, ParseMaintError
  28. import daklib.lintian as lintian
  29. import daklib.utils as utils
  30. import daklib.upload
  31. import apt_inst
  32. import apt_pkg
  33. from apt_pkg import version_compare
  34. from collections.abc import Iterable
  35. import datetime
  36. import os
  37. import subprocess
  38. import tempfile
  39. import textwrap
  40. import time
  41. from typing import TYPE_CHECKING
  42. import yaml
  43. if TYPE_CHECKING:
  44. import daklib.archive
  45. import re
  46. def check_fields_for_valid_utf8(filename, control):
  47. """Check all fields of a control file for valid UTF-8"""
  48. for field in control.keys():
  49. try:
  50. # Access the field value to make `TagSection` try to decode it.
  51. # We should also do the same for the field name, but this requires
  52. # https://bugs.debian.org/995118 to be fixed.
  53. # TODO: make sure the field name `field` is valid UTF-8 too
  54. control[field]
  55. except UnicodeDecodeError:
  56. raise Reject('{0}: The {1} field is not valid UTF-8'.format(filename, field))
  57. class Reject(Exception):
  58. """exception raised by failing checks"""
  59. pass
  60. class RejectExternalFilesMismatch(Reject):
  61. """exception raised by failing the external hashes check"""
  62. def __str__(self):
  63. return "'%s' has mismatching %s from the external files db ('%s' [current] vs '%s' [external])" % self.args[:4]
  64. class RejectACL(Reject):
  65. """exception raise by failing ACL checks"""
  66. def __init__(self, acl, reason):
  67. self.acl = acl
  68. self.reason = reason
  69. def __str__(self):
  70. return "ACL {0}: {1}".format(self.acl.name, self.reason)
  71. class Check:
  72. """base class for checks
  73. checks are called by :class:`daklib.archive.ArchiveUpload`. Failing tests should
  74. raise a :exc:`daklib.checks.Reject` exception including a human-readable
  75. description why the upload should be rejected.
  76. """
  77. def check(self, upload: 'daklib.archive.ArchiveUpload'):
  78. """do checks
  79. :param upload: upload to check
  80. :raises Reject: upload should be rejected
  81. """
  82. raise NotImplementedError
  83. def per_suite_check(self, upload: 'daklib.archive.ArchiveUpload', suite: Suite):
  84. """do per-suite checks
  85. :param upload: upload to check
  86. :param suite: suite to check
  87. :raises Reject: upload should be rejected
  88. """
  89. raise NotImplementedError
  90. @property
  91. def forcable(self) -> bool:
  92. """allow to force ignore failing test
  93. :const:`True` if it is acceptable to force ignoring a failing test,
  94. :const:`False` otherwise
  95. """
  96. return False
  97. class SignatureAndHashesCheck(Check):
  98. """Check signature of changes and dsc file (if included in upload)
  99. Make sure the signature is valid and done by a known user.
  100. """
  101. def check_replay(self, upload) -> bool:
  102. # Use private session as we want to remember having seen the .changes
  103. # in all cases.
  104. session = upload.session
  105. history = SignatureHistory.from_signed_file(upload.changes)
  106. r = history.query(session)
  107. if r is not None:
  108. raise Reject('Signature for changes file was already seen at {0}.\nPlease refresh the signature of the changes file if you want to upload it again.'.format(r.seen))
  109. return True
  110. def check(self, upload):
  111. allow_source_untrusted_sig_keys = Config().value_list('Dinstall::AllowSourceUntrustedSigKeys')
  112. changes = upload.changes
  113. if not changes.valid_signature:
  114. raise Reject("Signature for .changes not valid.")
  115. self.check_replay(upload)
  116. self._check_hashes(upload, changes.filename, changes.files.values())
  117. source = None
  118. try:
  119. source = changes.source
  120. except Exception as e:
  121. raise Reject("Invalid dsc file: {0}".format(e))
  122. if source is not None:
  123. if changes.primary_fingerprint not in allow_source_untrusted_sig_keys:
  124. if not source.valid_signature:
  125. raise Reject("Signature for .dsc not valid.")
  126. if source.primary_fingerprint != changes.primary_fingerprint:
  127. raise Reject(".changes and .dsc not signed by the same key.")
  128. self._check_hashes(upload, source.filename, source.files.values())
  129. if upload.fingerprint is None or upload.fingerprint.uid is None:
  130. raise Reject(".changes signed by unknown key.")
  131. def _check_hashes(self, upload: 'daklib.archive.ArchiveUpload', filename: str, files: Iterable[daklib.upload.HashedFile]):
  132. """Make sure hashes match existing files
  133. :param upload: upload we are processing
  134. :param filename: name of the file the expected hash values are taken from
  135. :param files: files to check the hashes for
  136. """
  137. try:
  138. for f in files:
  139. f.check(upload.directory)
  140. except daklib.upload.FileDoesNotExist as e:
  141. raise Reject('{0}: {1}\n'
  142. 'Perhaps you need to include the file in your upload?\n\n'
  143. 'If the orig tarball is missing, the -sa flag for dpkg-buildpackage will be your friend.'
  144. .format(filename, str(e)))
  145. except daklib.upload.UploadException as e:
  146. raise Reject('{0}: {1}'.format(filename, str(e)))
  147. class WeakSignatureCheck(Check):
  148. """Check that .changes and .dsc are not signed using a weak algorithm"""
  149. def check(self, upload):
  150. changes = upload.changes
  151. if changes.weak_signature:
  152. raise Reject("The .changes was signed using a weak algorithm (such as SHA-1)")
  153. source = changes.source
  154. if source is not None:
  155. if source.weak_signature:
  156. raise Reject("The source package was signed using a weak algorithm (such as SHA-1)")
  157. return True
  158. class SignatureTimestampCheck(Check):
  159. """Check timestamp of .changes signature"""
  160. def check(self, upload):
  161. changes = upload.changes
  162. now = datetime.datetime.utcnow()
  163. timestamp = changes.signature_timestamp
  164. age = now - timestamp
  165. age_max = datetime.timedelta(days=365)
  166. age_min = datetime.timedelta(days=-7)
  167. if age > age_max:
  168. raise Reject('{0}: Signature from {1} is too old (maximum age is {2} days)'.format(changes.filename, timestamp, age_max.days))
  169. if age < age_min:
  170. raise Reject('{0}: Signature from {1} is too far in the future (tolerance is {2} days)'.format(changes.filename, timestamp, abs(age_min.days)))
  171. return True
  172. class ChangesCheck(Check):
  173. """Check changes file for syntax errors."""
  174. def check(self, upload):
  175. changes = upload.changes
  176. control = changes.changes
  177. fn = changes.filename
  178. for field in ('Distribution', 'Source', 'Architecture', 'Version', 'Maintainer', 'Files', 'Changes'):
  179. if field not in control:
  180. raise Reject('{0}: misses mandatory field {1}'.format(fn, field))
  181. if len(changes.binaries) > 0:
  182. for field in ('Binary', 'Description'):
  183. if field not in control:
  184. raise Reject('{0}: binary upload requires {1} field'.format(fn, field))
  185. check_fields_for_valid_utf8(fn, control)
  186. source_match = re_field_source.match(control['Source'])
  187. if not source_match:
  188. raise Reject('{0}: Invalid Source field'.format(fn))
  189. version_match = re_field_version.match(control['Version'])
  190. if not version_match:
  191. raise Reject('{0}: Invalid Version field'.format(fn))
  192. version_without_epoch = version_match.group('without_epoch')
  193. match = re_file_changes.match(fn)
  194. if not match:
  195. raise Reject('{0}: Does not match re_file_changes'.format(fn))
  196. if match.group('package') != source_match.group('package'):
  197. raise Reject('{0}: Filename does not match Source field'.format(fn))
  198. if match.group('version') != version_without_epoch:
  199. raise Reject('{0}: Filename does not match Version field'.format(fn))
  200. for bn in changes.binary_names:
  201. if not re_field_package.match(bn):
  202. raise Reject('{0}: Invalid binary package name {1}'.format(fn, bn))
  203. if changes.sourceful and changes.source is None:
  204. raise Reject("Changes has architecture source, but no source found.")
  205. if changes.source is not None and not changes.sourceful:
  206. raise Reject("Upload includes source, but changes does not say so.")
  207. try:
  208. fix_maintainer(changes.changes['Maintainer'])
  209. except ParseMaintError as e:
  210. raise Reject('{0}: Failed to parse Maintainer field: {1}'.format(changes.filename, e))
  211. try:
  212. changed_by = changes.changes.get('Changed-By')
  213. if changed_by is not None:
  214. fix_maintainer(changed_by)
  215. except ParseMaintError as e:
  216. raise Reject('{0}: Failed to parse Changed-By field: {1}'.format(changes.filename, e))
  217. try:
  218. changes.byhand_files
  219. except daklib.upload.InvalidChangesException as e:
  220. raise Reject('{0}'.format(e))
  221. if len(changes.files) == 0:
  222. raise Reject("Changes includes no files.")
  223. for bugnum in changes.closed_bugs:
  224. if not re_isanum.match(bugnum):
  225. raise Reject('{0}: "{1}" in Closes field is not a number'.format(changes.filename, bugnum))
  226. return True
  227. class ExternalHashesCheck(Check):
  228. """Checks hashes in .changes and .dsc against an external database."""
  229. def check_single(self, session, f):
  230. q = session.execute("SELECT size, md5sum, sha1sum, sha256sum FROM external_files WHERE filename LIKE :pattern", {'pattern': '%/{}'.format(f.filename)})
  231. (ext_size, ext_md5sum, ext_sha1sum, ext_sha256sum) = q.fetchone() or (None, None, None, None)
  232. if not ext_size:
  233. return
  234. if ext_size != f.size:
  235. raise RejectExternalFilesMismatch(f.filename, 'size', f.size, ext_size)
  236. if ext_md5sum != f.md5sum:
  237. raise RejectExternalFilesMismatch(f.filename, 'md5sum', f.md5sum, ext_md5sum)
  238. if ext_sha1sum != f.sha1sum:
  239. raise RejectExternalFilesMismatch(f.filename, 'sha1sum', f.sha1sum, ext_sha1sum)
  240. if ext_sha256sum != f.sha256sum:
  241. raise RejectExternalFilesMismatch(f.filename, 'sha256sum', f.sha256sum, ext_sha256sum)
  242. def check(self, upload):
  243. cnf = Config()
  244. if not cnf.use_extfiles:
  245. return
  246. session = upload.session
  247. changes = upload.changes
  248. for f in changes.files.values():
  249. self.check_single(session, f)
  250. source = changes.source
  251. if source is not None:
  252. for f in source.files.values():
  253. self.check_single(session, f)
  254. class BinaryCheck(Check):
  255. """Check binary packages for syntax errors."""
  256. def check(self, upload):
  257. debug_deb_name_postfix = "-dbgsym"
  258. # XXX: Handle dynamic debug section name here
  259. self._architectures = set()
  260. for binary in upload.changes.binaries:
  261. self.check_binary(upload, binary)
  262. for arch in upload.changes.architectures:
  263. if arch == 'source':
  264. continue
  265. if arch not in self._architectures:
  266. raise Reject('{}: Architecture field includes {}, but no binary packages for {} are included in the upload'.format(upload.changes.filename, arch, arch))
  267. binaries = {binary.control['Package']: binary
  268. for binary in upload.changes.binaries}
  269. for name, binary in list(binaries.items()):
  270. if name in upload.changes.binary_names:
  271. # Package is listed in Binary field. Everything is good.
  272. pass
  273. elif daklib.utils.is_in_debug_section(binary.control):
  274. # If we have a binary package in the debug section, we
  275. # can allow it to not be present in the Binary field
  276. # in the .changes file, so long as its name (without
  277. # -dbgsym) is present in the Binary list.
  278. if not name.endswith(debug_deb_name_postfix):
  279. raise Reject('Package {0} is in the debug section, but '
  280. 'does not end in {1}.'.format(name, debug_deb_name_postfix))
  281. # Right, so, it's named properly, let's check that
  282. # the corresponding package is in the Binary list
  283. origin_package_name = name[:-len(debug_deb_name_postfix)]
  284. if origin_package_name not in upload.changes.binary_names:
  285. raise Reject(
  286. "Debug package {debug}'s corresponding binary package "
  287. "{origin} is not present in the Binary field.".format(
  288. debug=name, origin=origin_package_name))
  289. else:
  290. # Someone was a nasty little hacker and put a package
  291. # into the .changes that isn't in debian/control. Bad,
  292. # bad person.
  293. raise Reject('Package {0} is not mentioned in Binary field in changes'.format(name))
  294. return True
  295. def check_binary(self, upload, binary):
  296. fn = binary.hashed_file.filename
  297. control = binary.control
  298. for field in ('Package', 'Architecture', 'Version', 'Description', 'Section'):
  299. if field not in control:
  300. raise Reject('{0}: Missing mandatory field {1}.'.format(fn, field))
  301. check_fields_for_valid_utf8(fn, control)
  302. # check fields
  303. package = control['Package']
  304. if not re_field_package.match(package):
  305. raise Reject('{0}: Invalid Package field'.format(fn))
  306. version = control['Version']
  307. version_match = re_field_version.match(version)
  308. if not version_match:
  309. raise Reject('{0}: Invalid Version field'.format(fn))
  310. version_without_epoch = version_match.group('without_epoch')
  311. architecture = control['Architecture']
  312. if architecture not in upload.changes.architectures:
  313. raise Reject('{0}: Architecture not in Architecture field in changes file'.format(fn))
  314. if architecture == 'source':
  315. raise Reject('{0}: Architecture "source" invalid for binary packages'.format(fn))
  316. self._architectures.add(architecture)
  317. source = control.get('Source')
  318. if source is not None and not re_field_source.match(source):
  319. raise Reject('{0}: Invalid Source field'.format(fn))
  320. # check filename
  321. match = re_file_binary.match(fn)
  322. if package != match.group('package'):
  323. raise Reject('{0}: filename does not match Package field'.format(fn))
  324. if version_without_epoch != match.group('version'):
  325. raise Reject('{0}: filename does not match Version field'.format(fn))
  326. if architecture != match.group('architecture'):
  327. raise Reject('{0}: filename does not match Architecture field'.format(fn))
  328. # check dependency field syntax
  329. def check_dependency_field(
  330. field, control,
  331. dependency_parser=apt_pkg.parse_depends,
  332. allow_alternatives=True,
  333. allow_relations=('', '<', '<=', '=', '>=', '>')):
  334. value = control.get(field)
  335. if value is not None:
  336. if value.strip() == '':
  337. raise Reject('{0}: empty {1} field'.format(fn, field))
  338. try:
  339. depends = dependency_parser(value)
  340. except:
  341. raise Reject('{0}: APT could not parse {1} field'.format(fn, field))
  342. for group in depends:
  343. if not allow_alternatives and len(group) != 1:
  344. raise Reject('{0}: {1}: alternatives are not allowed'.format(fn, field))
  345. for dep_pkg, dep_ver, dep_rel in group:
  346. if dep_rel not in allow_relations:
  347. raise Reject('{}: {}: depends on {}, but only relations {} are allowed for this field'.format(fn, field, " ".join(dep_pkg, dep_rel, dep_ver), allow_relations))
  348. for field in ('Breaks', 'Conflicts', 'Depends', 'Enhances', 'Pre-Depends',
  349. 'Recommends', 'Replaces', 'Suggests'):
  350. check_dependency_field(field, control)
  351. check_dependency_field("Provides", control,
  352. allow_alternatives=False,
  353. allow_relations=('', '='))
  354. check_dependency_field("Built-Using", control,
  355. dependency_parser=apt_pkg.parse_src_depends,
  356. allow_alternatives=False,
  357. allow_relations=('=',))
  358. _DEB_ALLOWED_MEMBERS = {
  359. "debian-binary",
  360. *(f"control.tar.{comp}" for comp in ("gz", "xz")),
  361. *(f"data.tar.{comp}" for comp in ("gz", "bz2", "xz")),
  362. }
  363. class BinaryMembersCheck(Check):
  364. """check members of .deb file"""
  365. def check(self, upload):
  366. for binary in upload.changes.binaries:
  367. filename = binary.hashed_file.filename
  368. path = os.path.join(upload.directory, filename)
  369. self._check_binary(filename, path)
  370. return True
  371. def _check_binary(self, filename: str, path: str) -> None:
  372. deb = apt_inst.DebFile(path)
  373. members = set(member.name for member in deb.getmembers())
  374. if blocked_members := members - _DEB_ALLOWED_MEMBERS:
  375. raise Reject(f"{filename}: Contains blocked members {', '.join(blocked_members)}")
  376. class BinaryTimestampCheck(Check):
  377. """check timestamps of files in binary packages
  378. Files in the near future cause ugly warnings and extreme time travel
  379. can cause errors on extraction.
  380. """
  381. def check(self, upload):
  382. cnf = Config()
  383. future_cutoff = time.time() + cnf.find_i('Dinstall::FutureTimeTravelGrace', 24 * 3600)
  384. past_cutoff = time.mktime(time.strptime(cnf.find('Dinstall::PastCutoffYear', '1975'), '%Y'))
  385. class TarTime:
  386. def __init__(self):
  387. self.future_files: dict[str, int] = {}
  388. self.past_files: dict[str, int] = {}
  389. def callback(self, member, data) -> None:
  390. if member.mtime > future_cutoff:
  391. self.future_files[member.name] = member.mtime
  392. elif member.mtime < past_cutoff:
  393. self.past_files[member.name] = member.mtime
  394. def format_reason(filename, direction, files) -> str:
  395. reason = "{0}: has {1} file(s) with a timestamp too far in the {2}:\n".format(filename, len(files), direction)
  396. for fn, ts in files.items():
  397. reason += " {0} ({1})".format(fn, time.ctime(ts))
  398. return reason
  399. for binary in upload.changes.binaries:
  400. filename = binary.hashed_file.filename
  401. path = os.path.join(upload.directory, filename)
  402. deb = apt_inst.DebFile(path)
  403. tar = TarTime()
  404. for archive in (deb.control, deb.data):
  405. archive.go(tar.callback)
  406. if tar.future_files:
  407. raise Reject(format_reason(filename, 'future', tar.future_files))
  408. if tar.past_files:
  409. raise Reject(format_reason(filename, 'past', tar.past_files))
  410. class SourceCheck(Check):
  411. """Check source package for syntax errors."""
  412. def check_filename(self, control, filename, regex: re.Pattern) -> None:
  413. # In case we have an .orig.tar.*, we have to strip the Debian revison
  414. # from the version number. So handle this special case first.
  415. is_orig = True
  416. match = re_file_orig.match(filename)
  417. if not match:
  418. is_orig = False
  419. match = regex.match(filename)
  420. if not match:
  421. raise Reject('{0}: does not match regular expression for source filenames'.format(filename))
  422. if match.group('package') != control['Source']:
  423. raise Reject('{0}: filename does not match Source field'.format(filename))
  424. version = control['Version']
  425. if is_orig:
  426. upstream_match = re_field_version_upstream.match(version)
  427. if not upstream_match:
  428. raise Reject('{0}: Source package includes upstream tarball, but {1} has no Debian revision.'.format(filename, version))
  429. version = upstream_match.group('upstream')
  430. version_match = re_field_version.match(version)
  431. version_without_epoch = version_match.group('without_epoch')
  432. if match.group('version') != version_without_epoch:
  433. raise Reject('{0}: filename does not match Version field'.format(filename))
  434. def check(self, upload):
  435. if upload.changes.source is None:
  436. if upload.changes.sourceful:
  437. raise Reject("{}: Architecture field includes source, but no source package is included in the upload".format(upload.changes.filename))
  438. return True
  439. if not upload.changes.sourceful:
  440. raise Reject("{}: Architecture field does not include source, but a source package is included in the upload".format(upload.changes.filename))
  441. changes = upload.changes.changes
  442. source = upload.changes.source
  443. control = source.dsc
  444. dsc_fn = source._dsc_file.filename
  445. check_fields_for_valid_utf8(dsc_fn, control)
  446. # check fields
  447. if not re_field_package.match(control['Source']):
  448. raise Reject('{0}: Invalid Source field'.format(dsc_fn))
  449. if control['Source'] != changes['Source']:
  450. raise Reject('{0}: Source field does not match Source field in changes'.format(dsc_fn))
  451. if control['Version'] != changes['Version']:
  452. raise Reject('{0}: Version field does not match Version field in changes'.format(dsc_fn))
  453. # check filenames
  454. self.check_filename(control, dsc_fn, re_file_dsc)
  455. for f in source.files.values():
  456. self.check_filename(control, f.filename, re_file_source)
  457. # check dependency field syntax
  458. for field in ('Build-Conflicts', 'Build-Conflicts-Indep', 'Build-Depends', 'Build-Depends-Arch', 'Build-Depends-Indep'):
  459. value = control.get(field)
  460. if value is not None:
  461. if value.strip() == '':
  462. raise Reject('{0}: empty {1} field'.format(dsc_fn, field))
  463. try:
  464. apt_pkg.parse_src_depends(value)
  465. except Exception as e:
  466. raise Reject('{0}: APT could not parse {1} field: {2}'.format(dsc_fn, field, e))
  467. rejects = utils.check_dsc_files(dsc_fn, control, list(source.files.keys()))
  468. if len(rejects) > 0:
  469. raise Reject("\n".join(rejects))
  470. return True
  471. class SingleDistributionCheck(Check):
  472. """Check that the .changes targets only a single distribution."""
  473. def check(self, upload):
  474. if len(upload.changes.distributions) != 1:
  475. raise Reject("Only uploads to a single distribution are allowed.")
  476. class ACLCheck(Check):
  477. """Check the uploader is allowed to upload the packages in .changes"""
  478. def _does_hijack(self, session, upload, suite):
  479. # Try to catch hijacks.
  480. # This doesn't work correctly. Uploads to experimental can still
  481. # "hijack" binaries from unstable. Also one can hijack packages
  482. # via buildds (but people who try this should not be DMs).
  483. for binary_name in upload.changes.binary_names:
  484. binaries = session.query(DBBinary).join(DBBinary.source) \
  485. .filter(DBBinary.suites.contains(suite)) \
  486. .filter(DBBinary.package == binary_name)
  487. for binary in binaries:
  488. if binary.source.source != upload.changes.changes['Source']:
  489. return True, binary.package, binary.source.source
  490. return False, None, None
  491. def _check_acl(self, session, upload, acl):
  492. source_name = upload.changes.source_name
  493. if acl.match_fingerprint and upload.fingerprint not in acl.fingerprints:
  494. return None, None
  495. if acl.match_keyring is not None and upload.fingerprint.keyring != acl.match_keyring:
  496. return None, None
  497. if not acl.allow_new:
  498. if upload.new:
  499. return False, "NEW uploads are not allowed"
  500. for f in upload.changes.files.values():
  501. if f.section == 'byhand' or f.section.startswith("raw-"):
  502. return False, "BYHAND uploads are not allowed"
  503. if not acl.allow_source and upload.changes.source is not None:
  504. return False, "sourceful uploads are not allowed"
  505. binaries = upload.changes.binaries
  506. if len(binaries) != 0:
  507. if not acl.allow_binary:
  508. return False, "binary uploads are not allowed"
  509. if upload.changes.source is None and not acl.allow_binary_only:
  510. return False, "binary-only uploads are not allowed"
  511. if not acl.allow_binary_all:
  512. uploaded_arches = set(upload.changes.architectures)
  513. uploaded_arches.discard('source')
  514. allowed_arches = set(a.arch_string for a in acl.architectures)
  515. forbidden_arches = uploaded_arches - allowed_arches
  516. if len(forbidden_arches) != 0:
  517. return False, "uploads for architecture(s) {0} are not allowed".format(", ".join(forbidden_arches))
  518. if not acl.allow_hijack:
  519. for suite in upload.final_suites:
  520. does_hijack, hijacked_binary, hijacked_from = self._does_hijack(session, upload, suite)
  521. if does_hijack:
  522. return False, "hijacks are not allowed (binary={0}, other-source={1})".format(hijacked_binary, hijacked_from)
  523. acl_per_source = session.query(ACLPerSource).filter_by(acl=acl, fingerprint=upload.fingerprint, source=source_name).first()
  524. if acl.allow_per_source:
  525. if acl_per_source is None:
  526. return False, "not allowed to upload source package '{0}'".format(source_name)
  527. if acl.deny_per_source and acl_per_source is not None:
  528. return False, acl_per_source.reason or "forbidden to upload source package '{0}'".format(source_name)
  529. return True, None
  530. def check(self, upload):
  531. session = upload.session
  532. fingerprint = upload.fingerprint
  533. keyring = fingerprint.keyring
  534. if keyring is None:
  535. raise Reject('No keyring for fingerprint {0}'.format(fingerprint.fingerprint))
  536. if not keyring.active:
  537. raise Reject('Keyring {0} is not active'.format(keyring.name))
  538. acl = fingerprint.acl or keyring.acl
  539. if acl is None:
  540. raise Reject('No ACL for fingerprint {0}'.format(fingerprint.fingerprint))
  541. result, reason = self._check_acl(session, upload, acl)
  542. if not result:
  543. raise RejectACL(acl, reason)
  544. for acl in session.query(ACL).filter_by(is_global=True):
  545. result, reason = self._check_acl(session, upload, acl)
  546. if result is False:
  547. raise RejectACL(acl, reason)
  548. return True
  549. def per_suite_check(self, upload, suite):
  550. acls = suite.acls
  551. if len(acls) != 0:
  552. accept = False
  553. for acl in acls:
  554. result, reason = self._check_acl(upload.session, upload, acl)
  555. if result is False:
  556. raise Reject(reason)
  557. accept = accept or result
  558. if not accept:
  559. raise Reject('Not accepted by any per-suite acl (suite={0})'.format(suite.suite_name))
  560. return True
  561. class TransitionCheck(Check):
  562. """check for a transition"""
  563. def check(self, upload):
  564. if not upload.changes.sourceful:
  565. return True
  566. transitions = self.get_transitions()
  567. if transitions is None:
  568. return True
  569. session = upload.session
  570. control = upload.changes.changes
  571. source = re_field_source.match(control['Source']).group('package')
  572. for trans in transitions:
  573. t = transitions[trans]
  574. transition_source = t["source"]
  575. expected = t["new"]
  576. # Will be None if nothing is in testing.
  577. current = get_source_in_suite(transition_source, "testing", session)
  578. if current is not None:
  579. compare = apt_pkg.version_compare(current.version, expected)
  580. if current is None or compare < 0:
  581. # This is still valid, the current version in testing is older than
  582. # the new version we wait for, or there is none in testing yet
  583. # Check if the source we look at is affected by this.
  584. if source in t['packages']:
  585. # The source is affected, lets reject it.
  586. rejectmsg = "{0}: part of the {1} transition.\n\n".format(source, trans)
  587. if current is not None:
  588. currentlymsg = "at version {0}".format(current.version)
  589. else:
  590. currentlymsg = "not present in testing"
  591. rejectmsg += "Transition description: {0}\n\n".format(t["reason"])
  592. rejectmsg += "\n".join(textwrap.wrap("""Your package
  593. is part of a testing transition designed to get {0} migrated (it is
  594. currently {1}, we need version {2}). This transition is managed by the
  595. Release Team, and {3} is the Release-Team member responsible for it.
  596. Please mail debian-release@lists.debian.org or contact {3} directly if you
  597. need further assistance. You might want to upload to experimental until this
  598. transition is done.""".format(transition_source, currentlymsg, expected, t["rm"])))
  599. raise Reject(rejectmsg)
  600. return True
  601. def get_transitions(self):
  602. cnf = Config()
  603. path = cnf.get('Dinstall::ReleaseTransitions', '')
  604. if path == '' or not os.path.exists(path):
  605. return None
  606. with open(path, 'r') as fd:
  607. contents = fd.read()
  608. try:
  609. transitions = yaml.safe_load(contents)
  610. return transitions
  611. except yaml.YAMLError as msg:
  612. utils.warn('Not checking transitions, the transitions file is broken: {0}'.format(msg))
  613. return None
  614. class NoSourceOnlyCheck(Check):
  615. def is_source_only_upload(self, upload) -> bool:
  616. changes = upload.changes
  617. if changes.source is not None and len(changes.binaries) == 0:
  618. return True
  619. return False
  620. """Check for source-only upload
  621. Source-only uploads are only allowed if Dinstall::AllowSourceOnlyUploads is
  622. set. Otherwise they are rejected.
  623. Source-only uploads are only accepted for source packages having a
  624. Package-List field that also lists architectures per package. This
  625. check can be disabled via
  626. Dinstall::AllowSourceOnlyUploadsWithoutPackageList.
  627. Source-only uploads to NEW are only allowed if
  628. Dinstall::AllowSourceOnlyNew is set.
  629. Uploads not including architecture-independent packages are only
  630. allowed if Dinstall::AllowNoArchIndepUploads is set.
  631. """
  632. def check(self, upload):
  633. if not self.is_source_only_upload(upload):
  634. return True
  635. allow_source_only_uploads = Config().find_b('Dinstall::AllowSourceOnlyUploads')
  636. allow_source_only_uploads_without_package_list = Config().find_b('Dinstall::AllowSourceOnlyUploadsWithoutPackageList')
  637. allow_source_only_new = Config().find_b('Dinstall::AllowSourceOnlyNew')
  638. allow_source_only_new_keys = Config().value_list('Dinstall::AllowSourceOnlyNewKeys')
  639. allow_source_only_new_sources = Config().value_list('Dinstall::AllowSourceOnlyNewSources')
  640. allow_no_arch_indep_uploads = Config().find_b('Dinstall::AllowNoArchIndepUploads', True)
  641. changes = upload.changes
  642. if not allow_source_only_uploads:
  643. raise Reject('Source-only uploads are not allowed.')
  644. if not allow_source_only_uploads_without_package_list \
  645. and changes.source.package_list.fallback:
  646. raise Reject('Source-only uploads are only allowed if a Package-List field that also list architectures is included in the source package. dpkg (>= 1.17.7) includes this information.')
  647. if not allow_source_only_new and upload.new \
  648. and changes.primary_fingerprint not in allow_source_only_new_keys \
  649. and changes.source_name not in allow_source_only_new_sources:
  650. raise Reject('Source-only uploads to NEW are not allowed.')
  651. if 'all' not in changes.architectures and changes.source.package_list.has_arch_indep_packages():
  652. if not allow_no_arch_indep_uploads:
  653. raise Reject('Uploads must include architecture-independent packages.')
  654. return True
  655. class NewOverrideCheck(Check):
  656. """Override NEW requirement
  657. """
  658. def check(self, upload):
  659. if not upload.new:
  660. return True
  661. new_override_keys = Config().value_list('Dinstall::NewOverrideKeys')
  662. changes = upload.changes
  663. if changes.primary_fingerprint in new_override_keys:
  664. upload.new = False
  665. return True
  666. class ArchAllBinNMUCheck(Check):
  667. """Check for arch:all binNMUs"""
  668. def check(self, upload):
  669. changes = upload.changes
  670. if 'all' in changes.architectures and changes.changes.get('Binary-Only') == 'yes':
  671. raise Reject('arch:all binNMUs are not allowed.')
  672. return True
  673. class LintianCheck(Check):
  674. """Check package using lintian"""
  675. def check(self, upload):
  676. changes = upload.changes
  677. # Only check sourceful uploads.
  678. if changes.source is None:
  679. return True
  680. # Only check uploads to unstable or experimental.
  681. if 'unstable' not in changes.distributions and 'experimental' not in changes.distributions:
  682. return True
  683. cnf = Config()
  684. if 'Dinstall::LintianTags' not in cnf:
  685. return True
  686. tagfile = cnf['Dinstall::LintianTags']
  687. with open(tagfile, 'r') as sourcefile:
  688. sourcecontent = sourcefile.read()
  689. try:
  690. lintiantags = yaml.safe_load(sourcecontent)['lintian']
  691. except yaml.YAMLError as msg:
  692. raise Exception('Could not read lintian tags file {0}, YAML error: {1}'.format(tagfile, msg))
  693. with tempfile.NamedTemporaryFile(mode="w+t") as temptagfile:
  694. os.fchmod(temptagfile.fileno(), 0o644)
  695. for tags in lintiantags.values():
  696. for tag in tags:
  697. print(tag, file=temptagfile)
  698. temptagfile.flush()
  699. changespath = os.path.join(upload.directory, changes.filename)
  700. cmd = []
  701. user = cnf.get('Dinstall::UnprivUser') or None
  702. if user is not None:
  703. cmd.extend(['sudo', '-H', '-u', user])
  704. cmd.extend(['/usr/bin/lintian', '--show-overrides', '--tags-from-file', temptagfile.name, changespath])
  705. process = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, encoding="utf-8")
  706. output = process.stdout
  707. result = process.returncode
  708. if result == 2:
  709. utils.warn("lintian failed for %s [return code: %s]." %
  710. (changespath, result))
  711. utils.warn(utils.prefix_multi_line_string(output,
  712. " [possible output:] "))
  713. parsed_tags = lintian.parse_lintian_output(output)
  714. rejects = list(lintian.generate_reject_messages(parsed_tags, lintiantags))
  715. if len(rejects) != 0:
  716. raise Reject('\n'.join(rejects))
  717. return True
  718. class SourceFormatCheck(Check):
  719. """Check source format is allowed in the target suite"""
  720. def per_suite_check(self, upload, suite):
  721. source = upload.changes.source
  722. session = upload.session
  723. if source is None:
  724. return True
  725. source_format = source.dsc['Format']
  726. query = session.query(SrcFormat).filter_by(format_name=source_format).filter(SrcFormat.suites.contains(suite))
  727. if query.first() is None:
  728. raise Reject('source format {0} is not allowed in suite {1}'.format(source_format, suite.suite_name))
  729. class SuiteCheck(Check):
  730. def per_suite_check(self, upload, suite):
  731. if not suite.accept_source_uploads and upload.changes.source is not None:
  732. raise Reject('The suite "{0}" does not accept source uploads.'.format(suite.suite_name))
  733. if not suite.accept_binary_uploads and len(upload.changes.binaries) != 0:
  734. raise Reject('The suite "{0}" does not accept binary uploads.'.format(suite.suite_name))
  735. return True
  736. class SuiteArchitectureCheck(Check):
  737. def per_suite_check(self, upload, suite):
  738. session = upload.session
  739. for arch in upload.changes.architectures:
  740. query = session.query(Architecture).filter_by(arch_string=arch).filter(Architecture.suites.contains(suite))
  741. if query.first() is None:
  742. raise Reject('Architecture {0} is not allowed in suite {1}'.format(arch, suite.suite_name))
  743. return True
  744. class VersionCheck(Check):
  745. """Check version constraints"""
  746. def _highest_source_version(self, session, source_name, suite):
  747. db_source = session.query(DBSource).filter_by(source=source_name) \
  748. .filter(DBSource.suites.contains(suite)).order_by(DBSource.version.desc()).first()
  749. if db_source is None:
  750. return None
  751. else:
  752. return db_source.version
  753. def _highest_binary_version(self, session, binary_name, suite, architecture):
  754. db_binary = session.query(DBBinary).filter_by(package=binary_name) \
  755. .filter(DBBinary.suites.contains(suite)) \
  756. .join(DBBinary.architecture) \
  757. .filter(Architecture.arch_string.in_(['all', architecture])) \
  758. .order_by(DBBinary.version.desc()).first()
  759. if db_binary is None:
  760. return None
  761. else:
  762. return db_binary.version
  763. def _version_checks(self, upload, suite, other_suite, op, op_name):
  764. session = upload.session
  765. if upload.changes.source is not None:
  766. source_name = upload.changes.source.dsc['Source']
  767. source_version = upload.changes.source.dsc['Version']
  768. v = self._highest_source_version(session, source_name, other_suite)
  769. if v is not None and not op(version_compare(source_version, v)):
  770. raise Reject("Version check failed:\n"
  771. "Your upload included the source package {0}, version {1},\n"
  772. "however {3} already has version {2}.\n"
  773. "Uploads to {5} must have a {4} version than present in {3}."
  774. .format(source_name, source_version, v, other_suite.suite_name, op_name, suite.suite_name))
  775. for binary in upload.changes.binaries:
  776. binary_name = binary.control['Package']
  777. binary_version = binary.control['Version']
  778. architecture = binary.control['Architecture']
  779. v = self._highest_binary_version(session, binary_name, other_suite, architecture)
  780. if v is not None and not op(version_compare(binary_version, v)):
  781. raise Reject("Version check failed:\n"
  782. "Your upload included the binary package {0}, version {1}, for {2},\n"
  783. "however {4} already has version {3}.\n"
  784. "Uploads to {6} must have a {5} version than present in {4}."
  785. .format(binary_name, binary_version, architecture, v, other_suite.suite_name, op_name, suite.suite_name))
  786. def per_suite_check(self, upload, suite):
  787. session = upload.session
  788. vc_newer = session.query(dbconn.VersionCheck).filter_by(suite=suite) \
  789. .filter(dbconn.VersionCheck.check.in_(['MustBeNewerThan', 'Enhances']))
  790. must_be_newer_than = [vc.reference for vc in vc_newer]
  791. # Must be newer than old versions in `suite`
  792. must_be_newer_than.append(suite)
  793. for s in must_be_newer_than:
  794. self._version_checks(upload, suite, s, lambda result: result > 0, 'higher')
  795. vc_older = session.query(dbconn.VersionCheck).filter_by(suite=suite, check='MustBeOlderThan')
  796. must_be_older_than = [vc.reference for vc in vc_older]
  797. for s in must_be_older_than:
  798. self._version_checks(upload, suite, s, lambda result: result < 0, 'lower')
  799. return True
  800. @property
  801. def forcable(self) -> bool:
  802. return True