mirror of
https://github.com/1Panel-dev/1Panel.git
synced 2024-11-28 21:39:06 +08:00
fix: 生成 ssh 密钥加密文件
This commit is contained in:
parent
da54794aca
commit
b19cdd9339
@ -49,3 +49,57 @@ func (b *BaseApi) UpdateSSH(c *gin.Context) {
|
||||
}
|
||||
helper.SuccessWithData(c, nil)
|
||||
}
|
||||
|
||||
// @Tags SSH
|
||||
// @Summary Generate host ssh secret
|
||||
// @Description 生成 ssh 密钥
|
||||
// @Accept json
|
||||
// @Param request body dto.GenerateSSH true "request"
|
||||
// @Success 200
|
||||
// @Security ApiKeyAuth
|
||||
// @Router /host/ssh/generate [post]
|
||||
// @x-panel-log {"bodyKeys":[],"paramKeys":[],"BeforeFuntions":[],"formatZH":"生成 SSH 密钥 ","formatEN":"generate SSH secret"}
|
||||
func (b *BaseApi) GenerateSSH(c *gin.Context) {
|
||||
var req dto.GenerateSSH
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
helper.ErrorWithDetail(c, constant.CodeErrBadRequest, constant.ErrTypeInvalidParams, err)
|
||||
return
|
||||
}
|
||||
if err := global.VALID.Struct(req); err != nil {
|
||||
helper.ErrorWithDetail(c, constant.CodeErrBadRequest, constant.ErrTypeInvalidParams, err)
|
||||
return
|
||||
}
|
||||
|
||||
if err := sshService.GenerateSSH(req); err != nil {
|
||||
helper.ErrorWithDetail(c, constant.CodeErrInternalServer, constant.ErrTypeInternalServer, err)
|
||||
return
|
||||
}
|
||||
helper.SuccessWithData(c, nil)
|
||||
}
|
||||
|
||||
// @Tags SSH
|
||||
// @Summary Load host ssh secret
|
||||
// @Description 获取 ssh 密钥
|
||||
// @Accept json
|
||||
// @Param request body dto.GenerateLoad true "request"
|
||||
// @Success 200
|
||||
// @Security ApiKeyAuth
|
||||
// @Router /host/ssh/secret [post]
|
||||
func (b *BaseApi) LoadSSHSecret(c *gin.Context) {
|
||||
var req dto.GenerateLoad
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
helper.ErrorWithDetail(c, constant.CodeErrBadRequest, constant.ErrTypeInvalidParams, err)
|
||||
return
|
||||
}
|
||||
if err := global.VALID.Struct(req); err != nil {
|
||||
helper.ErrorWithDetail(c, constant.CodeErrBadRequest, constant.ErrTypeInvalidParams, err)
|
||||
return
|
||||
}
|
||||
|
||||
data, err := sshService.LoadSSHSecret(req.EncryptionMode)
|
||||
if err != nil {
|
||||
helper.ErrorWithDetail(c, constant.CodeErrInternalServer, constant.ErrTypeInternalServer, err)
|
||||
return
|
||||
}
|
||||
helper.SuccessWithData(c, data)
|
||||
}
|
||||
|
@ -1,15 +1,19 @@
|
||||
package dto
|
||||
|
||||
type SSHInfo struct {
|
||||
Port string `json:"port"`
|
||||
Port string `json:"port" validate:"required,number,max=65535,min=1"`
|
||||
ListenAddress string `json:"listenAddress"`
|
||||
PasswordAuthentication string `json:"passwordAuthentication"`
|
||||
PubkeyAuthentication string `json:"pubkeyAuthentication"`
|
||||
PermitRootLogin string `json:"permitRootLogin"`
|
||||
UseDNS string `json:"useDNS"`
|
||||
PasswordAuthentication string `json:"passwordAuthentication" validate:"required,oneof=yes no"`
|
||||
PubkeyAuthentication string `json:"pubkeyAuthentication" validate:"required,oneof=yes no"`
|
||||
PermitRootLogin string `json:"permitRootLogin" validate:"required,oneof=yes no without-password forced-commands-only"`
|
||||
UseDNS string `json:"useDNS" validate:"required,oneof=yes no"`
|
||||
}
|
||||
|
||||
type GenerateSSH struct {
|
||||
EncryptionMode string `json:"encryptionMode"`
|
||||
EncryptionMode string `json:"encryptionMode" validate:"required,oneof=rsa ed25519 ecdsa dsa"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
|
||||
type GenerateLoad struct {
|
||||
EncryptionMode string `json:"encryptionMode" validate:"required,oneof=rsa ed25519 ecdsa dsa"`
|
||||
}
|
||||
|
@ -3,13 +3,15 @@ package service
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"os/user"
|
||||
"strings"
|
||||
|
||||
"github.com/1Panel-dev/1Panel/backend/app/dto"
|
||||
"github.com/1Panel-dev/1Panel/backend/utils/cmd"
|
||||
"github.com/1Panel-dev/1Panel/backend/utils/files"
|
||||
)
|
||||
|
||||
const sshPath = "Downloads/sshd_config"
|
||||
const sshPath = "/etc/ssh/sshd_config"
|
||||
|
||||
type SSHService struct{}
|
||||
|
||||
@ -17,6 +19,7 @@ type ISSHService interface {
|
||||
GetSSHInfo() (*dto.SSHInfo, error)
|
||||
Update(key, value string) error
|
||||
GenerateSSH(req dto.GenerateSSH) error
|
||||
LoadSSHSecret(mode string) (string, error)
|
||||
}
|
||||
|
||||
func NewISSHService() ISSHService {
|
||||
@ -82,13 +85,62 @@ func (u *SSHService) Update(key, value string) error {
|
||||
}
|
||||
|
||||
func (u *SSHService) GenerateSSH(req dto.GenerateSSH) error {
|
||||
stdout, err := cmd.Exec(fmt.Sprintf("ssh-keygen -t %s -P %s -f ~/.ssh/id_%s |echo y", req.EncryptionMode, req.Password, req.EncryptionMode))
|
||||
currentUser, err := user.Current()
|
||||
if err != nil {
|
||||
return fmt.Errorf("load current user failed, err: %v", err)
|
||||
}
|
||||
secretFile := fmt.Sprintf("%s/.ssh/id_item_%s", currentUser.HomeDir, req.EncryptionMode)
|
||||
secretPubFile := fmt.Sprintf("%s/.ssh/id_item_%s.pub", currentUser.HomeDir, req.EncryptionMode)
|
||||
authFile := currentUser.HomeDir + "/.ssh/authorized_keys"
|
||||
|
||||
command := fmt.Sprintf("ssh-keygen -t %s -f %s/.ssh/id_item_%s | echo y", req.EncryptionMode, currentUser.HomeDir, req.EncryptionMode)
|
||||
if len(req.Password) != 0 {
|
||||
command = fmt.Sprintf("ssh-keygen -t %s -P %s -f %s/.ssh/id_item_%s | echo y", req.EncryptionMode, req.Password, currentUser.HomeDir, req.EncryptionMode)
|
||||
}
|
||||
stdout, err := cmd.Exec(command)
|
||||
if err != nil {
|
||||
return fmt.Errorf("generate failed, err: %v, message: %s", err, stdout)
|
||||
}
|
||||
defer func() {
|
||||
_ = os.Remove(secretFile)
|
||||
}()
|
||||
defer func() {
|
||||
_ = os.Remove(secretPubFile)
|
||||
}()
|
||||
|
||||
if _, err := os.Stat(authFile); err != nil {
|
||||
_, _ = os.Create(authFile)
|
||||
}
|
||||
stdout1, err := cmd.Execf("cat %s >> %s/.ssh/authorized_keys", secretPubFile, currentUser.HomeDir)
|
||||
if err != nil {
|
||||
return fmt.Errorf("generate failed, err: %v, message: %s", err, stdout1)
|
||||
}
|
||||
|
||||
fileOp := files.NewFileOp()
|
||||
if err := fileOp.Rename(secretFile, fmt.Sprintf("%s/.ssh/id_%s", currentUser.HomeDir, req.EncryptionMode)); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := fileOp.Rename(secretPubFile, fmt.Sprintf("%s/.ssh/id_%s.pub", currentUser.HomeDir, req.EncryptionMode)); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (u *SSHService) LoadSSHSecret(mode string) (string, error) {
|
||||
currentUser, err := user.Current()
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("load current user failed, err: %v", err)
|
||||
}
|
||||
|
||||
homeDir := currentUser.HomeDir
|
||||
if _, err := os.Stat(fmt.Sprintf("%s/.ssh/id_%s", homeDir, mode)); err != nil {
|
||||
return "", nil
|
||||
}
|
||||
file, err := os.ReadFile(fmt.Sprintf("%s/.ssh/id_%s", homeDir, mode))
|
||||
return string(file), err
|
||||
}
|
||||
|
||||
func updateSSHConf(oldFiles []string, param string, value interface{}) []string {
|
||||
hasKey := false
|
||||
var newFiles []string
|
||||
|
@ -1,47 +0,0 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/1Panel-dev/1Panel/backend/app/dto"
|
||||
)
|
||||
|
||||
func TestSfq(t *testing.T) {
|
||||
data := dto.SSHInfo{
|
||||
Port: "22",
|
||||
ListenAddress: "0.0.0.0",
|
||||
PasswordAuthentication: "yes",
|
||||
PubkeyAuthentication: "yes",
|
||||
PermitRootLogin: "yes",
|
||||
UseDNS: "yes",
|
||||
}
|
||||
sshConf, err := os.ReadFile("/Downloads/sshd_config")
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
}
|
||||
lines := strings.Split(string(sshConf), "\n")
|
||||
for _, line := range lines {
|
||||
if strings.HasPrefix(line, "Port ") {
|
||||
data.Port = strings.ReplaceAll(line, "Port ", "")
|
||||
}
|
||||
if strings.HasPrefix(line, "ListenAddress ") {
|
||||
data.ListenAddress = strings.ReplaceAll(line, "ListenAddress ", "")
|
||||
}
|
||||
if strings.HasPrefix(line, "PasswordAuthentication ") {
|
||||
data.PasswordAuthentication = strings.ReplaceAll(line, "PasswordAuthentication ", "")
|
||||
}
|
||||
if strings.HasPrefix(line, "PubkeyAuthentication ") {
|
||||
data.PubkeyAuthentication = strings.ReplaceAll(line, "PubkeyAuthentication ", "")
|
||||
}
|
||||
if strings.HasPrefix(line, "PermitRootLogin ") {
|
||||
data.PermitRootLogin = strings.ReplaceAll(line, "PermitRootLogin ", "")
|
||||
}
|
||||
if strings.HasPrefix(line, "UseDNS ") {
|
||||
data.UseDNS = strings.ReplaceAll(line, "UseDNS ", "")
|
||||
}
|
||||
}
|
||||
fmt.Println(data)
|
||||
}
|
@ -37,6 +37,8 @@ func (s *HostRouter) InitHostRouter(Router *gin.RouterGroup) {
|
||||
|
||||
hostRouter.POST("/ssh/search", baseApi.GetSSHInfo)
|
||||
hostRouter.POST("/ssh/update", baseApi.UpdateSSH)
|
||||
hostRouter.POST("/ssh/generate", baseApi.GenerateSSH)
|
||||
hostRouter.POST("/ssh/secret", baseApi.LoadSSHSecret)
|
||||
|
||||
hostRouter.GET("/command", baseApi.ListCommand)
|
||||
hostRouter.POST("/command", baseApi.CreateCommand)
|
||||
|
@ -114,4 +114,8 @@ export namespace Host {
|
||||
permitRootLogin: string;
|
||||
useDNS: string;
|
||||
}
|
||||
export interface SSHGenerate {
|
||||
encryptionMode: string;
|
||||
password: string;
|
||||
}
|
||||
}
|
||||
|
@ -104,6 +104,9 @@ export const getSSHInfo = () => {
|
||||
export const updateSSH = (key: string, value: string) => {
|
||||
return http.post(`/hosts/ssh/update`, { key: key, value: value });
|
||||
};
|
||||
export const generatePubKey = (encryptionMode: string) => {
|
||||
return http.post(`/hosts/ssh/generate`, { encryptionMode: encryptionMode });
|
||||
export const generateSecret = (params: Host.SSHGenerate) => {
|
||||
return http.post(`/hosts/ssh/generate`, params);
|
||||
};
|
||||
export const loadSecret = (mode: string) => {
|
||||
return http.post<string>(`/hosts/ssh/secret`, { encryptionMode: mode });
|
||||
};
|
||||
|
@ -839,6 +839,7 @@ const message = {
|
||||
key: '密钥',
|
||||
pubkey: '密钥信息',
|
||||
encryptionMode: '加密方式',
|
||||
passwordHelper: '请输入 6-10 位加密密码',
|
||||
generate: '生成密钥',
|
||||
reGenerate: '重新生成密钥',
|
||||
keyAuthHelper: '是否启用密钥认证,默认启用。',
|
||||
|
@ -147,7 +147,7 @@ const form = reactive({
|
||||
|
||||
const onSaveFile = async () => {
|
||||
loading.value = true;
|
||||
await SaveFileContent({ path: '/Users/slooop/Downloads/sshd_config', content: sshConf.value })
|
||||
await SaveFileContent({ path: '/etc/ssh/sshd_config', content: sshConf.value })
|
||||
.then(() => {
|
||||
loading.value = false;
|
||||
MsgSuccess(i18n.global.t('commons.msg.operationSuccess'));
|
||||
@ -202,7 +202,7 @@ function callback(error: any) {
|
||||
}
|
||||
|
||||
const loadSSHConf = async () => {
|
||||
const res = await LoadFile({ path: '/Users/slooop/Downloads/sshd_config' });
|
||||
const res = await LoadFile({ path: '/etc/ssh/sshd_config' });
|
||||
sshConf.value = res.data || '';
|
||||
};
|
||||
|
||||
|
@ -5,26 +5,34 @@
|
||||
:destroy-on-close="true"
|
||||
@close="handleClose"
|
||||
:close-on-click-modal="false"
|
||||
size="50%"
|
||||
size="30%"
|
||||
>
|
||||
<template #header>
|
||||
<DrawerHeader :header="$t('ssh.pubkey')" :back="handleClose" />
|
||||
</template>
|
||||
<el-form ref="formRef" label-position="top" :model="form" v-loading="loading">
|
||||
<el-form ref="formRef" label-position="top" :rules="rules" :model="form" v-loading="loading">
|
||||
<el-row type="flex" justify="center">
|
||||
<el-col :span="22">
|
||||
<el-form-item :label="$t('ssh.encryptionMode')" prop="encryptionMode">
|
||||
<el-select v-model="form.encryptionMode">
|
||||
<el-select v-model="form.encryptionMode" @change="onLoadSecret">
|
||||
<el-option label="ED25519" value="ed25519" />
|
||||
<el-option label="ECDSA" value="ecdsa" />
|
||||
<el-option label="RSA" value="rsa" />
|
||||
<el-option label="DSA" value="dsa" />
|
||||
</el-select>
|
||||
|
||||
<el-button link @click="onDownload" type="primary" class="margintop">
|
||||
</el-form-item>
|
||||
<el-form-item :label="$t('terminal.password')" prop="password">
|
||||
<el-input v-model="form.password" type="password" show-password>
|
||||
<template #append>
|
||||
<el-button @click="onCopy(form.password)" icon="DocumentCopy"></el-button>
|
||||
<el-button style="margin-left: 1px" @click="random" icon="RefreshRight"></el-button>
|
||||
</template>
|
||||
</el-input>
|
||||
<el-button link @click="onGenerate(formRef)" type="primary" class="margintop">
|
||||
{{ form.primaryKey ? $t('ssh.reGenerate') : $t('ssh.generate') }}
|
||||
</el-button>
|
||||
</el-form-item>
|
||||
|
||||
<el-form-item :label="$t('ssh.key')" prop="primaryKey" v-if="form.encryptionMode">
|
||||
<el-input
|
||||
v-model="form.primaryKey"
|
||||
@ -32,7 +40,13 @@
|
||||
type="textarea"
|
||||
/>
|
||||
<div v-if="form.primaryKey">
|
||||
<el-button link type="primary" icon="CopyDocument" class="margintop" @click="loadSSLs">
|
||||
<el-button
|
||||
link
|
||||
type="primary"
|
||||
icon="CopyDocument"
|
||||
class="margintop"
|
||||
@click="onCopy(form.primaryKey)"
|
||||
>
|
||||
{{ $t('file.copy') }}
|
||||
</el-button>
|
||||
<el-button link type="primary" icon="Download" class="margintop" @click="onDownload">
|
||||
@ -52,27 +66,92 @@
|
||||
</div>
|
||||
</template>
|
||||
<script lang="ts" setup>
|
||||
import { generateSecret, loadSecret } from '@/api/modules/host';
|
||||
import { Rules } from '@/global/form-rules';
|
||||
import i18n from '@/lang';
|
||||
import { MsgSuccess } from '@/utils/message';
|
||||
import { dateFormatForName, getRandomStr } from '@/utils/util';
|
||||
import { FormInstance } from 'element-plus';
|
||||
import { reactive, ref } from 'vue';
|
||||
|
||||
const loading = ref();
|
||||
const drawerVisiable = ref();
|
||||
|
||||
const formRef = ref();
|
||||
const form = reactive({
|
||||
password: '',
|
||||
encryptionMode: '',
|
||||
primaryKey: '',
|
||||
});
|
||||
const rules = reactive({
|
||||
encryptionMode: Rules.requiredSelect,
|
||||
password: [{ validator: checkPassword, trigger: 'blur' }],
|
||||
});
|
||||
|
||||
function checkPassword(rule: any, value: any, callback: any) {
|
||||
if (form.password !== '') {
|
||||
const reg = /^[A-Za-z0-9]{6,15}$/;
|
||||
if (!reg.test(form.password)) {
|
||||
return callback(new Error(i18n.global.t('ssh.passwordHelper')));
|
||||
}
|
||||
}
|
||||
callback();
|
||||
}
|
||||
|
||||
const acceptParams = async (): Promise<void> => {
|
||||
form.password = '';
|
||||
form.encryptionMode = 'rsa';
|
||||
form.primaryKey = '';
|
||||
onLoadSecret();
|
||||
drawerVisiable.value = true;
|
||||
};
|
||||
const emit = defineEmits<{ (e: 'search'): void }>();
|
||||
|
||||
const loadSSLs = async () => {};
|
||||
const random = async () => {
|
||||
form.password = getRandomStr(10);
|
||||
};
|
||||
|
||||
const onDownload = async () => {};
|
||||
const onLoadSecret = async () => {
|
||||
const res = await loadSecret(form.encryptionMode);
|
||||
form.primaryKey = res.data || '';
|
||||
};
|
||||
|
||||
const onCopy = async (str: string) => {
|
||||
try {
|
||||
await navigator.clipboard.writeText(str);
|
||||
MsgSuccess(i18n.global.t('commons.msg.copySuccess'));
|
||||
} catch (err) {
|
||||
MsgSuccess(i18n.global.t('commons.msg.copyfailed'));
|
||||
}
|
||||
};
|
||||
|
||||
const onGenerate = async (formEl: FormInstance | undefined) => {
|
||||
if (!formEl) return;
|
||||
formEl.validate(async (valid) => {
|
||||
if (!valid) return;
|
||||
let param = {
|
||||
encryptionMode: form.encryptionMode,
|
||||
password: form.password,
|
||||
};
|
||||
await generateSecret(param).then(() => {
|
||||
loading.value = false;
|
||||
MsgSuccess(i18n.global.t('commons.msg.operationSuccess'));
|
||||
onLoadSecret();
|
||||
});
|
||||
});
|
||||
};
|
||||
const onDownload = async () => {
|
||||
const downloadUrl = window.URL.createObjectURL(new Blob([form.primaryKey]));
|
||||
const a = document.createElement('a');
|
||||
a.style.display = 'none';
|
||||
a.href = downloadUrl;
|
||||
const href = window.location.href;
|
||||
const host = href.split('//')[1].split(':')[0];
|
||||
a.download = host + '_' + dateFormatForName(new Date()) + '_id_' + form.encryptionMode;
|
||||
const event = new MouseEvent('click');
|
||||
a.dispatchEvent(event);
|
||||
};
|
||||
|
||||
const handleClose = () => {
|
||||
emit('search');
|
||||
drawerVisiable.value = false;
|
||||
};
|
||||
|
||||
|
Loading…
Reference in New Issue
Block a user