Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JSch Authentication Failure: "Auth fail for methods 'publickey'" in AWS Lambda #750

Open
ManojlovicM opened this issue Jan 21, 2025 · 4 comments

Comments

@ManojlovicM
Copy link

I'm encountering an issue with JSch when attempting to establish an SFTP connection using a private key from an AWS Lambda function. The connection fails with the error:

com.jcraft.jsch.JSchException: Auth fail for methods 'publickey'.

This is the stack trace for the error:

com.jcraft.jsch.JSchException: Auth fail for methods 'publickey' at com.jcraft.jsch.Session.connect(Session.java:520) at com.jcraft.jsch.Session.connect(Session.java:198) at org.equias.util.SftpUtil.getChannelSftpWithPvtKey(SftpUtil.java:96) at org.equias.service.processing.eex.EexProcessor.<init>(EexProcessor.java:49) at org.equias.aws.lambda.Handler.handleRequest(Handler.java:76) at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(Unknown Source) at java.base/java.lang.reflect.Method.invoke(Unknown Source) at com.amazonaws.services.lambda.runtime.api.client.EventHandlerLoader$StreamMethodRequestHandler.handleRequest(EventHandlerLoader.java:831) at com.amazonaws.services.lambda.runtime.api.client.EventHandlerLoader$2.call(EventHandlerLoader.java:601) at com.amazonaws.services.lambda.runtime.api.client.AWSLambda.startRuntime(AWSLambda.java:240) at com.amazonaws.services.lambda.runtime.api.client.AWSLambda.startRuntime(AWSLambda.java:190) at com.amazonaws.services.lambda.runtime.api.client.AWSLambda.main(AWSLambda.java:180)

I am using the following implementation to connect to the SFTP server using a private key:

`public static ChannelSftp getChannelSftpWithPvtKey(String remoteServer, Regions region)
throws JSchException {
LOGGER.info("Starting to get SFTP channel with private key for remote server: {}", remoteServer);

    String secretName = String.format("customer/%s/SFTP", remoteServer);
    String pvtKeySecretName = String.format("customer/%s/pvtKey", remoteServer);

    Map<String, String> secretValues = AmazonSecretsManagerHelper.getSecret(secretName, region.getName());
    String privateKey = AmazonSecretsManagerHelper.getSecretString(pvtKeySecretName, region.getName());

    String host = secretValues.get("host");
    int port = Integer.parseInt(secretValues.get("port"));
    String username = secretValues.get("username");
    String password = secretValues.get("password");

    LOGGER.info("Connection Details: Host = {}, Port = {}, Username = {}", host, port, username);

    JSch jSch = new JSch();
    try {
        // Add the private key directly from a string
        byte[] privateKeyBytes = privateKey.getBytes(StandardCharsets.UTF_8);
        jSch.addIdentity("SFTPIdentity", privateKeyBytes, null, null);
        LOGGER.info("Private key successfully added to JSch.");
    } catch (Exception e) {
        LOGGER.error("Error adding private key to JSch.", e);
        throw new JSchException("Failed to add private key", e);
    }

    Session session = jSch.getSession(username, host, port);
    session.setPassword(password);

    Properties config = new Properties();
    config.put("StrictHostKeyChecking", "no");
    config.put("PreferredAuthentications", "publickey,password,keyboard-interactive");
    session.setConfig(config);

    LOGGER.info("Connecting to SFTP server...");
    session.connect();
    LOGGER.info("Connected to SFTP server.");

    ChannelSftp channelSftp = (ChannelSftp) session.openChannel("sftp");
    LOGGER.info("SFTP channel successfully opened.");

    return channelSftp;
}`
  • The same code works perfectly in the local development environment (MacBook/Windows with the same key and credentials).
  • Private Key Format: Verified that the private key is in the OpenSSH format
  • Enabled JSch.setLogger() to check the logs. Observed that the private key is being added, but the server rejects the connection with Auth fail for methods 'publickey'
  • Ensured that the Lambda has the necessary permissions to retrieve the private key and SFTP credentials from AWS Secrets Manager
  • Deployed the Lambda function in a VPC with internet access
  • Verified the private key and username using ssh -i private_key user@host from a terminal, which works without any issues

Runtime: AWS Lambda (Java 21)
JSch Version: 0.2.17

Could you please provide insights into why the authentication is failing in this specific case? Are there any additional configurations required for AWS Lambda environments or known issues with JSch in such setups?

Thank you for your assistance. Let me know if more details are needed!

@norrisjeremy
Copy link
Contributor

Hi @ManojlovicM,

We can't tell you why your remote server is rejecting your SSH authentication when you run it via an AWS Lambda.
You would need to talk with the administrators' of that remote server to better understand why your SSH key is rejected when used from AWS.

Thanks,
Jeremy

@ManojlovicM
Copy link
Author

Hi @norrisjeremy,

Thank you for your quick response. The issue seems to be with the SFTP configuration, not the code.

Best Regards,
Marko

@ManojlovicM
Copy link
Author

Hi @norrisjeremy,

Sorry for reopening this ticket, but after further analysis, it seems the issue is not with AWS or SFTP configuration but rather with the inclusion of the JSCH library.

When I run my code locally using the command:
java -classpath /Users/Marko/test/target/classes:/Users/Marko/.m2/repository/com/github/mwiede/jsch/0.2.22/jsch-0.2.22.jar ... the code works fine without any issues.

However, when I run it using: java -jar myApp.jar I encounter the aforementioned exception.

Could it be that the JSCH library is not being included properly in the JAR file during the build process?

Please let me know if you need any additional details or logs.

Best regards,
Marko

@norrisjeremy
Copy link
Contributor

Hi @ManojlovicM,

What you described sounds like a problem with the packaging of your application and not JSch.
I'm not exactly sure how you would expect us to help?

Thanks,
Jeremy

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants