checks.py 41 KB

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