Search in sources :

Example 91 with ProtectedStringType

use of com.evolveum.prism.xml.ns._public.types_3.ProtectedStringType in project midpoint by Evolveum.

the class ImportTest method test040ImportUserHermanNoEncryption.

@Test
public void test040ImportUserHermanNoEncryption() throws Exception {
    final String TEST_NAME = "test040ImportUserHermanNoEncryption";
    TestUtil.displayTestTile(this, TEST_NAME);
    // GIVEN
    InternalsConfig.readEncryptionChecks = false;
    Task task = taskManager.createTaskInstance();
    OperationResult result = new OperationResult(ImportTest.class.getName() + "." + TEST_NAME);
    FileInputStream stream = new FileInputStream(USER_HERMAN_FILE);
    ImportOptionsType importOptions = getDefaultImportOptions();
    importOptions.setEncryptProtectedValues(false);
    dummyAuditService.clear();
    // WHEN
    modelService.importObjectsFromStream(stream, importOptions, task, result);
    // THEN
    result.computeStatus();
    display("Result after good import", result);
    TestUtil.assertSuccess("Import has failed (result)", result);
    // Check import with fixed OID
    PrismObject<UserType> userHerman = getUser(USER_HERMAN_OID);
    display("Herman", userHerman);
    assertUser(userHerman, USER_HERMAN_OID, USER_HERMAN_USERNAME, "Herman Toothrot", "Herman", "Toothrot");
    // Check if the password was NOT encrypted
    ProtectedStringType protectedString = userHerman.asObjectable().getCredentials().getPassword().getValue();
    assertEquals("Er? Pirate sectrets still hidden?", "m0nk3y", protectedString.getClearValue());
    assertNull("Er? Encrypted data together with clear value?", protectedString.getEncryptedDataType());
    assertUsers(6);
    // Check audit
    display("Audit", dummyAuditService);
    dummyAuditService.assertRecords(2);
    dummyAuditService.assertSimpleRecordSanity();
    dummyAuditService.assertAnyRequestDeltas();
    dummyAuditService.assertExecutionDeltas(1);
    dummyAuditService.assertHasDelta(ChangeType.ADD, UserType.class);
    dummyAuditService.assertExecutionSuccess();
}
Also used : Task(com.evolveum.midpoint.task.api.Task) ImportOptionsType(com.evolveum.midpoint.xml.ns._public.common.api_types_3.ImportOptionsType) OperationResult(com.evolveum.midpoint.schema.result.OperationResult) ProtectedStringType(com.evolveum.prism.xml.ns._public.types_3.ProtectedStringType) FileInputStream(java.io.FileInputStream) Test(org.testng.annotations.Test) AbstractConfiguredModelIntegrationTest(com.evolveum.midpoint.model.intest.AbstractConfiguredModelIntegrationTest)

Example 92 with ProtectedStringType

use of com.evolveum.prism.xml.ns._public.types_3.ProtectedStringType in project midpoint by Evolveum.

the class TestScriptingBasic method checkPassword.

@SuppressWarnings("unchecked")
private void checkPassword(PipelineItem item, String userOid) throws CommunicationException, ObjectNotFoundException, SchemaException, SecurityViolationException, ConfigurationException, ExpressionEvaluationException, EncryptionException {
    PrismProperty<ProtectedStringType> returnedPassword = (PrismProperty<ProtectedStringType>) item.getValue().find(SchemaConstants.PATH_PASSWORD_VALUE);
    ProtectedStringType returnedRealValue = returnedPassword.getRealValue();
    PrismObject<UserType> user = getUser(userOid);
    ProtectedStringType repoRealValue = user.asObjectable().getCredentials().getPassword().getValue();
    String returnedClearValue = protector.decryptString(returnedRealValue);
    String repoClearValue = protector.decryptString(repoRealValue);
    System.out.println("Returned password = " + returnedClearValue + ", repo password = " + repoClearValue);
    assertEquals("Wrong password stored in repository", returnedClearValue, repoClearValue);
}
Also used : ProtectedStringType(com.evolveum.prism.xml.ns._public.types_3.ProtectedStringType)

Example 93 with ProtectedStringType

use of com.evolveum.prism.xml.ns._public.types_3.ProtectedStringType 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)

Example 94 with ProtectedStringType

use of com.evolveum.prism.xml.ns._public.types_3.ProtectedStringType in project midpoint by Evolveum.

the class TestUserChangeApprovalLegacy method test040UserModifyPasswordChangeBlocked.

@Test(enabled = true)
public void test040UserModifyPasswordChangeBlocked() throws Exception {
    TestUtil.displayTestTile(this, "test040UserModifyPasswordChangeBlocked");
    login(userAdministrator);
    PrismObject<UserType> jack = getUser(USER_JACK_OID);
    final ProtectedStringType originalPasswordValue = jack.asObjectable().getCredentials().getPassword().getValue();
    LOGGER.trace("password before test = " + originalPasswordValue);
    executeTest("test040UserModifyPasswordChangeBlocked", USER_JACK_OID, new TestDetails() {

        @Override
        int subtaskCount() {
            return 1;
        }

        @Override
        boolean immediate() {
            return false;
        }

        @Override
        boolean checkObjectOnSubtasks() {
            return true;
        }

        @Override
        public LensContext createModelContext(Task task, OperationResult result) throws Exception {
            LensContext<UserType> context = createUserLensContext();
            fillContextWithUser(context, USER_JACK_OID, result);
            encryptAndAddFocusModificationToContext(context, REQ_USER_JACK_MODIFY_CHANGE_PASSWORD);
            //context.setOptions(ModelExecuteOptions.createNoCrypt());
            return context;
        }

        @Override
        public void assertsAfterClockworkRun(Task rootTask, List<Task> wfSubtasks, OperationResult result) throws Exception {
            ModelContext taskModelContext = wfTaskUtil.getModelContext(rootTask, result);
            assertEquals("There are modifications left in primary focus delta", 0, taskModelContext.getFocusContext().getPrimaryDelta().getModifications().size());
        }

        @Override
        void assertsRootTaskFinishes(Task task, List<Task> subtasks, OperationResult result) throws Exception {
            PrismObject<UserType> jack = getUser(USER_JACK_OID);
            ProtectedStringType afterTestPasswordValue = jack.asObjectable().getCredentials().getPassword().getValue();
            LOGGER.trace("password after test = " + afterTestPasswordValue);
            //assertNotNull("password was not set", afterTestPasswordValue.getEncryptedData());
            assertTrue("password was changed", originalPasswordValue.getEncryptedDataType().equals(afterTestPasswordValue.getEncryptedDataType()));
            checkDummyTransportMessages("simpleUserNotifier", 0);
        // we don't check for modifyApproverRef because in this test the value was not changed (no change was executed)
        }

        @Override
        boolean decideOnApproval(String executionId) throws Exception {
            login(getUser(USER_ADMINISTRATOR_OID));
            return false;
        }
    });
}
Also used : Task(com.evolveum.midpoint.task.api.Task) OperationResult(com.evolveum.midpoint.schema.result.OperationResult) PolyString(com.evolveum.midpoint.prism.polystring.PolyString) LensContext(com.evolveum.midpoint.model.impl.lens.LensContext) JAXBException(javax.xml.bind.JAXBException) ModelContext(com.evolveum.midpoint.model.api.context.ModelContext) ProtectedStringType(com.evolveum.prism.xml.ns._public.types_3.ProtectedStringType) Test(org.testng.annotations.Test)

Example 95 with ProtectedStringType

use of com.evolveum.prism.xml.ns._public.types_3.ProtectedStringType in project midpoint by Evolveum.

the class TestDBTable method test005GetAccount.

// MID-1234
@Test(enabled = false)
public void test005GetAccount() throws Exception {
    final String TEST_NAME = "test005GetAccount";
    TestUtil.displayTestTile(TEST_NAME);
    // GIVEN
    OperationResult result = new OperationResult(TestDBTable.class.getName() + "." + TEST_NAME);
    Task task = taskManager.createTaskInstance();
    // WHEN
    PrismObject<ShadowType> account = provisioningService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, task, result);
    // THEN
    result.computeStatus();
    display(result);
    TestUtil.assertSuccess(result);
    PrismAsserts.assertEqualsPolyString("Name not equal.", ACCOUNT_WILL_USERNAME, account.asObjectable().getName());
    assertNotNull("No credentials", account.asObjectable().getCredentials());
    assertNotNull("No password", account.asObjectable().getCredentials().getPassword());
    assertNotNull("No password value", account.asObjectable().getCredentials().getPassword().getValue());
    ProtectedStringType password = account.asObjectable().getCredentials().getPassword().getValue();
    display("Password", password);
    String clearPassword = protector.decryptString(password);
    assertEquals("Wrong password", ACCOUNT_WILL_PASSWORD, clearPassword);
}
Also used : Task(com.evolveum.midpoint.task.api.Task) ShadowType(com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType) OperationResult(com.evolveum.midpoint.schema.result.OperationResult) ProtectedStringType(com.evolveum.prism.xml.ns._public.types_3.ProtectedStringType) AbstractIntegrationTest(com.evolveum.midpoint.test.AbstractIntegrationTest) Test(org.testng.annotations.Test)

Aggregations

ProtectedStringType (com.evolveum.prism.xml.ns._public.types_3.ProtectedStringType)120 OperationResult (com.evolveum.midpoint.schema.result.OperationResult)48 Test (org.testng.annotations.Test)48 Task (com.evolveum.midpoint.task.api.Task)39 UserType (com.evolveum.midpoint.xml.ns._public.common.common_3.UserType)25 ItemPath (com.evolveum.midpoint.prism.path.ItemPath)24 QName (javax.xml.namespace.QName)20 PolyString (com.evolveum.midpoint.prism.polystring.PolyString)18 PasswordType (com.evolveum.midpoint.xml.ns._public.common.common_3.PasswordType)18 CredentialsType (com.evolveum.midpoint.xml.ns._public.common.common_3.CredentialsType)15 SchemaException (com.evolveum.midpoint.util.exception.SchemaException)13 ObjectDelta (com.evolveum.midpoint.prism.delta.ObjectDelta)11 ShadowType (com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType)10 AbstractInitializedModelIntegrationTest (com.evolveum.midpoint.model.intest.AbstractInitializedModelIntegrationTest)9 AbstractModelIntegrationTest (com.evolveum.midpoint.model.test.AbstractModelIntegrationTest)9 EncryptionException (com.evolveum.midpoint.prism.crypto.EncryptionException)9 MapXNode (com.evolveum.midpoint.prism.xnode.MapXNode)9 Document (org.w3c.dom.Document)8 ArrayList (java.util.ArrayList)7 Entry (org.apache.directory.api.ldap.model.entry.Entry)7