sign.py 21 KB

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