sign.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609
  1. """Utilities for signing notebooks"""
  2. # Copyright (c) IPython Development Team.
  3. # Distributed under the terms of the Modified BSD License.
  4. import base64
  5. from collections import OrderedDict
  6. from contextlib import contextmanager
  7. from datetime import datetime
  8. import hashlib
  9. from hmac import HMAC
  10. import io
  11. import os
  12. import sys
  13. try:
  14. import sqlite3
  15. except ImportError:
  16. try:
  17. from pysqlite2 import dbapi2 as sqlite3
  18. except ImportError:
  19. sqlite3 = None
  20. from ipython_genutils.py3compat import unicode_type, cast_bytes, cast_unicode
  21. from traitlets import (
  22. Instance, Bytes, Enum, Any, Unicode, Bool, Integer, TraitType,
  23. default, observe,
  24. )
  25. from traitlets.config import LoggingConfigurable, MultipleInstanceError
  26. from jupyter_core.application import JupyterApp, base_flags
  27. from . import read, reads, NO_CONVERT, __version__
  28. try:
  29. # Python 3
  30. algorithms = hashlib.algorithms_guaranteed
  31. # shake algorithms in py36 are not compatible with hmac
  32. # due to required length argument in digests
  33. algorithms = [ a for a in algorithms if not a.startswith('shake_') ]
  34. except AttributeError:
  35. algorithms = hashlib.algorithms
  36. # This has been added to traitlets, but is not released as of traitlets 4.3.1,
  37. # so a copy is included here for now.
  38. class Callable(TraitType):
  39. """A trait which is callable.
  40. Notes
  41. -----
  42. Classes are callable, as are instances
  43. with a __call__() method."""
  44. info_text = 'a callable'
  45. def validate(self, obj, value):
  46. if callable(value):
  47. return value
  48. else:
  49. self.error(obj, value)
  50. class SignatureStore(object):
  51. """Base class for a signature store."""
  52. def store_signature(self, digest, algorithm):
  53. """Implement in subclass to store a signature.
  54. Should not raise if the signature is already stored.
  55. """
  56. raise NotImplementedError
  57. def check_signature(self, digest, algorithm):
  58. """Implement in subclass to check if a signature is known.
  59. Return True for a known signature, False for unknown.
  60. """
  61. raise NotImplementedError
  62. def remove_signature(self, digest, algorithm):
  63. """Implement in subclass to delete a signature.
  64. Should not raise if the signature is not stored.
  65. """
  66. raise NotImplementedError
  67. def close(self):
  68. """Close any open connections this store may use.
  69. If the store maintains any open connections (e.g. to a database),
  70. they should be closed.
  71. """
  72. pass
  73. class MemorySignatureStore(SignatureStore):
  74. """Non-persistent storage of signatures in memory.
  75. """
  76. cache_size = 65535
  77. def __init__(self):
  78. # We really only want an ordered set, but the stdlib has OrderedDict,
  79. # and it's easy to use a dict as a set.
  80. self.data = OrderedDict()
  81. def store_signature(self, digest, algorithm):
  82. key = (digest, algorithm)
  83. # Pop it so it goes to the end when we reinsert it
  84. self.data.pop(key, None)
  85. self.data[key] = None
  86. self._maybe_cull()
  87. def _maybe_cull(self):
  88. """If more than cache_size signatures are stored, delete the oldest 25%
  89. """
  90. if len(self.data) < self.cache_size:
  91. return
  92. for _ in range(len(self.data) // 4):
  93. self.data.popitem(last=False)
  94. def check_signature(self, digest, algorithm):
  95. key = (digest, algorithm)
  96. if key in self.data:
  97. # Move it to the end (.move_to_end() method is new in Py3)
  98. del self.data[key]
  99. self.data[key] = None
  100. return True
  101. return False
  102. def remove_signature(self, digest, algorithm):
  103. self.data.pop((digest, algorithm), None)
  104. class SQLiteSignatureStore(SignatureStore, LoggingConfigurable):
  105. """Store signatures in an SQLite database.
  106. """
  107. # 64k entries ~ 12MB
  108. cache_size = Integer(65535,
  109. help="""The number of notebook signatures to cache.
  110. When the number of signatures exceeds this value,
  111. the oldest 25% of signatures will be culled.
  112. """
  113. ).tag(config=True)
  114. def __init__(self, db_file, **kwargs):
  115. super(SQLiteSignatureStore, self).__init__(**kwargs)
  116. self.db_file = db_file
  117. self.db = self._connect_db(db_file)
  118. def close(self):
  119. if self.db is not None:
  120. self.db.close()
  121. def _connect_db(self, db_file):
  122. kwargs = dict(
  123. detect_types=sqlite3.PARSE_DECLTYPES | sqlite3.PARSE_COLNAMES)
  124. db = None
  125. try:
  126. db = sqlite3.connect(db_file, **kwargs)
  127. self.init_db(db)
  128. except (sqlite3.DatabaseError, sqlite3.OperationalError):
  129. if db_file != ':memory:':
  130. old_db_location = db_file + ".bak"
  131. if db is not None:
  132. db.close()
  133. self.log.warning(
  134. ("The signatures database cannot be opened; maybe it is corrupted or encrypted. "
  135. "You may need to rerun your notebooks to ensure that they are trusted to run Javascript. "
  136. "The old signatures database has been renamed to %s and a new one has been created."),
  137. old_db_location)
  138. try:
  139. os.rename(db_file, old_db_location)
  140. db = sqlite3.connect(db_file, **kwargs)
  141. self.init_db(db)
  142. except (sqlite3.DatabaseError, sqlite3.OperationalError, OSError):
  143. if db is not None:
  144. db.close()
  145. self.log.warning(
  146. ("Failed commiting signatures database to disk. "
  147. "You may need to move the database file to a non-networked file system, "
  148. "using config option `NotebookNotary.db_file`. "
  149. "Using in-memory signatures database for the remainder of this session."))
  150. self.db_file = ':memory:'
  151. db = sqlite3.connect(':memory:', **kwargs)
  152. self.init_db(db)
  153. else:
  154. raise
  155. return db
  156. def init_db(self, db):
  157. db.execute("""
  158. CREATE TABLE IF NOT EXISTS nbsignatures
  159. (
  160. id integer PRIMARY KEY AUTOINCREMENT,
  161. algorithm text,
  162. signature text,
  163. path text,
  164. last_seen timestamp
  165. )""")
  166. db.execute("""
  167. CREATE INDEX IF NOT EXISTS algosig ON nbsignatures(algorithm, signature)
  168. """)
  169. db.commit()
  170. def store_signature(self, digest, algorithm):
  171. if self.db is None:
  172. return
  173. if not self.check_signature(digest, algorithm):
  174. self.db.execute("""
  175. INSERT INTO nbsignatures (algorithm, signature, last_seen)
  176. VALUES (?, ?, ?)
  177. """, (algorithm, digest, datetime.utcnow())
  178. )
  179. else:
  180. self.db.execute("""UPDATE nbsignatures SET last_seen = ? WHERE
  181. algorithm = ? AND
  182. signature = ?;
  183. """, (datetime.utcnow(), algorithm, digest)
  184. )
  185. self.db.commit()
  186. # Check size and cull old entries if necessary
  187. n, = self.db.execute("SELECT Count(*) FROM nbsignatures").fetchone()
  188. if n > self.cache_size:
  189. self.cull_db()
  190. def check_signature(self, digest, algorithm):
  191. if self.db is None:
  192. return False
  193. r = self.db.execute("""SELECT id FROM nbsignatures WHERE
  194. algorithm = ? AND
  195. signature = ?;
  196. """, (algorithm, digest)).fetchone()
  197. if r is None:
  198. return False
  199. self.db.execute("""UPDATE nbsignatures SET last_seen = ? WHERE
  200. algorithm = ? AND
  201. signature = ?;
  202. """,
  203. (datetime.utcnow(), algorithm, digest),
  204. )
  205. self.db.commit()
  206. return True
  207. def remove_signature(self, digest, algorithm):
  208. self.db.execute("""DELETE FROM nbsignatures WHERE
  209. algorithm = ? AND
  210. signature = ?;
  211. """,
  212. (algorithm, digest)
  213. )
  214. self.db.commit()
  215. def cull_db(self):
  216. """Cull oldest 25% of the trusted signatures when the size limit is reached"""
  217. self.db.execute("""DELETE FROM nbsignatures WHERE id IN (
  218. SELECT id FROM nbsignatures ORDER BY last_seen DESC LIMIT -1 OFFSET ?
  219. );
  220. """, (max(int(0.75 * self.cache_size), 1),))
  221. def yield_everything(obj):
  222. """Yield every item in a container as bytes
  223. Allows any JSONable object to be passed to an HMAC digester
  224. without having to serialize the whole thing.
  225. """
  226. if isinstance(obj, dict):
  227. for key in sorted(obj):
  228. value = obj[key]
  229. yield cast_bytes(key)
  230. for b in yield_everything(value):
  231. yield b
  232. elif isinstance(obj, (list, tuple)):
  233. for element in obj:
  234. for b in yield_everything(element):
  235. yield b
  236. elif isinstance(obj, unicode_type):
  237. yield obj.encode('utf8')
  238. else:
  239. yield unicode_type(obj).encode('utf8')
  240. def yield_code_cells(nb):
  241. """Iterator that yields all cells in a notebook
  242. nbformat version independent
  243. """
  244. if nb.nbformat >= 4:
  245. for cell in nb['cells']:
  246. if cell['cell_type'] == 'code':
  247. yield cell
  248. elif nb.nbformat == 3:
  249. for ws in nb['worksheets']:
  250. for cell in ws['cells']:
  251. if cell['cell_type'] == 'code':
  252. yield cell
  253. @contextmanager
  254. def signature_removed(nb):
  255. """Context manager for operating on a notebook with its signature removed
  256. Used for excluding the previous signature when computing a notebook's signature.
  257. """
  258. save_signature = nb['metadata'].pop('signature', None)
  259. try:
  260. yield
  261. finally:
  262. if save_signature is not None:
  263. nb['metadata']['signature'] = save_signature
  264. class NotebookNotary(LoggingConfigurable):
  265. """A class for computing and verifying notebook signatures."""
  266. data_dir = Unicode()
  267. @default('data_dir')
  268. def _data_dir_default(self):
  269. app = None
  270. try:
  271. if JupyterApp.initialized():
  272. app = JupyterApp.instance()
  273. except MultipleInstanceError:
  274. pass
  275. if app is None:
  276. # create an app, without the global instance
  277. app = JupyterApp()
  278. app.initialize(argv=[])
  279. return app.data_dir
  280. store_factory = Callable(
  281. help="""A callable returning the storage backend for notebook signatures.
  282. The default uses an SQLite database.""").tag(config=True)
  283. @default('store_factory')
  284. def _store_factory_default(self):
  285. def factory():
  286. if sqlite3 is None:
  287. self.log.warning("Missing SQLite3, all notebooks will be untrusted!")
  288. return MemorySignatureStore()
  289. return SQLiteSignatureStore(self.db_file)
  290. return factory
  291. db_file = Unicode(
  292. help="""The sqlite file in which to store notebook signatures.
  293. By default, this will be in your Jupyter data directory.
  294. You can set it to ':memory:' to disable sqlite writing to the filesystem.
  295. """).tag(config=True)
  296. @default('db_file')
  297. def _db_file_default(self):
  298. if not self.data_dir:
  299. return ':memory:'
  300. return os.path.join(self.data_dir, u'nbsignatures.db')
  301. algorithm = Enum(algorithms, default_value='sha256',
  302. help="""The hashing algorithm used to sign notebooks."""
  303. ).tag(config=True)
  304. @observe('algorithm')
  305. def _algorithm_changed(self, change):
  306. self.digestmod = getattr(hashlib, change.new)
  307. digestmod = Any()
  308. @default('digestmod')
  309. def _digestmod_default(self):
  310. return getattr(hashlib, self.algorithm)
  311. secret_file = Unicode(
  312. help="""The file where the secret key is stored."""
  313. ).tag(config=True)
  314. @default('secret_file')
  315. def _secret_file_default(self):
  316. if not self.data_dir:
  317. return ''
  318. return os.path.join(self.data_dir, 'notebook_secret')
  319. secret = Bytes(
  320. help="""The secret key with which notebooks are signed."""
  321. ).tag(config=True)
  322. @default('secret')
  323. def _secret_default(self):
  324. # note : this assumes an Application is running
  325. if os.path.exists(self.secret_file):
  326. with io.open(self.secret_file, 'rb') as f:
  327. return f.read()
  328. else:
  329. secret = base64.encodestring(os.urandom(1024))
  330. self._write_secret_file(secret)
  331. return secret
  332. def __init__(self, **kwargs):
  333. super(NotebookNotary, self).__init__(**kwargs)
  334. self.store = self.store_factory()
  335. def _write_secret_file(self, secret):
  336. """write my secret to my secret_file"""
  337. self.log.info("Writing notebook-signing key to %s", self.secret_file)
  338. with io.open(self.secret_file, 'wb') as f:
  339. f.write(secret)
  340. try:
  341. os.chmod(self.secret_file, 0o600)
  342. except OSError:
  343. self.log.warning(
  344. "Could not set permissions on %s",
  345. self.secret_file
  346. )
  347. return secret
  348. def compute_signature(self, nb):
  349. """Compute a notebook's signature
  350. by hashing the entire contents of the notebook via HMAC digest.
  351. """
  352. hmac = HMAC(self.secret, digestmod=self.digestmod)
  353. # don't include the previous hash in the content to hash
  354. with signature_removed(nb):
  355. # sign the whole thing
  356. for b in yield_everything(nb):
  357. hmac.update(b)
  358. return hmac.hexdigest()
  359. def check_signature(self, nb):
  360. """Check a notebook's stored signature
  361. If a signature is stored in the notebook's metadata,
  362. a new signature is computed and compared with the stored value.
  363. Returns True if the signature is found and matches, False otherwise.
  364. The following conditions must all be met for a notebook to be trusted:
  365. - a signature is stored in the form 'scheme:hexdigest'
  366. - the stored scheme matches the requested scheme
  367. - the requested scheme is available from hashlib
  368. - the computed hash from notebook_signature matches the stored hash
  369. """
  370. if nb.nbformat < 3:
  371. return False
  372. signature = self.compute_signature(nb)
  373. return self.store.check_signature(signature, self.algorithm)
  374. def sign(self, nb):
  375. """Sign a notebook, indicating that its output is trusted on this machine
  376. Stores hash algorithm and hmac digest in a local database of trusted notebooks.
  377. """
  378. if nb.nbformat < 3:
  379. return
  380. signature = self.compute_signature(nb)
  381. self.store.store_signature(signature, self.algorithm)
  382. def unsign(self, nb):
  383. """Ensure that a notebook is untrusted
  384. by removing its signature from the trusted database, if present.
  385. """
  386. signature = self.compute_signature(nb)
  387. self.store.remove_signature(signature, self.algorithm)
  388. def mark_cells(self, nb, trusted):
  389. """Mark cells as trusted if the notebook's signature can be verified
  390. Sets ``cell.metadata.trusted = True | False`` on all code cells,
  391. depending on the *trusted* parameter. This will typically be the return
  392. value from ``self.check_signature(nb)``.
  393. This function is the inverse of check_cells
  394. """
  395. if nb.nbformat < 3:
  396. return
  397. for cell in yield_code_cells(nb):
  398. cell['metadata']['trusted'] = trusted
  399. def _check_cell(self, cell, nbformat_version):
  400. """Do we trust an individual cell?
  401. Return True if:
  402. - cell is explicitly trusted
  403. - cell has no potentially unsafe rich output
  404. If a cell has no output, or only simple print statements,
  405. it will always be trusted.
  406. """
  407. # explicitly trusted
  408. if cell['metadata'].pop("trusted", False):
  409. return True
  410. # explicitly safe output
  411. if nbformat_version >= 4:
  412. unsafe_output_types = ['execute_result', 'display_data']
  413. safe_keys = {"output_type", "execution_count", "metadata"}
  414. else: # v3
  415. unsafe_output_types = ['pyout', 'display_data']
  416. safe_keys = {"output_type", "prompt_number", "metadata"}
  417. for output in cell['outputs']:
  418. output_type = output['output_type']
  419. if output_type in unsafe_output_types:
  420. # if there are any data keys not in the safe whitelist
  421. output_keys = set(output)
  422. if output_keys.difference(safe_keys):
  423. return False
  424. return True
  425. def check_cells(self, nb):
  426. """Return whether all code cells are trusted.
  427. A cell is trusted if the 'trusted' field in its metadata is truthy, or
  428. if it has no potentially unsafe outputs.
  429. If there are no code cells, return True.
  430. This function is the inverse of mark_cells.
  431. """
  432. if nb.nbformat < 3:
  433. return False
  434. trusted = True
  435. for cell in yield_code_cells(nb):
  436. # only distrust a cell if it actually has some output to distrust
  437. if not self._check_cell(cell, nb.nbformat):
  438. trusted = False
  439. return trusted
  440. trust_flags = {
  441. 'reset' : (
  442. {'TrustNotebookApp' : { 'reset' : True}},
  443. """Delete the trusted notebook cache.
  444. All previously signed notebooks will become untrusted.
  445. """
  446. ),
  447. }
  448. trust_flags.update(base_flags)
  449. class TrustNotebookApp(JupyterApp):
  450. version = __version__
  451. description="""Sign one or more Jupyter notebooks with your key,
  452. to trust their dynamic (HTML, Javascript) output.
  453. Otherwise, you will have to re-execute the notebook to see output.
  454. """
  455. # This command line tool should use the same config file as the notebook
  456. @default('config_file_name')
  457. def _config_file_name_default(self):
  458. return 'jupyter_notebook_config'
  459. examples = """
  460. jupyter trust mynotebook.ipynb and_this_one.ipynb
  461. """
  462. flags = trust_flags
  463. reset = Bool(False,
  464. help="""If True, delete the trusted signature cache.
  465. After reset, all previously signed notebooks will become untrusted.
  466. """
  467. ).tag(config=True)
  468. notary = Instance(NotebookNotary)
  469. @default('notary')
  470. def _notary_default(self):
  471. return NotebookNotary(parent=self, data_dir=self.data_dir)
  472. def sign_notebook_file(self, notebook_path):
  473. """Sign a notebook from the filesystem"""
  474. if not os.path.exists(notebook_path):
  475. self.log.error("Notebook missing: %s" % notebook_path)
  476. self.exit(1)
  477. with io.open(notebook_path, encoding='utf8') as f:
  478. nb = read(f, NO_CONVERT)
  479. self.sign_notebook(nb, notebook_path)
  480. def sign_notebook(self, nb, notebook_path='<stdin>'):
  481. """Sign a notebook that's been loaded"""
  482. if self.notary.check_signature(nb):
  483. print("Notebook already signed: %s" % notebook_path)
  484. else:
  485. print("Signing notebook: %s" % notebook_path)
  486. self.notary.sign(nb)
  487. def generate_new_key(self):
  488. """Generate a new notebook signature key"""
  489. print("Generating new notebook key: %s" % self.notary.secret_file)
  490. self.notary._write_secret_file(os.urandom(1024))
  491. def start(self):
  492. if self.reset:
  493. if os.path.exists(self.notary.db_file):
  494. print("Removing trusted signature cache: %s" % self.notary.db_file)
  495. os.remove(self.notary.db_file)
  496. self.generate_new_key()
  497. return
  498. if not self.extra_args:
  499. self.log.debug("Reading notebook from stdin")
  500. nb_s = cast_unicode(sys.stdin.read())
  501. nb = reads(nb_s, NO_CONVERT)
  502. self.sign_notebook(nb, '<stdin>')
  503. else:
  504. for notebook_path in self.extra_args:
  505. self.sign_notebook_file(notebook_path)
  506. main = TrustNotebookApp.launch_instance
  507. if __name__ == '__main__':
  508. main()