Ejemplo n.º 1
0
 private static void reloadDefaultCredential() throws CredentialException {
   String proxyLocation = CoGProperties.getDefault().getProxyFile();
   defaultCred = new X509Credential(proxyLocation);
   credentialFile = new File(proxyLocation);
   credentialLastModified = credentialFile.lastModified();
   defaultCred.verify();
 }
Ejemplo n.º 2
0
  public GSIAuthenticationClient() throws GSSException, IOException {

    // override the search path for the CA directory: (GSI-SSHTERM writes in the
    // ~/.globus/certificates so we don;t use this)
    // 1) java X509_CERT_DIR property
    // 2) override with X509_CERT_DIR env var
    // 3) default /etc/grid-security/certificates
    String x509CertDir = System.getProperty("X509_CERT_DIR");
    if (x509CertDir == null) {
      x509CertDir = System.getenv("X509_CERT_DIR");
      if (x509CertDir == null) x509CertDir = "/etc/grid-security/certificates";
      System.setProperty("X509_CERT_DIR", x509CertDir);
    }

    String x509UserProxy = System.getProperty("X509_USER_PROXY");
    if (x509UserProxy == null) {
      x509UserProxy = System.getenv("X509_USER_PROXY");
      if (x509UserProxy != null) System.setProperty("X509_USER_PROXY", x509UserProxy);
    }
    if (x509UserProxy == null) x509UserProxy = CoGProperties.getDefault().getProxyFile();
    if (!new File(x509UserProxy).isFile())
      throw new IOException("User proxy certificate not found in environment");

    logger.info("Using proxy certificate:" + x509UserProxy);

    try {
      gsscredential = createUserCredential(x509UserProxy);
    } catch (GlobusCredentialException e) {
      throw new IOException("Could not load user proxy certificate from:" + x509UserProxy);
    }
    if (gsscredential == null) {
      throw new IOException(
          "User credential not initialized !Could not load user proxy certificate. Check your environmen if you have X509_USER_CERT proxy set up");
    }
  }
Ejemplo n.º 3
0
  public static void main(String args[]) {

    boolean dryrun = false;
    boolean error = false;
    boolean debug = false;
    File file = null;

    for (int i = 0; i < args.length; i++) {
      if (args[i].equalsIgnoreCase("-dryrun")) {
        dryrun = true;
      } else if (args[i].equalsIgnoreCase("-help") || args[i].equalsIgnoreCase("-usage")) {
        System.err.println(message);
        System.exit(1);
      } else {
        file = new File(args[i]);
        if (dryrun) {
          System.out.println("Would remove " + file.getAbsolutePath());
          continue;
        }
        Util.destroy(file);
      }
    }

    String fn = CoGProperties.getDefault().getProxyFile();
    if (fn == null) return;
    file = new File(fn);
    if (dryrun) {
      System.out.println("Would remove " + file.getAbsolutePath());
      return;
    }

    Util.destroy(file);
  }
Ejemplo n.º 4
0
 @Override
 public String saveProxy() {
   String path = this.localPath;
   if (StringUtils.isBlank(this.localPath)) {
     path = CoGProperties.getDefault().getProxyFile();
   }
   return saveProxy(path);
 }
Ejemplo n.º 5
0
 public Socket createSocket(InetAddress address, int port, InetAddress localAddr, int localPort)
     throws IOException {
   if (this.portRange.isEnabled() && localPort == 0) {
     return new PrSocket(createSocket(address, port, localAddr));
   } else {
     Socket s = new Socket(address, port, localAddr, localPort);
     s.setSoTimeout(CoGProperties.getDefault().getSocketTimeout());
     return s;
   }
 }
Ejemplo n.º 6
0
 /**
  * Installs SecureRandom provider. This function is automatically called when this class is
  * loaded.
  */
 public static void installSecureRandomProvider() {
   CoGProperties props = CoGProperties.getDefault();
   String providerName = props.getSecureRandomProvider();
   try {
     Class providerClass = Class.forName(providerName);
     Security.insertProviderAt((Provider) providerClass.newInstance(), 1);
   } catch (Exception e) {
     logger.debug("Unable to install PRNG. Using default PRNG.", e);
   }
 }
Ejemplo n.º 7
0
 /**
  * Verifies the validity of the credentials. All certificate path validation is performed using
  * trusted certificates in default locations.
  *
  * @exception CredentialException if one of the certificates in the chain expired or if path
  *     validiation fails.
  */
 public void verify() throws CredentialException {
   try {
     String caCertsLocation = "file:" + CoGProperties.getDefault().getCaCertLocations();
     String crlPattern = caCertsLocation + "/*.r*";
     String sigPolPattern = caCertsLocation + "/*.signing_policy";
     KeyStore keyStore =
         KeyStore.getInstance(GlobusProvider.KEYSTORE_TYPE, GlobusProvider.PROVIDER_NAME);
     CertStore crlStore =
         CertStore.getInstance(
             GlobusProvider.CERTSTORE_TYPE, new ResourceCertStoreParameters(null, crlPattern));
     ResourceSigningPolicyStore sigPolStore =
         new ResourceSigningPolicyStore(new ResourceSigningPolicyStoreParameters(sigPolPattern));
     keyStore.load(KeyStoreParametersFactory.createTrustStoreParameters(caCertsLocation));
     X509ProxyCertPathParameters parameters =
         new X509ProxyCertPathParameters(keyStore, crlStore, sigPolStore, false);
     X509ProxyCertPathValidator validator = new X509ProxyCertPathValidator();
     validator.engineValidate(CertificateUtil.getCertPath(certChain), parameters);
   } catch (Exception e) {
     throw new CredentialException(e);
   }
 }
Ejemplo n.º 8
0
public class GridSessionCred implements Cred {

  // public static boolean useGridSession = CommonGridProperties.getDefault()
  // .useGridSession();

  static final Logger myLogger = LoggerFactory.getLogger(GridSessionCred.class.getName());

  public static GridSessionCred create() {

    SessionClient sc;
    try {
      sc = new SessionClient();
      return new GridSessionCred(sc);
    } catch (Exception e) {
      throw new CredentialException("Can't create session: " + e.getLocalizedMessage());
    }
  }

  private final SessionClient session;

  private final String tempFilePath =
      CoGProperties.getDefault().getProxyFile() + "_temp_" + UUID.randomUUID().toString();

  private final File tempFile = new File(tempFilePath);

  private AbstractCred cachedCredential = null;
  private Map<String, AbstractCred> cachedGroupCredentials = Maps.newHashMap();

  // not used
  private boolean saveProxyOnCreation = true;

  public GridSessionCred(SessionClient client) {
    this(client, true);
  }

  public GridSessionCred(SessionClient client, boolean saveProxyOnCreation) {
    this.saveProxyOnCreation = saveProxyOnCreation;
    tempFile.deleteOnExit();

    if (client == null) {
      throw new RuntimeException("Client can't be null");
    }

    this.session = client;
  }

  public GridSessionCred(SessionClient client, Map<PROPERTY, Object> params) {
    this(client);
    init(params);
  }

  @Override
  public void destroy() {
    //		session.getSession().stop();
    session.getSession().destroy();
  }

  @Override
  public String getDN() {
    return session.getSession().dn();
  }

  @Override
  public String getMyProxyHost() {
    return session.getSession().myproxy_host();
  }

  @Override
  public char[] getMyProxyPassword() {
    return session.getSession().myproxy_password().toCharArray();
  }

  @Override
  public int getMyProxyPort() {
    return session.getSession().myproxy_port();
  }

  @Override
  public String getMyProxyUsername() {
    return session.getSession().myproxy_username();
  }

  @Override
  public int getRemainingLifetime() {
    return session.getSession().lifetime();
  }

  @Override
  public void init(Map<PROPERTY, Object> config) {

    Map<String, Object> configTemp = Maps.newHashMap();

    for (PROPERTY key : config.keySet()) {
      configTemp.put(key.toString(), config.get(key));
    }

    session.getSession().start(configTemp);
  }

  @Override
  public boolean isRenewable() {
    return session.getSession().is_renewable();
  }

  @Override
  public boolean isValid() {
    return session.getSession().is_logged_in();
  }

  @Override
  public boolean refresh() {
    return session.getSession().refresh();
  }

  @Override
  public String saveProxy() {
    return session.getSession().save_proxy();
  }

  @Override
  public String saveProxy(String path) {
    return session.getSession().save_proxy(path);
  }

  @Override
  public void setMinimumLifetime(int lifetimeInSeconds) {
    session.getSession().set_min_lifetime(lifetimeInSeconds);
  }

  @Override
  public void setMyProxyHost(String myProxyServer) {
    session.getSession().set_myproxy_host(myProxyServer);
  }

  @Override
  public void setMyProxyPort(int port) {
    session.getSession().set_myproxy_port(port);
  }

  @Override
  public void uploadMyProxy() {
    session.getSession().upload();
  }

  private synchronized AbstractCred getCachedCredential() {
    if (cachedCredential == null) {
      // might be that it's already a proxycred, then it doesn't get saved again.ls -l
      String temp = session.getSession().save_proxy(tempFilePath);
      cachedCredential = new ProxyCred(temp);
    }
    return cachedCredential;
  }

  private synchronized AbstractCred getCachedGroupCredential(String fqan) {

    if (StringUtils.isBlank(fqan) || Constants.NON_VO_FQAN.equals(fqan)) {
      return this.getCachedCredential();
    }

    if (cachedGroupCredentials.get(fqan) == null) {
      String fqanNormailzed = fqan.replace('/', '_');
      String path = tempFilePath + "_" + fqanNormailzed;
      new File(path).deleteOnExit();
      session.getSession().save_group_proxy(fqan, path);
      ProxyCred c = new ProxyCred(path);
      cachedGroupCredentials.put(fqan, c);
    }
    return cachedGroupCredentials.get(fqan);
  }

  @Override
  public GSSCredential getGSSCredential() {

    return getCachedCredential().getGSSCredential();
  }

  @Override
  public String getFqan() {
    // a session credential is always non-vomsified
    return Constants.NON_VO_FQAN;
  }

  @Override
  public Cred getGroupCredential(String fqan) {
    return getCachedGroupCredential(fqan);
  }

  @Override
  public Map<String, VO> getAvailableFqans() {
    return getCachedCredential().getAvailableFqans();
  }

  @Override
  public void setSaveProxyOnCreation(boolean save) {
    this.saveProxyOnCreation = save;
  }

  @Override
  public boolean getSaveProxyOnCreation() {
    return this.saveProxyOnCreation;
  }

  @Override
  public String getProxyPath() {
    return getCachedCredential().getProxyPath();
  }

  @Override
  public VOManager getVOManager() {
    return getCachedCredential().getVOManager();
  }
}
Ejemplo n.º 9
0
  @Override
  protected void initCred(Map<PROPERTY, Object> config) {

    Object proxyTemp = null;
    if (config != null) {

      proxyTemp = config.get(PROPERTY.LocalPath);
    }
    if ((proxyTemp == null)
        || !(proxyTemp instanceof String)
        || StringUtils.isBlank((String) proxyTemp)) {
      proxyTemp = CoGProperties.getDefault().getProxyFile();
    }

    getProxyFile().set((String) proxyTemp);
    this.localPath = proxyFile.getValue();

    String mpFilePath = this.localPath + BaseCred.DEFAULT_MYPROXY_FILE_EXTENSION;
    File mpFile = new File(mpFilePath);
    if (mpFile.exists()) {
      myLogger.debug("Loading credential myproxy metadata from {}...", mpFilePath);

      try {

        Properties props = new Properties();
        FileInputStream in = new FileInputStream(mpFile);
        props.load(in);
        in.close();

        String username = null;
        String host = null;
        int port = -1;
        char[] password = null;
        for (Object o : props.keySet()) {

          String key = (String) o;

          PROPERTY p = PROPERTY.valueOf(key);
          String value = props.getProperty(key);

          switch (p) {
            case MyProxyHost:
              host = value;
              break;
            case MyProxyUsername:
              username = value;
              break;
            case MyProxyPort:
              port = Integer.parseInt(value);
              break;
            case MyProxyPassword:
              password = value.toCharArray();
              break;
            default:
              throw new CredentialException("Property " + p + " not supported.");
          }
        }

        if (StringUtils.isNotBlank(host)) {
          setMyProxyHost(host);
        }

        if (StringUtils.isNotBlank(username)) {
          setMyProxyUsername(username);
        }

        if (port > 0) {
          setMyProxyPort(port);
        }

        if (password != null) {
          setMyProxyPassword(password);
        }

        isUploaded = true;

      } catch (Exception e) {
        myLogger.error("Can't load myproxy metadata file", e);
      }

    } else {
      myLogger.debug("No myproxy metadata file found for cred.");
    }
  }
Ejemplo n.º 10
0
  public static void main(String[] args) {

    boolean bOk = parseCmdLine(args);

    String userCertFile = "";
    String userKeyFile = "";
    String userCertReqFile = "";
    if (bOk) {

      // Get default location of cert.
      CoGProperties props = CoGProperties.getDefault();

      // If no alternate directory specified.
      if (certDir == null) {
        userCertFile = props.getUserCertFile();
        userKeyFile = props.getUserKeyFile();
        // Get root dir of default cert location.
        int pos = userKeyFile.lastIndexOf(File.separator);
        certDir = userKeyFile.substring(0, pos + 1);
      } else {
        // If alternate directory specified set cert locations.
        if (certDir.endsWith(File.separator) == false) {
          certDir += File.separator;
        }
        userCertFile = certDir + prefix + "cert.pem";
        userKeyFile = certDir + prefix + "key.pem";
      }

      // Cert request file name.
      userCertReqFile = userCertFile.substring(0, userCertFile.length() - 4) + "_request.pem";
    }

    File fDir = null;
    fDir = new File(certDir);
    if (bOk) {
      // Create dir if does not exists.
      if (!fDir.exists()) {
        fDir.mkdir();
      }

      // Make sure directory exists.
      if (!fDir.exists() || !fDir.isDirectory()) {
        System.out.println("The directory " + certDir + " does not exists.");
        bOk = false;
      }
    }

    // Make sure we can write to it.
    if (bOk) {
      if (!fDir.canWrite()) {
        System.out.println("Can't write to " + certDir);
        bOk = false;
      }
    }

    // Check not to overwrite any of these files.
    if (bOk) {
      if (force == false) {
        boolean bFileExists = false;
        File f = new File(userKeyFile);
        if (f.exists()) {
          System.out.println(userKeyFile + " exists");
          bFileExists = true;
        }
        f = new File(userCertFile);
        if (f.exists()) {
          System.out.println(userCertFile + " exists");
          bFileExists = true;
        }
        f = new File(userCertReqFile);
        if (f.exists()) {
          System.out.println(userCertReqFile + " exists");
          bFileExists = true;
        }

        if (bFileExists) {
          System.out.println("If you wish to overwrite, run the script again with -force.");
          bOk = false;
        }
      }
    }

    String password = "";
    if (bOk && !noPswd) {
      // Get password from user.
      bOk = false;
      int attempts = 0;

      System.out.println(message);

      while (bOk == false && attempts < 3) {
        password = Util.getInput("Enter PEM pass phrase: ");
        String password2 = Util.getInput("Verify password Enter PEM pass phrase: ");
        if (password.compareTo(password2) != 0) {
          System.out.println("Verify failure");
        } else {
          if (password.length() < 4) {
            System.out.println("phrase is too short, needs to be at least 4 chars");
          } else {
            bOk = true;
          }
        }
        attempts++;
      }
    }

    // Generate cert request.
    if (bOk) {

      try {
        System.out.println("writing new private key to " + userKeyFile);
        genCertificateRequest(
            cn, "*****@*****.**", password, userKeyFile, userCertFile, userCertReqFile);
      } catch (Exception e) {
        System.out.println("error: " + e);
        e.printStackTrace();
      }
    }
  }