Search in sources :

Example 11 with Principal

use of java.security.Principal in project kafka by apache.

the class SaslClientAuthenticator method configure.

public void configure(TransportLayer transportLayer, PrincipalBuilder principalBuilder, Map<String, ?> configs) throws KafkaException {
    try {
        this.transportLayer = transportLayer;
        this.configs = configs;
        setSaslState(handshakeRequestEnable ? SaslState.SEND_HANDSHAKE_REQUEST : SaslState.INITIAL);
        // determine client principal from subject.
        if (!subject.getPrincipals().isEmpty()) {
            Principal clientPrincipal = subject.getPrincipals().iterator().next();
            this.clientPrincipalName = clientPrincipal.getName();
        } else {
            clientPrincipalName = null;
        }
        callbackHandler = new SaslClientCallbackHandler();
        callbackHandler.configure(configs, Mode.CLIENT, subject, mechanism);
        saslClient = createSaslClient();
    } catch (Exception e) {
        throw new KafkaException("Failed to configure SaslClientAuthenticator", e);
    }
}
Also used : KafkaException(org.apache.kafka.common.KafkaException) Principal(java.security.Principal) KafkaPrincipal(org.apache.kafka.common.security.auth.KafkaPrincipal) KafkaException(org.apache.kafka.common.KafkaException) SaslException(javax.security.sasl.SaslException) SchemaException(org.apache.kafka.common.protocol.types.SchemaException) IllegalSaslStateException(org.apache.kafka.common.errors.IllegalSaslStateException) PrivilegedActionException(java.security.PrivilegedActionException) IOException(java.io.IOException) UnsupportedSaslMechanismException(org.apache.kafka.common.errors.UnsupportedSaslMechanismException) AuthenticationException(org.apache.kafka.common.errors.AuthenticationException)

Example 12 with Principal

use of java.security.Principal in project storm by apache.

the class Nimbus method submitTopologyWithOpts.

@Override
public void submitTopologyWithOpts(String topoName, String uploadedJarLocation, String jsonConf, StormTopology topology, SubmitOptions options) throws AlreadyAliveException, InvalidTopologyException, AuthorizationException, TException {
    try {
        submitTopologyWithOptsCalls.mark();
        assertIsLeader();
        assert (options != null);
        validateTopologyName(topoName);
        checkAuthorization(topoName, null, "submitTopology");
        assertTopoActive(topoName, false);
        @SuppressWarnings("unchecked") Map<String, Object> topoConf = (Map<String, Object>) JSONValue.parse(jsonConf);
        try {
            ConfigValidation.validateFields(topoConf);
        } catch (IllegalArgumentException ex) {
            throw new InvalidTopologyException(ex.getMessage());
        }
        validator.validate(topoName, topoConf, topology);
        Utils.validateTopologyBlobStoreMap(topoConf, Sets.newHashSet(blobStore.listKeys()));
        long uniqueNum = submittedCount.incrementAndGet();
        String topoId = topoName + "-" + uniqueNum + "-" + Time.currentTimeSecs();
        Map<String, String> creds = null;
        if (options.is_set_creds()) {
            creds = options.get_creds().get_creds();
        }
        topoConf.put(Config.STORM_ID, topoId);
        topoConf.put(Config.TOPOLOGY_NAME, topoName);
        topoConf = normalizeConf(conf, topoConf, topology);
        ReqContext req = ReqContext.context();
        Principal principal = req.principal();
        String submitterPrincipal = principal == null ? null : principal.toString();
        String submitterUser = principalToLocal.toLocal(principal);
        String systemUser = System.getProperty("user.name");
        @SuppressWarnings("unchecked") Set<String> topoAcl = new HashSet<>((List<String>) topoConf.getOrDefault(Config.TOPOLOGY_USERS, Collections.emptyList()));
        topoAcl.add(submitterPrincipal);
        topoAcl.add(submitterUser);
        topoConf.put(Config.TOPOLOGY_SUBMITTER_PRINCIPAL, OR(submitterPrincipal, ""));
        //Don't let the user set who we launch as
        topoConf.put(Config.TOPOLOGY_SUBMITTER_USER, OR(submitterUser, systemUser));
        topoConf.put(Config.TOPOLOGY_USERS, new ArrayList<>(topoAcl));
        topoConf.put(Config.STORM_ZOOKEEPER_SUPERACL, conf.get(Config.STORM_ZOOKEEPER_SUPERACL));
        if (!Utils.isZkAuthenticationConfiguredStormServer(conf)) {
            topoConf.remove(Config.STORM_ZOOKEEPER_TOPOLOGY_AUTH_SCHEME);
            topoConf.remove(Config.STORM_ZOOKEEPER_TOPOLOGY_AUTH_PAYLOAD);
        }
        if (!(Boolean) conf.getOrDefault(Config.STORM_TOPOLOGY_CLASSPATH_BEGINNING_ENABLED, false)) {
            topoConf.remove(Config.TOPOLOGY_CLASSPATH_BEGINNING);
        }
        Map<String, Object> totalConf = merge(conf, topoConf);
        topology = normalizeTopology(totalConf, topology);
        IStormClusterState state = stormClusterState;
        if (creds != null) {
            Map<String, Object> finalConf = Collections.unmodifiableMap(topoConf);
            for (INimbusCredentialPlugin autocred : nimbusAutocredPlugins) {
                autocred.populateCredentials(creds, finalConf);
            }
        }
        if (Utils.getBoolean(conf.get(Config.SUPERVISOR_RUN_WORKER_AS_USER), false) && (submitterUser == null || submitterUser.isEmpty())) {
            throw new AuthorizationException("Could not determine the user to run this topology as.");
        }
        //this validates the structure of the topology
        StormCommon.systemTopology(totalConf, topology);
        validateTopologySize(topoConf, conf, topology);
        if (Utils.isZkAuthenticationConfiguredStormServer(conf) && !Utils.isZkAuthenticationConfiguredTopology(topoConf)) {
            throw new IllegalArgumentException("The cluster is configured for zookeeper authentication, but no payload was provided.");
        }
        LOG.info("Received topology submission for {} with conf {}", topoName, Utils.redactValue(topoConf, Config.STORM_ZOOKEEPER_TOPOLOGY_AUTH_PAYLOAD));
        // cleanup thread killing topology in b/w assignment and starting the topology
        synchronized (submitLock) {
            assertTopoActive(topoName, false);
            //cred-update-lock is not needed here because creds are being added for the first time.
            if (creds != null) {
                state.setCredentials(topoId, new Credentials(creds), topoConf);
            }
            LOG.info("uploadedJar {}", uploadedJarLocation);
            setupStormCode(conf, topoId, uploadedJarLocation, totalConf, topology);
            waitForDesiredCodeReplication(totalConf, topoId);
            state.setupHeatbeats(topoId);
            if (Utils.getBoolean(totalConf.get(Config.TOPOLOGY_BACKPRESSURE_ENABLE), false)) {
                state.setupBackpressure(topoId);
            }
            notifyTopologyActionListener(topoName, "submitTopology");
            TopologyStatus status = null;
            switch(options.get_initial_status()) {
                case INACTIVE:
                    status = TopologyStatus.INACTIVE;
                    break;
                case ACTIVE:
                    status = TopologyStatus.ACTIVE;
                    break;
                default:
                    throw new IllegalArgumentException("Inital Status of " + options.get_initial_status() + " is not allowed.");
            }
            startTopology(topoName, topoId, status);
        }
    } catch (Exception e) {
        LOG.warn("Topology submission exception. (topology name='{}')", topoName, e);
        if (e instanceof TException) {
            throw (TException) e;
        }
        throw new RuntimeException(e);
    }
}
Also used : INimbusCredentialPlugin(org.apache.storm.security.INimbusCredentialPlugin) TException(org.apache.thrift.TException) AuthorizationException(org.apache.storm.generated.AuthorizationException) InvalidTopologyException(org.apache.storm.generated.InvalidTopologyException) ReqContext(org.apache.storm.security.auth.ReqContext) AuthorizationException(org.apache.storm.generated.AuthorizationException) NotAliveException(org.apache.storm.generated.NotAliveException) InterruptedIOException(java.io.InterruptedIOException) TException(org.apache.thrift.TException) IOException(java.io.IOException) AlreadyAliveException(org.apache.storm.generated.AlreadyAliveException) KeyAlreadyExistsException(org.apache.storm.generated.KeyAlreadyExistsException) KeyNotFoundException(org.apache.storm.generated.KeyNotFoundException) InvalidTopologyException(org.apache.storm.generated.InvalidTopologyException) BindException(java.net.BindException) IStormClusterState(org.apache.storm.cluster.IStormClusterState) TopologyStatus(org.apache.storm.generated.TopologyStatus) Map(java.util.Map) TimeCacheMap(org.apache.storm.utils.TimeCacheMap) ImmutableMap(com.google.common.collect.ImmutableMap) HashMap(java.util.HashMap) NimbusPrincipal(org.apache.storm.security.auth.NimbusPrincipal) Principal(java.security.Principal) Credentials(org.apache.storm.generated.Credentials) HashSet(java.util.HashSet)

Example 13 with Principal

use of java.security.Principal in project storm by apache.

the class DRPC method checkAuthorization.

@VisibleForTesting
static void checkAuthorization(ReqContext reqContext, IAuthorizer auth, String operation, String function) throws AuthorizationException {
    if (reqContext != null) {
        ThriftAccessLogger.logAccessFunction(reqContext.requestID(), reqContext.remoteAddress(), reqContext.principal(), operation, function);
    }
    if (auth != null) {
        Map<String, String> map = new HashMap<>();
        map.put(DRPCAuthorizerBase.FUNCTION_NAME, function);
        if (!auth.permit(reqContext, operation, map)) {
            Principal principal = reqContext.principal();
            String user = (principal != null) ? principal.getName() : "unknown";
            throw new AuthorizationException("DRPC request '" + operation + "' for '" + user + "' user is not authorized");
        }
    }
}
Also used : HashMap(java.util.HashMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) AuthorizationException(org.apache.storm.generated.AuthorizationException) Principal(java.security.Principal) VisibleForTesting(com.google.common.annotations.VisibleForTesting)

Example 14 with Principal

use of java.security.Principal in project storm by apache.

the class SingleUserSimpleTransport method getDefaultSubject.

@Override
protected Subject getDefaultSubject() {
    HashSet<Principal> principals = new HashSet<Principal>();
    principals.add(new Principal() {

        public String getName() {
            return "user";
        }

        public String toString() {
            return "user";
        }
    });
    return new Subject(true, principals, new HashSet<Object>(), new HashSet<Object>());
}
Also used : Principal(java.security.Principal) Subject(javax.security.auth.Subject) HashSet(java.util.HashSet)

Example 15 with Principal

use of java.security.Principal in project tomcat by apache.

the class SSLAuthenticator method doAuthenticate.

// --------------------------------------------------------- Public Methods
/**
     * Authenticate the user by checking for the existence of a certificate
     * chain, validating it against the trust manager for the connector and then
     * validating the user's identity against the configured Realm.
     *
     * @param request Request we are processing
     * @param response Response we are creating
     *
     * @exception IOException if an input/output error occurs
     */
@Override
protected boolean doAuthenticate(Request request, HttpServletResponse response) throws IOException {
    // TODO make this a configurable attribute (in SingleSignOn??)
    if (checkForCachedAuthentication(request, response, false)) {
        return true;
    }
    // Retrieve the certificate chain for this client
    if (containerLog.isDebugEnabled()) {
        containerLog.debug(" Looking up certificates");
    }
    X509Certificate[] certs = getRequestCertificates(request);
    if ((certs == null) || (certs.length < 1)) {
        if (containerLog.isDebugEnabled()) {
            containerLog.debug("  No certificates included with this request");
        }
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED, sm.getString("authenticator.certificates"));
        return false;
    }
    // Authenticate the specified certificate chain
    Principal principal = context.getRealm().authenticate(certs);
    if (principal == null) {
        if (containerLog.isDebugEnabled()) {
            containerLog.debug("  Realm.authenticate() returned false");
        }
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED, sm.getString("authenticator.unauthorized"));
        return false;
    }
    // Cache the principal (if requested) and record this authentication
    register(request, response, principal, HttpServletRequest.CLIENT_CERT_AUTH, null, null);
    return true;
}
Also used : X509Certificate(java.security.cert.X509Certificate) Principal(java.security.Principal)

Aggregations

Principal (java.security.Principal)931 Test (org.junit.Test)243 Subject (javax.security.auth.Subject)114 EveryonePrincipal (org.apache.jackrabbit.oak.spi.security.principal.EveryonePrincipal)114 HashSet (java.util.HashSet)89 User (org.apache.jackrabbit.api.security.user.User)75 Group (org.apache.jackrabbit.api.security.user.Group)74 Authorizable (org.apache.jackrabbit.api.security.user.Authorizable)58 Privilege (javax.jcr.security.Privilege)57 RepositoryException (javax.jcr.RepositoryException)51 IOException (java.io.IOException)50 ArrayList (java.util.ArrayList)48 HttpServletRequest (javax.servlet.http.HttpServletRequest)47 TestPrincipal (org.apache.jackrabbit.core.security.TestPrincipal)45 AbstractSecurityTest (org.apache.jackrabbit.oak.AbstractSecurityTest)43 EveryonePrincipal (org.apache.jackrabbit.core.security.principal.EveryonePrincipal)42 PrincipalIterator (org.apache.jackrabbit.api.security.principal.PrincipalIterator)40 HashMap (java.util.HashMap)39 PrincipalImpl (org.apache.jackrabbit.oak.spi.security.principal.PrincipalImpl)39 X500Principal (javax.security.auth.x500.X500Principal)38