mirror of
https://github.com/coder/coder.git
synced 2026-09-24 15:04:27 +08:00
feat: Add user scoped git ssh keys (#834)
This commit is contained in:
@@ -0,0 +1,125 @@
|
||||
// This file contains an adapted version of the original implementation available
|
||||
// under the following URL: https://github.com/mikesmitty/edkey/blob/3356ea4e686a1d47ae5d2d4c3cbc1832ce2df626/edkey.go
|
||||
|
||||
// The following changes have been made:
|
||||
// * Replaced usage of math/rand with crypto/rand
|
||||
|
||||
// This should be removed soon as support for marshaling ED25519 private keys
|
||||
// is added to the Golang standard library.
|
||||
// See: https://github.com/golang/go/issues/37132
|
||||
|
||||
// --- BEGIN ORIGINAL LICENSE ---
|
||||
// MIT License
|
||||
|
||||
// Copyright (c) 2017 Michael Smith
|
||||
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
|
||||
// The above copyright notice and this permission notice shall be included in all
|
||||
// copies or substantial portions of the Software.
|
||||
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
// SOFTWARE.
|
||||
// --- END ORIGINAL LICENSE ---
|
||||
|
||||
package gitsshkey
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/binary"
|
||||
|
||||
"golang.org/x/crypto/ed25519"
|
||||
"golang.org/x/crypto/ssh"
|
||||
"golang.org/x/xerrors"
|
||||
)
|
||||
|
||||
func MarshalED25519PrivateKey(key ed25519.PrivateKey) ([]byte, error) {
|
||||
// Add our key header (followed by a null byte)
|
||||
magic := append([]byte("openssh-key-v1"), 0)
|
||||
|
||||
var msg struct {
|
||||
CipherName string
|
||||
KdfName string
|
||||
KdfOpts string
|
||||
NumKeys uint32
|
||||
PubKey []byte
|
||||
PrivKeyBlock []byte
|
||||
}
|
||||
|
||||
// Fill out the private key fields
|
||||
pk1 := struct {
|
||||
Check1 uint32
|
||||
Check2 uint32
|
||||
Keytype string
|
||||
Pub []byte
|
||||
Priv []byte
|
||||
Comment string
|
||||
Pad []byte `ssh:"rest"`
|
||||
}{}
|
||||
|
||||
// Random check bytes
|
||||
var check uint32
|
||||
if err := binary.Read(rand.Reader, binary.BigEndian, &check); err != nil {
|
||||
return nil, xerrors.Errorf("generate random bytes: %w", err)
|
||||
}
|
||||
|
||||
pk1.Check1 = check
|
||||
pk1.Check2 = check
|
||||
|
||||
// Set our key type
|
||||
pk1.Keytype = ssh.KeyAlgoED25519
|
||||
|
||||
// Add the pubkey to the optionally-encrypted block
|
||||
pk, ok := key.Public().(ed25519.PublicKey)
|
||||
if !ok {
|
||||
return nil, xerrors.Errorf("ed25519.PublicKey type assertion failed on an ed25519 public key")
|
||||
}
|
||||
pubKey := []byte(pk)
|
||||
pk1.Pub = pubKey
|
||||
|
||||
// Add our private key
|
||||
pk1.Priv = []byte(key)
|
||||
|
||||
// Might be useful to put something in here at some point
|
||||
pk1.Comment = ""
|
||||
|
||||
// Add some padding to match the encryption block size within PrivKeyBlock (without Pad field)
|
||||
// 8 doesn't match the documentation, but that's what ssh-keygen uses for unencrypted keys. *shrug*
|
||||
bs := 8
|
||||
blockLen := len(ssh.Marshal(pk1))
|
||||
padLen := (bs - (blockLen % bs)) % bs
|
||||
pk1.Pad = make([]byte, padLen)
|
||||
|
||||
// Padding is a sequence of bytes like: 1, 2, 3...
|
||||
for i := 0; i < padLen; i++ {
|
||||
pk1.Pad[i] = byte(i + 1)
|
||||
}
|
||||
|
||||
// Generate the pubkey prefix "\0\0\0\nssh-ed25519\0\0\0 "
|
||||
prefix := []byte{0x0, 0x0, 0x0, 0x0b}
|
||||
prefix = append(prefix, []byte(ssh.KeyAlgoED25519)...)
|
||||
prefix = append(prefix, []byte{0x0, 0x0, 0x0, 0x20}...)
|
||||
prefix = append(prefix, pubKey...)
|
||||
|
||||
// Only going to support unencrypted keys for now
|
||||
msg.CipherName = "none"
|
||||
msg.KdfName = "none"
|
||||
msg.KdfOpts = ""
|
||||
msg.NumKeys = 1
|
||||
msg.PubKey = prefix
|
||||
msg.PrivKeyBlock = ssh.Marshal(pk1)
|
||||
|
||||
magic = append(magic, ssh.Marshal(msg)...)
|
||||
|
||||
return magic, nil
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
package gitsshkey
|
||||
|
||||
import (
|
||||
"crypto"
|
||||
"crypto/ecdsa"
|
||||
"crypto/ed25519"
|
||||
"crypto/elliptic"
|
||||
"crypto/rand"
|
||||
"crypto/rsa"
|
||||
"crypto/x509"
|
||||
"encoding/pem"
|
||||
"strings"
|
||||
|
||||
"golang.org/x/crypto/ssh"
|
||||
"golang.org/x/xerrors"
|
||||
)
|
||||
|
||||
type Algorithm string
|
||||
|
||||
const (
|
||||
// AlgorithmEd25519 is the Edwards-curve Digital Signature Algorithm using Curve25519
|
||||
AlgorithmEd25519 Algorithm = "ed25519"
|
||||
// AlgorithmECDSA is the Digital Signature Algorithm (DSA) using NIST Elliptic Curve
|
||||
AlgorithmECDSA Algorithm = "ecdsa"
|
||||
// AlgorithmRSA4096 is the venerable Rivest-Shamir-Adleman algorithm
|
||||
// and creates a key with a fixed size of 4096-bit.
|
||||
AlgorithmRSA4096 Algorithm = "rsa4096"
|
||||
)
|
||||
|
||||
// ParseAlgorithm returns a valid Algorithm or error if input is not a valid.
|
||||
func ParseAlgorithm(t string) (Algorithm, error) {
|
||||
ok := []string{
|
||||
string(AlgorithmEd25519),
|
||||
string(AlgorithmECDSA),
|
||||
string(AlgorithmRSA4096),
|
||||
}
|
||||
|
||||
for _, a := range ok {
|
||||
if strings.EqualFold(a, t) {
|
||||
return Algorithm(a), nil
|
||||
}
|
||||
}
|
||||
|
||||
return "", xerrors.Errorf(`invalid key type: %s, must be one of: %s`, t, strings.Join(ok, ","))
|
||||
}
|
||||
|
||||
// Generate creates a private key in the OpenSSH PEM format and public key in
|
||||
// the authorized key format.
|
||||
func Generate(algo Algorithm) (privateKey string, publicKey string, err error) {
|
||||
switch algo {
|
||||
case AlgorithmEd25519:
|
||||
return ed25519KeyGen()
|
||||
case AlgorithmECDSA:
|
||||
return ecdsaKeyGen()
|
||||
case AlgorithmRSA4096:
|
||||
return rsa4096KeyGen()
|
||||
default:
|
||||
return "", "", xerrors.Errorf("invalid algorithm: %s", algo)
|
||||
}
|
||||
}
|
||||
|
||||
// ed25519KeyGen returns an ED25519-based SSH private key.
|
||||
func ed25519KeyGen() (privateKey string, publicKey string, err error) {
|
||||
_, privateKeyRaw, err := ed25519.GenerateKey(rand.Reader)
|
||||
if err != nil {
|
||||
return "", "", xerrors.Errorf("generate ed25519 private key: %w", err)
|
||||
}
|
||||
|
||||
// NOTE: as of the time of writing, x/crypto/ssh is unable to marshal an ED25519 private key
|
||||
// into the format expected by OpenSSH. See: https://github.com/golang/go/issues/37132
|
||||
// Until this support is added, using a third-party implementation.
|
||||
byt, err := MarshalED25519PrivateKey(privateKeyRaw)
|
||||
if err != nil {
|
||||
return "", "", xerrors.Errorf("marshal ed25519 private key: %w", err)
|
||||
}
|
||||
|
||||
return generateKeys(pem.Block{
|
||||
Type: "OPENSSH PRIVATE KEY",
|
||||
Bytes: byt,
|
||||
}, privateKeyRaw)
|
||||
}
|
||||
|
||||
// ecdsaKeyGen returns an ECDSA-based SSH private key.
|
||||
func ecdsaKeyGen() (privateKey string, publicKey string, err error) {
|
||||
privateKeyRaw, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
|
||||
if err != nil {
|
||||
return "", "", xerrors.Errorf("generate ecdsa private key: %w", err)
|
||||
}
|
||||
byt, err := x509.MarshalECPrivateKey(privateKeyRaw)
|
||||
if err != nil {
|
||||
return "", "", xerrors.Errorf("marshal private key: %w", err)
|
||||
}
|
||||
|
||||
return generateKeys(pem.Block{
|
||||
Type: "EC PRIVATE KEY",
|
||||
Bytes: byt,
|
||||
}, privateKeyRaw)
|
||||
}
|
||||
|
||||
// rsaKeyGen returns an RSA-based SSH private key of size 4096.
|
||||
//
|
||||
// Administrators may configure this for SSH key compatibility with Azure DevOps.
|
||||
func rsa4096KeyGen() (privateKey string, publicKey string, err error) {
|
||||
privateKeyRaw, err := rsa.GenerateKey(rand.Reader, 4096)
|
||||
if err != nil {
|
||||
return "", "", xerrors.Errorf("generate RSA4096 private key: %w", err)
|
||||
}
|
||||
|
||||
return generateKeys(pem.Block{
|
||||
Type: "RSA PRIVATE KEY",
|
||||
Bytes: x509.MarshalPKCS1PrivateKey(privateKeyRaw),
|
||||
}, privateKeyRaw)
|
||||
}
|
||||
|
||||
func generateKeys(block pem.Block, cp crypto.Signer) (privateKey string, publicKey string, err error) {
|
||||
pkBytes := pem.EncodeToMemory(&block)
|
||||
privateKey = string(pkBytes)
|
||||
|
||||
publicKeyRaw := cp.Public()
|
||||
p, err := ssh.NewPublicKey(publicKeyRaw)
|
||||
if err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
publicKey = string(ssh.MarshalAuthorizedKey(p))
|
||||
|
||||
return privateKey, publicKey, nil
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package gitsshkey_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
"golang.org/x/crypto/ssh"
|
||||
|
||||
"github.com/coder/coder/coderd/gitsshkey"
|
||||
"github.com/coder/coder/cryptorand"
|
||||
)
|
||||
|
||||
func TestGitSSHKeys(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
verifyKeyPair := func(t *testing.T, private, public string) {
|
||||
signer, err := ssh.ParsePrivateKey([]byte(private))
|
||||
require.NoError(t, err)
|
||||
p, err := ssh.ParsePublicKey(signer.PublicKey().Marshal())
|
||||
require.NoError(t, err)
|
||||
publicKey := string(ssh.MarshalAuthorizedKey(p))
|
||||
require.Equal(t, publicKey, public)
|
||||
}
|
||||
|
||||
t.Run("Ed25519", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
pv, pb, err := gitsshkey.Generate(gitsshkey.AlgorithmEd25519)
|
||||
require.NoError(t, err)
|
||||
verifyKeyPair(t, pv, pb)
|
||||
})
|
||||
t.Run("ECDSA", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
pv, pb, err := gitsshkey.Generate(gitsshkey.AlgorithmECDSA)
|
||||
require.NoError(t, err)
|
||||
verifyKeyPair(t, pv, pb)
|
||||
})
|
||||
t.Run("RSA4096", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
pv, pb, err := gitsshkey.Generate(gitsshkey.AlgorithmRSA4096)
|
||||
require.NoError(t, err)
|
||||
verifyKeyPair(t, pv, pb)
|
||||
})
|
||||
t.Run("ParseAlgorithm", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
_, err := gitsshkey.ParseAlgorithm(string(gitsshkey.AlgorithmEd25519))
|
||||
require.NoError(t, err)
|
||||
_, err = gitsshkey.ParseAlgorithm(string(gitsshkey.AlgorithmECDSA))
|
||||
require.NoError(t, err)
|
||||
_, err = gitsshkey.ParseAlgorithm(string(gitsshkey.AlgorithmRSA4096))
|
||||
require.NoError(t, err)
|
||||
r, _ := cryptorand.String(6)
|
||||
_, err = gitsshkey.ParseAlgorithm(r)
|
||||
require.Error(t, err, "random string should fail")
|
||||
_, err = gitsshkey.ParseAlgorithm("")
|
||||
require.Error(t, err, "empty string should fail")
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user