Search in sources :

Example 1 with LoginFailureException

use of ch.cyberduck.core.exception.LoginFailureException in project cyberduck by iterate-ch.

the class BrickPairingSchedulerFeature method operate.

/**
 * Pool for pairing key from service
 *
 * @param callback Callback when service returns 200
 */
private void operate(final PasswordCallback callback) throws BackgroundException {
    try {
        final HttpPost resource = new HttpPost(String.format("%s/api/rest/v1/sessions/pairing_key/%s", new HostUrlProvider().withUsername(false).withPath(false).get(session.getHost()), token));
        resource.setHeader(HttpHeaders.ACCEPT, "application/json");
        resource.setHeader(HttpHeaders.CONTENT_TYPE, "application/json");
        if (log.isInfoEnabled()) {
            log.info(String.format("Fetch credentials for paring key %s from %s", token, resource));
        }
        final JsonObject json = session.getClient().execute(resource, new AbstractResponseHandler<JsonObject>() {

            @Override
            public JsonObject handleEntity(final HttpEntity entity) throws IOException {
                final ByteArrayOutputStream out = new ByteArrayOutputStream();
                IOUtils.copy(entity.getContent(), out);
                return JsonParser.parseReader(new InputStreamReader(new ByteArrayInputStream(out.toByteArray()))).getAsJsonObject();
            }
        });
        if (json.has("nickname")) {
            if (new HostPreferences(session.getHost()).getBoolean("brick.pairing.nickname.configure")) {
                final JsonPrimitive nickname = json.getAsJsonPrimitive("nickname");
                if (StringUtils.isNotBlank(host.getNickname())) {
                    if (!StringUtils.equals(host.getNickname(), nickname.getAsString())) {
                        log.warn(String.format("Mismatch of nickname. Previously authorized as %s and now paired as %s", host.getNickname(), nickname.getAsString()));
                        callback.close(null);
                        throw new LoginCanceledException();
                    }
                }
                host.setNickname(nickname.getAsString());
            }
        }
        final Credentials credentials = host.getCredentials();
        if (json.has("user_username")) {
            credentials.setUsername(json.getAsJsonPrimitive("user_username").getAsString());
        } else {
            throw new LoginFailureException(String.format("Invalid response for pairing key %s", token));
        }
        if (json.has("password")) {
            credentials.setPassword(json.getAsJsonPrimitive("password").getAsString());
        } else {
            throw new LoginFailureException(String.format("Invalid response for pairing key %s", token));
        }
        if (json.has("server")) {
            if (new HostPreferences(session.getHost()).getBoolean("brick.pairing.hostname.configure")) {
                host.setHostname(URI.create(json.getAsJsonPrimitive("server").getAsString()).getHost());
            }
        }
        callback.close(credentials.getUsername());
    } catch (JsonParseException e) {
        throw new DefaultIOExceptionMappingService().map(new IOException(e.getMessage(), e));
    } catch (HttpResponseException e) {
        switch(e.getStatusCode()) {
            case HttpStatus.SC_NOT_FOUND:
                log.warn(String.format("Missing login for pairing key %s", token));
                cancel.verify();
                break;
            default:
                throw new DefaultHttpResponseExceptionMappingService().map(e);
        }
    } catch (IOException e) {
        throw new DefaultIOExceptionMappingService().map(e);
    }
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) DefaultHttpResponseExceptionMappingService(ch.cyberduck.core.http.DefaultHttpResponseExceptionMappingService) HostUrlProvider(ch.cyberduck.core.HostUrlProvider) HttpEntity(org.apache.http.HttpEntity) InputStreamReader(java.io.InputStreamReader) JsonPrimitive(com.google.gson.JsonPrimitive) LoginCanceledException(ch.cyberduck.core.exception.LoginCanceledException) JsonObject(com.google.gson.JsonObject) HttpResponseException(org.apache.http.client.HttpResponseException) IOException(java.io.IOException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) JsonParseException(com.google.gson.JsonParseException) HostPreferences(ch.cyberduck.core.preferences.HostPreferences) LoginFailureException(ch.cyberduck.core.exception.LoginFailureException) ByteArrayInputStream(java.io.ByteArrayInputStream) DefaultIOExceptionMappingService(ch.cyberduck.core.DefaultIOExceptionMappingService) Credentials(ch.cyberduck.core.Credentials)

Example 2 with LoginFailureException

use of ch.cyberduck.core.exception.LoginFailureException in project cyberduck by iterate-ch.

the class SDSExceptionMappingService method map.

@Override
public BackgroundException map(final ApiException failure) {
    for (Throwable cause : ExceptionUtils.getThrowableList(failure)) {
        if (cause instanceof SocketException) {
            // Map Connection has been shutdown: javax.net.ssl.SSLException: java.net.SocketException: Broken pipe
            return new DefaultSocketExceptionMappingService().map((SocketException) cause);
        }
        if (cause instanceof HttpResponseException) {
            return new DefaultHttpResponseExceptionMappingService().map((HttpResponseException) cause);
        }
        if (cause instanceof IOException) {
            return new DefaultIOExceptionMappingService().map((IOException) cause);
        }
        if (cause instanceof IllegalStateException) {
            // Caused by: ch.cyberduck.core.sds.io.swagger.client.ApiException: javax.ws.rs.ProcessingException: java.lang.IllegalStateException: Connection pool shut down
            return new ConnectionCanceledException(cause);
        }
    }
    final StringBuilder buffer = new StringBuilder();
    if (null != failure.getResponseBody()) {
        try {
            final JsonObject json = JsonParser.parseReader(new StringReader(failure.getResponseBody())).getAsJsonObject();
            if (json.has("errorCode")) {
                if (json.get("errorCode").isJsonPrimitive()) {
                    final int errorCode = json.getAsJsonPrimitive("errorCode").getAsInt();
                    if (log.isDebugEnabled()) {
                        log.debug(String.format("Failure with errorCode %s", errorCode));
                    }
                    final String key = String.format("Error %d", errorCode);
                    final String localized = LocaleFactory.get().localize(key, "SDS");
                    this.append(buffer, localized);
                    if (StringUtils.equals(localized, key)) {
                        log.warn(String.format("Missing user message for error code %d", errorCode));
                        if (json.has("debugInfo")) {
                            if (json.get("debugInfo").isJsonPrimitive()) {
                                this.append(buffer, json.getAsJsonPrimitive("debugInfo").getAsString());
                            }
                        }
                    }
                    switch(failure.getCode()) {
                        case HttpStatus.SC_BAD_REQUEST:
                            switch(errorCode) {
                                case -10100:
                                    // [-10100] Invalid authentication method
                                    return new AccessDeniedException(buffer.toString(), failure);
                            }
                        case HttpStatus.SC_NOT_FOUND:
                            switch(errorCode) {
                                case -70020:
                                // [-70020] User does not have a keypair
                                case -70501:
                                // [-70501] User not found
                                case -40761:
                                    // [-40761] Filekey not found for encrypted file
                                    return new AccessDeniedException(buffer.toString(), failure);
                            }
                            break;
                        case HttpStatus.SC_PRECONDITION_FAILED:
                            switch(errorCode) {
                                case -10108:
                                    // [-10108] Radius Access-Challenge required.
                                    if (json.has("replyMessage")) {
                                        if (json.get("replyMessage").isJsonPrimitive()) {
                                            final JsonPrimitive replyMessage = json.getAsJsonPrimitive("replyMessage");
                                            if (log.isDebugEnabled()) {
                                                log.debug(String.format("Failure with replyMessage %s", replyMessage));
                                            }
                                            buffer.append(replyMessage.getAsString());
                                        }
                                    }
                                    return new PartialLoginFailureException(buffer.toString(), failure);
                            }
                            break;
                        case HttpStatus.SC_UNAUTHORIZED:
                            switch(errorCode) {
                                case -10012:
                                    // [-10012] Wrong token.
                                    return new ExpiredTokenException(buffer.toString(), failure);
                            }
                            break;
                    }
                }
            } else {
                switch(failure.getCode()) {
                    case HttpStatus.SC_INTERNAL_SERVER_ERROR:
                        break;
                    default:
                        if (json.has("debugInfo")) {
                            log.warn(String.format("Missing error code for failure %s", json));
                            if (json.get("debugInfo").isJsonPrimitive()) {
                                this.append(buffer, json.getAsJsonPrimitive("debugInfo").getAsString());
                            }
                        }
                }
            }
        } catch (JsonParseException e) {
        // Ignore
        }
    }
    switch(failure.getCode()) {
        case HttpStatus.SC_FORBIDDEN:
            if (failure.getResponseHeaders().containsKey("X-Forbidden")) {
                return new AccessDeniedException(LocaleFactory.localizedString("The AV scanner detected that the file could be malicious", "SDS"));
            }
            break;
        case 901:
            // Server with AV scanners will block transfer attempts of infected files (upload or download) and answer the request 901
            return new AccessDeniedException(LocaleFactory.localizedString("The AV scanner detected that the file could be malicious", "SDS"));
        case HttpStatus.SC_PRECONDITION_FAILED:
            // [-10106] Username must be changed
            return new LoginFailureException(buffer.toString(), failure);
    }
    return new DefaultHttpResponseExceptionMappingService().map(failure, buffer, failure.getCode());
}
Also used : SocketException(java.net.SocketException) DefaultHttpResponseExceptionMappingService(ch.cyberduck.core.http.DefaultHttpResponseExceptionMappingService) AccessDeniedException(ch.cyberduck.core.exception.AccessDeniedException) ExpiredTokenException(ch.cyberduck.core.exception.ExpiredTokenException) JsonPrimitive(com.google.gson.JsonPrimitive) ConnectionCanceledException(ch.cyberduck.core.exception.ConnectionCanceledException) PartialLoginFailureException(ch.cyberduck.core.exception.PartialLoginFailureException) JsonObject(com.google.gson.JsonObject) HttpResponseException(org.apache.http.client.HttpResponseException) IOException(java.io.IOException) JsonParseException(com.google.gson.JsonParseException) LoginFailureException(ch.cyberduck.core.exception.LoginFailureException) PartialLoginFailureException(ch.cyberduck.core.exception.PartialLoginFailureException) DefaultSocketExceptionMappingService(ch.cyberduck.core.DefaultSocketExceptionMappingService) StringReader(java.io.StringReader) DefaultIOExceptionMappingService(ch.cyberduck.core.DefaultIOExceptionMappingService)

Example 3 with LoginFailureException

use of ch.cyberduck.core.exception.LoginFailureException in project cyberduck by iterate-ch.

the class MantaHttpExceptionMappingService method map.

@Override
public BackgroundException map(final MantaClientHttpResponseException failure) {
    switch(failure.getStatusCode()) {
        case 403:
            final StringBuilder buffer = new StringBuilder();
            this.append(buffer, failure.getStatusMessage());
            return new LoginFailureException(buffer.toString(), failure);
    }
    return new DefaultHttpResponseExceptionMappingService().map(new HttpResponseException(failure.getStatusCode(), failure.getStatusMessage()));
}
Also used : DefaultHttpResponseExceptionMappingService(ch.cyberduck.core.http.DefaultHttpResponseExceptionMappingService) LoginFailureException(ch.cyberduck.core.exception.LoginFailureException) MantaClientHttpResponseException(com.joyent.manta.exception.MantaClientHttpResponseException) HttpResponseException(org.apache.http.client.HttpResponseException)

Example 4 with LoginFailureException

use of ch.cyberduck.core.exception.LoginFailureException in project cyberduck by iterate-ch.

the class S3Session method login.

@Override
public void login(final Proxy proxy, final LoginCallback prompt, final CancelCallback cancel) throws BackgroundException {
    if (Scheme.isURL(host.getProtocol().getContext())) {
        try {
            final Credentials temporary = new AWSSessionCredentialsRetriever(trust, key, this, host.getProtocol().getContext()).get();
            client.setProviderCredentials(new AWSSessionCredentials(temporary.getUsername(), temporary.getPassword(), temporary.getToken()));
        } catch (ConnectionTimeoutException | ConnectionRefusedException | ResolveFailedException | NotfoundException | InteroperabilityException e) {
            log.warn(String.format("Failure to retrieve session credentials from . %s", e.getMessage()));
            throw new LoginFailureException(e.getDetail(false), e);
        }
    } else {
        final Credentials credentials;
        // Only for AWS
        if (isAwsHostname(host.getHostname())) {
            // Try auto-configure
            credentials = new STSCredentialsConfigurator(new ThreadLocalHostnameDelegatingTrustManager(trust, host.getHostname()), key, prompt).configure(host);
        } else {
            credentials = host.getCredentials();
        }
        if (StringUtils.isNotBlank(credentials.getToken())) {
            client.setProviderCredentials(credentials.isAnonymousLogin() ? null : new AWSSessionCredentials(credentials.getUsername(), credentials.getPassword(), credentials.getToken()));
        } else {
            client.setProviderCredentials(credentials.isAnonymousLogin() ? null : new AWSCredentials(credentials.getUsername(), credentials.getPassword()));
        }
    }
    if (host.getCredentials().isPassed()) {
        log.warn(String.format("Skip verifying credentials with previous successful authentication event for %s", this));
        return;
    }
    try {
        final Location.Name location = new S3PathStyleFallbackAdapter<>(this, new BackgroundExceptionCallable<Location.Name>() {

            @Override
            public Location.Name call() throws BackgroundException {
                return new S3LocationFeature(S3Session.this, client.getRegionEndpointCache()).getLocation(new DelegatingHomeFeature(new DefaultPathHomeFeature(host)).find());
            }
        }).call();
        if (log.isDebugEnabled()) {
            log.debug(String.format("Retrieved region %s", location));
        }
        if (!Location.unknown.equals(location)) {
            client.getConfiguration().setProperty("storage-service.default-region", location.getIdentifier());
        }
    } catch (AccessDeniedException | InteroperabilityException e) {
        log.warn(String.format("Failure %s querying region", e));
        final Path home = new DefaultHomeFinderService(this).find();
        if (log.isDebugEnabled()) {
            log.debug(String.format("Retrieved %s", home));
        }
    }
}
Also used : Path(ch.cyberduck.core.Path) NotfoundException(ch.cyberduck.core.exception.NotfoundException) AccessDeniedException(ch.cyberduck.core.exception.AccessDeniedException) InteroperabilityException(ch.cyberduck.core.exception.InteroperabilityException) DelegatingHomeFeature(ch.cyberduck.core.shared.DelegatingHomeFeature) DefaultPathHomeFeature(ch.cyberduck.core.shared.DefaultPathHomeFeature) DefaultHomeFinderService(ch.cyberduck.core.shared.DefaultHomeFinderService) ConnectionRefusedException(ch.cyberduck.core.exception.ConnectionRefusedException) ResolveFailedException(ch.cyberduck.core.exception.ResolveFailedException) AWSCredentials(org.jets3t.service.security.AWSCredentials) BackgroundExceptionCallable(ch.cyberduck.core.threading.BackgroundExceptionCallable) ConnectionTimeoutException(ch.cyberduck.core.exception.ConnectionTimeoutException) LoginFailureException(ch.cyberduck.core.exception.LoginFailureException) AWSSessionCredentials(org.jets3t.service.security.AWSSessionCredentials) ThreadLocalHostnameDelegatingTrustManager(ch.cyberduck.core.ssl.ThreadLocalHostnameDelegatingTrustManager) AWSSessionCredentialsRetriever(ch.cyberduck.core.auth.AWSSessionCredentialsRetriever) AWSCredentials(org.jets3t.service.security.AWSCredentials) Credentials(ch.cyberduck.core.Credentials) AWSSessionCredentials(org.jets3t.service.security.AWSSessionCredentials) STSCredentialsConfigurator(ch.cyberduck.core.sts.STSCredentialsConfigurator)

Example 5 with LoginFailureException

use of ch.cyberduck.core.exception.LoginFailureException in project cyberduck by iterate-ch.

the class STSCredentialsConfigurator method fetchSsoCredentials.

/**
 * Read SSO credentials from cache file of AWS CLI
 *
 * @throws LoginFailureException Error reading from file
 * @throws ExpiredTokenException Expired SSO credentials in cache
 */
private CachedCredential fetchSsoCredentials(final Credentials credentials, final Map<String, String> properties, final Local awsDirectory) throws LoginFailureException {
    // See https://github.com/boto/botocore/blob/23ee17f5446c78167ff442302471f9928c3b4b7c/botocore/credentials.py#L2004
    try {
        final String ssoStartUrl = properties.get("sso_start_url");
        final String ssoAccountId = properties.get("sso_account_id");
        final String ssoRoleName = properties.get("sso_role_name");
        final String cacheKey = String.format("{\"accountId\":\"%s\",\"roleName\":\"%s\",\"startUrl\":\"%s\"}", ssoAccountId, ssoRoleName, ssoStartUrl);
        final HashCode hashCode = Hashing.sha1().newHasher().putString(cacheKey, Charsets.UTF_8).hash();
        final String hash = BaseEncoding.base16().lowerCase().encode(hashCode.asBytes());
        final String cachedCredentialsJson = String.format("%s.json", hash);
        final Local cachedCredentialsFile = LocalFactory.get(LocalFactory.get(LocalFactory.get(awsDirectory, "cli"), "cache"), cachedCredentialsJson);
        if (log.isDebugEnabled()) {
            log.debug(String.format("Attempting to read SSO credentials from %s", cachedCredentialsFile.getAbsolute()));
        }
        if (!cachedCredentialsFile.exists()) {
            throw new LoginFailureException(String.format("Missing file %s with cached SSO credentials.", cachedCredentialsFile.getAbsolute()));
        }
        try (InputStream in = cachedCredentialsFile.getInputStream()) {
            final ObjectMapper mapper = new ObjectMapper();
            mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            final CachedCredentials cached = mapper.readValue(in, CachedCredentials.class);
            if (null == cached.credentials) {
                throw new LoginFailureException("Failure parsing SSO credentials.");
            }
            final Instant expiration = Instant.parse(cached.credentials.expiration);
            if (expiration.isBefore(Instant.now())) {
                throw new ExpiredTokenException("Expired AWS SSO credentials.");
            }
            return cached.credentials;
        }
    } catch (IOException | AccessDeniedException e) {
        throw new LoginFailureException("Failure retrieving SSO credentials.", e);
    }
}
Also used : AccessDeniedException(ch.cyberduck.core.exception.AccessDeniedException) HashCode(com.google.common.hash.HashCode) LoginFailureException(ch.cyberduck.core.exception.LoginFailureException) ExpiredTokenException(ch.cyberduck.core.exception.ExpiredTokenException) InputStream(java.io.InputStream) Instant(java.time.Instant) Local(ch.cyberduck.core.Local) IOException(java.io.IOException) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Aggregations

LoginFailureException (ch.cyberduck.core.exception.LoginFailureException)31 AccessDeniedException (ch.cyberduck.core.exception.AccessDeniedException)11 Credentials (ch.cyberduck.core.Credentials)9 InteroperabilityException (ch.cyberduck.core.exception.InteroperabilityException)9 IOException (java.io.IOException)9 Test (org.junit.Test)8 DefaultIOExceptionMappingService (ch.cyberduck.core.DefaultIOExceptionMappingService)6 DefaultHttpResponseExceptionMappingService (ch.cyberduck.core.http.DefaultHttpResponseExceptionMappingService)6 LoginCanceledException (ch.cyberduck.core.exception.LoginCanceledException)5 HttpResponseException (org.apache.http.client.HttpResponseException)5 BackgroundException (ch.cyberduck.core.exception.BackgroundException)4 ConnectionRefusedException (ch.cyberduck.core.exception.ConnectionRefusedException)4 ConnectionTimeoutException (ch.cyberduck.core.exception.ConnectionTimeoutException)4 ExpiredTokenException (ch.cyberduck.core.exception.ExpiredTokenException)4 NotfoundException (ch.cyberduck.core.exception.NotfoundException)4 Local (ch.cyberduck.core.Local)3 JsonObject (com.google.gson.JsonObject)3 JsonParseException (com.google.gson.JsonParseException)3 DisabledCancelCallback (ch.cyberduck.core.DisabledCancelCallback)2 HostUrlProvider (ch.cyberduck.core.HostUrlProvider)2