Search in sources :

Example 11 with EncryptionException

use of com.evolveum.midpoint.prism.crypto.EncryptionException in project midpoint by Evolveum.

the class PageSecurityQuestions method resetPassword.

private void resetPassword(UserType user, AjaxRequestTarget target) {
    Task task = createAnonymousTask(OPERATION_RESET_PASSWORD);
    OperationResult result = task.getResult();
    LOGGER.debug("Resetting password for {}", user);
    ProtectedStringType password = new ProtectedStringType();
    Collection<SelectorOptions<GetOperationOptions>> options = SelectorOptions.createCollection(GetOperationOptions.createResolve(), SystemConfigurationType.F_DEFAULT_USER_TEMPLATE, SystemConfigurationType.F_GLOBAL_PASSWORD_POLICY);
    PrismObject<SystemConfigurationType> systemConfig = null;
    String newPassword = "";
    PageBase page = (PageBase) getPage();
    ModelService modelService = page.getModelService();
    try {
        systemConfig = modelService.getObject(SystemConfigurationType.class, SystemObjectsType.SYSTEM_CONFIGURATION.value(), options, task, result);
        LOGGER.trace("system config {}", systemConfig);
        if (systemConfig.asObjectable().getNotificationConfiguration() != null) {
            // Security policy with the minumum number of chars
            if (systemConfig.asObjectable().getGlobalPasswordPolicyRef() != null) {
                PrismObject<ValuePolicyType> valPolicy = modelService.getObject(ValuePolicyType.class, systemConfig.asObjectable().getGlobalPasswordPolicyRef().getOid(), options, task, result);
                LOGGER.trace("password policy {}", valPolicy);
                newPassword = getModelInteractionService().generateValue(valPolicy.asObjectable().getStringPolicy(), valPolicy.asObjectable().getStringPolicy().getLimitations().getMinLength(), false, user.asPrismObject(), "security questions password generation", task, result);
            } else {
                // TODO What if there is no policy? What should be done to
                // provide a new automatic password
                warn(getString("pageSecurityQuestions.message.noPolicySet"));
                target.add(getFeedbackPanel());
                return;
            }
        } else {
            // TODO localization
            getSession().error(getString("pageSecurityQuestions.message.notificationsNotSet"));
            LOGGER.trace("Notificatons not set, returning to login page");
            throw new RestartResponseException(PageLogin.class);
        }
    } catch (ObjectNotFoundException | ExpressionEvaluationException e1) {
        LoggingUtils.logUnexpectedException(LOGGER, "Couldn't reset password", e1);
    } catch (SchemaException e1) {
        LoggingUtils.logUnexpectedException(LOGGER, "Couldn't reset password", e1);
        e1.printStackTrace();
    } catch (SecurityViolationException e1) {
        LoggingUtils.logUnexpectedException(LOGGER, "Couldn't reset password", e1);
    } catch (CommunicationException e1) {
        LoggingUtils.logUnexpectedException(LOGGER, "Couldn't reset password", e1);
    } catch (ConfigurationException e1) {
        LoggingUtils.logUnexpectedException(LOGGER, "Couldn't reset password", e1);
    }
    password.setClearValue(newPassword);
    WebComponentUtil.encryptProtectedString(password, true, getMidpointApplication());
    final ItemPath valuePath = new ItemPath(SchemaConstantsGenerated.C_CREDENTIALS, CredentialsType.F_PASSWORD, PasswordType.F_VALUE);
    SchemaRegistry registry = getPrismContext().getSchemaRegistry();
    Collection<ObjectDelta<? extends ObjectType>> deltas = new ArrayList<ObjectDelta<? extends ObjectType>>();
    PrismObjectDefinition objDef = registry.findObjectDefinitionByCompileTimeClass(UserType.class);
    PropertyDelta delta = PropertyDelta.createModificationReplaceProperty(valuePath, objDef, password);
    Class<? extends ObjectType> type = UserType.class;
    deltas.add(ObjectDelta.createModifyDelta(user.getOid(), delta, type, getPrismContext()));
    try {
        modelService.executeChanges(deltas, null, task, result);
        OperationResult parentResult = new OperationResult(OPERATION_LOAD_RESET_PASSWORD_POLICY);
        try {
            if (getModelInteractionService().getCredentialsPolicy(null, null, parentResult).getSecurityQuestions().getResetMethod().getResetType().equals(CredentialsResetTypeType.SECURITY_QUESTIONS)) {
                getSession().setAttribute("pwdReset", newPassword);
                setResponsePage(PageShowPassword.class);
            } else if (getModelInteractionService().getCredentialsPolicy(null, null, parentResult).getSecurityQuestions().getResetMethod().getResetType().equals(CredentialsResetTypeType.SECURITY_QUESTIONS_EMAIL)) {
                if (systemConfig.asObjectable().getNotificationConfiguration() != null && systemConfig.asObjectable().getNotificationConfiguration().getMail() != null) {
                    MailConfigurationType mailConfig = systemConfig.asObjectable().getNotificationConfiguration().getMail();
                    if (mailConfig.getServer() != null) {
                        List serverList = mailConfig.getServer();
                        if (serverList.size() > 0) {
                            MailServerConfigurationType mailServerType = mailConfig.getServer().get(0);
                            sendMailToUser(mailServerType.getUsername(), getMidpointApplication().getProtector().decryptString(mailServerType.getPassword()), newPassword, mailServerType.getHost(), mailServerType.getPort().toString(), mailConfig.getDefaultFrom(), user.getEmailAddress());
                        } else {
                            getSession().error(getString("pageLogin.message.ForgetPasswordSettingsWrong"));
                            throw new RestartResponseException(PageLogin.class);
                        }
                    } else {
                        getSession().error(getString("pageLogin.message.ForgetPasswordSettingsWrong"));
                        throw new RestartResponseException(PageLogin.class);
                    }
                } else {
                    // System.out.println("ifff4");
                    getSession().error(getString("pageLogin.message.ForgetPasswordSettingsWrong"));
                    throw new RestartResponseException(PageLogin.class);
                }
            }
        } catch (ObjectNotFoundException | SchemaException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    // TODO ASAP a message should be shown as the result of the process
    // MailMessage mailMessage=new MailMessage(, port);
    // mailTransport.send(mailMessage, transportName, task,
    // parentResult);
    } catch (ObjectAlreadyExistsException | ObjectNotFoundException | SchemaException | ExpressionEvaluationException | CommunicationException | ConfigurationException | PolicyViolationException | SecurityViolationException | EncryptionException e) {
        LoggingUtils.logUnexpectedException(LOGGER, "reset password exception", e);
    }
}
Also used : Task(com.evolveum.midpoint.task.api.Task) ExpressionEvaluationException(com.evolveum.midpoint.util.exception.ExpressionEvaluationException) ValuePolicyType(com.evolveum.midpoint.xml.ns._public.common.common_3.ValuePolicyType) SecurityViolationException(com.evolveum.midpoint.util.exception.SecurityViolationException) ArrayList(java.util.ArrayList) MailServerConfigurationType(com.evolveum.midpoint.xml.ns._public.common.common_3.MailServerConfigurationType) OperationResult(com.evolveum.midpoint.schema.result.OperationResult) ObjectType(com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType) ConfigurationException(com.evolveum.midpoint.util.exception.ConfigurationException) EncryptionException(com.evolveum.midpoint.prism.crypto.EncryptionException) PropertyDelta(com.evolveum.midpoint.prism.delta.PropertyDelta) List(java.util.List) ArrayList(java.util.ArrayList) ObjectDelta(com.evolveum.midpoint.prism.delta.ObjectDelta) PolicyViolationException(com.evolveum.midpoint.util.exception.PolicyViolationException) ObjectAlreadyExistsException(com.evolveum.midpoint.util.exception.ObjectAlreadyExistsException) SchemaException(com.evolveum.midpoint.util.exception.SchemaException) CommunicationException(com.evolveum.midpoint.util.exception.CommunicationException) PrismObjectDefinition(com.evolveum.midpoint.prism.PrismObjectDefinition) MailConfigurationType(com.evolveum.midpoint.xml.ns._public.common.common_3.MailConfigurationType) PageLogin(com.evolveum.midpoint.web.page.login.PageLogin) PageBase(com.evolveum.midpoint.gui.api.page.PageBase) ModelService(com.evolveum.midpoint.model.api.ModelService) SelectorOptions(com.evolveum.midpoint.schema.SelectorOptions) RestartResponseException(org.apache.wicket.RestartResponseException) ObjectNotFoundException(com.evolveum.midpoint.util.exception.ObjectNotFoundException) SystemConfigurationType(com.evolveum.midpoint.xml.ns._public.common.common_3.SystemConfigurationType) ProtectedStringType(com.evolveum.prism.xml.ns._public.types_3.ProtectedStringType) SchemaRegistry(com.evolveum.midpoint.prism.schema.SchemaRegistry) UserType(com.evolveum.midpoint.xml.ns._public.common.common_3.UserType) ItemPath(com.evolveum.midpoint.prism.path.ItemPath)

Example 12 with EncryptionException

use of com.evolveum.midpoint.prism.crypto.EncryptionException in project midpoint by Evolveum.

the class PageMyPasswordQuestions method createUsersSecurityQuestionsList.

public List<SecurityQuestionAnswerDTO> createUsersSecurityQuestionsList(PrismObject<UserType> user) {
    LOGGER.debug("Security Questions Loading for user: " + user.getOid());
    if (user.asObjectable().getCredentials() != null && user.asObjectable().getCredentials().getSecurityQuestions() != null) {
        List<SecurityQuestionAnswerType> secQuestAnsList = user.asObjectable().getCredentials().getSecurityQuestions().getQuestionAnswer();
        if (secQuestAnsList != null) {
            LOGGER.debug("User SecurityQuestion ANswer List is Not null");
            List<SecurityQuestionAnswerDTO> secQuestAnswListDTO = new ArrayList<SecurityQuestionAnswerDTO>();
            for (Iterator iterator = secQuestAnsList.iterator(); iterator.hasNext(); ) {
                SecurityQuestionAnswerType securityQuestionAnswerType = (SecurityQuestionAnswerType) iterator.next();
                Protector protector = getPrismContext().getDefaultProtector();
                String decoded = "";
                if (securityQuestionAnswerType.getQuestionAnswer().getEncryptedDataType() != null) {
                    try {
                        decoded = protector.decryptString(securityQuestionAnswerType.getQuestionAnswer());
                    } catch (EncryptionException e) {
                        LoggingUtils.logUnexpectedException(LOGGER, "Couldn't decrypt user answer", e);
                    }
                }
                //LOGGER.debug("SecAnswerIdentifier:"+securityQuestionAnswerType.getQuestionIdentifier());
                secQuestAnswListDTO.add(new SecurityQuestionAnswerDTO(securityQuestionAnswerType.getQuestionIdentifier(), decoded));
            }
            return secQuestAnswListDTO;
        }
    }
    return null;
}
Also used : SecurityQuestionAnswerDTO(com.evolveum.midpoint.web.page.admin.home.dto.SecurityQuestionAnswerDTO) ArrayList(java.util.ArrayList) Iterator(java.util.Iterator) EncryptionException(com.evolveum.midpoint.prism.crypto.EncryptionException) SecurityQuestionAnswerType(com.evolveum.midpoint.xml.ns._public.common.common_3.SecurityQuestionAnswerType) Protector(com.evolveum.midpoint.prism.crypto.Protector)

Example 13 with EncryptionException

use of com.evolveum.midpoint.prism.crypto.EncryptionException in project midpoint by Evolveum.

the class UserMenuPanel method createUsersSecurityQuestionsList.

public List<SecurityQuestionAnswerDTO> createUsersSecurityQuestionsList(PrismObject<UserType> user) {
    SecurityQuestionsCredentialsType credentialsPolicyType = user.asObjectable().getCredentials().getSecurityQuestions();
    if (credentialsPolicyType == null) {
        return null;
    }
    List<SecurityQuestionAnswerType> secQuestAnsList = credentialsPolicyType.getQuestionAnswer();
    if (secQuestAnsList != null) {
        List<SecurityQuestionAnswerDTO> secQuestAnswListDTO = new ArrayList<SecurityQuestionAnswerDTO>();
        for (Iterator iterator = secQuestAnsList.iterator(); iterator.hasNext(); ) {
            SecurityQuestionAnswerType securityQuestionAnswerType = (SecurityQuestionAnswerType) iterator.next();
            Protector protector = ((PageBase) getPage()).getPrismContext().getDefaultProtector();
            if (securityQuestionAnswerType.getQuestionAnswer() != null && securityQuestionAnswerType.getQuestionAnswer().getEncryptedDataType() != null) {
                try {
                    String decoded = protector.decryptString(securityQuestionAnswerType.getQuestionAnswer());
                    secQuestAnswListDTO.add(new SecurityQuestionAnswerDTO(securityQuestionAnswerType.getQuestionIdentifier(), decoded));
                } catch (EncryptionException e) {
                    // TODO do we need to thrown exception here?
                    LOGGER.error("Could not get security questions. Error: " + e.getMessage(), e);
                    continue;
                }
            }
        }
        return secQuestAnswListDTO;
    } else {
        return null;
    }
}
Also used : SecurityQuestionAnswerDTO(com.evolveum.midpoint.web.page.admin.home.dto.SecurityQuestionAnswerDTO) EncryptionException(com.evolveum.midpoint.prism.crypto.EncryptionException) Protector(com.evolveum.midpoint.prism.crypto.Protector)

Example 14 with EncryptionException

use of com.evolveum.midpoint.prism.crypto.EncryptionException in project midpoint by Evolveum.

the class ChangeExecutor method executeChanges.

// returns true if current operation has to be restarted, see
// ObjectAlreadyExistsException handling (TODO specify more exactly)
public <O extends ObjectType> boolean executeChanges(LensContext<O> context, Task task, OperationResult parentResult) throws ObjectAlreadyExistsException, ObjectNotFoundException, SchemaException, CommunicationException, ConfigurationException, SecurityViolationException, ExpressionEvaluationException {
    OperationResult result = parentResult.createSubresult(OPERATION_EXECUTE);
    // FOCUS
    context.checkAbortRequested();
    LensFocusContext<O> focusContext = context.getFocusContext();
    if (focusContext != null) {
        ObjectDelta<O> focusDelta = focusContext.getWaveExecutableDelta(context.getExecutionWave());
        focusDelta = policyRuleProcessor.applyAssignmentSituation(context, focusDelta);
        if (focusDelta != null) {
            ObjectPolicyConfigurationType objectPolicyConfigurationType = focusContext.getObjectPolicyConfigurationType();
            applyObjectPolicy(focusContext, focusDelta, objectPolicyConfigurationType);
            OperationResult subResult = result.createSubresult(OPERATION_EXECUTE_FOCUS + "." + focusContext.getObjectTypeClass().getSimpleName());
            try {
                // Will remove credential deltas or hash them
                focusDelta = credentialsProcessor.transformFocusExectionDelta(context, focusDelta);
            } catch (EncryptionException e) {
                recordFatalError(subResult, result, null, e);
                result.computeStatus();
                throw new SystemException(e.getMessage(), e);
            }
            try {
                context.reportProgress(new ProgressInformation(FOCUS_OPERATION, ENTERING));
                executeDelta(focusDelta, focusContext, context, null, null, task, subResult);
                subResult.computeStatus();
            } catch (SchemaException | ObjectNotFoundException | CommunicationException | ConfigurationException | SecurityViolationException | ExpressionEvaluationException | RuntimeException e) {
                recordFatalError(subResult, result, null, e);
                throw e;
            } catch (ObjectAlreadyExistsException e) {
                subResult.computeStatus();
                if (!subResult.isSuccess() && !subResult.isHandledError()) {
                    subResult.recordFatalError(e);
                }
                result.computeStatusComposite();
                throw e;
            } finally {
                context.reportProgress(new ProgressInformation(FOCUS_OPERATION, subResult));
            }
        } else {
            LOGGER.trace("Skipping focus change execute, because user delta is null");
        }
    }
    // PROJECTIONS
    context.checkAbortRequested();
    boolean restartRequested = false;
    for (LensProjectionContext projCtx : context.getProjectionContexts()) {
        if (projCtx.getWave() != context.getExecutionWave()) {
            continue;
        }
        if (!projCtx.isCanProject()) {
            continue;
        }
        // we should not get here, but just to be sure
        if (projCtx.getSynchronizationPolicyDecision() == SynchronizationPolicyDecision.IGNORE) {
            LOGGER.trace("Skipping ignored projection context {}", projCtx.toHumanReadableString());
            continue;
        }
        OperationResult subResult = result.createSubresult(OPERATION_EXECUTE_PROJECTION + "." + projCtx.getObjectTypeClass().getSimpleName());
        subResult.addContext("discriminator", projCtx.getResourceShadowDiscriminator());
        if (projCtx.getResource() != null) {
            subResult.addParam("resource", projCtx.getResource().getName());
        }
        try {
            context.checkAbortRequested();
            context.reportProgress(new ProgressInformation(RESOURCE_OBJECT_OPERATION, projCtx.getResourceShadowDiscriminator(), ENTERING));
            executeReconciliationScript(projCtx, context, BeforeAfterType.BEFORE, task, subResult);
            ObjectDelta<ShadowType> projDelta = projCtx.getExecutableDelta();
            if (shouldBeDeleted(projDelta, projCtx)) {
                projDelta = ObjectDelta.createDeleteDelta(projCtx.getObjectTypeClass(), projCtx.getOid(), prismContext);
            }
            if (projCtx.getSynchronizationPolicyDecision() == SynchronizationPolicyDecision.BROKEN) {
                if (context.getFocusContext() != null && context.getFocusContext().getDelta() != null && context.getFocusContext().getDelta().isDelete() && context.getOptions() != null && ModelExecuteOptions.isForce(context.getOptions())) {
                    if (projDelta == null) {
                        projDelta = ObjectDelta.createDeleteDelta(projCtx.getObjectTypeClass(), projCtx.getOid(), prismContext);
                    }
                }
                if (projDelta != null && projDelta.isDelete()) {
                    executeDelta(projDelta, projCtx, context, null, projCtx.getResource(), task, subResult);
                }
            } else {
                if (projDelta == null || projDelta.isEmpty()) {
                    if (LOGGER.isTraceEnabled()) {
                        LOGGER.trace("No change for " + projCtx.getResourceShadowDiscriminator());
                    }
                    if (focusContext != null) {
                        updateLinks(focusContext, projCtx, task, subResult);
                    }
                    // Make sure post-reconcile delta is always executed,
                    // even if there is no change
                    executeReconciliationScript(projCtx, context, BeforeAfterType.AFTER, task, subResult);
                    subResult.computeStatus();
                    subResult.recordNotApplicableIfUnknown();
                    continue;
                } else if (projDelta.isDelete() && projCtx.getResourceShadowDiscriminator() != null && projCtx.getResourceShadowDiscriminator().getOrder() > 0) {
                    // HACK ... for higher-order context check if this was
                    // already deleted
                    LensProjectionContext lowerOrderContext = LensUtil.findLowerOrderContext(context, projCtx);
                    if (lowerOrderContext != null && lowerOrderContext.isDelete()) {
                        // We assume that this was already executed
                        subResult.setStatus(OperationResultStatus.NOT_APPLICABLE);
                        continue;
                    }
                }
                executeDelta(projDelta, projCtx, context, null, projCtx.getResource(), task, subResult);
            }
            subResult.computeStatus();
            if (focusContext != null) {
                updateLinks(focusContext, projCtx, task, subResult);
            }
            executeReconciliationScript(projCtx, context, BeforeAfterType.AFTER, task, subResult);
            subResult.computeStatus();
            subResult.recordNotApplicableIfUnknown();
        } catch (SchemaException e) {
            recordProjectionExecutionException(e, projCtx, subResult, SynchronizationPolicyDecision.BROKEN);
            continue;
        } catch (ObjectNotFoundException e) {
            recordProjectionExecutionException(e, projCtx, subResult, SynchronizationPolicyDecision.BROKEN);
            continue;
        } catch (ObjectAlreadyExistsException e) {
            if (isRepeatedAlreadyExistsException(projCtx)) {
                recordProjectionExecutionException(e, projCtx, subResult, SynchronizationPolicyDecision.BROKEN);
                continue;
            }
            // in his case we do not need to set account context as
            // broken, instead we need to restart projector for this
            // context to recompute new account or find out if the
            // account was already linked..
            // and also do not set fatal error to the operation result, this
            // is a special case
            // if it is fatal, it will be set later
            // but we need to set some result
            subResult.recordSuccess();
            subResult.muteLastSubresultError();
            restartRequested = true;
            // we will process remaining projections when retrying
            break;
        // the wave
        } catch (CommunicationException e) {
            recordProjectionExecutionException(e, projCtx, subResult, SynchronizationPolicyDecision.BROKEN);
            continue;
        } catch (ConfigurationException e) {
            recordProjectionExecutionException(e, projCtx, subResult, SynchronizationPolicyDecision.BROKEN);
            continue;
        } catch (SecurityViolationException e) {
            recordProjectionExecutionException(e, projCtx, subResult, SynchronizationPolicyDecision.BROKEN);
            continue;
        } catch (ExpressionEvaluationException e) {
            recordProjectionExecutionException(e, projCtx, subResult, SynchronizationPolicyDecision.BROKEN);
            continue;
        } catch (RuntimeException e) {
            recordProjectionExecutionException(e, projCtx, subResult, SynchronizationPolicyDecision.BROKEN);
            continue;
        } finally {
            context.reportProgress(new ProgressInformation(RESOURCE_OBJECT_OPERATION, projCtx.getResourceShadowDiscriminator(), subResult));
        }
    }
    // Result computation here needs to be slightly different
    result.computeStatusComposite();
    return restartRequested;
}
Also used : OperationResult(com.evolveum.midpoint.schema.result.OperationResult) ProgressInformation(com.evolveum.midpoint.model.api.ProgressInformation) EncryptionException(com.evolveum.midpoint.prism.crypto.EncryptionException)

Example 15 with EncryptionException

use of com.evolveum.midpoint.prism.crypto.EncryptionException in project midpoint by Evolveum.

the class MailTransport method send.

@Override
public void send(Message mailMessage, String transportName, Event event, Task task, OperationResult parentResult) {
    OperationResult result = parentResult.createSubresult(DOT_CLASS + "send");
    result.addCollectionOfSerializablesAsParam("mailMessage recipient(s)", mailMessage.getTo());
    result.addParam("mailMessage subject", mailMessage.getSubject());
    SystemConfigurationType systemConfiguration = NotificationFunctionsImpl.getSystemConfiguration(cacheRepositoryService, new OperationResult("dummy"));
    if (systemConfiguration == null || systemConfiguration.getNotificationConfiguration() == null || systemConfiguration.getNotificationConfiguration().getMail() == null) {
        String msg = "No notifications are configured. Mail notification to " + mailMessage.getTo() + " will not be sent.";
        LOGGER.warn(msg);
        result.recordWarning(msg);
        return;
    }
    //		if (mailConfigurationType == null) {
    MailConfigurationType mailConfigurationType = systemConfiguration.getNotificationConfiguration().getMail();
    //		}
    String redirectToFile = mailConfigurationType.getRedirectToFile();
    if (redirectToFile != null) {
        try {
            TransportUtil.appendToFile(redirectToFile, formatToFile(mailMessage));
            result.recordSuccess();
        } catch (IOException e) {
            LoggingUtils.logException(LOGGER, "Couldn't write to mail redirect file {}", e, redirectToFile);
            result.recordPartialError("Couldn't write to mail redirect file " + redirectToFile, e);
        }
        return;
    }
    if (mailConfigurationType.getServer().isEmpty()) {
        String msg = "Mail server(s) are not defined, mail notification to " + mailMessage.getTo() + " will not be sent.";
        LOGGER.warn(msg);
        result.recordWarning(msg);
        return;
    }
    long start = System.currentTimeMillis();
    String defaultFrom = mailConfigurationType.getDefaultFrom() != null ? mailConfigurationType.getDefaultFrom() : "nobody@nowhere.org";
    for (MailServerConfigurationType mailServerConfigurationType : mailConfigurationType.getServer()) {
        OperationResult resultForServer = result.createSubresult(DOT_CLASS + "send.forServer");
        final String host = mailServerConfigurationType.getHost();
        resultForServer.addContext("server", host);
        resultForServer.addContext("port", mailServerConfigurationType.getPort());
        Properties properties = System.getProperties();
        properties.setProperty("mail.smtp.host", host);
        if (mailServerConfigurationType.getPort() != null) {
            properties.setProperty("mail.smtp.port", String.valueOf(mailServerConfigurationType.getPort()));
        }
        MailTransportSecurityType mailTransportSecurityType = mailServerConfigurationType.getTransportSecurity();
        boolean sslEnabled = false, starttlsEnable = false, starttlsRequired = false;
        if (mailTransportSecurityType != null) {
            switch(mailTransportSecurityType) {
                case STARTTLS_ENABLED:
                    starttlsEnable = true;
                    break;
                case STARTTLS_REQUIRED:
                    starttlsEnable = true;
                    starttlsRequired = true;
                    break;
                case SSL:
                    sslEnabled = true;
                    break;
            }
        }
        properties.put("mail.smtp.ssl.enable", "" + sslEnabled);
        properties.put("mail.smtp.starttls.enable", "" + starttlsEnable);
        properties.put("mail.smtp.starttls.required", "" + starttlsRequired);
        if (Boolean.TRUE.equals(mailConfigurationType.isDebug())) {
            properties.put("mail.debug", "true");
        }
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Using mail properties: ");
            for (Object key : properties.keySet()) {
                if (key instanceof String && ((String) key).startsWith("mail.")) {
                    LOGGER.debug(" - " + key + " = " + properties.get(key));
                }
            }
        }
        task.recordState("Sending notification mail via " + host);
        Session session = Session.getInstance(properties);
        try {
            MimeMessage mimeMessage = new MimeMessage(session);
            String from = mailMessage.getFrom() != null ? mailMessage.getFrom() : defaultFrom;
            mimeMessage.setFrom(new InternetAddress(from));
            for (String recipient : mailMessage.getTo()) {
                mimeMessage.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(recipient));
            }
            for (String recipientCc : mailMessage.getCc()) {
                mimeMessage.addRecipient(javax.mail.Message.RecipientType.CC, new InternetAddress(recipientCc));
            }
            for (String recipientBcc : mailMessage.getBcc()) {
                mimeMessage.addRecipient(javax.mail.Message.RecipientType.BCC, new InternetAddress(recipientBcc));
            }
            mimeMessage.setSubject(mailMessage.getSubject(), "utf-8");
            String contentType = mailMessage.getContentType();
            if (StringUtils.isEmpty(contentType)) {
                contentType = "text/plain; charset=UTF-8";
            }
            mimeMessage.setContent(mailMessage.getBody(), contentType);
            javax.mail.Transport t = session.getTransport("smtp");
            if (StringUtils.isNotEmpty(mailServerConfigurationType.getUsername())) {
                ProtectedStringType passwordProtected = mailServerConfigurationType.getPassword();
                String password = null;
                if (passwordProtected != null) {
                    try {
                        password = protector.decryptString(passwordProtected);
                    } catch (EncryptionException e) {
                        String msg = "Couldn't send mail message to " + mailMessage.getTo() + " via " + host + ", because the plaintext password value couldn't be obtained. Trying another mail server, if there is any.";
                        LoggingUtils.logException(LOGGER, msg, e);
                        resultForServer.recordFatalError(msg, e);
                        continue;
                    }
                }
                t.connect(mailServerConfigurationType.getUsername(), password);
            } else {
                t.connect();
            }
            t.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
            LOGGER.info("Message sent successfully to " + mailMessage.getTo() + " via server " + host + ".");
            resultForServer.recordSuccess();
            result.recordSuccess();
            long duration = System.currentTimeMillis() - start;
            task.recordState("Notification mail sent successfully via " + host + ", in " + duration + " ms overall.");
            task.recordNotificationOperation(NAME, true, duration);
            return;
        } catch (MessagingException e) {
            String msg = "Couldn't send mail message to " + mailMessage.getTo() + " via " + host + ", trying another mail server, if there is any";
            LoggingUtils.logException(LOGGER, msg, e);
            resultForServer.recordFatalError(msg, e);
            task.recordState("Error sending notification mail via " + host);
        }
    }
    LOGGER.warn("No more mail servers to try, mail notification to " + mailMessage.getTo() + " will not be sent.");
    result.recordWarning("Mail notification to " + mailMessage.getTo() + " could not be sent.");
    task.recordNotificationOperation(NAME, false, System.currentTimeMillis() - start);
}
Also used : InternetAddress(javax.mail.internet.InternetAddress) MessagingException(javax.mail.MessagingException) MailConfigurationType(com.evolveum.midpoint.xml.ns._public.common.common_3.MailConfigurationType) MailServerConfigurationType(com.evolveum.midpoint.xml.ns._public.common.common_3.MailServerConfigurationType) OperationResult(com.evolveum.midpoint.schema.result.OperationResult) IOException(java.io.IOException) Properties(java.util.Properties) MailTransportSecurityType(com.evolveum.midpoint.xml.ns._public.common.common_3.MailTransportSecurityType) MimeMessage(javax.mail.internet.MimeMessage) EncryptionException(com.evolveum.midpoint.prism.crypto.EncryptionException) SystemConfigurationType(com.evolveum.midpoint.xml.ns._public.common.common_3.SystemConfigurationType) ProtectedStringType(com.evolveum.prism.xml.ns._public.types_3.ProtectedStringType) Session(javax.mail.Session)

Aggregations

EncryptionException (com.evolveum.midpoint.prism.crypto.EncryptionException)20 OperationResult (com.evolveum.midpoint.schema.result.OperationResult)7 ProtectedStringType (com.evolveum.prism.xml.ns._public.types_3.ProtectedStringType)6 Protector (com.evolveum.midpoint.prism.crypto.Protector)5 SchemaException (com.evolveum.midpoint.util.exception.SchemaException)5 ArrayList (java.util.ArrayList)5 ObjectAlreadyExistsException (com.evolveum.midpoint.util.exception.ObjectAlreadyExistsException)4 SystemException (com.evolveum.midpoint.util.exception.SystemException)3 SecurityQuestionAnswerDTO (com.evolveum.midpoint.web.page.admin.home.dto.SecurityQuestionAnswerDTO)3 List (java.util.List)3 AuthenticationServiceException (org.springframework.security.authentication.AuthenticationServiceException)3 PrismObject (com.evolveum.midpoint.prism.PrismObject)2 PolyString (com.evolveum.midpoint.prism.polystring.PolyString)2 ObjectNotFoundException (com.evolveum.midpoint.util.exception.ObjectNotFoundException)2 MailConfigurationType (com.evolveum.midpoint.xml.ns._public.common.common_3.MailConfigurationType)2 MailServerConfigurationType (com.evolveum.midpoint.xml.ns._public.common.common_3.MailServerConfigurationType)2 SecurityQuestionAnswerType (com.evolveum.midpoint.xml.ns._public.common.common_3.SecurityQuestionAnswerType)2 SystemConfigurationType (com.evolveum.midpoint.xml.ns._public.common.common_3.SystemConfigurationType)2 UserType (com.evolveum.midpoint.xml.ns._public.common.common_3.UserType)2 GuardedString (org.identityconnectors.common.security.GuardedString)2