Search in sources :

Example 16 with PerunPrincipal

use of cz.metacentrum.perun.core.api.PerunPrincipal in project perun by CESNET.

the class RegistrarBaseIntegrationTest method setupTest.

@Before
public void setupTest() throws Exception {
    if (vo == null || session == null) {
        session = perun.getPerunSession(new PerunPrincipal("perunTests", ExtSourcesManager.EXTSOURCE_NAME_INTERNAL, ExtSourcesManager.EXTSOURCE_INTERNAL), new PerunClient());
        // create test VO
        vo = new Vo(0, "registrarTestVO", "regTestVO");
        vo = perun.getVosManagerBl().createVo(session, vo);
    }
}
Also used : PerunClient(cz.metacentrum.perun.core.api.PerunClient) PerunPrincipal(cz.metacentrum.perun.core.api.PerunPrincipal) Vo(cz.metacentrum.perun.core.api.Vo) Before(org.junit.Before)

Example 17 with PerunPrincipal

use of cz.metacentrum.perun.core.api.PerunPrincipal in project perun by CESNET.

the class Api method setupPerunPrincipal.

private static PerunPrincipal setupPerunPrincipal(HttpServletRequest req, Deserializer des) throws UserNotExistsException {
    String extSourceLoaString = null;
    String extLogin = null;
    String extSourceName = null;
    String extSourceType = null;
    int extSourceLoa;
    Map<String, String> additionalInformations = new HashMap<>();
    String shibIdentityProvider = getStringAttribute(req, SHIB_IDENTITY_PROVIDER);
    String sourceIdpEntityId = getStringAttribute(req, SOURCE_IDP_ENTITY_ID);
    String remoteUser = req.getRemoteUser();
    CoreConfig config = BeansUtils.getCoreConfig();
    // If we have header Shib-Identity-Provider, then the user uses identity federation to authenticate
    if (isNotEmpty(shibIdentityProvider)) {
        extSourceName = getOriginalIdP(shibIdentityProvider, sourceIdpEntityId);
        extSourceType = ExtSourcesManager.EXTSOURCE_IDP;
        extSourceLoaString = getStringAttribute(req, LOA);
        if (isEmpty(extSourceLoaString))
            extSourceLoaString = BeansUtils.getCoreConfig().getDefaultLoaIdP();
        // FIXME: find better place where do the operation with attributes from federation
        String eppn = getStringAttribute(req, "eppn");
        if (isNotEmpty(eppn)) {
            // Remove scope from the eppn attribute
            additionalInformations.put("eppnwoscope", StringUtils.substringBefore(eppn, "@"));
        }
        // Store IdP used by user to session, since for IdentityConsolidator and Registrar we need to know,
        // if user logged in through proxy or not - we provide different links etc.
        additionalInformations.put(UsersManagerBl.ORIGIN_IDENTITY_PROVIDER_KEY, shibIdentityProvider);
        if (isNotEmpty(remoteUser)) {
            extLogin = remoteUser;
        }
    } else // If OIDC_CLAIM_sub header is present, it means user authenticated via OAuth2 with MITRE.
    if (isNotEmpty(req.getHeader(OIDC_CLAIM_SUB))) {
        extLogin = req.getHeader(OIDC_CLAIM_SUB);
        // this is configurable, as the OIDC server has the source of sub claim also configurable
        String iss = req.getHeader(OIDC_CLAIM_ISS);
        if (iss != null) {
            extSourceName = BeansUtils.getCoreConfig().getOidcIssuersExtsourceNames().get(iss);
            extSourceType = BeansUtils.getCoreConfig().getOidcIssuersExtsourceTypes().get(iss);
            if (extSourceName == null || extSourceType == null) {
                throw new InternalErrorException("OIDC issuer " + iss + " not configured");
            }
        } else {
            throw new InternalErrorException("OIDC issuer not send by Authorization Server");
        }
        extSourceLoaString = "-1";
        log.debug("detected OIDC/OAuth2 client for sub={},iss={}", extLogin, iss);
    } else // EXT_SOURCE was defined in Apache configuration (e.g. Kerberos or Local)
    if (req.getAttribute(EXTSOURCE) != null) {
        extSourceName = getStringAttribute(req, EXTSOURCE);
        extSourceType = getStringAttribute(req, EXTSOURCETYPE);
        extSourceLoaString = getStringAttribute(req, EXTSOURCELOA);
        extLogin = getExtLogin(req, extSourceName, remoteUser);
    } else // Cert must be last since Apache asks for certificate everytime and fills cert properties even when Kerberos is in place.
    if (Objects.equals(req.getAttribute(SSL_CLIENT_VERIFY), SUCCESS)) {
        String certDN = getStringAttribute(req, SSL_CLIENT_SUBJECT_DN);
        String caDN = getStringAttribute(req, SSL_CLIENT_ISSUER_DN);
        String wholeCert = getStringAttribute(req, SSL_CLIENT_CERT);
        extSourceName = caDN;
        extSourceType = ExtSourcesManager.EXTSOURCE_X509;
        extSourceLoaString = getStringAttribute(req, EXTSOURCELOA);
        extLogin = certDN;
        // Store X509 certificate in the additionalInformations structure
        // FIXME: duplicit
        additionalInformations.put("userCertificates", AttributesManagerBlImpl.escapeMapAttributeValue(certDN) + AttributesManagerImpl.KEY_VALUE_DELIMITER + AttributesManagerBlImpl.escapeMapAttributeValue(wholeCert));
        additionalInformations.put("userCertDNs", AttributesManagerBlImpl.escapeMapAttributeValue(certDN) + AttributesManagerImpl.KEY_VALUE_DELIMITER + AttributesManagerBlImpl.escapeMapAttributeValue(caDN));
        additionalInformations.put(SSL_CLIENT_SUBJECT_DN, certDN);
        // Store X509
        additionalInformations.put("dn", certDN);
        additionalInformations.put("cadn", caDN);
        additionalInformations.put("certificate", wholeCert);
        // Get organization from the certificate
        Pattern p = Pattern.compile("[oO]\\s*=\\s*([^/]*)");
        Matcher m = p.matcher(certDN);
        if (m.find()) {
            additionalInformations.put("o", m.group(1));
        }
        // Get CN from the certificate
        Pattern p2 = Pattern.compile("CN=([^/]*)");
        Matcher m2 = p2.matcher(certDN);
        if (m2.find()) {
            additionalInformations.put("cn", m2.group(1));
        }
        // Get the X.509 certificate object
        X509Certificate[] certs = (X509Certificate[]) req.getAttribute("javax.servlet.request.X509Certificate");
        // Get the emails
        if (certs != null && certs.length > 0 && certs[0] != null) {
            String emails = "";
            Collection<List<?>> altNames;
            try {
                altNames = certs[0].getSubjectAlternativeNames();
                if (altNames != null) {
                    for (List<?> entry : altNames) {
                        if (((Integer) entry.get(0)) == 1) {
                            emails = (String) entry.get(1);
                        }
                    }
                }
            } catch (CertificateParsingException e) {
                log.error("Error during parsing certificate {}", Arrays.asList(certs));
            }
            additionalInformations.put("mail", emails);
        }
    }
    // store selected attributes for update
    for (AttributeDefinition attr : config.getAttributesForUpdate().getOrDefault(extSourceType, Collections.emptyList())) {
        String attrValue = (String) req.getAttribute(attr.getFriendlyName());
        if (attrValue != null) {
            // fix shibboleth encoding
            if (ExtSourcesManager.EXTSOURCE_IDP.equals(extSourceType)) {
                attrValue = new String(attrValue.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
            }
            log.debug("storing {}={} to additionalInformations", attr.getFriendlyName(), attrValue);
            additionalInformations.put(attr.getFriendlyName(), attrValue);
        }
    }
    // If the RPC was called by the user who can do delegation and delegatedLogin is set, set the values sent in the request
    if (des != null && extLogin != null) {
        List<String> powerUsers = config.getRpcPowerusers();
        if (powerUsers.contains(extLogin) && des.contains(DELEGATED_LOGIN)) {
            // Rewrite the remoteUser and extSource
            extLogin = des.readString(DELEGATED_LOGIN);
            extSourceName = des.readString(DELEGATED_EXTSOURCE_NAME);
            extSourceType = des.readString(DELEGATED_EXTSOURCE_TYPE);
            // Clear additionalInformations because they were valid only to the user who can do delegation
            additionalInformations.clear();
        }
    }
    // extSourceLoa must be number, if any specified then set to 0
    if (isEmpty(extSourceLoaString)) {
        extSourceLoa = 0;
    } else {
        try {
            extSourceLoa = Integer.parseInt(extSourceLoaString);
        } catch (NumberFormatException ex) {
            extSourceLoa = 0;
        }
    }
    // Check if any of authentication system returns extLogin and extSourceName
    if (isEmpty(extLogin) || isEmpty(extSourceName)) {
        throw new UserNotExistsException("extLogin or extSourceName is empty");
    }
    log.trace("creating PerunPrincipal(actor={},extSourceName={},extSourceType={},extSourceLoa={},additionalInformations={})", extLogin, extSourceName, extSourceType, extSourceLoa, additionalInformations);
    return new PerunPrincipal(extLogin, extSourceName, extSourceType, extSourceLoa, additionalInformations);
}
Also used : Pattern(java.util.regex.Pattern) CertificateParsingException(java.security.cert.CertificateParsingException) HashMap(java.util.HashMap) CoreConfig(cz.metacentrum.perun.core.api.CoreConfig) Matcher(java.util.regex.Matcher) UserNotExistsException(cz.metacentrum.perun.core.api.exceptions.UserNotExistsException) AttributeDefinition(cz.metacentrum.perun.core.api.AttributeDefinition) InternalErrorException(cz.metacentrum.perun.core.api.exceptions.InternalErrorException) X509Certificate(java.security.cert.X509Certificate) Collection(java.util.Collection) PerunPrincipal(cz.metacentrum.perun.core.api.PerunPrincipal) List(java.util.List) ArrayList(java.util.ArrayList)

Example 18 with PerunPrincipal

use of cz.metacentrum.perun.core.api.PerunPrincipal in project perun by CESNET.

the class Api method doGet.

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    checkOriginHeader(req, resp);
    if (req.getPathInfo() == null || req.getPathInfo().equals("/")) {
        resp.setContentType("text/plain; charset=utf-8");
        Writer wrt = resp.getWriter();
        PerunPrincipal perunPrincipal;
        try {
            perunPrincipal = setupPerunPrincipal(req, null);
            wrt.write("OK! Version: " + getPerunRpcVersion() + ", User: " + perunPrincipal.getActor() + ", extSource: " + perunPrincipal.getExtSourceName());
        } catch (InternalErrorException | UserNotExistsException e) {
            wrt.write("ERROR! Exception " + e.getMessage());
        }
        wrt.write("\n");
        wrt.close();
    } else {
        serve(req, resp, true, false);
    }
}
Also used : UserNotExistsException(cz.metacentrum.perun.core.api.exceptions.UserNotExistsException) PerunPrincipal(cz.metacentrum.perun.core.api.PerunPrincipal) InternalErrorException(cz.metacentrum.perun.core.api.exceptions.InternalErrorException) PrintWriter(java.io.PrintWriter) Writer(java.io.Writer)

Example 19 with PerunPrincipal

use of cz.metacentrum.perun.core.api.PerunPrincipal in project perun by CESNET.

the class PerunBlImpl method getPerunSession.

/**
 * This method is used only internally.
 */
private PerunSession getPerunSession() {
    PerunPrincipal principal = new PerunPrincipal(INTERNALPRINCIPAL, ExtSourcesManager.EXTSOURCE_NAME_INTERNAL, ExtSourcesManager.EXTSOURCE_INTERNAL);
    PerunClient client = new PerunClient();
    return new PerunSessionImpl(this, principal, client);
}
Also used : PerunClient(cz.metacentrum.perun.core.api.PerunClient) PerunPrincipal(cz.metacentrum.perun.core.api.PerunPrincipal) PerunSessionImpl(cz.metacentrum.perun.core.impl.PerunSessionImpl)

Example 20 with PerunPrincipal

use of cz.metacentrum.perun.core.api.PerunPrincipal in project perun by CESNET.

the class EventProcessor method createTaskFromEvent.

/**
 * Creates Task from Event data. Tries to resolve Service and Facility pairs from Event.
 * Events for non existing entities are discarded.
 *
 * @param event Event to parse
 * @throws ServiceNotExistsException When Service from Event doesn't exists anymore
 * @throws InvalidEventMessageException  When Message has invalid format.
 * @throws InternalErrorException  When implementation fails
 * @throws PrivilegeException  When dispatcher lack privileges to call core methods
 */
private void createTaskFromEvent(Event event) throws ServiceNotExistsException, InvalidEventMessageException, PrivilegeException {
    Map<Facility, Set<Service>> resolvedServices = eventServiceResolver.resolveEvent(event.getData());
    for (Entry<Facility, Set<Service>> map : resolvedServices.entrySet()) {
        Facility facility = map.getKey();
        for (Service service : map.getValue()) {
            if (!service.isEnabled()) {
                log.debug("Service not enabled: {}.", service);
                continue;
            }
            if (((PerunBl) perun).getServicesManagerBl().isServiceBlockedOnFacility(service, facility)) {
                log.debug("Service blocked on Facility: {} , {}.", service, facility);
                continue;
            }
            // Check if all destinations are not blocked
            try {
                // init session
                try {
                    if (sess == null) {
                        sess = perun.getPerunSession(new PerunPrincipal(dispatcherProperties.getProperty("perun.principal.name"), dispatcherProperties.getProperty("perun.principal.extSourceName"), dispatcherProperties.getProperty("perun.principal.extSourceType")), new PerunClient());
                    }
                } catch (InternalErrorException e1) {
                    log.error("Error establishing perun session to create Task from Event: ", e1);
                    continue;
                }
                List<Destination> destinations = perun.getServicesManager().getDestinations(sess, service, facility);
                if (destinations != null && !destinations.isEmpty()) {
                    Iterator<Destination> iter = destinations.iterator();
                    while (iter.hasNext()) {
                        Destination dest = iter.next();
                        if (((PerunBl) perun).getServicesManagerBl().isServiceBlockedOnDestination(service, dest.getId())) {
                            iter.remove();
                        }
                    }
                    if (destinations.isEmpty()) {
                        // All service destinations were blocked -> Task is denied to be sent to engine just like
                        // when service is blocked globally in Perun or on facility as a whole.
                        log.debug("{} blocked on all destinations on {}.", service, facility);
                        continue;
                    }
                }
            } catch (ServiceNotExistsException e) {
                log.error("Service not exist: {}.", service);
            } catch (FacilityNotExistsException e) {
                log.error("Facility not exist: {}.", facility);
            } catch (InternalErrorException | PrivilegeException e) {
                log.error("{}", e);
            }
            // check for presence of task for this <Service, Facility> pair
            // NOTE: this must be atomic enough to not create duplicate
            // tasks in schedulingPool (are we running in parallel
            // here?)
            boolean isForced = determineForcedPropagation(event);
            Task task = schedulingPool.getTask(facility, service);
            if (task != null) {
                // there already is a task in schedulingPool
                // signal that task needs to regenerate data and be forced next time
                task.setDestinations(null);
                task.setSourceUpdated(true);
                if (isForced)
                    task.setPropagationForced(true);
                task.setRecurrence(0);
                log.debug("[{}] Task is already in pool. Re-setting source updated and forced flags, {}.", task.getId(), task);
            } else {
                // no such task yet, create one
                task = new Task();
                task.setFacility(facility);
                task.setService(service);
                task.setStatus(TaskStatus.WAITING);
                task.setRecurrence(0);
                task.setDelay(service.getDelay());
                task.setSchedule(LocalDateTime.now());
                task.setSourceUpdated(false);
                task.setPropagationForced(isForced);
                try {
                    schedulingPool.addToPool(task);
                    log.debug("[{}] New Task added to pool. {}.", task.getId(), task);
                } catch (TaskStoreException e) {
                    log.error("[{}] Could not add Task to pool. Task {} will be lost: {}", task.getId(), task, e);
                }
                schedulingPool.scheduleTask(task, -1);
            }
        }
    }
}
Also used : Destination(cz.metacentrum.perun.core.api.Destination) Task(cz.metacentrum.perun.taskslib.model.Task) Set(java.util.Set) Service(cz.metacentrum.perun.core.api.Service) FacilityNotExistsException(cz.metacentrum.perun.core.api.exceptions.FacilityNotExistsException) InternalErrorException(cz.metacentrum.perun.core.api.exceptions.InternalErrorException) TaskStoreException(cz.metacentrum.perun.taskslib.exceptions.TaskStoreException) ServiceNotExistsException(cz.metacentrum.perun.core.api.exceptions.ServiceNotExistsException) PerunClient(cz.metacentrum.perun.core.api.PerunClient) PrivilegeException(cz.metacentrum.perun.core.api.exceptions.PrivilegeException) PerunPrincipal(cz.metacentrum.perun.core.api.PerunPrincipal) Facility(cz.metacentrum.perun.core.api.Facility)

Aggregations

PerunPrincipal (cz.metacentrum.perun.core.api.PerunPrincipal)27 PerunClient (cz.metacentrum.perun.core.api.PerunClient)24 Before (org.junit.Before)13 InternalErrorException (cz.metacentrum.perun.core.api.exceptions.InternalErrorException)10 Facility (cz.metacentrum.perun.core.api.Facility)8 Service (cz.metacentrum.perun.core.api.Service)8 Vo (cz.metacentrum.perun.core.api.Vo)8 Group (cz.metacentrum.perun.core.api.Group)7 Resource (cz.metacentrum.perun.core.api.Resource)7 ArrayList (java.util.ArrayList)6 AttributeDefinition (cz.metacentrum.perun.core.api.AttributeDefinition)5 PerunSession (cz.metacentrum.perun.core.api.PerunSession)5 User (cz.metacentrum.perun.core.api.User)5 UserNotExistsException (cz.metacentrum.perun.core.api.exceptions.UserNotExistsException)5 JdbcPerunTemplate (org.springframework.jdbc.core.JdbcPerunTemplate)5 Owner (cz.metacentrum.perun.core.api.Owner)4 ExecService (cz.metacentrum.perun.taskslib.model.ExecService)4 HashMap (java.util.HashMap)4 Attribute (cz.metacentrum.perun.core.api.Attribute)3 Candidate (cz.metacentrum.perun.core.api.Candidate)3