fff34f3679a226315ff33569a1eb2ad83b39a133
[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.opendaylight.aaa.encrypt.PKIUtil;
14 import org.opendaylight.netconf.shaded.sshd.client.future.AuthFuture;
15 import org.opendaylight.netconf.shaded.sshd.client.session.ClientSession;
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 LoginPasswordHandler {
23     private KeyPair keyPair = null;
24     private static final Logger LOG = LoggerFactory.getLogger(PublicKeyAuth.class);
25
26     public PublicKeyAuth(final String username, final String password, final String keyPath,
27                          String passPhrase) {
28         super(username, password);
29         try {
30             boolean isKeyPathAbsent = Strings.isNullOrEmpty(keyPath);
31             passPhrase = Strings.isNullOrEmpty(passPhrase) ? "" : passPhrase;
32             if (!isKeyPathAbsent) {
33                 this.keyPair = new PKIUtil().decodePrivateKey(keyPath, passPhrase);
34             } else {
35                 LOG.info("Private key path not specified in the config file.");
36             }
37         } catch (IOException ioEx) {
38             LOG.warn("Not able to read the private key and passphrase for netconf client", ioEx);
39         }
40     }
41
42     @Override
43     public AuthFuture authenticate(final ClientSession session) throws IOException {
44         if (keyPair != null) {
45             session.addPublicKeyIdentity(keyPair);
46         }
47
48         return super.authenticate(session);
49     }
50 }