Skip to content

Commit

Permalink
use native golang SSH library but ssh-keygen when enable built-in SSH…
Browse files Browse the repository at this point in the history
… server to remove dependent on that command lines
  • Loading branch information
lunny committed Feb 7, 2019
1 parent da1edbf commit f008f89
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 4 deletions.
4 changes: 2 additions & 2 deletions integrations/git_helper_for_declarative_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,20 +12,20 @@ import (
"net/http"
"net/url"
"os"
"os/exec"
"path/filepath"
"testing"
"time"

"code.gitea.io/git"
"code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/modules/ssh"
"github.com/Unknwon/com"
"github.com/stretchr/testify/assert"
)

func withKeyFile(t *testing.T, keyname string, callback func(string)) {
keyFile := filepath.Join(setting.AppDataPath, keyname)
err := exec.Command("ssh-keygen", "-f", keyFile, "-t", "rsa", "-N", "").Run()
err := ssh.GenKeyPair(keyFile)
assert.NoError(t, err)

//Setup ssh wrapper
Expand Down
44 changes: 42 additions & 2 deletions modules/ssh/ssh.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,10 @@
package ssh

import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"io"
"io/ioutil"
"net"
Expand Down Expand Up @@ -176,9 +180,9 @@ func Listen(host string, port int, ciphers []string, keyExchanges []string, macs
log.Error(4, "Failed to create dir %s: %v", filePath, err)
}

_, stderr, err := com.ExecCmd("ssh-keygen", "-f", keyPath, "-t", "rsa", "-N", "")
err := GenKeyPair(keyPath)
if err != nil {
log.Fatal(4, "Failed to generate private key: %v - %s", err, stderr)
log.Fatal(4, "Failed to generate private key: %v", err)
}
log.Trace("SSH: New private key is generateed: %s", keyPath)
}
Expand All @@ -195,3 +199,39 @@ func Listen(host string, port int, ciphers []string, keyExchanges []string, macs

go listen(config, host, port)
}

// GenKeyPair make a pair of public and private keys for SSH access.
// Public key is encoded in the format for inclusion in an OpenSSH authorized_keys file.
// Private Key generated is PEM encoded
func GenKeyPair(keyPath string) error {
privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
return err
}

privateKeyPEM := &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(privateKey)}
f, err := os.Create(keyPath)
if err != nil {
return err
}
defer f.Close()

if err := pem.Encode(f, privateKeyPEM); err != nil {
return err
}

// generate public key
pub, err := ssh.NewPublicKey(&privateKey.PublicKey)
if err != nil {
return err
}

public := ssh.MarshalAuthorizedKey(pub)
p, err := os.Create(keyPath + ".pub")
if err != nil {
return err
}
defer p.Close()
_, err = p.Write(public)
return err
}

0 comments on commit f008f89

Please sign in to comment.