def test_view_config_changes_bad_backups_dir(self): # There shouldn't be any "in progress directories when this is called # It must just be clean checkpoints filesystem.makedirs(os.path.join(self.config.backup_dir, "in_progress")) self.assertRaises( errors.ReverterError, self.reverter.view_config_changes)
def make_or_verify_dir(directory, mode=0o755, strict=False): """Make sure directory exists with proper permissions. :param str directory: Path to a directory. :param int mode: Directory mode. :param bool strict: require directory to be owned by current user :raises .errors.Error: if a directory already exists, but has wrong permissions or owner :raises OSError: if invalid or inaccessible file names and paths, or other arguments that have the correct type, but are not accepted by the operating system. """ try: filesystem.makedirs(directory, mode) except OSError as exception: if exception.errno == errno.EEXIST: if strict and not filesystem.check_permissions(directory, mode): raise errors.Error( "%s exists, but it should be owned by current user with" " permissions %s" % (directory, oct(mode))) else: raise
def setUp(self): super(RenewHookTest, self).setUp() self.config.renew_hook = "foo" filesystem.makedirs(self.config.renewal_deploy_hooks_dir) self.dir_hook = os.path.join(self.config.renewal_deploy_hooks_dir, "bar") create_hook(self.dir_hook)
def _set_up_challenges(self): if not os.path.isdir(self.challenge_dir): filesystem.makedirs(self.challenge_dir, 0o755) responses = [] for achall in self.achalls: responses.append(self._set_up_challenge(achall)) return responses
def setUp(self): super().setUp() self.config.post_hook = "bar" filesystem.makedirs(self.config.renewal_post_hooks_dir) self.dir_hook = os.path.join(self.config.renewal_post_hooks_dir, "foo") create_hook(self.dir_hook) # Reset this value as it may have been modified by past tests self._reset_post_hook_eventually()
def setUp(self): super(PreHookTest, self).setUp() self.config.pre_hook = "foo" filesystem.makedirs(self.config.renewal_pre_hooks_dir) self.dir_hook = os.path.join(self.config.renewal_pre_hooks_dir, "bar") create_hook(self.dir_hook) # Reset this value as it may have been modified by past tests self._reset_pre_hook_already()
def test_makedirs_correct_permissions(self): path = os.path.join(self.tempdir, 'dir') subpath = os.path.join(path, 'subpath') filesystem.makedirs(subpath, 0o700) everybody = win32security.ConvertStringSidToSid(EVERYBODY_SID) dacl = _get_security_dacl(subpath).GetSecurityDescriptorDacl() self.assertFalse([dacl.GetAce(index) for index in range(0, dacl.GetAceCount()) if dacl.GetAce(index)[2] == everybody])
def test_makedirs_switch_os_mkdir(self): path = os.path.join(self.tempdir, 'dir') import os as std_os # pylint: disable=os-module-forbidden original_mkdir = std_os.mkdir filesystem.makedirs(path) self.assertEqual(original_mkdir, std_os.mkdir) try: filesystem.makedirs(path) # Will fail because path already exists except OSError: pass self.assertEqual(original_mkdir, std_os.mkdir)
def test_makedirs_correct_permissions(self): path = os.path.join(self.tempdir, 'dir') subpath = os.path.join(path, 'subpath') previous_umask = filesystem.umask(0o022) try: filesystem.makedirs(subpath, 0o700) assert filesystem.check_mode(path, 0o700) assert filesystem.check_mode(subpath, 0o700) finally: filesystem.umask(previous_umask)
def test_certificates_no_files(self, mock_utility, mock_logger): empty_tempdir = tempfile.mkdtemp() empty_config = configuration.NamespaceConfig( mock.MagicMock(config_dir=os.path.join(empty_tempdir, "config"), work_dir=os.path.join(empty_tempdir, "work"), logs_dir=os.path.join(empty_tempdir, "logs"), quiet=False)) filesystem.makedirs(empty_config.renewal_configs_dir) self._certificates(empty_config) self.assertFalse(mock_logger.warning.called) self.assertTrue(mock_utility.called) shutil.rmtree(empty_tempdir)
def test_makedirs_correct_permissions(self): path = os.path.join(self.tempdir, 'dir') subpath = os.path.join(path, 'subpath') previous_umask = os.umask(0o022) try: filesystem.makedirs(subpath, 0o700) import os as std_os # pylint: disable=os-module-forbidden assert stat.S_IMODE(std_os.stat(path).st_mode) == 0o700 assert stat.S_IMODE(std_os.stat(subpath).st_mode) == 0o700 finally: os.umask(previous_umask)
def test_foreign_webconfig_multiple_domains(self): # Covers bug https://github.com/certbot/certbot/issues/9091 achall_2 = achallenges.KeyAuthorizationAnnotatedChallenge( challb=acme_util.chall_to_challb(challenges.HTTP01(token=b"bingo"), "pending"), domain="second-thing.com", account_key=KEY) self.config.webroot_map["second-thing.com"] = self.path challenge_path = os.path.join(self.path, ".well-known", "acme-challenge") filesystem.makedirs(challenge_path) webconfig_path = os.path.join(challenge_path, "web.config") with open(webconfig_path, "w") as file: file.write("something") self.auth.perform([self.achall, achall_2])
def _set_up_challenges(self): if not os.path.isdir(self.challenge_dir): old_umask = filesystem.umask(0o022) try: filesystem.makedirs(self.challenge_dir, 0o755) except OSError as exception: if exception.errno not in (errno.EEXIST, errno.EISDIR): raise errors.PluginError( "Couldn't create root for http-01 challenge") finally: filesystem.umask(old_umask) responses = [] for achall in self.achalls: responses.append(self._set_up_challenge(achall)) return responses
def make_lineage(config_dir: str, testfile: str, ec: bool = False) -> str: """Creates a lineage defined by testfile. This creates the archive, live, and renewal directories if necessary and creates a simple lineage. :param str config_dir: path to the configuration directory :param str testfile: configuration file to base the lineage on :param bool ec: True if we generate the lineage with an ECDSA key :returns: path to the renewal conf file for the created lineage :rtype: str """ lineage_name = testfile[:-len('.conf')] conf_dir = os.path.join(config_dir, constants.RENEWAL_CONFIGS_DIR) archive_dir = os.path.join(config_dir, constants.ARCHIVE_DIR, lineage_name) live_dir = os.path.join(config_dir, constants.LIVE_DIR, lineage_name) for directory in ( archive_dir, conf_dir, live_dir, ): if not os.path.exists(directory): filesystem.makedirs(directory) sample_archive = vector_path( 'sample-archive{}'.format('-ec' if ec else '')) for kind in os.listdir(sample_archive): shutil.copyfile(os.path.join(sample_archive, kind), os.path.join(archive_dir, kind)) for kind in storage.ALL_FOUR: os.symlink(os.path.join(archive_dir, '{0}1.pem'.format(kind)), os.path.join(live_dir, '{0}.pem'.format(kind))) conf_path = os.path.join(config_dir, conf_dir, testfile) with open(vector_path(testfile)) as src: with open(conf_path, 'w') as dst: dst.writelines( line.replace('MAGICDIR', config_dir) for line in src) return conf_path
def setUp(self): super().setUp() self.config.quiet = False filesystem.makedirs(self.config.renewal_configs_dir) self.domains = { "example.org": None, "other.com": os.path.join(self.config.config_dir, "specialarchive") } self.config_files = {domain: self._set_up_config(domain, self.domains[domain]) for domain in self.domains} # We also create a file that isn't a renewal config in the same # location to test that logic that reads in all-and-only renewal # configs will ignore it and NOT attempt to parse it. with open(os.path.join(self.config.renewal_configs_dir, "IGNORE.THIS"), "w") as junk: junk.write("This file should be ignored!")
def test_foreign_webconfig_file_handling(self, mock_get_utility): mock_display = mock_get_utility() mock_display.menu.return_value = ( display_util.OK, 1, ) challenge_path = os.path.join(self.path, ".well-known", "acme-challenge") filesystem.makedirs(challenge_path) webconfig_path = os.path.join(challenge_path, "web.config") with open(webconfig_path, "w") as file: file.write("something") self.auth.perform([self.achall]) from certbot import crypto_util webconfig_hash = crypto_util.sha256sum(webconfig_path) from certbot._internal.plugins.webroot import _WEB_CONFIG_SHA256SUMS self.assertTrue(webconfig_hash not in _WEB_CONFIG_SHA256SUMS)
def setUp(self): super().setUp() display_obj.set_display(display_obj.FileDisplay(sys.stdout, False)) self.account_keys_dir = os.path.join(self.tempdir, "keys") filesystem.makedirs(self.account_keys_dir, 0o700) self.config = mock.MagicMock( accounts_dir=self.tempdir, account_keys_dir=self.account_keys_dir, server="certbot-demo.org") self.key = KEY self.acc1 = account.Account(messages.RegistrationResource( uri=None, body=messages.Registration.from_data( email="*****@*****.**")), self.key) self.acc2 = account.Account(messages.RegistrationResource( uri=None, body=messages.Registration.from_data( email="*****@*****.**", phone="phone")), self.key)
def setUp(self): from certbot._internal import storage super().setUp() # TODO: maybe provide NamespaceConfig.make_dirs? # TODO: main() should create those dirs, c.f. #902 filesystem.makedirs( os.path.join(self.config.config_dir, "live", "example.org")) archive_path = os.path.join(self.config.config_dir, "archive", "example.org") filesystem.makedirs(archive_path) filesystem.makedirs(os.path.join(self.config.config_dir, "renewal")) config_file = configobj.ConfigObj() for kind in ALL_FOUR: kind_path = os.path.join(self.config.config_dir, "live", "example.org", kind + ".pem") config_file[kind] = kind_path with open( os.path.join(self.config.config_dir, "live", "example.org", "README"), 'a'): pass config_file["archive"] = archive_path config_file.filename = os.path.join(self.config.config_dir, "renewal", "example.org.conf") config_file.write() self.config_file = config_file # We also create a file that isn't a renewal config in the same # location to test that logic that reads in all-and-only renewal # configs will ignore it and NOT attempt to parse it. with open( os.path.join(self.config.config_dir, "renewal", "IGNORE.THIS"), "w") as junk: junk.write("This file should be ignored!") self.defaults = configobj.ConfigObj() with mock.patch( "certbot._internal.storage.RenewableCert._check_symlinks" ) as check: check.return_value = True self.test_rc = storage.RenewableCert(config_file.filename, self.config)
def _set_up_config(self, domain, custom_archive): # TODO: maybe provide NamespaceConfig.make_dirs? # TODO: main() should create those dirs, c.f. #902 filesystem.makedirs(os.path.join(self.config.live_dir, domain)) config_file = configobj.ConfigObj() if custom_archive is not None: filesystem.makedirs(custom_archive) config_file["archive_dir"] = custom_archive else: filesystem.makedirs(os.path.join(self.config.default_archive_dir, domain)) for kind in ALL_FOUR: config_file[kind] = os.path.join(self.config.live_dir, domain, kind + ".pem") config_file.filename = os.path.join(self.config.renewal_configs_dir, domain + ".conf") config_file.write() return config_file
def new_lineage(cls, lineagename, cert, privkey, chain, cli_config): """Create a new certificate lineage. Attempts to create a certificate lineage -- enrolled for potential future renewal -- with the (suggested) lineage name lineagename, and the associated cert, privkey, and chain (the associated fullchain will be created automatically). Optional configurator and renewalparams record the configuration that was originally used to obtain this cert, so that it can be reused later during automated renewal. Returns a new RenewableCert object referring to the created lineage. (The actual lineage name, as well as all the relevant file paths, will be available within this object.) :param str lineagename: the suggested name for this lineage (normally the current cert's first subject DNS name) :param str cert: the initial certificate version in PEM format :param str privkey: the private key in PEM format :param str chain: the certificate chain in PEM format :param .NamespaceConfig cli_config: parsed command line arguments :returns: the newly-created RenewalCert object :rtype: :class:`storage.renewableCert` """ # Examine the configuration and find the new lineage's name for i in (cli_config.renewal_configs_dir, cli_config.default_archive_dir, cli_config.live_dir): if not os.path.exists(i): filesystem.makedirs(i, 0o700) logger.debug("Creating directory %s.", i) config_file, config_filename = util.unique_lineage_name( cli_config.renewal_configs_dir, lineagename) base_readme_path = os.path.join(cli_config.live_dir, README) if not os.path.exists(base_readme_path): _write_live_readme_to(base_readme_path, is_base_dir=True) # Determine where on disk everything will go # lineagename will now potentially be modified based on which # renewal configuration file could actually be created lineagename = lineagename_for_filename(config_filename) archive = full_archive_path(None, cli_config, lineagename) live_dir = _full_live_path(cli_config, lineagename) if os.path.exists(archive) and (not os.path.isdir(archive) or os.listdir(archive)): config_file.close() raise errors.CertStorageError("archive directory exists for " + lineagename) if os.path.exists(live_dir) and (not os.path.isdir(live_dir) or os.listdir(live_dir)): config_file.close() raise errors.CertStorageError("live directory exists for " + lineagename) for i in (archive, live_dir): if not os.path.exists(i): filesystem.makedirs(i) logger.debug("Creating directory %s.", i) # Put the data into the appropriate files on disk target = { kind: os.path.join(live_dir, kind + ".pem") for kind in ALL_FOUR } archive_target = { kind: os.path.join(archive, kind + "1.pem") for kind in ALL_FOUR } for kind in ALL_FOUR: os.symlink(_relpath_from_file(archive_target[kind], target[kind]), target[kind]) with open(target["cert"], "wb") as f: logger.debug("Writing certificate to %s.", target["cert"]) f.write(cert) with util.safe_open(archive_target["privkey"], "wb", chmod=BASE_PRIVKEY_MODE) as f: logger.debug("Writing private key to %s.", target["privkey"]) f.write(privkey) # XXX: Let's make sure to get the file permissions right here with open(target["chain"], "wb") as f: logger.debug("Writing chain to %s.", target["chain"]) f.write(chain) with open(target["fullchain"], "wb") as f: # assumes that OpenSSL.crypto.dump_certificate includes # ending newline character logger.debug("Writing full chain to %s.", target["fullchain"]) f.write(cert + chain) # Write a README file to the live directory readme_path = os.path.join(live_dir, README) _write_live_readme_to(readme_path) # Document what we've done in a new renewal config file config_file.close() # Save only the config items that are relevant to renewal values = relevant_values(vars(cli_config.namespace)) new_config = write_renewal_config(config_filename, config_filename, archive, target, values) return cls(new_config.filename, cli_config)