1
1
mirror of https://github.com/go-gitea/gitea synced 2024-11-18 08:04:25 +00:00
gitea/modules/ssh/ssh.go

193 lines
5.1 KiB
Go
Raw Normal View History

2014-07-26 04:24:27 +00:00
// Copyright 2014 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package ssh
import (
"io"
2014-07-26 04:24:27 +00:00
"io/ioutil"
"net"
"os"
"os/exec"
"path/filepath"
2014-07-26 04:24:27 +00:00
"strings"
"github.com/Unknwon/com"
"golang.org/x/crypto/ssh"
2014-07-26 04:24:27 +00:00
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/setting"
2014-07-26 04:24:27 +00:00
)
func cleanCommand(cmd string) string {
i := strings.Index(cmd, "git")
if i == -1 {
return cmd
}
return cmd[i:]
}
func handleServerConn(keyID string, chans <-chan ssh.NewChannel) {
2014-07-26 04:24:27 +00:00
for newChan := range chans {
if newChan.ChannelType() != "session" {
newChan.Reject(ssh.UnknownChannelType, "unknown channel type")
continue
}
ch, reqs, err := newChan.Accept()
2014-07-26 04:24:27 +00:00
if err != nil {
log.Error(3, "Error accepting channel: %v", err)
2014-07-26 04:24:27 +00:00
continue
}
go func(in <-chan *ssh.Request) {
defer ch.Close()
2014-07-26 04:24:27 +00:00
for req := range in {
payload := cleanCommand(string(req.Payload))
2014-07-26 04:24:27 +00:00
switch req.Type {
case "env":
args := strings.Split(strings.Replace(payload, "\x00", "", -1), "\v")
if len(args) != 2 {
log.Warn("SSH: Invalid env arguments: '%#v'", args)
2015-12-13 11:15:10 +00:00
continue
2014-07-26 04:24:27 +00:00
}
args[0] = strings.TrimLeft(args[0], "\x04")
_, _, err := com.ExecCmdBytes("env", args[0]+"="+args[1])
if err != nil {
log.Error(3, "env: %v", err)
return
2014-07-26 04:24:27 +00:00
}
case "exec":
cmdName := strings.TrimLeft(payload, "'()")
log.Trace("SSH: Payload: %v", cmdName)
args := []string{"serv", "key-" + keyID, "--config=" + setting.CustomConf}
log.Trace("SSH: Arguments: %v", args)
cmd := exec.Command(setting.AppPath, args...)
cmd.Env = append(
os.Environ(),
"SSH_ORIGINAL_COMMAND="+cmdName,
"SKIP_MINWINSVC=1",
)
stdout, err := cmd.StdoutPipe()
if err != nil {
log.Error(3, "SSH: StdoutPipe: %v", err)
return
}
stderr, err := cmd.StderrPipe()
if err != nil {
log.Error(3, "SSH: StderrPipe: %v", err)
return
}
input, err := cmd.StdinPipe()
if err != nil {
log.Error(3, "SSH: StdinPipe: %v", err)
return
2014-07-26 04:24:27 +00:00
}
2015-11-15 22:07:44 +00:00
// FIXME: check timeout
if err = cmd.Start(); err != nil {
log.Error(3, "SSH: Start: %v", err)
return
2015-11-14 18:21:31 +00:00
}
2016-01-25 19:04:46 +00:00
req.Reply(true, nil)
2015-11-14 18:21:31 +00:00
go io.Copy(input, ch)
io.Copy(ch, stdout)
io.Copy(ch.Stderr(), stderr)
if err = cmd.Wait(); err != nil {
log.Error(3, "SSH: Wait: %v", err)
return
}
ch.SendRequest("exit-status", false, []byte{0, 0, 0, 0})
return
default:
2014-07-26 04:24:27 +00:00
}
}
}(reqs)
2014-07-26 04:24:27 +00:00
}
}
func listen(config *ssh.ServerConfig, host string, port int) {
listener, err := net.Listen("tcp", host+":"+com.ToStr(port))
2014-07-26 04:24:27 +00:00
if err != nil {
log.Fatal(4, "Failed to start SSH server: %v", err)
2014-07-26 04:24:27 +00:00
}
for {
// Once a ServerConfig has been configured, connections can be accepted.
conn, err := listener.Accept()
if err != nil {
log.Error(3, "SSH: Error accepting incoming connection: %v", err)
2014-07-26 04:24:27 +00:00
continue
}
2014-07-26 04:24:27 +00:00
// Before use, a handshake must be performed on the incoming net.Conn.
// It must be handled in a separate goroutine,
// otherwise one user could easily block entire loop.
// For example, user could be asked to trust server key fingerprint and hangs.
go func() {
log.Trace("SSH: Handshaking for %s", conn.RemoteAddr())
sConn, chans, reqs, err := ssh.NewServerConn(conn, config)
if err != nil {
if err == io.EOF {
log.Warn("SSH: Handshaking was terminated: %v", err)
} else {
log.Error(3, "SSH: Error on handshaking: %v", err)
}
return
}
log.Trace("SSH: Connection from %s (%s)", sConn.RemoteAddr(), sConn.ClientVersion())
// The incoming Request channel must be serviced.
go ssh.DiscardRequests(reqs)
go handleServerConn(sConn.Permissions.Extensions["key-id"], chans)
}()
2014-07-26 04:24:27 +00:00
}
}
// Listen starts a SSH server listens on given port.
func Listen(host string, port int) {
2014-07-26 04:24:27 +00:00
config := &ssh.ServerConfig{
PublicKeyCallback: func(conn ssh.ConnMetadata, key ssh.PublicKey) (*ssh.Permissions, error) {
pkey, err := models.SearchPublicKeyByContent(strings.TrimSpace(string(ssh.MarshalAuthorizedKey(key))))
if err != nil {
log.Error(3, "SearchPublicKeyByContent: %v", err)
return nil, err
}
return &ssh.Permissions{Extensions: map[string]string{"key-id": com.ToStr(pkey.ID)}}, nil
2014-07-26 04:24:27 +00:00
},
}
2015-11-14 18:21:31 +00:00
keyPath := filepath.Join(setting.AppDataPath, "ssh/gogs.rsa")
if !com.IsExist(keyPath) {
2016-11-30 23:56:15 +00:00
filePath := filepath.Dir(keyPath)
if err := os.MkdirAll(filePath, os.ModePerm); err != nil {
log.Error(4, "Failed to create dir %s: %v", filePath, err)
2016-11-30 23:56:15 +00:00
}
2015-11-14 18:21:31 +00:00
_, stderr, err := com.ExecCmd("ssh-keygen", "-f", keyPath, "-t", "rsa", "-N", "")
if err != nil {
log.Fatal(4, "Failed to generate private key: %v - %s", err, stderr)
2015-11-14 18:21:31 +00:00
}
log.Trace("SSH: New private key is generateed: %s", keyPath)
2015-11-14 18:21:31 +00:00
}
privateBytes, err := ioutil.ReadFile(keyPath)
2014-07-26 04:24:27 +00:00
if err != nil {
log.Fatal(4, "SSH: Failed to load private key")
2014-07-26 04:24:27 +00:00
}
private, err := ssh.ParsePrivateKey(privateBytes)
if err != nil {
log.Fatal(4, "SSH: Failed to parse private key")
2014-07-26 04:24:27 +00:00
}
config.AddHostKey(private)
go listen(config, host, port)
2014-07-26 04:24:27 +00:00
}