283089c7d686b9463ab5ff316cbbc57e5d100c6e
[netconf.git] / netconf / netconf-netty-util / src / main / java / org / opendaylight / netconf / nettyutil / handler / ssh / authentication / PublicKeyAuth.java
1 /*
2  * Copyright (c) 2017 Brocade Communication Systems and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.netconf.nettyutil.handler.ssh.authentication;
9
10 import com.google.common.base.Strings;
11 import java.io.IOException;
12 import java.security.KeyPair;
13 import org.apache.sshd.ClientSession;
14 import org.apache.sshd.client.future.AuthFuture;
15 import org.opendaylight.aaa.encrypt.PKIUtil;
16 import org.slf4j.Logger;
17 import org.slf4j.LoggerFactory;
18
19 /**
20  * Represents Auth information for the public key based authentication for netconf.
21  */
22 public class PublicKeyAuth extends LoginPassword {
23     private KeyPair keyPair = null;
24     private static final Logger LOG = LoggerFactory.getLogger(PublicKeyAuth.class);
25
26     public PublicKeyAuth(String username, String password, String keyPath, String passPhrase) {
27         super(username, password);
28         try {
29             boolean isKeyPathAbsent = Strings.isNullOrEmpty(keyPath);
30             passPhrase = Strings.isNullOrEmpty(passPhrase) ? "" : passPhrase;
31             if (!isKeyPathAbsent) {
32                 this.keyPair = new PKIUtil().decodePrivateKey(keyPath, passPhrase);
33             } else {
34                 LOG.info("Private key path not specified in the config file.");
35             }
36         } catch (IOException ioEx) {
37             LOG.warn("Not able to read the private key and passphrase for netconf client", ioEx);
38         }
39     }
40
41     @Override
42     public AuthFuture authenticate(final ClientSession session) throws IOException {
43         if (keyPair != null) {
44             session.addPublicKeyIdentity(keyPair);
45         }
46         session.addPasswordIdentity(password);
47         return session.auth();
48     }
49 }