Debian Codegraph @

docs/concepts.rst

raw
1 General Concepts
2 ================
3
4
5 Serializer vs Signer
6 --------------------
7
8 ItsDangerous provides two levels of data handling. The :doc:`/signer` is
9 the basic system that signs a given ``bytes`` value based on the given
10 signing parameters. The :doc:`/serializer` wraps a signer to enable
11 serializing and signing other data besides ``bytes``.
12
13 Typically, you'll want to use a serializer, not a signer. You can
14 configure the signing parameters through the serializer, and even
15 provide fallback signers to upgrade old tokens to new parameters.
16
17
18 The Secret Key
19 --------------
20
21 Signatures are secured by the ``secret_key``. Typically one secret key
22 is used with all signers, and the salt is used to distinguish different
23 contexts. Changing the secret key will invalidate existing tokens.
24
25 It should be a long random string of bytes. This value must be kept
26 secret and should not be saved in source code or committed to version
27 control. If an attacker learns the secret key, they can change and
28 resign data to look valid. If you suspect this happened, change the
29 secret key to invalidate existing tokens.
30
31 One way to keep the secret key separate is to read it from an
32 environment variable. When deploying for the first time, generate a key
33 and set the environment variable when running the application. All
34 process managers (like systemd) and hosting services have a way to
35 specify environment variables.
36
37 .. code-block:: python
38
39 import os
40 from itsdangerous.serializer import Serializer
41 SECRET_KEY = os.environ.get("SECRET_KEY")
42 s = Serializer(SECRET_KEY)
43
44 .. code-block:: text
45
46 $ export SECRET_KEY="base64 encoded random bytes"
47 $ python application.py
48
49 One way to generate a key is to use :func:`os.urandom`.
50
51 .. code-block:: text
52
53 $ python3 -c 'import os; print(os.urandom(16).hex())'
54
55
56 The Salt
57 --------
58
59 The salt is combined with the secret key to derive a unique key for
60 distinguishing different contexts. Unlike the secret key, the salt
61 doesn't have to be random, and can be saved in code. It only has to be
62 unique between contexts, not private.
63
64 For example, you want to email activation links to activate user
65 accounts, and upgrade links to upgrade users to a paid accounts. If all
66 you sign is the user id, and you don't use different salts, a user could
67 reuse the token from the activation link to upgrade the account. If you
68 use different salts, the signatures will be different and will not be
69 valid in the other context.
70
71 .. code-block:: python
72
73 from itsdangerous.url_safe import URLSafeSerializer
74
75 s1 = URLSafeSerializer("secret-key", salt="activate")
76 s1.dumps(42)
77 'NDI.MHQqszw6Wc81wOBQszCrEE_RlzY'
78
79 s2 = URLSafeSerializer("secret-key", salt="upgrade")
80 s2.dumps(42)
81 'NDI.c0MpsD6gzpilOAeUPra3NShPXsE'
82
83 The second serializer can't load data dumped with the first because the
84 salts differ.
85
86 .. code-block:: python
87
88 s2.loads(s1.dumps(42))
89 Traceback (most recent call last):
90 ...
91 BadSignature: Signature does not match
92
93 Only the serializer with the same salt can load the data.
94
95 .. code-block:: python
96
97 s2.loads(s2.dumps(42))
98 42
99
100
101 Key Rotation
102 ------------
103
104 Key rotation can provide an extra layer of mitigation against an
105 attacker discovering a secret key. A rotation system will keep a list of
106 valid keys, generating a new key and removing the oldest key
107 periodically. If it takes four weeks for an attacker to crack a key, but
108 the key is rotated out after three weeks, they will not be able to use
109 any keys they crack. However, if a user doesn't refresh their token
110 within three weeks it will be invalid too.
111
112 The system that generates and maintains this list is outside the scope
113 of ItsDangerous, but ItsDangerous does support validating against a list
114 of keys.
115
116 Instead of passing a single key, you can pass a list of keys, oldest to
117 newest. When signing the last (newest) key will be used, and when
118 validating each key will be tried from newest to oldest before raising
119 a validation error.
120
121 .. code-block:: python
122
123 SECRET_KEYS = ["2b9cd98e", "169d7886", "b6af09f5"]
124
125 # sign some data with the latest key
126 s = Serializer(SECRET_KEYS)
127 t = s.dumps({"id": 42})
128
129 # rotate a new key in and the oldest key out
130 SECRET_KEYS.append("cf9b3588")
131 del SECRET_KEYS[0]
132
133 s = Serializer(SECRET_KEYS)
134 s.loads(t) # valid even though it was signed with a previous key
135
136
137 Digest Method Security
138 ----------------------
139
140 A signer is configured with a ``digest_method``, a hash function that
141 is used as an intermediate step when generating the HMAC signature. The
142 default method is :func:`hashlib.sha1`. Occasionally, users are
143 concerned about this default because they have heard about hash
144 collisions with SHA-1.
145
146 When used as the intermediate, iterated step in HMAC, SHA-1 is not
147 insecure. In fact, even MD5 is still secure in HMAC. The security of the
148 hash alone doesn't apply when used in HMAC.
149
150 If a project considers SHA-1 a risk anyway, they can configure the
151 signer with a different digest method such as :func:`hashlib.sha512`.
152 A fallback signer for SHA-1 can be configured so that old tokens will be
153 upgraded. SHA-512 produces a longer hash, so tokens will take up more
154 space, which is relevant in cookies and URLs.