Java Code Examples for javax.security.auth.Subject

The following are top voted examples for showing how to use javax.security.auth.Subject. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: monarch   File: KerberosTicketOperations.java   View source code 7 votes vote down vote up
public static String validateServiceTicket(Subject subject, final byte[] serviceTicket)
    throws GSSException, IllegalAccessException, NoSuchFieldException, ClassNotFoundException,
    PrivilegedActionException {
  // Kerberos version 5 OID
  Oid krb5Oid = KerberosUtils.getOidInstance("GSS_KRB5_MECH_OID");


  // Accept the context and return the client principal name.
  return Subject.doAs(subject, new PrivilegedExceptionAction<String>() {

    @Override
    public String run() throws Exception {
      String clientName = null;
      // Identify the server that communications are being made to.
      GSSManager manager = GSSManager.getInstance();
      GSSContext context = manager.createContext((GSSCredential) null);
      context.acceptSecContext(serviceTicket, 0, serviceTicket.length);
      clientName = context.getSrcName().toString();
      return clientName;
    }
  });
}
 
Example 2
Project: jdk8u-jdk   File: ConnectorBootstrap.java   View source code 6 votes vote down vote up
private void checkAccessFileEntries(Subject subject) {
    if (subject == null) {
        throw new SecurityException(
                "Access denied! No matching entries found in " +
                "the access file [" + accessFile + "] as the " +
                "authenticated Subject is null");
    }
    final Set<Principal> principals = subject.getPrincipals();
    for (Principal p1: principals) {
        if (properties.containsKey(p1.getName())) {
            return;
        }
    }

    final Set<String> principalsStr = new HashSet<>();
    for (Principal p2: principals) {
        principalsStr.add(p2.getName());
    }
    throw new SecurityException(
            "Access denied! No entries found in the access file [" +
            accessFile + "] for any of the authenticated identities " +
            principalsStr);
}
 
Example 3
Project: fdt   File: PostRename.java   View source code 6 votes vote down vote up
public void postProcessFileList(ProcessorInfo processorInfo, Subject peerSubject, Throwable downCause, String downMessage) throws Exception {
    logger.log(Level.INFO, " [ PostRename ] Subject: " + peerSubject);
    String filePrefix = System.getProperty(PREFIX, DEFAULT_PREFIX);

    for (int i = 0; i < processorInfo.fileList.length; i++) {
        try {
            String name = processorInfo.fileList[i];
            final String outFilename = processorInfo.destinationDir + File.separator + filePrefix + name;
            final String orgFileName = processorInfo.destinationDir + File.separator + name;
            logger.log(Level.INFO, "Renaming file: " + name + " to: " + filePrefix + name);
            new File(orgFileName).renameTo(new File(outFilename));
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
 
Example 4
Project: openjdk-jdk10   File: NotificationAccessControllerTest.java   View source code 6 votes vote down vote up
@Override
public void fetchNotification(
    String connectionId,
    ObjectName name,
    Notification notification,
    Subject subject)
    throws SecurityException {
    echo("fetchNotification:");
    echo("\tconnectionId: " +  connectionId);
    echo("\tname: " +  name);
    echo("\tnotification: " +  notification);
    echo("\tsubject: " +
         (subject == null ? null : subject.getPrincipals()));
    if (!throwException)
        if (name.getCanonicalName().equals("domain:name=2,type=NB")
            &&
            subject != null
            &&
            subject.getPrincipals().contains(new JMXPrincipal("role")))
            throw new SecurityException();
}
 
Example 5
Project: shibboleth-idp-oidc-extension   File: SelectAuthenticationFlowTest.java   View source code 6 votes vote down vote up
@Test
public void testRequestPickActive() {
    final AuthenticationContext authCtx = prc.getSubcontext(AuthenticationContext.class);
    final List<Principal> principals = Arrays.<Principal> asList(new TestPrincipal("test3"), new TestPrincipal(
            "test2"));
    final RequestedPrincipalContext rpc = new RequestedPrincipalContext();
    rpc.getPrincipalEvalPredicateFactoryRegistry().register(TestPrincipal.class, "exact",
            new ExactPrincipalEvalPredicateFactory());
    rpc.setOperator("exact");
    rpc.setRequestedPrincipals(principals);
    authCtx.addSubcontext(rpc, true);
    final AuthenticationResult active = new AuthenticationResult("test3", new Subject());
    active.getSubject().getPrincipals().add(new TestPrincipal("test3"));
    authCtx.setActiveResults(Arrays.asList(active));
    authCtx.getPotentialFlows().get("test3").setSupportedPrincipals(ImmutableList.of(principals.get(0)));

    final Event event = action.execute(src);

    ActionTestingSupport.assertProceedEvent(event);
    Assert.assertEquals(active, authCtx.getAuthenticationResult());
}
 
Example 6
Project: hadoop-oss   File: UserGroupInformation.java   View source code 6 votes vote down vote up
private static LoginContext
newLoginContext(String appName, Subject subject,
  javax.security.auth.login.Configuration loginConf)
    throws LoginException {
  // Temporarily switch the thread's ContextClassLoader to match this
  // class's classloader, so that we can properly load HadoopLoginModule
  // from the JAAS libraries.
  Thread t = Thread.currentThread();
  ClassLoader oldCCL = t.getContextClassLoader();
  t.setContextClassLoader(HadoopLoginModule.class.getClassLoader());
  try {
    return new LoginContext(appName, subject, null, loginConf);
  } finally {
    t.setContextClassLoader(oldCCL);
  }
}
 
Example 7
Project: openjdk-jdk10   File: SubjectNullTests.java   View source code 6 votes vote down vote up
private static void testIsEmpty() {
    Subject populatedSubj = makeSubj(false, false, false);
    Subject emptySubj = new Subject();

    System.out.println("------ isEmpty() -----");

    if (populatedSubj.getPrincipals().isEmpty()) {
        throw new RuntimeException(
                "Populated Subject Principals incorrectly returned empty");
    }
    if (emptySubj.getPrincipals().isEmpty() == false) {
        throw new RuntimeException(
                "Empty Subject Principals incorrectly returned non-empty");
    }
    System.out.println("isEmpty() test passed");
}
 
Example 8
Project: jdk8u-jdk   File: Krb5Util.java   View source code 6 votes vote down vote up
/**
 * Retrieves the ServiceCreds for the specified server principal from
 * the Subject in the specified AccessControlContext. If not found, and if
 * useSubjectCredsOnly is false, then obtain from a LoginContext.
 *
 * NOTE: This method is also used by JSSE Kerberos Cipher Suites
 */
public static ServiceCreds getServiceCreds(GSSCaller caller,
    String serverPrincipal, AccessControlContext acc)
            throws LoginException {

    Subject accSubj = Subject.getSubject(acc);
    ServiceCreds sc = null;
    if (accSubj != null) {
        sc = ServiceCreds.getInstance(accSubj, serverPrincipal);
    }
    if (sc == null && !GSSUtil.useSubjectCredsOnly(caller)) {
        Subject subject = GSSUtil.login(caller, GSSUtil.GSS_KRB5_MECH_OID);
        sc = ServiceCreds.getInstance(subject, serverPrincipal);
    }
    return sc;
}
 
Example 9
Project: openjdk-jdk10   File: RMIConnector.java   View source code 6 votes vote down vote up
public synchronized MBeanServerConnection
        getMBeanServerConnection(Subject delegationSubject)
        throws IOException {

    if (terminated) {
        if (logger.traceOn())
            logger.trace("getMBeanServerConnection","[" + this.toString() +
                    "] already closed.");
        throw new IOException("Connection closed");
    } else if (!connected) {
        if (logger.traceOn())
            logger.trace("getMBeanServerConnection","[" + this.toString() +
                    "] is not connected.");
        throw new IOException("Not connected");
    }

    return getConnectionWithSubject(delegationSubject);
}
 
Example 10
Project: openjdk-jdk10   File: RMIConnector.java   View source code 6 votes vote down vote up
private MBeanServerConnection getConnectionWithSubject(Subject delegationSubject) {
    MBeanServerConnection conn = null;

    if (delegationSubject == null) {
        if (nullSubjectConnRef == null
                || (conn = nullSubjectConnRef.get()) == null) {
            conn = new RemoteMBeanServerConnection(null);
            nullSubjectConnRef = new WeakReference<MBeanServerConnection>(conn);
        }
    } else {
        WeakReference<MBeanServerConnection> wr = rmbscMap.get(delegationSubject);
        if (wr == null || (conn = wr.get()) == null) {
            conn = new RemoteMBeanServerConnection(delegationSubject);
            rmbscMap.put(delegationSubject, new WeakReference<MBeanServerConnection>(conn));
        }
    }
    return conn;
}
 
Example 11
Project: taskana   File: CurrentUserContext.java   View source code 6 votes vote down vote up
private static String getUseridFromJAASSubject() {
    Subject subject = Subject.getSubject(AccessController.getContext());
    LOGGER.trace("Subject of caller: {}", subject);
    if (subject != null) {
        Set<Principal> principals = subject.getPrincipals();
        LOGGER.trace("Public principals of caller: {}", principals);
        for (Principal pC : principals) {
            if (!(pC instanceof Group)) {
                String userIdFound = pC.getName();
                String userIdUsed = userIdFound;
                if (TaskanaEngineConfiguration.shouldUseLowerCaseForAccessIds() && userIdFound != null) {
                    userIdUsed = userIdFound.toLowerCase();
                }
                LOGGER.trace("Found User id {}. Returning User id {} ", userIdFound, userIdUsed);
                return userIdUsed;
            }
        }
    }
    LOGGER.trace("No userid found in subject!");
    return null;
}
 
Example 12
Project: org.ops4j.pax.transx   File: CredentialExtractor.java   View source code 6 votes vote down vote up
public boolean matches(Subject subject, UserPasswordConnectionRequestInfo connectionRequestInfo, UserPasswordManagedConnectionFactory managedConnectionFactory) throws ResourceAdapterInternalException {
    assert managedConnectionFactory != null;

    if (subject != null) {
        Set<PasswordCredential> credentials = subject.getPrivateCredentials(PasswordCredential.class);
        for (PasswordCredential passwordCredential : credentials) {
            if (managedConnectionFactory.equals(passwordCredential.getManagedConnectionFactory())) {
                return (userName == null ? passwordCredential.getUserName() == null : userName.equals(passwordCredential.getUserName())
                    && (password == null ? passwordCredential.getPassword() == null : Arrays.equals(password.toCharArray(), passwordCredential.getPassword())));
            }
        }
        throw new ResourceAdapterInternalException("No credential found for this ManagedConnectionFactory: " + managedConnectionFactory);
    }
    if (connectionRequestInfo != null && connectionRequestInfo.getUserName() != null) {
        return (userName.equals(connectionRequestInfo.getUserName()))
            && (password == null
                ? connectionRequestInfo.getPassword() == null
                : password.equals(connectionRequestInfo.getPassword()));
    }
    return (userName == null ? managedConnectionFactory.getUserName() == null : userName.equals(managedConnectionFactory.getUserName())
        && (password == null ? managedConnectionFactory.getPassword() == null : password.equals(managedConnectionFactory.getPassword())));
}
 
Example 13
Project: openjdk-jdk10   File: NotificationAccessControllerTest.java   View source code 6 votes vote down vote up
@Override
public void removeNotificationListener(
    String connectionId,
    ObjectName name,
    Subject subject)
    throws SecurityException {
    echo("removeNotificationListener:");
    echo("\tconnectionId: " +  connectionId);
    echo("\tname: " +  name);
    echo("\tsubject: " +
         (subject == null ? null : subject.getPrincipals()));
    if (throwException)
        if (name.getCanonicalName().equals("domain:name=2,type=NB")
            &&
            subject != null
            &&
            subject.getPrincipals().contains(new JMXPrincipal("role")))
            throw new SecurityException();
}
 
Example 14
Project: lams   File: JAASMemoryLoginModule.java   View source code 6 votes vote down vote up
/**
 * Initialize this <code>LoginModule</code> with the specified
 * configuration information.
 *
 * @param subject The <code>Subject</code> to be authenticated
 * @param callbackHandler A <code>CallbackHandler</code> for communicating
 *  with the end user as necessary
 * @param sharedState State information shared with other
 *  <code>LoginModule</code> instances
 * @param options Configuration information for this specific
 *  <code>LoginModule</code> instance
 */
public void initialize(Subject subject, CallbackHandler callbackHandler,
                       Map sharedState, Map options) {
    log.debug("Init");

    // Save configuration values
    this.subject = subject;
    this.callbackHandler = callbackHandler;
    this.sharedState = sharedState;
    this.options = options;

    // Perform instance-specific initialization
    if (options.get("pathname") != null)
        this.pathname = (String) options.get("pathname");

    // Load our defined Principals
    load();

}
 
Example 15
Project: fdt   File: ControlChannel.java   View source code 6 votes vote down vote up
/**
 * @param parent
 */
public ControlChannel(GSIServer parent, Socket s, Subject peerSubject, ControlChannelNotifier notifier)
        throws Exception {
    try {

        this.controlSocket = s;
        this.subject = peerSubject;
        this.remoteAddress = s.getInetAddress();
        this.remotePort = s.getPort();
        this.localPort = s.getLocalPort();

        this.notifier = notifier;

        initStreams();
        controlSocket.setTcpNoDelay(true);
        controlSocket.setSoTimeout(1000);

    } catch (Throwable t) {
        close("Cannot instantiate ControlChannel", t);
        throw new Exception(t);
    }
}
 
Example 16
Project: openjdk-jdk10   File: ConfSecurityLayer.java   View source code 6 votes vote down vote up
private static Subject doLogin(String msg) throws LoginException {
    LoginContext lc = null;
    if (verbose) {
        System.out.println(msg);
    }
    try {
        lc = new LoginContext(msg, new TextCallbackHandler());

        // Attempt authentication
        // You might want to do this in a "for" loop to give
        // user more than one chance to enter correct username/password
        lc.login();

    } catch (LoginException le) {
        throw le;
    }
    return lc.getSubject();
}
 
Example 17
Project: openjdk-jdk10   File: NestedActions.java   View source code 5 votes vote down vote up
@Override
public Object run() throws Exception {
    Utils.writeFile(filename);
    AccessControlContext acc = AccessController.getContext();
    Subject subject = Subject.getSubject(acc);
    ReadFromFileExceptionAction readFromFile =
            new ReadFromFileExceptionAction(filename);
    return Subject.doAs(subject, readFromFile);
}
 
Example 18
Project: jdk8u-jdk   File: NestedActions.java   View source code 5 votes vote down vote up
@Override
public java.lang.Object run() {
    System.out.println("ReadPropertyAction: "
            + "try to read 'java.class.path' property");

    AccessControlContext acc = AccessController.getContext();
    Subject s = Subject.getSubject(acc);
    System.out.println("principals = " + s.getPrincipals());
    System.out.println("java.class.path = "
            + System.getProperty("java.class.path"));

    return null;
}
 
Example 19
Project: OpenJSharp   File: SubjectDelegator.java   View source code 5 votes vote down vote up
public AccessControlContext
    delegatedContext(AccessControlContext authenticatedACC,
                     Subject delegatedSubject,
                     boolean removeCallerContext)
        throws SecurityException {

    if (System.getSecurityManager() != null && authenticatedACC == null) {
        throw new SecurityException("Illegal AccessControlContext: null");
    }

    // Check if the subject delegation permission allows the
    // authenticated subject to assume the identity of each
    // principal in the delegated subject
    //
    Collection<Principal> ps = getSubjectPrincipals(delegatedSubject);
    final Collection<Permission> permissions = new ArrayList<>(ps.size());
    for(Principal p : ps) {
        final String pname = p.getClass().getName() + "." + p.getName();
        permissions.add(new SubjectDelegationPermission(pname));
    }
    PrivilegedAction<Void> action =
        new PrivilegedAction<Void>() {
            public Void run() {
                for (Permission sdp : permissions) {
                    AccessController.checkPermission(sdp);
                }
                return null;
            }
        };
    AccessController.doPrivileged(action, authenticatedACC);

    return getDelegatedAcc(delegatedSubject, removeCallerContext);
}
 
Example 20
Project: jdk8u-jdk   File: Comparator.java   View source code 5 votes vote down vote up
@Override
public boolean implies (Subject subject) {
    if (subject.getPrincipals().contains(p1[0])) {
        return true;
    }
    return false;
}
 
Example 21
Project: kafka-0.11.0.0-src-with-comment   File: SaslClientAuthenticator.java   View source code 5 votes vote down vote up
public SaslClientAuthenticator(String node, Subject subject, String servicePrincipal, String host, String mechanism, boolean handshakeRequestEnable) throws IOException {
    this.node = node;
    this.subject = subject;
    this.host = host;
    this.servicePrincipal = servicePrincipal;
    this.mechanism = mechanism;
    this.handshakeRequestEnable = handshakeRequestEnable;
    this.correlationId = -1;
}
 
Example 22
Project: jdk8u-jdk   File: NestedActions.java   View source code 5 votes vote down vote up
@Override
public Object run() {
    Utils.readFile(filename);

    AccessControlContext acc = AccessController.getContext();
    Subject subject = Subject.getSubject(acc);
    ReadPropertyAction readProperty = new ReadPropertyAction();
    if (anotherSubject != null) {
        return Subject.doAs(anotherSubject, readProperty);
    } else {
        return Subject.doAs(subject, readProperty);
    }
}
 
Example 23
Project: kafka-0.11.0.0-src-with-comment   File: SaslServerAuthenticator.java   View source code 5 votes vote down vote up
public SaslServerAuthenticator(String node, JaasContext jaasContext, final Subject subject, KerberosShortNamer kerberosNameParser, String host, int maxReceiveSize, CredentialCache credentialCache) throws IOException {
    if (subject == null)
        throw new IllegalArgumentException("subject cannot be null");
    this.node = node;
    this.jaasContext = jaasContext;
    this.subject = subject;
    this.kerberosNamer = kerberosNameParser;
    this.maxReceiveSize = maxReceiveSize;
    this.host = host;
    this.credentialCache = credentialCache;
}
 
Example 24
Project: OpenJSharp   File: SubjectComber.java   View source code 5 votes vote down vote up
static <T> T find(Subject subject, String serverPrincipal,
    String clientPrincipal, Class<T> credClass) {

    // findAux returns T if oneOnly.
    return credClass.cast(findAux(subject, serverPrincipal,
                                  clientPrincipal, credClass, true));
}
 
Example 25
Project: OpenJSharp   File: ConnectorBootstrap.java   View source code 5 votes vote down vote up
public Subject authenticate(Object credentials) {
    final JMXAuthenticator authenticator =
            new JMXPluggableAuthenticator(environment);
    final Subject subject = authenticator.authenticate(credentials);
    checkAccessFileEntries(subject);
    return subject;
}
 
Example 26
Project: ditb   File: HttpDoAsClient.java   View source code 5 votes vote down vote up
public static void main(String[] args) throws Exception {

    if (args.length < 3 || args.length > 4) {

      System.out.println("Invalid arguments!");
      System.out.println("Usage: HttpDoAsClient host port doAsUserName [security=true]");
      System.exit(-1);
    }

    host = args[0];
    port = Integer.parseInt(args[1]);
    doAsUser = args[2];
    if (args.length > 3) {
      secure = Boolean.parseBoolean(args[3]);
      principal = getSubject().getPrincipals().iterator().next().getName();
    }

    final HttpDoAsClient client = new HttpDoAsClient();
    Subject.doAs(getSubject(),
        new PrivilegedExceptionAction<Void>() {
          @Override
          public Void run() throws Exception {
            client.run();
            return null;
          }
        });
  }
 
Example 27
Project: jdk8u-jdk   File: LCTest.java   View source code 5 votes vote down vote up
private void clearState() {
    if (commitSucceeded) {
        final Subject s = subject;
        final UnixPrincipal up = userPrincipal;
        java.security.AccessController.doPrivileged
                ((java.security.PrivilegedAction) () -> {
                    s.getPrincipals().remove(up);
                    return null;
                });
    }
    username = null;
    password = null;
    userPrincipal = null;
}
 
Example 28
Project: hadoop-oss   File: UserGroupInformation.java   View source code 5 votes vote down vote up
/**
 * Run the given action as the user, potentially throwing an exception.
 * @param <T> the return type of the run method
 * @param action the method to execute
 * @return the value from the run method
 * @throws IOException if the action throws an IOException
 * @throws Error if the action throws an Error
 * @throws RuntimeException if the action throws a RuntimeException
 * @throws InterruptedException if the action throws an InterruptedException
 * @throws UndeclaredThrowableException if the action throws something else
 */
@InterfaceAudience.Public
@InterfaceStability.Evolving
public <T> T doAs(PrivilegedExceptionAction<T> action
                  ) throws IOException, InterruptedException {
  try {
    logPrivilegedAction(subject, action);
    return Subject.doAs(subject, action);
  } catch (PrivilegedActionException pae) {
    Throwable cause = pae.getCause();
    if (LOG.isDebugEnabled()) {
      LOG.debug("PrivilegedActionException as:" + this + " cause:" + cause);
    }
    if (cause == null) {
      throw new RuntimeException("PrivilegedActionException with no " +
              "underlying cause. UGI [" + this + "]" +": " + pae, pae);
    } else if (cause instanceof IOException) {
      throw (IOException) cause;
    } else if (cause instanceof Error) {
      throw (Error) cause;
    } else if (cause instanceof RuntimeException) {
      throw (RuntimeException) cause;
    } else if (cause instanceof InterruptedException) {
      throw (InterruptedException) cause;
    } else {
      throw new UndeclaredThrowableException(cause);
    }
  }
}
 
Example 29
Project: openjdk-jdk10   File: TestSampleLoginModule.java   View source code 5 votes vote down vote up
public void initialize(Subject subject,
        CallbackHandler callbackHandler,
        Map<String,?> sharedState,
        Map<String,?> options) {

    this.subject = subject;
    this.callbackHandler = callbackHandler;
    this.sharedState = sharedState;
    this.options = options;
}
 
Example 30
Project: jdk8u-jdk   File: RMIConnectionImpl.java   View source code 5 votes vote down vote up
public void removeNotificationListeners(ObjectName name,
                                        Integer[] listenerIDs,
                                        Subject delegationSubject)
    throws
    InstanceNotFoundException,
    ListenerNotFoundException,
    IOException {

    if (name == null || listenerIDs == null)
        throw new IllegalArgumentException("Illegal null parameter");

    for (int i = 0; i < listenerIDs.length; i++) {
        if (listenerIDs[i] == null)
            throw new IllegalArgumentException("Null listener ID");
    }

    try {
        final Object params[] = new Object[] { name, listenerIDs };

        if (logger.debugOn()) logger.debug("removeNotificationListener"+
                               "(ObjectName,Integer[])",
                               "connectionId=" + connectionId
                               +", name=" + name
                               +", listenerIDs=" + objects(listenerIDs));

        doPrivilegedOperation(
          REMOVE_NOTIFICATION_LISTENER,
          params,
          delegationSubject);
    } catch (PrivilegedActionException pe) {
        Exception e = extractException(pe);
        if (e instanceof InstanceNotFoundException)
            throw (InstanceNotFoundException) e;
        if (e instanceof ListenerNotFoundException)
            throw (ListenerNotFoundException) e;
        if (e instanceof IOException)
            throw (IOException) e;
        throw newIOException("Got unexpected server exception: " + e, e);
    }
}
 
Example 31
Project: OpenJSharp   File: AuthPolicyFile.java   View source code 5 votes vote down vote up
@Override
public PermissionCollection getPermissions(final Subject subject,
                                           final CodeSource codesource) {

    // 1)   if code instantiates PolicyFile directly, then it will need
    //      all the permissions required for the PolicyFile initialization
    // 2)   if code calls Policy.getPolicy, then it simply needs
    //      AuthPermission(getPolicy), and the javax.security.auth.Policy
    //      implementation instantiates PolicyFile in a doPrivileged block
    // 3)   if after instantiating a Policy (either via #1 or #2),
    //      code calls getPermissions, PolicyFile wraps the call
    //      in a doPrivileged block.
    return AccessController.doPrivileged
        (new PrivilegedAction<PermissionCollection>() {
        @Override public PermissionCollection run() {
            SubjectCodeSource scs = new SubjectCodeSource(
                subject, null,
                codesource == null ? null : codesource.getLocation(),
                codesource == null ? null : codesource.getCertificates());
            if (initialized) {
                return getPermissions(new Permissions(), scs);
            } else {
                return new PolicyPermissions(AuthPolicyFile.this, scs);
            }
        }
    });
}
 
Example 32
Project: calcite-avatica   File: KerberosConnection.java   View source code 5 votes vote down vote up
/**
 * Logout and log back in with the Kerberos identity.
 */
void renew() {
  try {
    // Lock on the instance of KerberosUtil
    synchronized (utilInstance) {
      Entry<LoginContext, Subject> pair = utilInstance.login(context, conf, subject);
      context = pair.getKey();
      subject = pair.getValue();
    }
  } catch (Exception e) {
    throw new RuntimeException("Failed to perform kerberos login");
  }
}
 
Example 33
Project: openjdk-jdk10   File: GetLocalHostWithSM.java   View source code 5 votes vote down vote up
public static void main(String[] args) throws Exception {

            // try setting the local hostname
            InetAddress localHost = InetAddress.getLocalHost();
            if (localHost.isLoopbackAddress()) {
                System.err.println("Local host name is resolved into a loopback address. Quit now!");
                return;
            }
            System.setProperty("host.name", localHost.
                                            getHostName());
            String policyFileName = System.getProperty("test.src", ".") +
                          "/" + "policy.file";
            System.setProperty("java.security.policy", policyFileName);
            System.setSecurityManager(new SecurityManager());

            InetAddress localHost1 = null;
            InetAddress localHost2 = null;

            localHost1 = InetAddress.getLocalHost();

            Subject mySubject = new Subject();
            MyPrincipal userPrincipal = new MyPrincipal("test");
            mySubject.getPrincipals().add(userPrincipal);
            localHost2 = (InetAddress)Subject.doAsPrivileged(mySubject,
                                new MyAction(), null);

            if (localHost1.equals(localHost2)) {
                System.out.println("localHost1 = " + localHost1);
                throw new RuntimeException("InetAddress.getLocalHost() test " +
                                           " fails. localHost2 should be " +
                                           " the real address instead of " +
                                           " the loopback address."+localHost2);
            }
        }
 
Example 34
Project: hadoop   File: UserGroupInformation.java   View source code 5 votes vote down vote up
private void logPrivilegedAction(Subject subject, Object action) {
  if (LOG.isDebugEnabled()) {
    // would be nice if action included a descriptive toString()
    String where = new Throwable().getStackTrace()[2].toString();
    LOG.debug("PrivilegedAction as:"+this+" from:"+where);
  }
}
 
Example 35
Project: hadoop   File: TestSecureLogins.java   View source code 5 votes vote down vote up
public LoginContext createLoginContextZookeeperLocalhost() throws
    LoginException {
  String principalAndRealm = getPrincipalAndRealm(ZOOKEEPER_LOCALHOST);
  Set<Principal> principals = new HashSet<Principal>();
  principals.add(new KerberosPrincipal(ZOOKEEPER_LOCALHOST));
  Subject subject = new Subject(false, principals, new HashSet<Object>(),
      new HashSet<Object>());
  return new LoginContext("", subject, null,
      KerberosConfiguration.createServerConfig(ZOOKEEPER_LOCALHOST, keytab_zk));
}
 
Example 36
Project: neoscada   File: LoginModule.java   View source code 5 votes vote down vote up
@SuppressWarnings ( "rawtypes" )
@Override
public void initialize ( final Subject subject, final CallbackHandler callbackHandler, final Map sharedState, final Map options )
{
    this.subject = subject;
    this.callbackHandler = callbackHandler;
}
 
Example 37
Project: OperatieBRP   File: PropertiesAccessController.java   View source code 5 votes vote down vote up
private void check(final Subject subject, final Function<Access, Boolean> accessCheck) {
    for (final Principal principal : subject.getPrincipals()) {
        final Access access = accesses.get(principal.getName());
        LOGGER.log(Level.FINE, "Check for principal: {0} -> {1}", new Object[]{principal.getName(), access});
        if (access != null && accessCheck.apply(access)) {
            return;
        }
    }

    throw new SecurityException("Illegal access");
}
 
Example 38
Project: fuck_zookeeper   File: DigestLoginModule.java   View source code 5 votes vote down vote up
public void initialize(Subject subject, CallbackHandler callbackHandler, Map<String,?> sharedState, Map<String,?> options) {
    if (options.containsKey("username")) {
        // Zookeeper client: get username and password from JAAS conf (only used if using DIGEST-MD5).
        this.subject = subject;
        String username = (String)options.get("username");
        this.subject.getPublicCredentials().add((Object)username);
        String password = (String)options.get("password");
        this.subject.getPrivateCredentials().add((Object)password);
    }
    return;
}
 
Example 39
Project: jdk8u-jdk   File: RMIConnectionImpl.java   View source code 5 votes vote down vote up
@SuppressWarnings("rawtypes")  // MarshalledObject
public Set<ObjectInstance>
    queryMBeans(ObjectName name,
                MarshalledObject query,
                Subject delegationSubject)
    throws IOException {
    final QueryExp queryValue;
    final boolean debug=logger.debugOn();

    if (debug) logger.debug("queryMBeans",
             "connectionId=" + connectionId
             +" unwrapping query with defaultClassLoader.");

    queryValue = unwrap(query, defaultContextClassLoader, QueryExp.class, delegationSubject);

    try {
        final Object params[] = new Object[] { name, queryValue };

        if (debug) logger.debug("queryMBeans",
             "connectionId=" + connectionId
             +", name="+name +", query="+query);

        return cast(
            doPrivilegedOperation(
              QUERY_MBEANS,
              params,
              delegationSubject));
    } catch (PrivilegedActionException pe) {
        Exception e = extractException(pe);
        if (e instanceof IOException)
            throw (IOException) e;
        throw newIOException("Got unexpected server exception: " + e, e);
    }
}
 
Example 40
Project: openjdk-jdk10   File: RMIConnectionImpl.java   View source code 5 votes vote down vote up
public void removeNotificationListener(ObjectName name,
                                       ObjectName listener,
                                       Subject delegationSubject)
    throws
    InstanceNotFoundException,
    ListenerNotFoundException,
    IOException {

    checkNonNull("Target MBean name", name);
    checkNonNull("Listener MBean name", listener);

    try {
        final Object params[] = new Object[] { name, listener };

        if (logger.debugOn()) logger.debug("removeNotificationListener"+
                               "(ObjectName,ObjectName)",
                               "connectionId=" + connectionId
                               +", name=" + name
                               +", listenerName=" + listener);

        doPrivilegedOperation(
          REMOVE_NOTIFICATION_LISTENER_OBJECTNAME,
          params,
          delegationSubject);
    } catch (PrivilegedActionException pe) {
        Exception e = extractException(pe);
        if (e instanceof InstanceNotFoundException)
            throw (InstanceNotFoundException) e;
        if (e instanceof ListenerNotFoundException)
            throw (ListenerNotFoundException) e;
        if (e instanceof IOException)
            throw (IOException) e;
        throw newIOException("Got unexpected server exception: " + e, e);
    }
}