Ejemplo n.º 1
0
func TestAgentForward(t *testing.T) {
	server := newServer(t)
	defer server.Shutdown()
	conn := server.Dial(clientConfig())
	defer conn.Close()

	keyring := agent.NewKeyring()
	keyring.Add(testPrivateKeys["dsa"], nil, "")
	pub := testPublicKeys["dsa"]

	sess, err := conn.NewSession()
	if err != nil {
		t.Fatalf("NewSession: %v", err)
	}
	if err := agent.RequestAgentForwarding(sess); err != nil {
		t.Fatalf("RequestAgentForwarding: %v", err)
	}

	if err := agent.ForwardToAgent(conn, keyring); err != nil {
		t.Fatalf("SetupForwardKeyring: %v", err)
	}
	out, err := sess.CombinedOutput("ssh-add -L")
	if err != nil {
		t.Fatalf("running ssh-add: %v, out %s", err, out)
	}
	key, _, _, _, err := ssh.ParseAuthorizedKey(out)
	if err != nil {
		t.Fatalf("ParseAuthorizedKey(%q): %v", out, err)
	}

	if !bytes.Equal(key.Marshal(), pub.Marshal()) {
		t.Fatalf("got key %s, want %s", ssh.MarshalAuthorizedKey(key), ssh.MarshalAuthorizedKey(pub))
	}
}
Ejemplo n.º 2
0
func theseTwoPublicKeysAreEqual(one, other ssh.PublicKey) bool {
	oneKeyMshld := ssh.MarshalAuthorizedKey(one)
	otherKeyMshld := ssh.MarshalAuthorizedKey(other)
	if len(oneKeyMshld) != len(otherKeyMshld) {
		return false
	}
	for i, elm := range oneKeyMshld {
		if elm != otherKeyMshld[i] {
			return false
		}
	}
	return true
}
Ejemplo n.º 3
0
// GenerateSSHKeyPair generates new key-pair for use with SSH.
func GenerateSSHKeyPair() (*SSHKeyPair, error) {
	priv, err := rsa.GenerateKey(rand.Reader, 1024)
	if err != nil {
		return nil, err
	}

	var privBuf bytes.Buffer

	privPEM := &pem.Block{
		Type:  "RSA PRIVATE KEY",
		Bytes: x509.MarshalPKCS1PrivateKey(priv),
	}

	if err := pem.Encode(&privBuf, privPEM); err != nil {
		return nil, err
	}

	pub, err := ssh.NewPublicKey(&priv.PublicKey)
	if err != nil {
		return nil, err
	}

	key := &SSHKeyPair{
		Private: bytes.TrimSpace(privBuf.Bytes()),
		Public:  bytes.TrimSpace(ssh.MarshalAuthorizedKey(pub)),
	}

	sum := sha1.Sum(key.Private)
	key.Name = "koding-ssh-keypair-" + hex.EncodeToString(sum[:])

	return key, nil
}
Ejemplo n.º 4
0
// ParseKey reads the given RSA private key and create a public one for it.
func ParseKey(pem string) (*Key, error) {
	p, err := ioutil.ReadFile(pem)
	if err != nil {
		return nil, err
	}
	key, err := ssh.ParseRawPrivateKey(p)
	if err != nil {
		return nil, err
	}
	rsaKey, ok := key.(*rsa.PrivateKey)
	if !ok {
		return nil, fmt.Errorf("%q is not a RSA key", pem)
	}
	pub, err := ssh.NewPublicKey(&rsaKey.PublicKey)
	if err != nil {
		return nil, err
	}
	// Compute key fingerprint.
	var buf bytes.Buffer
	for _, b := range md5.Sum(pub.Marshal()) {
		fmt.Fprintf(&buf, "%0.2x:", b)
	}
	return &Key{
		Label:       strings.TrimSuffix(filepath.Base(pem), ".pem"),               // trim .pem file extension
		Key:         string(bytes.TrimRight(ssh.MarshalAuthorizedKey(pub), "\n")), // trim newline
		Fingerprint: string(bytes.TrimRight(buf.Bytes(), ":")),                    // trim dangling colon
		Note:        "{}",
		Tags:        make(Tags),
	}, nil
}
Ejemplo n.º 5
0
func (g GitConfig) HideKey() GitConfig {
	if g.Key == "" {
		return g
	}
	key, err := ssh.ParseRawPrivateKey([]byte(g.Key))
	if err != nil {
		g.Key = secretReplacement
		return g
	}

	privKey, ok := key.(*rsa.PrivateKey)
	if !ok {
		g.Key = secretReplacement
		return g
	}

	pubKey, err := ssh.NewPublicKey(&privKey.PublicKey)
	if err != nil {
		g.Key = secretReplacement
		return g
	}

	g.Key = string(ssh.MarshalAuthorizedKey(pubKey))
	return g
}
Ejemplo n.º 6
0
func handleAuth(conn ssh.ConnMetadata, key ssh.PublicKey) (*ssh.Permissions, error) {
	if *authHook == "" {
		// allow all
		return &ssh.Permissions{
			Extensions: map[string]string{
				"user": conn.User(),
			},
		}, nil
	}

	keydata := string(bytes.TrimSpace(ssh.MarshalAuthorizedKey(key)))
	cmd, err := handlerCmd(*authHook, conn.User(), keydata)
	if err != nil {
		return nil, err
	}
	var output bytes.Buffer
	cmd.Stdout = &output
	cmd.Stderr = &output
	status, err := exitStatus(cmd.Run())
	if err != nil {
		return nil, err
	}
	if status.Status == 0 {
		return &ssh.Permissions{
			Extensions: map[string]string{
				"environ": strings.Trim(output.String(), "\n"),
				"user":    conn.User(),
			},
		}, nil
	}
	debug("authentication hook status:", status.Status)
	return nil, fmt.Errorf("authentication failed")
}
Ejemplo n.º 7
0
func generateSshKeyPair() Keypair {

	priv, err := rsa.GenerateKey(rand.Reader, 2014)
	if err != nil {
		util.Fatalf("Error generating key", err)
	}

	// Get der format. priv_der []byte
	priv_der := x509.MarshalPKCS1PrivateKey(priv)

	// pem.Block
	// blk pem.Block
	priv_blk := pem.Block{
		Type:    "RSA PRIVATE KEY",
		Headers: nil,
		Bytes:   priv_der,
	}

	// Resultant private key in PEM format.
	// priv_pem string
	priv_pem := string(pem.EncodeToMemory(&priv_blk))

	// Public Key generation
	sshPublicKey, err := ssh.NewPublicKey(&priv.PublicKey)
	pubBytes := ssh.MarshalAuthorizedKey(sshPublicKey)

	return Keypair{
		pub:  []byte(pubBytes),
		priv: []byte(priv_pem),
	}
}
Ejemplo n.º 8
0
func EncodeSSHKey(public *rsa.PublicKey) ([]byte, error) {
	publicKey, err := ssh.NewPublicKey(public)
	if err != nil {
		return nil, err
	}
	return ssh.MarshalAuthorizedKey(publicKey), nil
}
Ejemplo n.º 9
0
func CmdAdd(name, keyPath, svcName string, id IDeployKeys, is services.IServices) error {
	if strings.ContainsAny(name, config.InvalidChars) {
		return fmt.Errorf("Invalid SSH key name. Names must not contain the following characters: %s", config.InvalidChars)
	}
	if _, err := os.Stat(keyPath); os.IsNotExist(err) {
		return fmt.Errorf("A file does not exist at path '%s'", keyPath)
	}
	service, err := is.RetrieveByLabel(svcName)
	if err != nil {
		return err
	}
	if service == nil {
		return fmt.Errorf("Could not find a service with the label \"%s\". You can list services with the \"catalyze services\" command.", svcName)
	}
	if service.Type != "code" {
		return fmt.Errorf("You can only add deploy keys to code services, not %s services", service.Type)
	}
	key, err := ioutil.ReadFile(keyPath)
	if err != nil {
		return err
	}
	k, err := id.ParsePublicKey(key)
	if err != nil {
		return err
	}
	key = ssh.MarshalAuthorizedKey(k)
	return id.Add(name, "ssh", string(key), service.ID)
}
Ejemplo n.º 10
0
func sshkey(bits int) (string, string, string, error) {
	key, err := rsa.GenerateKey(rand.Reader, bits)
	if err != nil {
		return "", "", "", err
	}

	private := pem.EncodeToMemory(
		&pem.Block{
			Type:  "RSA PRIVATE KEY",
			Bytes: x509.MarshalPKCS1PrivateKey(key),
		},
	)

	pub := key.Public()
	pubkey, err := ssh.NewPublicKey(pub)
	if err != nil {
		return "", "", "", err
	}
	public := ssh.MarshalAuthorizedKey(pubkey)

	var fp []string
	f := []byte(fmt.Sprintf("%x", md5.Sum(pubkey.Marshal())))
	for i := 0; i < len(f); i += 2 {
		fp = append(fp, string(f[i:i+2]))
	}
	fingerprint := strings.Join(fp, ":")

	return string(private), string(public), string(fingerprint), nil
}
Ejemplo n.º 11
0
func CreatePrivateKey(d *schema.ResourceData, meta interface{}) error {
	keyAlgoName := d.Get("algorithm").(string)
	var keyFunc keyAlgo
	var ok bool
	if keyFunc, ok = keyAlgos[keyAlgoName]; !ok {
		return fmt.Errorf("invalid key_algorithm %#v", keyAlgoName)
	}

	key, err := keyFunc(d)
	if err != nil {
		return err
	}

	var keyPemBlock *pem.Block
	switch k := key.(type) {
	case *rsa.PrivateKey:
		keyPemBlock = &pem.Block{
			Type:  "RSA PRIVATE KEY",
			Bytes: x509.MarshalPKCS1PrivateKey(k),
		}
	case *ecdsa.PrivateKey:
		keyBytes, err := x509.MarshalECPrivateKey(k)
		if err != nil {
			return fmt.Errorf("error encoding key to PEM: %s", err)
		}
		keyPemBlock = &pem.Block{
			Type:  "EC PRIVATE KEY",
			Bytes: keyBytes,
		}
	default:
		return fmt.Errorf("unsupported private key type")
	}
	keyPem := string(pem.EncodeToMemory(keyPemBlock))

	pubKey := publicKey(key)
	pubKeyBytes, err := x509.MarshalPKIXPublicKey(pubKey)
	if err != nil {
		return fmt.Errorf("failed to marshal public key: %s", err)
	}
	pubKeyPemBlock := &pem.Block{
		Type:  "PUBLIC KEY",
		Bytes: pubKeyBytes,
	}

	d.SetId(hashForState(string((pubKeyBytes))))
	d.Set("private_key_pem", keyPem)
	d.Set("public_key_pem", string(pem.EncodeToMemory(pubKeyPemBlock)))

	sshPubKey, err := ssh.NewPublicKey(pubKey)
	if err == nil {
		// Not all EC types can be SSH keys, so we'll produce this only
		// if an appropriate type was selected.
		sshPubKeyBytes := ssh.MarshalAuthorizedKey(sshPubKey)
		d.Set("public_key_openssh", string(sshPubKeyBytes))
	} else {
		d.Set("public_key_openssh", "")
	}

	return nil
}
Ejemplo n.º 12
0
func CmdAdd(name, path string, ik IKeys, id deploykeys.IDeployKeys) error {
	if strings.ContainsAny(name, config.InvalidChars) {
		return fmt.Errorf("Invalid key name. Names must not contain the following characters: %s", config.InvalidChars)
	}
	fullPath, err := homedir.Expand(path)
	if err != nil {
		return err
	}
	keyBytes, err := ioutil.ReadFile(fullPath)
	if err != nil {
		return err
	}
	k, err := id.ParsePublicKey(keyBytes)
	if err != nil {
		return err
	}
	key := ssh.MarshalAuthorizedKey(k)
	if err != nil {
		return err
	}
	err = ik.Add(name, string(key))
	if err != nil {
		return err
	}
	logrus.Printf("Key '%s' added to your account.", name)
	logrus.Println("If you use an ssh-agent, make sure you add this key to your ssh-agent in order to push code")
	return nil
}
func getSshKey(d *schema.ResourceData, path string) (privatekey string, publickey string, err error) {
	pemBytes, err := ioutil.ReadFile(path)

	if err != nil {
		return "", "", err
	}

	block, _ := pem.Decode(pemBytes)

	if block == nil {
		return "", "", errors.New("File " + path + " contains nothing")
	}

	priv, err := x509.ParsePKCS1PrivateKey(block.Bytes)

	if err != nil {
		return "", "", err
	}

	priv_blk := pem.Block{
		Type:    "RSA PRIVATE KEY",
		Headers: nil,
		Bytes:   x509.MarshalPKCS1PrivateKey(priv),
	}

	pub, err := ssh.NewPublicKey(&priv.PublicKey)
	if err != nil {
		return "", "", err
	}
	publickey = string(ssh.MarshalAuthorizedKey(pub))
	privatekey = string(pem.EncodeToMemory(&priv_blk))

	return privatekey, publickey, nil
}
Ejemplo n.º 14
0
// Serialize an RSA public key to disk format, specifically to the
// format used by SSH. Should return nil if the conversion fails.
func RSAPubKeyToDisk(rsaPubKey *rsa.PublicKey) (out []byte, err error) {
	pubKey, err := ssh.NewPublicKey(rsaPubKey)
	if err == nil {
		out = ssh.MarshalAuthorizedKey(pubKey)
	}
	return out, nil
}
Ejemplo n.º 15
0
func NewRandomKeyPair() (*KeyPair, error) {
	privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
	if err != nil {
		return nil, err
	}

	privateKeyDer := x509.MarshalPKCS1PrivateKey(privateKey)
	privateKeyBlock := pem.Block{
		Type:    "RSA PRIVATE KEY",
		Headers: nil,
		Bytes:   privateKeyDer,
	}
	privateKeyPem := string(pem.EncodeToMemory(&privateKeyBlock))

	publicKey := privateKey.PublicKey
	pub, err := ssh.NewPublicKey(&publicKey)
	if err != nil {
		return nil, err
	}
	pubBytes := ssh.MarshalAuthorizedKey(pub)

	return &KeyPair{
		PublicKey:  string(pubBytes),
		PrivateKey: privateKeyPem,
	}, nil
}
Ejemplo n.º 16
0
// MakeSSHKeyPair 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
// StackOverflow: Greg http://stackoverflow.com/users/328645/greg in
// http://stackoverflow.com/questions/21151714/go-generate-an-ssh-public-key
// No licence added
func makeSSHKeyPair(bits int, pubKeyPath, privateKeyPath string) error {
	if bits < 1024 {
		return errors.New("Reject using too few bits for key")
	}
	privateKey, err := rsa.GenerateKey(rand.Reader, bits)
	if err != nil {
		return err
	}

	// generate and write private key as PEM
	privateKeyFile, err := os.OpenFile(privateKeyPath, os.O_WRONLY|os.O_CREATE, 0600)
	defer privateKeyFile.Close()
	if err != nil {
		return err
	}
	privateKeyPEM := &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(privateKey)}
	if err := pem.Encode(privateKeyFile, privateKeyPEM); err != nil {
		return err
	}

	// generate and write public key
	pub, err := ssh.NewPublicKey(&privateKey.PublicKey)
	if err != nil {
		return err
	}
	return ioutil.WriteFile(pubKeyPath, ssh.MarshalAuthorizedKey(pub), 0600)
}
Ejemplo n.º 17
0
// Listen starts a SSH server listens on given port.
func Listen(port int) {
	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
		},
	}

	keyPath := filepath.Join(setting.AppDataPath, "ssh/gogs.rsa")
	if !com.IsExist(keyPath) {
		os.MkdirAll(filepath.Dir(keyPath), os.ModePerm)
		_, stderr, err := com.ExecCmd("ssh-keygen", "-f", keyPath, "-t", "rsa", "-N", "")
		if err != nil {
			panic(fmt.Sprintf("Fail to generate private key: %v - %s", err, stderr))
		}
		log.Trace("New private key is generateed: %s", keyPath)
	}

	privateBytes, err := ioutil.ReadFile(keyPath)
	if err != nil {
		panic("Fail to load private key")
	}
	private, err := ssh.ParsePrivateKey(privateBytes)
	if err != nil {
		panic("Fail to parse private key")
	}
	config.AddHostKey(private)

	go listen(config, port)
}
Ejemplo n.º 18
0
func keyAlert(metadata ssh.ConnMetadata, key ssh.PublicKey) string {
	meta := baseAlertMap(metadata)
	meta["authtype"] = "publickey"
	meta["key"] = string(ssh.MarshalAuthorizedKey(key))

	return alert.NewSplunkAlertMessage(meta)
}
Ejemplo n.º 19
0
func (S) TestPatterns(c *C) {
	const sep = " "
	var input bytes.Buffer

	key := genPublicKey(c)
	keyBytes := bytes.TrimRight(bytes.TrimSpace(ssh.MarshalAuthorizedKey(key)), "\n")

	// format: pattern
	input.WriteString("*.example")
	input.WriteString(sep)
	input.Write(keyBytes)
	input.WriteString("\n")

	// format: negated pattern
	input.WriteString("!*.example.or?")
	input.WriteString(sep)
	input.Write(keyBytes)
	input.WriteString("\n")

	k, err := Unmarshal(bytes.NewReader(input.Bytes()))
	c.Assert(err, IsNil)

	// Test HostKeyCallback
	addr := &net.TCPAddr{
		Port: 22,
	}
	c.Assert(k.HostKeyCallback("foo.example:22", addr, key), IsNil)                         // pattern match
	c.Assert(k.HostKeyCallback("foo.example.org:22", addr, key), Equals, HostNotFoundError) // negated pattern match
	c.Assert(k.HostKeyCallback("anything.example.com:22", addr, key), IsNil)                // negated pattern miss

	// Make sure output is the same as input
	var output bytes.Buffer
	c.Assert(k.Marshal(&output), IsNil)
	c.Assert(output.String(), Equals, input.String())
}
Ejemplo n.º 20
0
// helper function that marshalls an RSA Public Key to an SSH
// .authorized_keys format
func MarshalPublicKey(pubkey *rsa.PublicKey) string {
	pk, err := ssh.NewPublicKey(pubkey)
	if err != nil {
		return ""
	}

	return string(ssh.MarshalAuthorizedKey(pk))
}
Ejemplo n.º 21
0
func uploadPublicKey(client *godo.Client, publicKey ssh.PublicKey, id string) (*godo.Key, error) {
	createRequest := &godo.KeyCreateRequest{
		Name:      keyBaseName + id,
		PublicKey: string(ssh.MarshalAuthorizedKey(publicKey)),
	}
	key, _, err := client.Keys.Create(createRequest)
	return key, err
}
Ejemplo n.º 22
0
func GetAuthorizedKey(seed string) ([]byte, error) {
	key := generateKey(seed)
	ssh_key, err := ssh.NewPublicKey(&key.PublicKey)
	if err != nil {
		return nil, err
	}
	return ssh.MarshalAuthorizedKey(ssh_key), nil
}
Ejemplo n.º 23
0
//export c_MarshalAuthorizedKey
func c_MarshalAuthorizedKey(key uint64) (*C.char, int) {
	obj, ok := GetObject(Handle(key))
	if !ok {
		return nil, 0
	}
	obj_key := obj.(ssh.PublicKey)
	mak := ssh.MarshalAuthorizedKey(obj_key)
	return C.CString(string(mak)), len(mak)
}
Ejemplo n.º 24
0
func TestCreateServerWithKeyPair(t *testing.T) {
	client, err := newClient()
	th.AssertNoErr(t, err)

	if testing.Short() {
		t.Skip("Skipping test that requires server creation in short mode.")
	}

	privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
	publicKey := privateKey.PublicKey
	pub, err := ssh.NewPublicKey(&publicKey)
	th.AssertNoErr(t, err)
	pubBytes := ssh.MarshalAuthorizedKey(pub)
	pk := string(pubBytes)

	kp, err := keypairs.Create(client, keypairs.CreateOpts{
		Name:      keyName,
		PublicKey: pk,
	}).Extract()
	th.AssertNoErr(t, err)
	t.Logf("Created key pair: %s\n", kp)

	choices, err := ComputeChoicesFromEnv()
	th.AssertNoErr(t, err)

	name := tools.RandomString("Gophercloud-", 8)
	t.Logf("Creating server [%s] with key pair.", name)

	serverCreateOpts := servers.CreateOpts{
		Name:      name,
		FlavorRef: choices.FlavorID,
		ImageRef:  choices.ImageID,
	}

	server, err := servers.Create(client, keypairs.CreateOptsExt{
		serverCreateOpts,
		keyName,
	}).Extract()
	th.AssertNoErr(t, err)
	defer servers.Delete(client, server.ID)
	if err = waitForStatus(client, server, "ACTIVE"); err != nil {
		t.Fatalf("Unable to wait for server: %v", err)
	}

	server, err = servers.Get(client, server.ID).Extract()
	t.Logf("Created server: %+v\n", server)
	th.AssertNoErr(t, err)
	th.AssertEquals(t, server.KeyName, keyName)

	t.Logf("Deleting key pair [%s]...", kp.Name)
	err = keypairs.Delete(client, keyName).ExtractErr()
	th.AssertNoErr(t, err)

	t.Logf("Deleting server [%s]...", name)
}
Ejemplo n.º 25
0
// newServer returns a new mock ssh server.
func newServer(t *testing.T) *server {
	if testing.Short() {
		t.Skip("skipping test due to -short")
	}
	dir, err := ioutil.TempDir("", "sshtest")
	if err != nil {
		t.Fatal(err)
	}
	f, err := os.Create(filepath.Join(dir, "sshd_config"))
	if err != nil {
		t.Fatal(err)
	}
	err = configTmpl.Execute(f, map[string]string{
		"Dir": dir,
	})
	if err != nil {
		t.Fatal(err)
	}
	f.Close()

	for k, v := range testdata.PEMBytes {
		filename := "id_" + k
		writeFile(filepath.Join(dir, filename), v)
		writeFile(filepath.Join(dir, filename+".pub"), ssh.MarshalAuthorizedKey(testPublicKeys[k]))
	}

	var authkeys bytes.Buffer
	for k, _ := range testdata.PEMBytes {
		authkeys.Write(ssh.MarshalAuthorizedKey(testPublicKeys[k]))
	}
	writeFile(filepath.Join(dir, "authorized_keys"), authkeys.Bytes())

	return &server{
		t:          t,
		configfile: f.Name(),
		cleanup: func() {
			if err := os.RemoveAll(dir); err != nil {
				t.Error(err)
			}
		},
	}
}
Ejemplo n.º 26
0
func renderHostLine(addr string, key gossh.PublicKey) []byte {
	keyByte := gossh.MarshalAuthorizedKey(key)
	// allocate line space in advance
	length := len(addr) + 1 + len(keyByte)
	line := make([]byte, 0, length)

	w := bytes.NewBuffer(line)
	w.Write([]byte(addr))
	w.WriteByte(' ')
	w.Write(keyByte)
	return w.Bytes()
}
Ejemplo n.º 27
0
// PublicKey returns the public key for any private key. The public key is
// suitable to be added into an authorized_keys file, and has the comment
// passed in as the comment part of the key.
func PublicKey(privateKey []byte, comment string) (string, error) {
	signer, err := ssh.ParsePrivateKey(privateKey)
	if err != nil {
		return "", errors.Annotate(err, "failed to load key")
	}

	auth_key := string(ssh.MarshalAuthorizedKey(signer.PublicKey()))
	// Strip off the trailing new line so we can add a comment.
	auth_key = strings.TrimSpace(auth_key)
	public := fmt.Sprintf("%s %s\n", auth_key, comment)

	return public, nil
}
Ejemplo n.º 28
0
// PubKeys exports the list of public keys in authorized_keys format.
//
// Expected to be used directly from javascript, so panic (i.e. throw)
// rather than returning an error object.
func (a *Agent) PubKeys() string {
	signers, err := a.Signers()
	if err != nil {
		panic(err)
	}

	var keys []byte
	for _, signer := range signers {
		keys = append(keys, ssh.MarshalAuthorizedKey(signer.PublicKey())...)
		keys = append(keys, '\n')
	}

	return strings.TrimSpace(string(keys))
}
Ejemplo n.º 29
0
func GenerateECDSAKeyPair(keysize int, password string) (public, private []byte, err error) {
	var curve elliptic.Curve
	switch keysize {
	case 256:
		curve = elliptic.P256()
	case 384:
		curve = elliptic.P384()
	case 521:
		curve = elliptic.P521()
	default:
		return
	}

	// Generate the public/private key pair
	prvKey, err := ecdsa.GenerateKey(curve, rand.Reader)
	if err != nil {
		return
	}

	// Marshal the public key
	sshPubKey, err := ssh.NewPublicKey(&prvKey.PublicKey)
	if err != nil {
		return
	}
	public = ssh.MarshalAuthorizedKey(sshPubKey)

	// Marshal the private key
	prvKeyDer, err := x509.MarshalECPrivateKey(prvKey)
	if err != nil {
		return
	}
	block := &pem.Block{Type: "EC PRIVATE KEY", Bytes: prvKeyDer}

	// Encrypt the private key
	if len(password) != 0 {
		// AES-128 is the only option for private key encryption just like in ssh-keygen.
		block, err = x509.EncryptPEMBlock(rand.Reader,
			"EC PRIVATE KEY",
			prvKeyDer,
			[]byte(password),
			x509.PEMCipherAES128)
		if err != nil {
			return
		}
	}

	private = pem.EncodeToMemory(block)
	return
}
Ejemplo n.º 30
0
func newKey(name, user, raw string) (*Key, error) {
	key, comment, _, _, err := ssh.ParseAuthorizedKey([]byte(raw))
	if err != nil {
		return nil, ErrInvalidKey
	}
	body := ssh.MarshalAuthorizedKey(key.(ssh.PublicKey))
	k := Key{
		Name:      name,
		Body:      string(body),
		Comment:   comment,
		UserName:  user,
		CreatedAt: time.Now(),
	}
	return &k, nil
}