Debian Codegraph @

src/CedarBackup3/extend/encrypt.py

raw
1 # vim: set ft=python ts=4 sw=4 expandtab:
2 # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
3 #
4 # C E D A R
5 # S O L U T I O N S "Software done right."
6 # S O F T W A R E
7 #
8 # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
9 #
10 # Copyright (c) 2007,2010,2015 Kenneth J. Pronovici.
11 # All rights reserved.
12 #
13 # This program is free software; you can redistribute it and/or
14 # modify it under the terms of the GNU General Public License,
15 # Version 2, as published by the Free Software Foundation.
16 #
17 # This program is distributed in the hope that it will be useful,
18 # but WITHOUT ANY WARRANTY; without even the implied warranty of
19 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
20 #
21 # Copies of the GNU General Public License are available from
22 # the Free Software Foundation website, http://www.gnu.org/.
23 #
24 # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
25 #
26 # Author : Kenneth J. Pronovici <[email protected]>
27 # Language : Python 3
28 # Project : Official Cedar Backup Extensions
29 # Purpose : Provides an extension to encrypt staging directories.
30 #
31 # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
32
33 ########################################################################
34 # Module documentation
35 ########################################################################
36
37 """
38 Provides an extension to encrypt staging directories.
39
40 When this extension is executed, all backed-up files in the configured Cedar
41 Backup staging directory will be encrypted using gpg. Any directory which has
42 already been encrypted (as indicated by the ``cback.encrypt`` file) will be
43 ignored.
44
45 This extension requires a new configuration section <encrypt> and is intended
46 to be run immediately after the standard stage action or immediately before the
47 standard store action. Aside from its own configuration, it requires the
48 options and staging configuration sections in the standard Cedar Backup
49 configuration file.
50
51 :author: Kenneth J. Pronovici <[email protected]>
52 """
53
54 ########################################################################
55 # Imported modules
56 ########################################################################
57
58 import logging
59 import os
60 from functools import total_ordering
61
62 from CedarBackup3.actions.util import findDailyDirs, getBackupFiles, writeIndicatorFile
63 from CedarBackup3.util import changeOwnership, executeCommand, resolveCommand
64 from CedarBackup3.xmlutil import addContainerNode, addStringNode, createInputDom, readFirstChild, readString
65
66 ########################################################################
67 # Module-wide constants and variables
68 ########################################################################
69
70 logger = logging.getLogger("CedarBackup3.log.extend.encrypt")
71
72 GPG_COMMAND = [
73 "gpg",
74 ]
75 VALID_ENCRYPT_MODES = [
76 "gpg",
77 ]
78 ENCRYPT_INDICATOR = "cback.encrypt"
79
80
81 ########################################################################
82 # EncryptConfig class definition
83 ########################################################################
84
85
86 @total_ordering
87 class EncryptConfig:
88 """
89 Class representing encrypt configuration.
90
91 Encrypt configuration is used for encrypting staging directories.
92
93 The following restrictions exist on data in this class:
94
95 - The encrypt mode must be one of the values in ``VALID_ENCRYPT_MODES``
96 - The encrypt target value must be a non-empty string
97
98 """
99
100 def __init__(self, encryptMode=None, encryptTarget=None):
101 """
102 Constructor for the ``EncryptConfig`` class.
103
104 Args:
105 encryptMode: Encryption mode
106 encryptTarget: Encryption target (for instance, GPG recipient)
107
108 Raises:
109 ValueError: If one of the values is invalid
110 """
111 self._encryptMode = None
112 self._encryptTarget = None
113 self.encryptMode = encryptMode
114 self.encryptTarget = encryptTarget
115
116 def __repr__(self):
117 """
118 Official string representation for class instance.
119 """
120 return "EncryptConfig(%s, %s)" % (self.encryptMode, self.encryptTarget)
121
122 def __str__(self):
123 """
124 Informal string representation for class instance.
125 """
126 return self.__repr__()
127
128 def __eq__(self, other):
129 """Equals operator, iplemented in terms of original Python 2 compare operator."""
130 return self.__cmp__(other) == 0
131
132 def __lt__(self, other):
133 """Less-than operator, iplemented in terms of original Python 2 compare operator."""
134 return self.__cmp__(other) < 0
135
136 def __gt__(self, other):
137 """Greater-than operator, iplemented in terms of original Python 2 compare operator."""
138 return self.__cmp__(other) > 0
139
140 def __cmp__(self, other):
141 """
142 Original Python 2 comparison operator.
143 Lists within this class are "unordered" for equality comparisons.
144 Args:
145 other: Other object to compare to
146 Returns:
147 -1/0/1 depending on whether self is ``<``, ``=`` or ``>`` other
148 """
149 if other is None:
150 return 1
151 if self.encryptMode != other.encryptMode:
152 if str(self.encryptMode or "") < str(other.encryptMode or ""):
153 return -1
154 else:
155 return 1
156 if self.encryptTarget != other.encryptTarget:
157 if str(self.encryptTarget or "") < str(other.encryptTarget or ""):
158 return -1
159 else:
160 return 1
161 return 0
162
163 def _setEncryptMode(self, value):
164 """
165 Property target used to set the encrypt mode.
166 If not ``None``, the mode must be one of the values in ``VALID_ENCRYPT_MODES``.
167 Raises:
168 ValueError: If the value is not valid
169 """
170 if value is not None:
171 if value not in VALID_ENCRYPT_MODES:
172 raise ValueError("Encrypt mode must be one of %s." % VALID_ENCRYPT_MODES)
173 self._encryptMode = value
174
175 def _getEncryptMode(self):
176 """
177 Property target used to get the encrypt mode.
178 """
179 return self._encryptMode
180
181 def _setEncryptTarget(self, value):
182 """
183 Property target used to set the encrypt target.
184 """
185 if value is not None:
186 if len(value) < 1:
187 raise ValueError("Encrypt target must be non-empty string.")
188 self._encryptTarget = value
189
190 def _getEncryptTarget(self):
191 """
192 Property target used to get the encrypt target.
193 """
194 return self._encryptTarget
195
196 encryptMode = property(_getEncryptMode, _setEncryptMode, None, doc="Encrypt mode.")
197 encryptTarget = property(_getEncryptTarget, _setEncryptTarget, None, doc="Encrypt target (i.e. GPG recipient).")
198
199
200 ########################################################################
201 # LocalConfig class definition
202 ########################################################################
203
204
205 @total_ordering
206 class LocalConfig:
207 """
208 Class representing this extension's configuration document.
209
210 This is not a general-purpose configuration object like the main Cedar
211 Backup configuration object. Instead, it just knows how to parse and emit
212 encrypt-specific configuration values. Third parties who need to read and
213 write configuration related to this extension should access it through the
214 constructor, ``validate`` and ``addConfig`` methods.
215
216 *Note:* Lists within this class are "unordered" for equality comparisons.
217
218 """
219
220 def __init__(self, xmlData=None, xmlPath=None, validate=True):
221 """
222 Initializes a configuration object.
223
224 If you initialize the object without passing either ``xmlData`` or
225 ``xmlPath`` then configuration will be empty and will be invalid until it
226 is filled in properly.
227
228 No reference to the original XML data or original path is saved off by
229 this class. Once the data has been parsed (successfully or not) this
230 original information is discarded.
231
232 Unless the ``validate`` argument is ``False``, the :any:`LocalConfig.validate`
233 method will be called (with its default arguments) against configuration
234 after successfully parsing any passed-in XML. Keep in mind that even if
235 ``validate`` is ``False``, it might not be possible to parse the passed-in
236 XML document if lower-level validations fail.
237
238 *Note:* It is strongly suggested that the ``validate`` option always be set
239 to ``True`` (the default) unless there is a specific need to read in
240 invalid configuration from disk.
241
242 Args:
243 xmlData (String data): XML data representing configuration
244 xmlPath (Absolute path to a file on disk): Path to an XML file on disk
245 validate (Boolean true/false): Validate the document after parsing it
246 Raises:
247 ValueError: If both ``xmlData`` and ``xmlPath`` are passed-in
248 ValueError: If the XML data in ``xmlData`` or ``xmlPath`` cannot be parsed
249 ValueError: If the parsed configuration document is not valid
250 """
251 self._encrypt = None
252 self.encrypt = None
253 if xmlData is not None and xmlPath is not None:
254 raise ValueError("Use either xmlData or xmlPath, but not both.")
255 if xmlData is not None:
256 self._parseXmlData(xmlData)
257 if validate:
258 self.validate()
259 elif xmlPath is not None:
260 with open(xmlPath) as f:
261 xmlData = f.read()
262 self._parseXmlData(xmlData)
263 if validate:
264 self.validate()
265
266 def __repr__(self):
267 """
268 Official string representation for class instance.
269 """
270 return "LocalConfig(%s)" % (self.encrypt)
271
272 def __str__(self):
273 """
274 Informal string representation for class instance.
275 """
276 return self.__repr__()
277
278 def __eq__(self, other):
279 """Equals operator, iplemented in terms of original Python 2 compare operator."""
280 return self.__cmp__(other) == 0
281
282 def __lt__(self, other):
283 """Less-than operator, iplemented in terms of original Python 2 compare operator."""
284 return self.__cmp__(other) < 0
285
286 def __gt__(self, other):
287 """Greater-than operator, iplemented in terms of original Python 2 compare operator."""
288 return self.__cmp__(other) > 0
289
290 def __cmp__(self, other):
291 """
292 Original Python 2 comparison operator.
293 Lists within this class are "unordered" for equality comparisons.
294 Args:
295 other: Other object to compare to
296 Returns:
297 -1/0/1 depending on whether self is ``<``, ``=`` or ``>`` other
298 """
299 if other is None:
300 return 1
301 if self.encrypt != other.encrypt:
302 if self.encrypt < other.encrypt:
303 return -1
304 else:
305 return 1
306 return 0
307
308 def _setEncrypt(self, value):
309 """
310 Property target used to set the encrypt configuration value.
311 If not ``None``, the value must be a ``EncryptConfig`` object.
312 Raises:
313 ValueError: If the value is not a ``EncryptConfig``
314 """
315 if value is None:
316 self._encrypt = None
317 else:
318 if not isinstance(value, EncryptConfig):
319 raise ValueError("Value must be a ``EncryptConfig`` object.")
320 self._encrypt = value
321
322 def _getEncrypt(self):
323 """
324 Property target used to get the encrypt configuration value.
325 """
326 return self._encrypt
327
328 encrypt = property(_getEncrypt, _setEncrypt, None, "Encrypt configuration in terms of a ``EncryptConfig`` object.")
329
330 def validate(self):
331 """
332 Validates configuration represented by the object.
333
334 Encrypt configuration must be filled in. Within that, both the encrypt
335 mode and encrypt target must be filled in.
336
337 Raises:
338 ValueError: If one of the validations fails
339 """
340 if self.encrypt is None:
341 raise ValueError("Encrypt section is required.")
342 if self.encrypt.encryptMode is None:
343 raise ValueError("Encrypt mode must be set.")
344 if self.encrypt.encryptTarget is None:
345 raise ValueError("Encrypt target must be set.")
346
347 def addConfig(self, xmlDom, parentNode):
348 """
349 Adds an <encrypt> configuration section as the next child of a parent.
350
351 Third parties should use this function to write configuration related to
352 this extension.
353
354 We add the following fields to the document::
355
356 encryptMode //cb_config/encrypt/encrypt_mode
357 encryptTarget //cb_config/encrypt/encrypt_target
358
359 Args:
360 xmlDom: DOM tree as from ``impl.createDocument()``
361 parentNode: Parent that the section should be appended to
362 """
363 if self.encrypt is not None:
364 sectionNode = addContainerNode(xmlDom, parentNode, "encrypt")
365 addStringNode(xmlDom, sectionNode, "encrypt_mode", self.encrypt.encryptMode)
366 addStringNode(xmlDom, sectionNode, "encrypt_target", self.encrypt.encryptTarget)
367
368 def _parseXmlData(self, xmlData):
369 """
370 Internal method to parse an XML string into the object.
371
372 This method parses the XML document into a DOM tree (``xmlDom``) and then
373 calls a static method to parse the encrypt configuration section.
374
375 Args:
376 xmlData (String data): XML data to be parsed
377 Raises:
378 ValueError: If the XML cannot be successfully parsed
379 """
380 (_, parentNode) = createInputDom(xmlData)
381 self._encrypt = LocalConfig._parseEncrypt(parentNode)
382
383 @staticmethod
384 def _parseEncrypt(parent):
385 """
386 Parses an encrypt configuration section.
387
388 We read the following individual fields::
389
390 encryptMode //cb_config/encrypt/encrypt_mode
391 encryptTarget //cb_config/encrypt/encrypt_target
392
393 Args:
394 parent: Parent node to search beneath
395
396 Returns:
397 ``EncryptConfig`` object or ``None`` if the section does not exist
398 Raises:
399 ValueError: If some filled-in value is invalid
400 """
401 encrypt = None
402 section = readFirstChild(parent, "encrypt")
403 if section is not None:
404 encrypt = EncryptConfig()
405 encrypt.encryptMode = readString(section, "encrypt_mode")
406 encrypt.encryptTarget = readString(section, "encrypt_target")
407 return encrypt
408
409
410 ########################################################################
411 # Public functions
412 ########################################################################
413
414 ###########################
415 # executeAction() function
416 ###########################
417
418
419 def executeAction(configPath, options, config): # ruff: ignore[unused-function-argument]
420 """
421 Executes the encrypt backup action.
422
423 Args:
424 configPath (String representing a path on disk): Path to configuration file on disk
425 options (Options object): Program command-line options
426 config (Config object): Program configuration
427 Raises:
428 ValueError: Under many generic error conditions
429 IOError: If there are I/O problems reading or writing files
430 """
431 logger.debug("Executing encrypt extended action.")
432 if config.options is None or config.stage is None:
433 raise ValueError("Cedar Backup configuration is not properly filled in.")
434 local = LocalConfig(xmlPath=configPath)
435 if local.encrypt.encryptMode != "gpg":
436 raise ValueError("Unknown encrypt mode [%s]" % local.encrypt.encryptMode)
437 if local.encrypt.encryptMode == "gpg":
438 _confirmGpgRecipient(local.encrypt.encryptTarget)
439 dailyDirs = findDailyDirs(config.stage.targetDir, ENCRYPT_INDICATOR)
440 for dailyDir in dailyDirs:
441 _encryptDailyDir(
442 dailyDir, local.encrypt.encryptMode, local.encrypt.encryptTarget, config.options.backupUser, config.options.backupGroup
443 )
444 writeIndicatorFile(dailyDir, ENCRYPT_INDICATOR, config.options.backupUser, config.options.backupGroup)
445 logger.info("Executed the encrypt extended action successfully.")
446
447
448 ##############################
449 # _encryptDailyDir() function
450 ##############################
451
452
453 def _encryptDailyDir(dailyDir, encryptMode, encryptTarget, backupUser, backupGroup):
454 """
455 Encrypts the contents of a daily staging directory.
456
457 Indicator files are ignored. All other files are encrypted. The only valid
458 encrypt mode is ``"gpg"``.
459
460 Args:
461 dailyDir: Daily directory to encrypt
462 encryptMode: Encryption mode (only "gpg" is allowed)
463 encryptTarget: Encryption target (GPG recipient for "gpg" mode)
464 backupUser: User that target files should be owned by
465 backupGroup: Group that target files should be owned by
466
467 Raises:
468 ValueError: If the encrypt mode is not supported
469 ValueError: If the daily staging directory does not exist
470 """
471 logger.debug("Begin encrypting contents of [%s].", dailyDir)
472 fileList = getBackupFiles(dailyDir) # ignores indicator files
473 for path in fileList:
474 _encryptFile(path, encryptMode, encryptTarget, backupUser, backupGroup, removeSource=True)
475 logger.debug("Completed encrypting contents of [%s].", dailyDir)
476
477
478 ##########################
479 # _encryptFile() function
480 ##########################
481
482
483 def _encryptFile(sourcePath, encryptMode, encryptTarget, backupUser, backupGroup, removeSource=False):
484 """
485 Encrypts the source file using the indicated mode.
486
487 The encrypted file will be owned by the indicated backup user and group. If
488 ``removeSource`` is ``True``, then the source file will be removed after it is
489 successfully encrypted.
490
491 Currently, only the ``"gpg"`` encrypt mode is supported.
492
493 Args:
494 sourcePath: Absolute path of the source file to encrypt
495 encryptMode: Encryption mode (only "gpg" is allowed)
496 encryptTarget: Encryption target (GPG recipient)
497 backupUser: User that target files should be owned by
498 backupGroup: Group that target files should be owned by
499 removeSource: Indicates whether to remove the source file
500
501 Returns:
502 Path to the newly-created encrypted file
503
504 Raises:
505 ValueError: If an invalid encrypt mode is passed in
506 IOError: If there is a problem accessing, encrypting or removing the source file
507 """
508 if not os.path.exists(sourcePath):
509 raise ValueError("Source path [%s] does not exist." % sourcePath)
510 if encryptMode == "gpg":
511 encryptedPath = _encryptFileWithGpg(sourcePath, recipient=encryptTarget)
512 else:
513 raise ValueError("Unknown encrypt mode [%s]" % encryptMode)
514 changeOwnership(encryptedPath, backupUser, backupGroup)
515 if removeSource:
516 if os.path.exists(sourcePath):
517 try:
518 os.remove(sourcePath)
519 logger.debug("Completed removing old file [%s].", sourcePath)
520 except Exception:
521 raise OSError("Failed to remove file [%s] after encrypting it." % (sourcePath))
522 return encryptedPath
523
524
525 #################################
526 # _encryptFileWithGpg() function
527 #################################
528
529
530 def _encryptFileWithGpg(sourcePath, recipient):
531 """
532 Encrypts the indicated source file using GPG.
533
534 The encrypted file will be in GPG's binary output format and will have the
535 same name as the source file plus a ``".gpg"`` extension. The source file
536 will not be modified or removed by this function call.
537
538 Args:
539 sourcePath: Absolute path of file to be encrypted
540 recipient: Recipient name to be passed to GPG's ``"-r"`` option
541
542 Returns:
543 Path to the newly-created encrypted file
544
545 Raises:
546 IOError: If there is a problem encrypting the file
547 """
548 encryptedPath = "%s.gpg" % sourcePath
549 command = resolveCommand(GPG_COMMAND)
550 args = ["--batch", "--yes", "-e", "-r", recipient, "-o", encryptedPath, sourcePath]
551 result = executeCommand(command, args)[0]
552 if result != 0:
553 raise OSError("Error [%d] calling gpg to encrypt [%s]." % (result, sourcePath))
554 if not os.path.exists(encryptedPath):
555 raise OSError("After call to [%s], encrypted file [%s] does not exist." % (command, encryptedPath))
556 logger.debug("Completed encrypting file [%s] to [%s].", sourcePath, encryptedPath)
557 return encryptedPath
558
559
560 #################################
561 # _confirmGpgRecpient() function
562 #################################
563
564
565 def _confirmGpgRecipient(recipient):
566 """
567 Confirms that a recipient's public key is known to GPG.
568 Throws an exception if there is a problem, or returns normally otherwise.
569 Args:
570 recipient: Recipient name
571 Raises:
572 IOError: If the recipient's public key is not known to GPG
573 """
574 command = resolveCommand(GPG_COMMAND)
575 args = ["--batch", "-k", recipient] # should use --with-colons if the output will be parsed
576 result = executeCommand(command, args)[0]
577 if result != 0:
578 raise OSError("GPG unable to find public key for [%s]." % recipient)