org.subethamail.smtp.AuthenticationHandlerFactory Java Examples

The following examples show how to use org.subethamail.smtp.AuthenticationHandlerFactory. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SmtpServerConfiguratorTest.java    From fake-smtp-server with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldConfigureAuthenticationWhenAuthenticationIsConfiguredProperly(){
    var username = "username";
    var password = "password";
    var authentication = mock(FakeSmtpConfigurationProperties.Authentication.class);
    when(authentication.getUsername()).thenReturn(username);
    when(authentication.getPassword()).thenReturn(password);
    when(fakeSmtpConfigurationProperties.getAuthentication()).thenReturn(authentication);

    var smtpServer = mock(SMTPServer.class);

    sut.configure(smtpServer);

    var argumentCaptor = ArgumentCaptor.forClass(AuthenticationHandlerFactory.class);
    verify(smtpServer).setAuthenticationHandlerFactory(argumentCaptor.capture());

    var authenticationHandlerFactory = argumentCaptor.getValue();
    assertNotNull(authenticationHandlerFactory);
    assertThat(authenticationHandlerFactory, instanceOf(EasyAuthenticationHandlerFactory.class));

    var easyAuthenticationHandlerFactory = (EasyAuthenticationHandlerFactory)authenticationHandlerFactory;
    assertSame(basicUsernamePasswordValidator, easyAuthenticationHandlerFactory.getValidator());
}
 
Example #2
Source File: SMTPServer.java    From subethasmtp with Apache License 2.0 6 votes vote down vote up
/**
 * Complex constructor.
 * 
 * @param authHandlerFact
 *            the {@link AuthenticationHandlerFactory} which performs
 *            authentication in the SMTP AUTH command. If null,
 *            authentication is not supported. Note that setting an
 *            authentication handler does not enforce authentication, it
 *            only makes authentication possible. Enforcing authentication
 *            is the responsibility of the client application, which usually
 *            enforces it only selectively. Use
 *            {@link Session#isAuthenticated} to check whether the client
 *            was authenticated in the session.
 * @param executorService
 *            the ExecutorService which will handle client connections, one
 *            task per connection. The SMTPServer will shut down this
 *            ExecutorService when the SMTPServer itself stops. If null, a
 *            default one is created by
 *            {@link Executors#newCachedThreadPool()}.
 */
public SMTPServer(MessageHandlerFactory msgHandlerFact, AuthenticationHandlerFactory authHandlerFact, ExecutorService executorService)
{
	this.messageHandlerFactory = msgHandlerFact;
	this.authenticationHandlerFactory = authHandlerFact;

	if (executorService != null) {
		this.executorService = executorService;
	} else {
		this.executorService = Executors.newCachedThreadPool();
	}

	try
	{
		this.hostName = InetAddress.getLocalHost().getCanonicalHostName();
	}
	catch (UnknownHostException e)
	{
		this.hostName = UNKNOWN_HOSTNAME;
	}

	this.commandHandler = new CommandHandler();
}
 
Example #3
Source File: SubethaEmailServer.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public void startup()
{
    serverImpl = new SMTPServer(new HandlerFactory());
    
    // MER - May need to override SMTPServer.createSSLSocket to specify non default keystore.
    serverImpl.setPort(getPort());
    serverImpl.setHostName(getDomain());
    serverImpl.setMaxConnections(getMaxConnections());
    
    serverImpl.setHideTLS(isHideTLS());
    serverImpl.setEnableTLS(isEnableTLS());
    serverImpl.setRequireTLS(isRequireTLS());
    
    if(isAuthenticate())
    {
        AuthenticationHandlerFactory authenticationHandler = new EasyAuthenticationHandlerFactory(new AlfrescoLoginUsernamePasswordValidator());
        serverImpl.setAuthenticationHandlerFactory(authenticationHandler);
    }
    
    serverImpl.start();
    log.info("Inbound SMTP Email Server has started successfully, on hostName:" + getDomain() + "port:" + getPort());
}
 
Example #4
Source File: MultipleAuthenticationHandlerFactory.java    From subethasmtp with Apache License 2.0 5 votes vote down vote up
/** */
public void addFactory(AuthenticationHandlerFactory fact)
{
	List<String> partialMechanisms = fact.getAuthenticationMechanisms();
	for (String mechanism: partialMechanisms)
	{
		if (!this.mechanisms.contains(mechanism))
		{
			this.mechanisms.add(mechanism);
			this.plugins.put(mechanism, fact);
		}
	}
}
 
Example #5
Source File: TestUtils.java    From digdag with Apache License 2.0 5 votes vote down vote up
public static Wiser startMailServer(String hostname, AuthenticationHandlerFactory authenticationHandlerFactory)
{
    Wiser server = new Wiser();
    server.getServer().setAuthenticationHandlerFactory(authenticationHandlerFactory);
    server.setHostname(hostname);
    server.setPort(0);
    server.start();
    return server;
}
 
Example #6
Source File: MultipleAuthenticationHandlerFactory.java    From subethasmtp with Apache License 2.0 5 votes vote down vote up
/** */
public MultipleAuthenticationHandlerFactory(Collection<AuthenticationHandlerFactory> factories)
{
	for (AuthenticationHandlerFactory fact: factories)
	{
		this.addFactory(fact);
	}
}
 
Example #7
Source File: SMTPTestWiser.java    From vertx-mail-client with Apache License 2.0 5 votes vote down vote up
protected void startSMTP(String factory) {
  wiser = new Wiser();

  wiser.setPort(1587);
  wiser.getServer().setAuthenticationHandlerFactory(new AuthenticationHandlerFactory() {
    /*
     * AUTH PLAIN handler which returns success on any string
     */
    @Override
    public List<String> getAuthenticationMechanisms() {
      return Arrays.asList("PLAIN");
    }

    @Override
    public AuthenticationHandler create() {
      return new AuthenticationHandler() {

        @Override
        public String auth(final String clientInput) throws RejectException {
          log.info(clientInput);
          return null;
        }

        @Override
        public Object getIdentity() {
          return "username";
        }
      };
    }
  });

  Security.setProperty("ssl.SocketFactory.provider", factory);
  wiser.getServer().setEnableTLS(true);

  wiser.start();
}
 
Example #8
Source File: SmtpServerConfiguratorTest.java    From fake-smtp-server with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldSkipConfigurationOfAuthenticationWhenPasswordIsEmptyString(){
    var username = "username";
    var authentication = mock(FakeSmtpConfigurationProperties.Authentication.class);
    when(authentication.getUsername()).thenReturn(username);
    when(authentication.getPassword()).thenReturn("");
    when(fakeSmtpConfigurationProperties.getAuthentication()).thenReturn(authentication);

    var smtpServer = mock(SMTPServer.class);

    sut.configure(smtpServer);

    verify(smtpServer, never()).setAuthenticationHandlerFactory(any(AuthenticationHandlerFactory.class));
    verify(logger).error(startsWith("Password"));
}
 
Example #9
Source File: SmtpServerConfiguratorTest.java    From fake-smtp-server with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldSkipConfigurationOfAuthenticationWhenPasswordIsNull(){
    var username = "username";
    var authentication = mock(FakeSmtpConfigurationProperties.Authentication.class);
    when(authentication.getUsername()).thenReturn(username);
    when(authentication.getPassword()).thenReturn(null);
    when(fakeSmtpConfigurationProperties.getAuthentication()).thenReturn(authentication);

    var smtpServer = mock(SMTPServer.class);

    sut.configure(smtpServer);

    verify(smtpServer, never()).setAuthenticationHandlerFactory(any(AuthenticationHandlerFactory.class));
    verify(logger).error(startsWith("Password"));
}
 
Example #10
Source File: SmtpServerConfiguratorTest.java    From fake-smtp-server with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldSkipConfigurationOfAuthenticationWhenUsernameIsEmptyString(){
    var authentication = mock(FakeSmtpConfigurationProperties.Authentication.class);
    when(authentication.getUsername()).thenReturn("");
    when(fakeSmtpConfigurationProperties.getAuthentication()).thenReturn(authentication);

    var smtpServer = mock(SMTPServer.class);

    sut.configure(smtpServer);

    verify(smtpServer, never()).setAuthenticationHandlerFactory(any(AuthenticationHandlerFactory.class));
    verify(logger).error(startsWith("Username"));
}
 
Example #11
Source File: SmtpServerConfiguratorTest.java    From fake-smtp-server with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldSkipConfigurationOfAuthenticationWhenUsernameIsNull(){
    var authentication = mock(FakeSmtpConfigurationProperties.Authentication.class);
    when(authentication.getUsername()).thenReturn(null);
    when(fakeSmtpConfigurationProperties.getAuthentication()).thenReturn(authentication);

    var smtpServer = mock(SMTPServer.class);

    sut.configure(smtpServer);

    verify(smtpServer, never()).setAuthenticationHandlerFactory(any(AuthenticationHandlerFactory.class));
    verify(logger).error(startsWith("Username"));
}
 
Example #12
Source File: SmtpServerConfiguratorTest.java    From fake-smtp-server with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldConfigureBasicParameters(){
    var port = 1234;
    var bindingAddress = mock(InetAddress.class);
    when(fakeSmtpConfigurationProperties.getPort()).thenReturn(port);
    when(fakeSmtpConfigurationProperties.getBindAddress()).thenReturn(bindingAddress);

    var smtpServer = mock(SMTPServer.class);

    sut.configure(smtpServer);

    verify(smtpServer).setPort(port);
    verify(smtpServer).setBindAddress(bindingAddress);
    verify(smtpServer, never()).setAuthenticationHandlerFactory(any(AuthenticationHandlerFactory.class));
}
 
Example #13
Source File: SMTPServer.java    From subethasmtp with Apache License 2.0 4 votes vote down vote up
/**
 * Constructor with {@link AuthenticationHandlerFactory}.
 */
public SMTPServer(MessageHandlerFactory handlerFactory, AuthenticationHandlerFactory authHandlerFact)
{
    this(handlerFactory, authHandlerFact, null);
}
 
Example #14
Source File: SMTPServer.java    From subethasmtp with Apache License 2.0 4 votes vote down vote up
/**
 * @return the factory for auth handlers, or null if no such factory has been set.
 */
public AuthenticationHandlerFactory getAuthenticationHandlerFactory()
{
	return this.authenticationHandlerFactory;
}
 
Example #15
Source File: SMTPServer.java    From subethasmtp with Apache License 2.0 4 votes vote down vote up
/** */
public void setAuthenticationHandlerFactory(AuthenticationHandlerFactory fact)
{
	this.authenticationHandlerFactory = fact;
}
 
Example #16
Source File: EhloCommand.java    From subethasmtp with Apache License 2.0 4 votes vote down vote up
/** */
	@Override
	public void execute(String commandString, Session sess) throws IOException
	{
		String[] args = this.getArgs(commandString);
		if (args.length < 2)
		{
			sess.sendResponse("501 Syntax: EHLO hostname");
			return;
		}

		sess.resetMailTransaction();
		sess.setHelo(args[1]);

//		postfix returns...
//		250-server.host.name
//		250-PIPELINING
//		250-SIZE 10240000
//		250-ETRN
//		250 8BITMIME

		// Once upon a time this code tracked whether or not HELO/EHLO has been seen
		// already and gave an error msg.  However, this is stupid and pointless.
		// Postfix doesn't care, so we won't either.  If you want more, read:
		// http://homepages.tesco.net/J.deBoynePollard/FGA/smtp-avoid-helo.html

		StringBuilder response = new StringBuilder();

		response.append("250-");
		response.append(sess.getServer().getHostName());
		response.append("\r\n" + "250-8BITMIME");

		int maxSize = sess.getServer().getMaxMessageSize();
		if (maxSize > 0)
		{
			response.append("\r\n" + "250-SIZE ");
			response.append(maxSize);
		}

		// Enabling / Hiding TLS is a server setting
		if (sess.getServer().getEnableTLS() && !sess.getServer().getHideTLS())
		{
			response.append("\r\n" + "250-STARTTLS");
		}

		// Check to see if we support authentication
		AuthenticationHandlerFactory authFact = sess.getServer().getAuthenticationHandlerFactory();
		if (authFact != null)
		{
			List<String> supportedMechanisms = authFact.getAuthenticationMechanisms();
			if (!supportedMechanisms.isEmpty())
			{
				response.append("\r\n" + "250-" + AuthCommand.VERB + " ");
				response.append(TextUtils.joinTogether(supportedMechanisms, " "));
			}
		}

		response.append("\r\n" + "250 Ok");

		sess.sendResponse(response.toString());
	}
 
Example #17
Source File: AuthCommand.java    From subethasmtp with Apache License 2.0 4 votes vote down vote up
/** */
@Override
public void execute(String commandString, Session sess)
		throws IOException
{
	if (sess.isAuthenticated())
	{
		sess.sendResponse("503 Refusing any other AUTH command.");
		return;
	}

	AuthenticationHandlerFactory authFactory = sess.getServer().getAuthenticationHandlerFactory();

	if (authFactory == null)
	{
		sess.sendResponse("502 Authentication not supported");
		return;
	}

	AuthenticationHandler authHandler = authFactory.create();

	String[] args = this.getArgs(commandString);
	// Let's check the command syntax
	if (args.length < 2)
	{
		sess.sendResponse("501 Syntax: " + VERB + " mechanism [initial-response]");
		return;
	}

	// Let's check if we support the required authentication mechanism
	String mechanism = args[1];
	if (!authFactory.getAuthenticationMechanisms().contains(mechanism.toUpperCase(Locale.ENGLISH)))
	{
		sess.sendResponse("504 The requested authentication mechanism is not supported");
		return;
	}
	// OK, let's go trough the authentication process.
	try
	{
		// The authentication process may require a series of challenge-responses
		CRLFTerminatedReader reader = sess.getReader();

		String response = authHandler.auth(commandString);
		if (response != null)
		{
			// challenge-response iteration
			sess.sendResponse(response);
		}

		while (response != null)
		{
			String clientInput = reader.readLine();
			if (clientInput.trim().equals(AUTH_CANCEL_COMMAND))
			{
				// RFC 2554 explicitly states this:
				sess.sendResponse("501 Authentication canceled by client.");
				return;
			}
			else
			{
				response = authHandler.auth(clientInput);
				if (response != null)
				{
					// challenge-response iteration
					sess.sendResponse(response);
				}
			}
		}

		sess.sendResponse("235 Authentication successful.");
		sess.setAuthenticationHandler(authHandler);
	}
	catch (RejectException authFailed)
	{
		sess.sendResponse(authFailed.getErrorResponse());
	}
}
 
Example #18
Source File: TestUtils.java    From digdag with Apache License 2.0 4 votes vote down vote up
public static Wiser startMailServer(String hostname, String user, String password)
{
    AuthenticationHandlerFactory authenticationHandlerFactory = new AuthenticationHandlerFactory()
    {
        @Override
        public List<String> getAuthenticationMechanisms()
        {
            return ImmutableList.of("PLAIN");
        }

        @Override
        public AuthenticationHandler create()
        {
            return new AuthenticationHandler()
            {

                private String identity;

                @Override
                public String auth(String clientInput)
                        throws RejectException
                {
                    String prefix = "AUTH PLAIN ";
                    if (!clientInput.startsWith(prefix)) {
                        throw new RejectException();
                    }
                    String credentialsBase64 = clientInput.substring(prefix.length());
                    byte[] credentials = Base64.getDecoder().decode(credentialsBase64);

                    // [authzid] UTF8NUL authcid UTF8NUL passwd
                    byte[] expectedCredentials = concat(
                            user.getBytes(UTF_8),
                            new byte[] {0},
                            user.getBytes(UTF_8),
                            new byte[] {0},
                            password.getBytes(UTF_8)
                    );

                    if (!Arrays.equals(credentials, expectedCredentials)) {
                        throw new RejectException();
                    }

                    this.identity = user;
                    return null;
                }

                @Override
                public Object getIdentity()
                {
                    return identity;
                }
            };
        }
    };
    return startMailServer(hostname, authenticationHandlerFactory);
}