Search in sources :

Example 1 with NtlmPasswordAuthentication

use of jcifs.smb.NtlmPasswordAuthentication in project iaf by ibissource.

the class SambaFileSystemTestHelper method setUp.

@Override
public void setUp() throws ConfigurationException, IOException, FileSystemException {
    NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication(domain, username, password);
    context = new SmbFile(share, auth);
}
Also used : NtlmPasswordAuthentication(jcifs.smb.NtlmPasswordAuthentication) SmbFile(jcifs.smb.SmbFile)

Example 2 with NtlmPasswordAuthentication

use of jcifs.smb.NtlmPasswordAuthentication in project iaf by ibissource.

the class Samba1FileSystem method configure.

@Override
public void configure() throws ConfigurationException {
    if (getShare() == null)
        throw new ConfigurationException("server share endpoint is required");
    if (!getShare().startsWith("smb://"))
        throw new ConfigurationException("attribute share must begin with [smb://]");
    // Setup credentials if applied, may be null.
    // NOTE: When using NtmlPasswordAuthentication without username it returns GUEST
    CredentialFactory cf = new CredentialFactory(getAuthAlias(), getUsername(), getPassword());
    if (StringUtils.isNotEmpty(cf.getUsername())) {
        auth = new NtlmPasswordAuthentication(getDomain(), cf.getUsername(), cf.getPassword());
        log.debug("setting authentication to [" + auth.toString() + "]");
    }
}
Also used : ConfigurationException(nl.nn.adapterframework.configuration.ConfigurationException) CredentialFactory(nl.nn.adapterframework.util.CredentialFactory) NtlmPasswordAuthentication(jcifs.smb.NtlmPasswordAuthentication)

Example 3 with NtlmPasswordAuthentication

use of jcifs.smb.NtlmPasswordAuthentication in project cas by apereo.

the class NtlmAuthenticationHandler method doAuthentication.

@Override
protected AuthenticationHandlerExecutionResult doAuthentication(final Credential credential) throws GeneralSecurityException {
    val ntlmCredential = (SpnegoCredential) credential;
    val src = ntlmCredential.getInitToken();
    var success = false;
    try {
        val dc = getUniAddress();
        val challenge = SmbSession.getChallenge(dc);
        switch(src[NTLM_TOKEN_TYPE_FIELD_INDEX]) {
            case NTLM_TOKEN_TYPE_ONE:
                LOGGER.debug("Type 1 received");
                val type1 = new Type1Message(src);
                val type2 = new Type2Message(type1, challenge, null);
                LOGGER.debug("Type 2 returned. Setting next token.");
                ntlmCredential.setNextToken(type2.toByteArray());
                break;
            case NTLM_TOKEN_TYPE_THREE:
                LOGGER.debug("Type 3 received");
                val type3 = new Type3Message(src);
                val lmResponse = type3.getLMResponse() == null ? ArrayUtils.EMPTY_BYTE_ARRAY : type3.getLMResponse();
                val ntResponse = type3.getNTResponse() == null ? ArrayUtils.EMPTY_BYTE_ARRAY : type3.getNTResponse();
                val ntlm = new NtlmPasswordAuthentication(type3.getDomain(), type3.getUser(), challenge, lmResponse, ntResponse);
                LOGGER.debug("Trying to authenticate [{}] with domain controller", type3.getUser());
                try {
                    SmbSession.logon(dc, ntlm);
                    ntlmCredential.setPrincipal(this.principalFactory.createPrincipal(type3.getUser()));
                    success = true;
                } catch (final SmbAuthException sae) {
                    throw new FailedLoginException(sae.getMessage());
                }
                break;
            default:
                LOGGER.debug("Unknown type: [{}]", src[NTLM_TOKEN_TYPE_FIELD_INDEX]);
        }
    } catch (final Exception e) {
        throw new FailedLoginException(e.getMessage());
    }
    if (!success) {
        throw new FailedLoginException();
    }
    return new DefaultAuthenticationHandlerExecutionResult(this, new BasicCredentialMetaData(ntlmCredential), ntlmCredential.getPrincipal());
}
Also used : lombok.val(lombok.val) Type1Message(jcifs.ntlmssp.Type1Message) SpnegoCredential(org.apereo.cas.support.spnego.authentication.principal.SpnegoCredential) SmbAuthException(jcifs.smb.SmbAuthException) FailedLoginException(javax.security.auth.login.FailedLoginException) NtlmPasswordAuthentication(jcifs.smb.NtlmPasswordAuthentication) Type2Message(jcifs.ntlmssp.Type2Message) Type3Message(jcifs.ntlmssp.Type3Message) DefaultAuthenticationHandlerExecutionResult(org.apereo.cas.authentication.DefaultAuthenticationHandlerExecutionResult) GeneralSecurityException(java.security.GeneralSecurityException) FailedLoginException(javax.security.auth.login.FailedLoginException) SmbAuthException(jcifs.smb.SmbAuthException) BasicCredentialMetaData(org.apereo.cas.authentication.metadata.BasicCredentialMetaData)

Example 4 with NtlmPasswordAuthentication

use of jcifs.smb.NtlmPasswordAuthentication in project opennms by OpenNMS.

the class JCifsMonitor method poll.

/**
 * This method queries the CIFS share.
 *
 * @param svc        the monitored service
 * @param parameters the parameter map
 * @return the poll status for this system
 */
@Override
public PollStatus poll(MonitoredService svc, Map<String, Object> parameters) {
    final String domain = parameters.containsKey("domain") ? (String) parameters.get("domain") : "";
    final String username = parameters.containsKey("username") ? (String) parameters.get("username") : "";
    final String password = parameters.containsKey("password") ? (String) parameters.get("password") : "";
    String mode = parameters.containsKey("mode") ? ((String) parameters.get("mode")).toUpperCase() : "PATH_EXIST";
    String path = parameters.containsKey("path") ? (String) parameters.get("path") : "";
    String smbHost = parameters.containsKey("smbHost") ? (String) parameters.get("smbHost") : "";
    final String folderIgnoreFiles = parameters.containsKey("folderIgnoreFiles") ? (String) parameters.get("folderIgnoreFiles") : "";
    // changing to Ip address of MonitoredService if no smbHost is given
    if ("".equals(smbHost)) {
        smbHost = svc.getIpAddr();
    }
    // Filename filter to give user the possibility to ignore specific files in folder for the folder check.
    SmbFilenameFilter smbFilenameFilter = new SmbFilenameFilter() {

        @Override
        public boolean accept(SmbFile smbFile, String s) throws SmbException {
            return !s.matches(folderIgnoreFiles);
        }
    };
    // Initialize mode with default as PATH_EXIST
    Mode enumMode = Mode.PATH_EXIST;
    try {
        enumMode = Mode.valueOf(mode);
    } catch (IllegalArgumentException exception) {
        logger.error("Mode '{}‘ does not exists. Valid candidates are {}", mode, modeCandidates);
        return PollStatus.unknown("Mode " + mode + " does not exists. Valid candidates are " + modeCandidates);
    }
    // Checking path parameter
    if (!path.startsWith("/")) {
        path = "/" + path;
        logger.debug("Added leading / to path.");
    }
    // Build authentication string for NtlmPasswordAuthentication: syntax: domain;username:password
    String authString = "";
    // Setting up authenticationString...
    if (domain != null && !"".equals(domain)) {
        authString += domain + ";";
    }
    authString += username + ":" + password;
    // ... and path
    String fullUrl = "smb://" + smbHost + path;
    logger.debug("Domain: [{}], Username: [{}], Password: [{}], Mode: [{}], Path: [{}], Authentication: [{}], Full Url: [{}]", new Object[] { domain, username, password, mode, path, authString, fullUrl });
    // Initializing TimeoutTracker with default values
    TimeoutTracker tracker = new TimeoutTracker(parameters, DEFAULT_RETRY, DEFAULT_TIMEOUT);
    // Setting default PollStatus
    PollStatus serviceStatus = PollStatus.unknown();
    for (tracker.reset(); tracker.shouldRetry() && !serviceStatus.isAvailable(); tracker.nextAttempt()) {
        NtlmPasswordAuthentication ntlmPasswordAuthentication = new NtlmPasswordAuthentication(authString);
        try {
            // Creating SmbFile object
            SmbFile smbFile = new SmbFile(fullUrl, ntlmPasswordAuthentication);
            // Setting the defined timeout
            smbFile.setConnectTimeout(tracker.getConnectionTimeout());
            // Does the file exists?
            boolean smbFileExists = smbFile.exists();
            switch(enumMode) {
                case PATH_EXIST:
                    if (smbFileExists) {
                        serviceStatus = PollStatus.up();
                    } else {
                        serviceStatus = PollStatus.down("File " + fullUrl + " should exists but doesn't!");
                    }
                    break;
                case PATH_NOT_EXIST:
                    if (!smbFileExists) {
                        serviceStatus = PollStatus.up();
                    } else {
                        serviceStatus = PollStatus.down("File " + fullUrl + " should not exists but does!");
                    }
                    break;
                case FOLDER_EMPTY:
                    if (smbFileExists) {
                        if (smbFile.list(smbFilenameFilter).length == 0) {
                            serviceStatus = PollStatus.up();
                        } else {
                            serviceStatus = PollStatus.down("Directory " + fullUrl + " should be empty but isn't!");
                        }
                    } else {
                        serviceStatus = PollStatus.down("Directory " + fullUrl + " should exists but doesn't!");
                    }
                    break;
                case FOLDER_NOT_EMPTY:
                    if (smbFileExists) {
                        if (smbFile.list(smbFilenameFilter).length > 0) {
                            serviceStatus = PollStatus.up();
                        } else {
                            serviceStatus = PollStatus.down("Directory " + fullUrl + " should not be empty but is!");
                        }
                    } else {
                        serviceStatus = PollStatus.down("Directory " + fullUrl + " should exists but doesn't!");
                    }
                    break;
                default:
                    logger.warn("There is no implementation for the specified mode '{}'", mode);
                    break;
            }
        } catch (MalformedURLException exception) {
            logger.error("Malformed URL on '{}' with error: '{}'", smbHost, exception.getMessage());
            serviceStatus = PollStatus.down(exception.getMessage());
        } catch (SmbException exception) {
            logger.error("SMB error on '{}' with error: '{}'", smbHost, exception.getMessage());
            serviceStatus = PollStatus.down(exception.getMessage());
        }
    }
    return serviceStatus;
}
Also used : SmbException(jcifs.smb.SmbException) MalformedURLException(java.net.MalformedURLException) PollStatus(org.opennms.netmgt.poller.PollStatus) TimeoutTracker(org.opennms.core.utils.TimeoutTracker) NtlmPasswordAuthentication(jcifs.smb.NtlmPasswordAuthentication) SmbFilenameFilter(jcifs.smb.SmbFilenameFilter) SmbFile(jcifs.smb.SmbFile)

Example 5 with NtlmPasswordAuthentication

use of jcifs.smb.NtlmPasswordAuthentication in project iaf by ibissource.

the class SambaSenderOld method configure.

@Override
public void configure() throws ConfigurationException {
    super.configure();
    if (getShare() == null)
        throw new ConfigurationException(getLogPrefix() + "server share endpoint is required");
    if (!getShare().startsWith("smb://"))
        throw new ConfigurationException(getLogPrefix() + "url must begin with [smb://]");
    if (getAction() == null)
        throw new ConfigurationException(getLogPrefix() + "action must be specified");
    if (!actions.contains(getAction()))
        throw new ConfigurationException(getLogPrefix() + "unknown or invalid action [" + getAction() + "] supported actions are " + actions.toString() + "");
    // Check if necessarily parameters are available
    ParameterList parameterList = getParameterList();
    if (getAction().equals("upload") && (parameterList == null || parameterList.findParameter("file") == null))
        throw new ConfigurationException(getLogPrefix() + "the upload action requires the file parameter to be present");
    if (getAction().equals("rename") && (parameterList == null || parameterList.findParameter("destination") == null))
        throw new ConfigurationException(getLogPrefix() + "the rename action requires a destination parameter to be present");
    // Setup credentials if applied, may be null.
    // NOTE: When using NtmlPasswordAuthentication without username it returns GUEST
    CredentialFactory cf = new CredentialFactory(getAuthAlias(), getUsername(), getPassword());
    if (StringUtils.isNotEmpty(cf.getUsername())) {
        auth = new NtlmPasswordAuthentication(getAuthDomain(), cf.getUsername(), cf.getPassword());
        log.debug("setting authentication to [" + auth.toString() + "]");
    }
    try {
        // Try to initially connect to the host and create the SMB session.
        // The session automatically closes and re-creates when required.
        smbContext = new SmbFile(getShare(), auth);
    } catch (MalformedURLException e) {
        throw new ConfigurationException(e);
    }
}
Also used : MalformedURLException(java.net.MalformedURLException) ConfigurationException(nl.nn.adapterframework.configuration.ConfigurationException) CredentialFactory(nl.nn.adapterframework.util.CredentialFactory) NtlmPasswordAuthentication(jcifs.smb.NtlmPasswordAuthentication) ParameterList(nl.nn.adapterframework.parameters.ParameterList) SmbFile(jcifs.smb.SmbFile)

Aggregations

NtlmPasswordAuthentication (jcifs.smb.NtlmPasswordAuthentication)5 SmbFile (jcifs.smb.SmbFile)3 MalformedURLException (java.net.MalformedURLException)2 ConfigurationException (nl.nn.adapterframework.configuration.ConfigurationException)2 CredentialFactory (nl.nn.adapterframework.util.CredentialFactory)2 GeneralSecurityException (java.security.GeneralSecurityException)1 FailedLoginException (javax.security.auth.login.FailedLoginException)1 Type1Message (jcifs.ntlmssp.Type1Message)1 Type2Message (jcifs.ntlmssp.Type2Message)1 Type3Message (jcifs.ntlmssp.Type3Message)1 SmbAuthException (jcifs.smb.SmbAuthException)1 SmbException (jcifs.smb.SmbException)1 SmbFilenameFilter (jcifs.smb.SmbFilenameFilter)1 lombok.val (lombok.val)1 ParameterList (nl.nn.adapterframework.parameters.ParameterList)1 DefaultAuthenticationHandlerExecutionResult (org.apereo.cas.authentication.DefaultAuthenticationHandlerExecutionResult)1 BasicCredentialMetaData (org.apereo.cas.authentication.metadata.BasicCredentialMetaData)1 SpnegoCredential (org.apereo.cas.support.spnego.authentication.principal.SpnegoCredential)1 TimeoutTracker (org.opennms.core.utils.TimeoutTracker)1 PollStatus (org.opennms.netmgt.poller.PollStatus)1