Exemplo n.º 1
0
    def test_add_ca_to_dir(self, temp_mock, os_mock, open_mock):
        """ Test the add_ca_to_dir functions. """
        os_mock.path.join.side_effect = os.path.join
        os_mock.path.exists.return_value = False
        cert_pem = TESTCERT_AND_KEY[0]
        cert_hash = TESTCERT_HASH
        # Try just writing a single CA and check it gets written to the
        # correct name.
        res = X509Utils.add_ca_to_dir([cert_pem], "/mydir")
        self.assertEqual(res, "/mydir")
        open_mock.assert_has_calls([
            mock.call("/mydir/%s.0" % cert_hash, "w"),
            mock.call("/mydir/%s.signing_policy" % cert_hash, "w")
        ],
                                   any_order=True)
        # Test directory creation
        temp_mock.mkdtemp.return_value = "/tmpca.test"
        res = X509Utils.add_ca_to_dir([cert_pem])
        self.assertEqual(res, "/tmpca.test")
        # Check that duplicate CA causes an exception
        os_mock.path.exists.return_value = True
        self.assertRaises(Exception, X509Utils.add_ca_to_dir, [cert_pem],
                          "/mydir")

        def pol_exists(path):
            return path.endswith('.signing_policy')

        os_mock.path.exists.side_effect = pol_exists
        self.assertRaises(Exception, X509Utils.add_ca_to_dir, [cert_pem],
                          "/mydir")
Exemplo n.º 2
0
 def test_add_ca_to_dir_template(self, dir_util_mock, temp_mock):
     """ Test that the add_ca_to_dir template function
         works as expected.
     """
     temp_mock.mkdtemp.return_value = "/new/dir"
     res = X509Utils.add_ca_to_dir([], template_dir="/my/template")
     self.assertEqual(res, "/new/dir")
     dir_util_mock.copy_tree.assert_called_with("/my/template",
                                                "/new/dir",
                                                preserve_symlinks=True)
Exemplo n.º 3
0
Arquivo: Worker.py Projeto: ic-hep/pdm
def temporary_ca_dir(cas, dir_path=None, template_dir=None):
    """
    Context for creating a temporary CA directory.

    Temporary directory is automatically removed when exiting context.

    Args:
        cas (list): List of CA certs in string form.
        dir_path (str): Path to use for temporary ca directory. If None (default) then a
                        random dir_path is created.
        template_dir (str): Path to a directory to use as a template for the temporary
                            ca dir. All certs in this directory are duplicated in the new one.
                            If None (default) then don't use a template directory.

    Returns:
        str: The temporary ca dir.
    """
    ca_dir = X509Utils.add_ca_to_dir(cas,
                                     dir_path=dir_path,
                                     template_dir=template_dir)
    yield ca_dir
    shutil.rmtree(ca_dir, ignore_errors=True)
Exemplo n.º 4
0
 def logon(myproxy_server,
           username,
           password,
           ca_certs=None,
           voms=None,
           hours=12,
           myproxy_bin=None,
           vomses=None,
           log=None):
     """ Runs the myproxy-logon command with the various parameters.
         myproxy_server - Server to contact in hostname:port format.
         username - Username to use a remote site.
         password - Password to use at remote site.
         ca_certs - Either None to use the system CA,
                    A string to use as the path to a CA dir,
                    Or a list of strings containing individual PEM files
                    to use as the CA(s).
         voms - An optional VO name to request a VOMS extension for.
         hours - Number of hours to request as the lifetime of the new
                 credential.
         myproxy_bin - Location of the myproxy-logon executable to use,
                       if unset, $PATH will be searched instead.
         vomses - Location of the vomses directory to use if issuing a VOMS
                  proxy. Inherited from parent process otherwise.
         log - Optional logger object to write debug information to.
         Returns a string with the new credential PEM. Raises a
         RuntimeError exception if anything goes wrong.
     """
     with tempfile.NamedTemporaryFile() as proxy:
         hostname, port = myproxy_server.split(':', 1)
         myproxy_opts = [
             'myproxy-logon',  # Exectuable name
             '-s',
             hostname,  # MyProxy server name
             '-p',
             '%s' % port,  # MyProxy port number
             '-l',
             username,  # Username at remote site
             '-t',
             '%u' % hours,  # Lifetime in hours
             '-o',
             proxy.name,  # Proxy on stdout
             '-q',  # Quiet (output only on error)
             '-S',  # Password on stdin
         ]
         if myproxy_bin:
             myproxy_opts[0] = myproxy_bin
         if voms:
             myproxy_opts.extend(['-m', voms])
         env = copy.deepcopy(os.environ)
         ca_dir = None
         if ca_certs:
             if isinstance(ca_certs, str):
                 # CA certs is a path to a cert dir
                 env["X509_CERT_DIR"] = ca_certs
             else:
                 # ca_certs is a list of PEM strings
                 ca_dir = X509Utils.add_ca_to_dir(ca_certs, None)
                 env["X509_CERT_DIR"] = ca_dir
         if vomses:
             env["VOMS_USERCONF"] = vomses
         # Actually run the command
         if log:
             log.debug("Running myproxy-logon with: %s",
                       " ".join(myproxy_opts))
             log.debug("  myproxy-logon env: %s", str(env))
         proc = Popen(myproxy_opts,
                      shell=False,
                      stdin=PIPE,
                      stdout=PIPE,
                      stderr=PIPE,
                      env=env)
         try:
             stdout, stderr = proc.communicate('%s\n' % password)
         except Exception as err:
             if log:
                 log.warn("myproxy-logon command failed: %s", str(err))
             raise RuntimeError("Logon error: Failed to run myproxy-logon")
         finally:
             # Make sure we tidy up the CA dir if we created one
             if ca_dir:
                 shutil.rmtree(ca_dir, ignore_errors=True)
         # Check the return code
         if proc.returncode != 0:
             # Command failed, attempt to infer the reason
             error_str = "Unknown myproxy failure"
             if "invalid password" in stderr:
                 error_str = "Incorrect password"
             elif "Unable to connect to" in stderr:
                 error_str = "Connection error"
             elif "No credentials exist for username" in stderr:
                 error_str = "Unrecognised user"
             elif "Error in service module" in stderr:
                 error_str = "Unrecognised user/config error"
             if log:
                 log.warn("myproxy-logon command failed with code %u (%s)",
                          proc.returncode, error_str)
                 log.debug("myproxy-logon stderr: %s", stderr)
             raise RuntimeError("Logon error: %s" % error_str)
         # Re-open the file to avoid any buffering
         with open(proxy.name, "r") as proxy_fd:
             proxy_str = proxy_fd.read().strip()
         return proxy_str  # Proxy is just a string on stdout