/**
   * Merges the two {@link Subject}s in to a new {@link Subject}. The new subjects contains all the
   * {@link Principal}s from both subjects. If {@link #retainSubjectsPrivateCredentials} is true
   * then the new subject will contain all the private credentials from both subjects, if not the
   * new subject will not contain private credentials. If {@link #retainSubjectsPublicCredentials}
   * is true then the new subject will contain all the public credentials from both subjects, if not
   * the new subject will not contain public credentials.
   *
   * @param subject1 first subject to merge, may be null
   * @param subject2 second subject to merge, may be null
   * @return subject containing the merged information
   */
  protected Subject mergeSubjects(Subject subject1, Subject subject2) {
    if (subject1 == null && subject2 == null) {
      return new Subject();
    }

    if (subject1 == null) {
      return subject2;
    }

    if (subject2 == null) {
      return subject1;
    }

    Set<Principal> principals = new HashSet<Principal>(3);
    principals.addAll(subject1.getPrincipals());
    principals.addAll(subject2.getPrincipals());

    Set<Object> publicCredentials = new HashSet<Object>(3);
    if (retainSubjectsPublicCredentials) {
      LOG.debug("Merging in subjects public credentials");
      publicCredentials.addAll(subject1.getPublicCredentials());
      publicCredentials.addAll(subject2.getPublicCredentials());
    }

    Set<Object> privateCredentials = new HashSet<Object>(3);
    if (retainSubjectsPrivateCredentials) {
      LOG.debug("Merging in subjects private credentials");
      privateCredentials.addAll(subject1.getPrivateCredentials());
      privateCredentials.addAll(subject2.getPrivateCredentials());
    }

    return new Subject(false, principals, publicCredentials, privateCredentials);
  }
Ejemplo n.º 2
0
  /**
   * Builds a security subject object based on the principal name and credential you pass.
   *
   * <p>
   *
   * @param principal
   * @param passwordCredential
   * @return a subject for use in the WBEMClient
   */
  public Subject subject(final String principal, final String passwordCredential) {
    final Subject subject = new Subject();

    subject.getPrincipals().add(new UserPrincipal(principal));

    subject.getPrivateCredentials().add(new GetCim.PasswordCredential(passwordCredential));

    return subject;
  }
 /**
  * Obtain the collection of tokens associated with this user.
  *
  * @return an unmodifiable collection of tokens associated with user
  */
 public synchronized Collection<Token<? extends TokenIdentifier>> getTokens() {
   Set<Object> creds = subject.getPrivateCredentials();
   List<Token<?>> result = new ArrayList<Token<?>>(creds.size());
   for (Object o : creds) {
     if (o instanceof Token<?>) {
       result.add((Token<?>) o);
     }
   }
   return Collections.unmodifiableList(result);
 }
Ejemplo n.º 4
0
  /* (non-Javadoc)
   * @see org.apache.servicemix.components.util.TransformComponentSupport#transform(javax.jbi.messaging.MessageExchange, javax.jbi.messaging.NormalizedMessage, javax.jbi.messaging.NormalizedMessage)
   */
  @Override
  protected boolean transform(
      MessageExchange exchange, NormalizedMessage inMsg, NormalizedMessage outMsg)
      throws Exception {
    boolean success = false;

    try {
      Subject subject = inMsg.getSecuritySubject();

      // Get principal
      Principal principal = null;
      Set<GridIdentifierPrincipal> principals =
          subject.getPrincipals(GridIdentifierPrincipal.class);
      if (principals == null || principals.size() == 0) {
        throw new RuntimeException("No GridIdentifierPrincipal found!");
      } else if (principals.size() > 1) {
        throw new RuntimeException(principals.size() + " GridIdentifierPrincipals found!");
      }
      principal = principals.iterator().next();
      System.out.println("## Principal is: " + principal.getName());

      // Get cert chain
      X509Certificate[] chain = null;
      Set<X509Certificate[]> chains = subject.getPublicCredentials(X509Certificate[].class);
      if (chains == null || chains.size() == 0) {
        throw new RuntimeException("No X509Certificate[] found!");
      } else if (chains.size() > 1) {
        throw new RuntimeException(chains.size() + " X509Certificate[]s found!");
      }
      chain = chains.iterator().next();

      // Get private key
      PrivateKey privateKey = null;
      Set<PrivateKey> privateKeys = subject.getPrivateCredentials(PrivateKey.class);
      if (privateKeys == null || privateKeys.size() == 0) {
        throw new RuntimeException("No PrivateKey found!");
      } else if (privateKeys.size() > 1) {
        throw new RuntimeException(chains.size() + " PrivateKeys found!");
      }
      privateKey = privateKeys.iterator().next();

      GlobusCredential cred = new GlobusCredential(privateKey, chain);

      System.out.println("## Identity is: " + cred.getIdentity());

      String inMsgXml = new SourceTransformer().contentToString(inMsg);
      outMsg.setContent(new StreamSource(new ByteArrayInputStream(inMsgXml.getBytes())));

      success = true;
    } catch (Exception ex) {
      ex.printStackTrace();
    }

    return success;
  }
 public String getPassword() {
   String ret = null;
   try {
     ret =
         ((ConfigFileCredentials) subject.getPrivateCredentials().iterator().next()).getPassword();
   } catch (Throwable t) {
     LOG.warn("UserGroupInformation.getPassword fail, exception: " + t);
     // t.printStackTrace();
   }
   return ret;
 }
 public static UserGroupInformation createConfigFileUser(String user, String password) {
   if (user == null || "".equals(user)) {
     throw new IllegalArgumentException("Null user");
   }
   Subject subject = new Subject();
   subject.getPrincipals().add(new User(user));
   subject.getPrivateCredentials().add(new ConfigFileCredentials(password));
   UserGroupInformation result = new UserGroupInformation(subject);
   result.setAuthenticationMethod(AuthenticationMethod.CONFIGFILE);
   return result;
 }
Ejemplo n.º 7
0
  // helper methods here on down
  private static SSOToken getSSOToken(Subject subject) {
    Set privateCred = subject.getPrivateCredentials();

    for (Iterator i = privateCred.iterator(); i.hasNext(); ) {
      Object o = i.next();

      if (o instanceof SSOToken) {
        return (SSOToken) o;
      }
    }

    return null;
  }
  private boolean validLoginContext() {

    if (loginContext == null) return false;

    Subject subject = loginContext.getSubject();
    if (subject == null) return false;
    Set<KerberosTicket> privateCreds = subject.getPrivateCredentials(KerberosTicket.class);
    if (privateCreds == null || privateCreds.size() == 0) return false;

    Iterator<KerberosTicket> iterator = privateCreds.iterator();
    KerberosTicket ticket = iterator.next();
    return ticket.isCurrent();
  }
 /**
  * Get the Kerberos TGT
  *
  * @return the user's TGT or null if none was found
  */
 private synchronized KerberosTicket getTGT() {
   Set<KerberosTicket> tickets = subject.getPrivateCredentials(KerberosTicket.class);
   for (KerberosTicket ticket : tickets) {
     KerberosPrincipal server = ticket.getServer();
     if (server.getName().equals("krbtgt/" + server.getRealm() + "@" + server.getRealm())) {
       if (LOG.isDebugEnabled()) {
         LOG.debug("Found tgt " + ticket);
       }
       return ticket;
     }
   }
   return null;
 }
  /**
   * Put user into realm.
   *
   * @param userName The user to add
   * @param credential The users Credentials
   * @param roles The users roles
   * @return UserIdentity
   */
  public synchronized UserIdentity putUser(String userName, Credential credential, String[] roles) {
    Principal userPrincipal = new KnownUser(userName, credential);
    Subject subject = new Subject();
    subject.getPrincipals().add(userPrincipal);
    subject.getPrivateCredentials().add(credential);

    if (roles != null)
      for (String role : roles) subject.getPrincipals().add(new RolePrincipal(role));

    subject.setReadOnly();
    UserIdentity identity = _identityService.newUserIdentity(subject, userPrincipal, roles);
    _users.put(userName, identity);
    return identity;
  }
  public Map<String, Set<String>> getAttributes(Subject subject, Set<String> attrNames)
      throws EntitlementException {
    // read original attributes
    Map<String, Set<String>> attributes = super.getAttributes(subject, attrNames);

    // find token if present
    Set<AccessToken> accessTokenCredentials = subject.getPrivateCredentials(AccessToken.class);

    if (accessTokenCredentials != null && !accessTokenCredentials.isEmpty()) {
      Set<String> set = new HashSet<String>();
      set.add(accessTokenCredentials.iterator().next().getToken());
      attributes.put(ACCESS_TOKEN_ATTRIBUTE_NAME, set);
    }
    return attributes;
  }
  public String getserverstatus(
      String ipAddress,
      String username,
      String password,
      String namespace,
      String port,
      String protocol,
      String ftag) {

    this.status = "OFFLINE";
    this.ftag = ftag;
    String unsecureClientNameSpace = protocol + "://" + ipAddress + ":" + port + "/" + namespace;

    try {
      CIMObjectPath cns = new CIMObjectPath(unsecureClientNameSpace);
      UserPrincipal up = new UserPrincipal(username);
      PasswordCredential pc = new PasswordCredential(password);

      Subject s = new Subject();
      s.getPrincipals().add(up);
      s.getPrivateCredentials().add(pc);
      this.cc = WBEMClientFactory.getClient("CIM-XML");
      Locale[] l = {Locale.ENGLISH, Locale.CHINESE};
      this.cc.initialize(cns, s, l);
      try {
        this.instanceEnum =
            this.cc.enumerateInstances(
                new CIMObjectPath("CIM_System", namespace), true, false, true, null);
      } catch (WBEMException ce) {

        this.instanceEnum = null;
      }
      if (this.instanceEnum == null) {
        this.status = "OFFLINE";
        // this.ucs.updateCimom(Cimom.STATUS_OFFLINE, cimomId);
      } else if (instanceEnum != null) {
        this.status = "ONLINE";
        // this.ucs.updateCimom(Cimom.STATUS_ONLINE, cimomId);
      }

    } catch (WBEMException ce) {
      // ucs.updateCimom(Cimom.STATUS_OFFLINE, cimomId);
    }
    // return this.cc;
    return this.status;
  }
Ejemplo n.º 13
0
 @Override
 public UserGroupInformation cloneUgi(UserGroupInformation baseUgi) throws IOException {
   // Based on UserGroupInformation::createProxyUser.
   // TODO: use a proper method after we can depend on HADOOP-13081.
   if (getSubjectMethod == null) {
     throw new IOException("The UGI method was not found: " + ugiCloneError);
   }
   try {
     Subject origSubject = (Subject) getSubjectMethod.invoke(baseUgi);
     Subject subject =
         new Subject(
             false,
             origSubject.getPrincipals(),
             origSubject.getPublicCredentials(),
             origSubject.getPrivateCredentials());
     return ugiCtor.newInstance(subject);
   } catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {
     throw new IOException(e);
   }
 }
  /**
   * Put user into realm. Called by implementations to put the user data loaded from file/db etc
   * into the user structure.
   *
   * @param userName User name
   * @param info a UserIdentity instance, or a String password or Credential instance
   * @return User instance
   */
  protected synchronized UserIdentity putUser(String userName, Object info) {
    final UserIdentity identity;
    if (info instanceof UserIdentity) identity = (UserIdentity) info;
    else {
      Credential credential =
          (info instanceof Credential)
              ? (Credential) info
              : Credential.getCredential(info.toString());

      Principal userPrincipal = new KnownUser(userName, credential);
      Subject subject = new Subject();
      subject.getPrincipals().add(userPrincipal);
      subject.getPrivateCredentials().add(credential);
      subject.setReadOnly();
      identity = _identityService.newUserIdentity(subject, userPrincipal, IdentityService.NO_ROLES);
    }

    _users.put(userName, identity);
    return identity;
  }
  /** whether user is authorized? */
  public boolean isAuthorized() {
    if (!useConfiguredFileAuth) {
      return true;
    }

    Set privateCredList = subject.getPrivateCredentials();
    String userName = user.getName();
    String userPassword = null;
    if ((userName == null) || (privateCredList == null)) {
      return false;
    }

    userPassword = getPassword();
    try {
      String correctPassword = groups.getPassword(user.getName());
      if ((correctPassword != null) && (correctPassword.equals(userPassword))) {
        return true;
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    return false;
  }
    @Override
    public boolean commit() throws LoginException {
      // if we already have a user, we are done.
      if (!subject.getPrincipals(User.class).isEmpty()) {
        return true;
      }
      Principal user = null;
      // if we are using kerberos, try it out
      if (useKerberos) {
        user = getCanonicalUser(KerberosPrincipal.class);
      }

      // if we don't have a kerberos user, use configured user
      if ((user == null) && (useConfiguredFileAuth)) {
        if (configUGIInformation == null) {
          configUGIInformation = conf.getStrings("hadoop.client.ugi");
        }

        if ((configUGIInformation != null) && (configUGIInformation.length == 2)) {
          LOG.info(
              "Using the configured user name and password, user name is "
                  + configUGIInformation[0]);
          user = new User(configUGIInformation[0].trim(), configUGIInformation[1].trim());
          ConfigFileCredentials configFileCredentials =
              new ConfigFileCredentials(configUGIInformation[1]);
          subject.getPrivateCredentials().add(configFileCredentials);
        } else if ((configUGIInformation != null) && (configUGIInformation.length == 1)) {
          // get the username and password from config file
          String configedPath = configUGIInformation[0];
          String filePath = null;
          if ("/".equals(configedPath.substring(0, 1))) {
            filePath = configedPath;
          } else {
            // Get path from home directory
            String usrHome = System.getProperty("user.home");
            filePath = usrHome + "/" + configedPath;
          }
          BufferedReader reader = null;
          try {
            File file = new File(filePath);
            reader = new BufferedReader(new FileReader(file));
            // Only read the first line
            String tempString = reader.readLine();
            reader.close();

            configUGIInformation = tempString.split(",");
            if ((configUGIInformation != null) && (configUGIInformation.length == 2)) {
              LOG.info(
                  "Load user ugi information from "
                      + filePath
                      + ", user name is "
                      + configUGIInformation[0]);
              user = new User(configUGIInformation[0].trim(), configUGIInformation[1].trim());
              ConfigFileCredentials configFileCredentials =
                  new ConfigFileCredentials(configUGIInformation[1]);
              subject.getPrivateCredentials().add(configFileCredentials);
            }
          } catch (IOException e) {
            throw new LoginException("Read username password file fail");
          } finally {
            if (reader != null) {
              try {
                reader.close();
              } catch (IOException e1) {
                throw new LoginException("Read username password file fail");
              }
            }
          }
        }
      }

      // if we don't have a configured user, use the OS user
      if (user == null) {
        user = getCanonicalUser(OS_PRINCIPAL_CLASS);
      }
      // if we found the user, add our principal
      if (user != null) {
        if ((user instanceof User) && (((User) user).getPassword() != null)) {
          subject.getPrincipals().add(new User(user.getName(), ((User) user).getPassword()));
        } else {
          subject.getPrincipals().add(new User(user.getName()));
        }
        return true;
      }
      LOG.error("Can't find user in " + subject);
      throw new LoginException("Can't find user name");
    }
Ejemplo n.º 17
0
  /** Create a KerberosSaslNettyClient for authentication with servers. */
  public KerberosSaslNettyClient(Map storm_conf, String jaas_section) {
    LOG.debug(
        "KerberosSaslNettyClient: Creating SASL {} client to authenticate to server ",
        SaslUtils.KERBEROS);

    LOG.info("Creating Kerberos Client.");

    Configuration login_conf;
    try {
      login_conf = AuthUtils.GetConfiguration(storm_conf);
    } catch (Throwable t) {
      LOG.error("Failed to get login_conf: ", t);
      throw t;
    }
    LOG.debug("KerberosSaslNettyClient: authmethod {}", SaslUtils.KERBEROS);

    SaslClientCallbackHandler ch = new SaslClientCallbackHandler();

    subject = null;
    try {
      LOG.debug("Setting Configuration to login_config: {}", login_conf);
      // specify a configuration object to be used
      Configuration.setConfiguration(login_conf);
      // now login
      LOG.debug("Trying to login.");
      Login login = new Login(jaas_section, ch);
      subject = login.getSubject();
      LOG.debug("Got Subject: {}", subject.toString());
    } catch (LoginException ex) {
      LOG.error("Client failed to login in principal:" + ex, ex);
      throw new RuntimeException(ex);
    }

    // check the credential of our principal
    if (subject.getPrivateCredentials(KerberosTicket.class).isEmpty()) {
      LOG.error("Failed to verify user principal.");
      throw new RuntimeException(
          "Fail to verify user principal with section \""
              + jaas_section
              + "\" in login configuration file "
              + login_conf);
    }

    String serviceName = null;
    try {
      serviceName = AuthUtils.get(login_conf, jaas_section, "serviceName");
    } catch (IOException e) {
      LOG.error("Failed to get service name.", e);
      throw new RuntimeException(e);
    }

    try {
      Principal principal = (Principal) subject.getPrincipals().toArray()[0];
      final String fPrincipalName = principal.getName();
      final String fHost = (String) storm_conf.get(Config.PACEMAKER_HOST);
      final String fServiceName = serviceName;
      final CallbackHandler fch = ch;
      LOG.debug("Kerberos Client with principal: {}, host: {}", fPrincipalName, fHost);
      saslClient =
          Subject.doAs(
              subject,
              new PrivilegedExceptionAction<SaslClient>() {
                public SaslClient run() {
                  try {
                    Map<String, String> props = new TreeMap<String, String>();
                    props.put(Sasl.QOP, "auth");
                    props.put(Sasl.SERVER_AUTH, "false");
                    return Sasl.createSaslClient(
                        new String[] {SaslUtils.KERBEROS},
                        fPrincipalName,
                        fServiceName,
                        fHost,
                        props,
                        fch);
                  } catch (Exception e) {
                    LOG.error("Subject failed to create sasl client.", e);
                    return null;
                  }
                }
              });
      LOG.info("Got Client: {}", saslClient);

    } catch (PrivilegedActionException e) {
      LOG.error("KerberosSaslNettyClient: Could not create Sasl Netty Client.");
      throw new RuntimeException(e);
    }
  }
  public UserIdentity login(String userName, Object credential) {
    // AuthFactory supports both a bare username, as well as user@domain. However, UserManager only
    // accepts the bare
    // username. If the provided value includes a domain, use only the node-part (after verifying
    // that it's actually
    // a user of our domain).
    final String[] parts = userName.split("@", 2);
    if (parts.length > 1) {
      if (XMPPServer.getInstance().getServerInfo().getXMPPDomain().equals(parts[1])) {
        userName = parts[0];
      } else {
        Log.error("access denied, unknown domain" + userName);
        return null;
      }
    }

    UserIdentity identity = null;

    if (identities.containsKey(userName)) {
      identity = identities.get(userName);

      if (authTokens.containsKey(userName) == false) {
        Log.debug("UserIdentity login " + userName + " ");

        try {

          AuthToken authToken = AuthFactory.authenticate(userName, (String) credential);
          authTokens.put(userName, authToken);

        } catch (UnauthorizedException e) {
          Log.error("access denied, bad password " + userName);
          return null;

        } catch (Exception e) {
          Log.error("access denied " + userName);
          return null;
        }
      }

    } else {

      Log.debug("UserIdentity login " + userName + " ");

      try {
        userManager.getUser(userName);
      } catch (UserNotFoundException e) {
        Log.error("user not found " + userName, e);
        return null;
      }

      try {

        AuthToken authToken = AuthFactory.authenticate(userName, (String) credential);
        authTokens.put(userName, authToken);

      } catch (UnauthorizedException e) {
        Log.error("access denied, bad password " + userName);
        return null;

      } catch (Exception e) {
        Log.error("access denied " + userName);
        return null;
      }

      Principal userPrincipal = new KnownUser(userName, credential);
      Subject subject = new Subject();
      subject.getPrincipals().add(userPrincipal);
      subject.getPrivateCredentials().add(credential);
      subject.getPrincipals().add(new RolePrincipal("ofmeet"));
      subject.setReadOnly();

      identity = _identityService.newUserIdentity(subject, userPrincipal, new String[] {"ofmeet"});
      identities.put(userName, identity);
    }

    return identity;
  }
 public void setJAASInfo(Subject subject) {
   subject.getPrincipals().add(this.principal);
   subject.getPrivateCredentials().add(this.user.getCredential());
   subject.getPrincipals().addAll(roles);
 }
 /**
  * Add a token to this UGI
  *
  * @param token Token to be added
  * @return true on successful add of new token
  */
 public synchronized boolean addToken(Token<? extends TokenIdentifier> token) {
   return subject.getPrivateCredentials().add(token);
 }
 public void unsetJAASInfo(Subject subject) {
   subject.getPrincipals().remove(this.principal);
   subject.getPrivateCredentials().remove(this.user.getCredential());
   subject.getPrincipals().removeAll(this.roles);
 }
 /**
  * Create a UserGroupInformation for the given subject. This does not change the subject or
  * acquire new credentials.
  *
  * @param subject the user's subject
  */
 UserGroupInformation(Subject subject) {
   this.subject = subject;
   this.user = subject.getPrincipals(User.class).iterator().next();
   this.isKeytab = !subject.getPrivateCredentials(KerberosKey.class).isEmpty();
   this.isKrbTkt = !subject.getPrivateCredentials(KerberosTicket.class).isEmpty();
 }