Add an admin command that re-encrypts passwords after a key rollover

This commit is contained in:
Rodolphe Breard 2019-07-27 18:29:18 +02:00
parent d358eb8aef
commit 0e03f327b1
4 changed files with 28 additions and 2 deletions

View file

View file

View file

@ -0,0 +1,26 @@
from django.core.management.base import BaseCommand, CommandError
from pwdb.models import SharedPassword, IV_LENGTH
import secrets
class Command(BaseCommand):
help = "Re-encrypts all the shared passwords after a secret key rollover"
def add_arguments(self, parser):
parser.add_argument("old_key", type=str)
def handle(self, *args, **options):
self.stdout.write("Re-encrypting passwords with the new secret key.")
self.old_key = options["old_key"]
try:
for p in SharedPassword.objects.all():
self.update_password(p)
self.stdout.write("Done.")
except ValueError:
self.stderr.write("Invalid key.")
def update_password(self, password):
clear_password = password.decrypt_password(key=self.old_key)
password.iv = secrets.token_bytes(IV_LENGTH)
password.set_password(clear_password)
password.save()

View file

@ -77,8 +77,8 @@ class SharedPassword(models.Model):
encryptor.update(clear_password) + encryptor.finalize() encryptor.update(clear_password) + encryptor.finalize()
) )
def decrypt_password(self): def decrypt_password(self, key=None):
key = SharedPassword.get_key(self.uuid) key = SharedPassword.get_key(self.uuid, key=key)
cipher = SharedPassword.get_cipher(key, self.iv) cipher = SharedPassword.get_cipher(key, self.iv)
decryptor = cipher.decryptor() decryptor = cipher.decryptor()
clear_password = ( clear_password = (