Skip to content

Commit

Permalink
[collector] bugfix sshd cannot use private key to connect (#1084)
Browse files Browse the repository at this point in the history
Co-authored-by: Musk.Chen <[email protected]>
Co-authored-by: tomsun28 <[email protected]>
  • Loading branch information
3 people committed Mar 10, 2024
1 parent daf9056 commit 78b45ef
Show file tree
Hide file tree
Showing 16 changed files with 132 additions and 151 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -17,15 +17,16 @@

package org.dromara.hertzbeat.collector.collect.ssh;

import org.apache.sshd.common.util.security.SecurityUtils;
import org.dromara.hertzbeat.collector.collect.AbstractCollect;
import org.dromara.hertzbeat.collector.collect.common.cache.CacheIdentifier;
import org.dromara.hertzbeat.collector.collect.common.cache.CommonCache;
import org.dromara.hertzbeat.collector.collect.common.cache.SshConnect;
import org.dromara.hertzbeat.collector.collect.common.ssh.CommonSshClient;
import org.dromara.hertzbeat.collector.dispatch.DispatchConstants;
import org.dromara.hertzbeat.collector.util.CollectUtil;
import org.dromara.hertzbeat.collector.util.PrivateKeyUtils;
import org.dromara.hertzbeat.common.constants.CollectorConstants;
import org.dromara.hertzbeat.collector.util.KeyPairUtil;
import org.dromara.hertzbeat.common.entity.job.Metrics;
import org.dromara.hertzbeat.common.entity.job.protocol.SshProtocol;
import org.dromara.hertzbeat.common.entity.message.CollectRep;
Expand All @@ -39,8 +40,10 @@
import org.springframework.util.StringUtils;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.ConnectException;
import java.security.GeneralSecurityException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
Expand All @@ -55,15 +58,14 @@
* ssh协议采集实现
*
* @author tom
*
*/
@Slf4j
public class SshCollectImpl extends AbstractCollect {

private static final String PARSE_TYPE_ONE_ROW = "oneRow";
private static final String PARSE_TYPE_MULTI_ROW = "multiRow";
private static final String PARSE_TYPE_NETCAT = "netcat";

private static final int DEFAULT_TIMEOUT = 10_000;

public SshCollectImpl() {
Expand Down Expand Up @@ -236,7 +238,7 @@ private void parseResponseDataByMulti(String result, List<String> aliasFields,
builder.addValues(valueRowBuilder.build());
}
}

private void removeConnectSessionCache(SshProtocol sshProtocol) {
CacheIdentifier identifier = CacheIdentifier.builder()
.ip(sshProtocol.getHost()).port(sshProtocol.getPort())
Expand All @@ -245,7 +247,7 @@ private void removeConnectSessionCache(SshProtocol sshProtocol) {
CommonCache.getInstance().removeCache(identifier);
}

private ClientSession getConnectSession(SshProtocol sshProtocol, int timeout) throws IOException {
private ClientSession getConnectSession(SshProtocol sshProtocol, int timeout) throws IOException, GeneralSecurityException {
CacheIdentifier identifier = CacheIdentifier.builder()
.ip(sshProtocol.getHost()).port(sshProtocol.getPort())
.username(sshProtocol.getUsername()).password(sshProtocol.getPassword())
Expand Down Expand Up @@ -274,14 +276,11 @@ private ClientSession getConnectSession(SshProtocol sshProtocol, int timeout) th
if (StringUtils.hasText(sshProtocol.getPassword())) {
clientSession.addPasswordIdentity(sshProtocol.getPassword());
} else if (StringUtils.hasText(sshProtocol.getPrivateKey())) {
var keyPair = KeyPairUtil.getKeyPairFromPrivateKey(sshProtocol.getPrivateKey());
if (keyPair != null) {
clientSession.addPublicKeyIdentity(keyPair);
}
} else {
clientSession.close();
throw new IllegalArgumentException("please input password or secret.");
}
var resourceKey = PrivateKeyUtils.writePrivateKey(sshProtocol.getHost(), sshProtocol.getPrivateKey());
SecurityUtils.loadKeyPairIdentities(null, () -> resourceKey, new FileInputStream(resourceKey), null)
.forEach(clientSession::addPublicKeyIdentity);
} // else auth with localhost private public key certificates

// auth
if (!clientSession.auth().verify(timeout, TimeUnit.MILLISECONDS).isSuccess()) {
clientSession.close();
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
package org.dromara.hertzbeat.collector.util;

import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Objects;

/**
* 将私钥写入~/.ssh
*
* @author <a href="mailto:[email protected]">gcdd1993</a>
* Created by gcdd1993 on 2023/7/9
*/
@Slf4j
@UtilityClass
public class PrivateKeyUtils {

private static final String KEY_PATH = System.getProperty("user.home") + "/.ssh";

/**
* write private key to ~/.ssh, filename is ~/.ssh/id_rsa_${host}
*
* @param host host
* @param keyStr key string
* @return key file path
* @throws IOException if ~/.ssh is not exist and create dir error
*/
public static String writePrivateKey(String host, String keyStr) throws IOException {
var sshPath = Paths.get(KEY_PATH);
if (!Files.exists(sshPath)) {
Files.createDirectories(sshPath);
}
var keyPath = Paths.get(KEY_PATH, "id_rsa_" + host);
if (!Files.exists(keyPath)) {
Files.writeString(keyPath, keyStr);
} else {
var oldKey = Files.readString(keyPath);
if (!Objects.equals(oldKey, keyStr)) {
Files.writeString(keyPath, keyStr);
}
}
return keyPath.toString();
}

}

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.dromara.hertzbeat.collector.util;

import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;

import java.io.IOException;

/**
* @author <a href="mailto:[email protected]">gcdd1993</a>
* Created by gcdd1993 on 2023/7/9
*/
class PrivateKeyUtilsTest {

@DisplayName("write key to ~/.ssh")
@Test
void writePrivateKey() throws IOException {
var key = "-----BEGIN RSA PRIVATE KEY-----\n" +
"MIIEogIBAAKCAQEA4ctFYk/xy89L6/6YFeeMrwCW9lCP/ThXMn+9G63s5bGn4oIN\n" +
"8cEf/JYkmGw8vMP41IAP9dyH8ji2wI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+4jAIz/19bsbc7\n" +
"zDIqaovrKe8tMMglXg/ZE0e0aLvdvqRkRAKU1Z51Ob5lLuDwEYoyWZCgk1gL90Vp\n" +
"wpT+P3zlcyCBo39IWMDB8C8IydRbF/GbaaNtoKds92m+qWwwUd87XCf+3M0wvvI6\n" +
"75TW1PLEbyOgFz8Khh8hAoGBAJbDc87Ul9sCAtp2Ip2hvWk2coPR8vfADz9C8cn5\n" +
"/BShBOcVfipSt2b1n8GCP/TnFU4XgBVeiSkA9+4Rg6AzMzejdY1+JvWvfqCnRVM/\n" +
"GkOnMzZb17tyZi+ck8OKC/IcHkAyUYFWL0GWQSOojvBsPQxt+0V8aEIwsHjNSSha\n" +
"nyNpAoGAd0XqdByRxbWgg5ZsvM0tvrpMITpEZsGMG9VeQPGl0wsQvC2zw5QGLvz/\n" +
"57YhofOOr0M3yElcFA9Imvek5CYZsyL8eIWGZyadfRiYvGOUyvDDO3BYRG4DmhyF\n" +
"KVk3URjEuOCC29ORvZ/7HaCO9iuEbvAA/mrAtd7KdCA+3PzfEOw=\n" +
"-----END RSA PRIVATE KEY-----";
PrivateKeyUtils.writePrivateKey("127.0.0.1", key);
}
}
1 change: 1 addition & 0 deletions manager/src/main/resources/define/app-almalinux.yml
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,7 @@ params:
# type-param field type(most mapping the html input type)
# type-字段类型,样式(大部分映射input标签type属性)
type: textarea
placeholder: -----BEGIN RSA PRIVATE KEY-----
# required-true or false
# required-是否是必输项 true-必填 false-可选
required: false
Expand Down
1 change: 1 addition & 0 deletions manager/src/main/resources/define/app-centos.yml
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,7 @@ params:
# type-param field type(most mapping the html input type)
# type-字段类型,样式(大部分映射input标签type属性)
type: textarea
placeholder: -----BEGIN RSA PRIVATE KEY-----
# required-true or false
# required-是否是必输项 true-必填 false-可选
required: false
Expand Down
1 change: 1 addition & 0 deletions manager/src/main/resources/define/app-coreos.yml
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,7 @@ params:
# type-param field type(most mapping the html input type)
# type-字段类型,样式(大部分映射input标签type属性)
type: textarea
placeholder: -----BEGIN RSA PRIVATE KEY-----
# required-true or false
# required-是否是必输项 true-必填 false-可选
required: false
Expand Down
1 change: 1 addition & 0 deletions manager/src/main/resources/define/app-debian.yml
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,7 @@ params:
# type-param field type(most mapping the html input type)
# type-字段类型,样式(大部分映射input标签type属性)
type: textarea
placeholder: -----BEGIN RSA PRIVATE KEY-----
# required-true or false
# required-是否是必输项 true-必填 false-可选
required: false
Expand Down
1 change: 1 addition & 0 deletions manager/src/main/resources/define/app-euleros.yml
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,7 @@ params:
# type-param field type(most mapping the html input type)
# type-字段类型,样式(大部分映射input标签type属性)
type: textarea
placeholder: -----BEGIN RSA PRIVATE KEY-----
# required-true or false
# required-是否是必输项 true-必填 false-可选
required: false
Expand Down
1 change: 1 addition & 0 deletions manager/src/main/resources/define/app-freebsd.yml
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,7 @@ params:
# type-param field type(most mapping the html input type)
# type-字段类型,样式(大部分映射input标签type属性)
type: textarea
placeholder: -----BEGIN RSA PRIVATE KEY-----
# required-true or false
# required-是否是必输项 true-必填 false-可选
required: false
Expand Down
1 change: 1 addition & 0 deletions manager/src/main/resources/define/app-linux.yml
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,7 @@ params:
# type-param field type(most mapping the html input type)
# type-字段类型,样式(大部分映射input标签type属性)
type: textarea
placeholder: -----BEGIN RSA PRIVATE KEY-----
# required-true or false
# required-是否是必输项 true-必填 false-可选
required: false
Expand Down
Loading

0 comments on commit 78b45ef

Please sign in to comment.