Exemplo n.º 1
0
// Key method for ssh.ClientKeyring interface
func (k *SimpleKeychain) Key(i int) (ssh.PublicKey, error) {
	if i < 0 || i >= len(k.keys) {
		return nil, nil
	}
	switch key := k.keys[i].(type) {
	case *rsa.PrivateKey:
		return ssh.NewPublicKey(&key.PublicKey)
	case *dsa.PrivateKey:
		return ssh.NewPublicKey(&key.PublicKey)
	}
	panic("unknown key type")
}
Exemplo n.º 2
0
func (k *Keychain) Key(i int) (key ssh.PublicKey, err error) {
	if i < 0 || i >= len(k.keys) {
		return nil, nil
	}

	switch key := k.keys[i].(type) {
	case *rsa.PrivateKey:
		return ssh.NewPublicKey(&key.PublicKey)
	case *dsa.PrivateKey:
		return ssh.NewPublicKey(&key.PublicKey)
	}

	return nil, errors.New("ssh: Unknown key type")
}
Exemplo n.º 3
0
// CreateSSHKey is used to generate rsa private & public keys that are used to
// set keys for ssh login to a server.
func CreateSSHKey() (string, string, error) {

	pk, e := rsa.GenerateKey(rand.Reader, 2014)
	if e != nil {
		return "", "", e
	}

	pkDer := x509.MarshalPKCS1PrivateKey(pk)
	pkBlk := pem.Block{
		Type:    "RSA PRIVATE KEY",
		Headers: nil,
		Bytes:   pkDer,
	}
	pkPem := string(pem.EncodeToMemory(&pkBlk))

	pubK := pk.PublicKey

	pub, e := ssh.NewPublicKey(&pubK)
	if e != nil {
		return "", "", e
	}

	pubBytes := ssh.MarshalAuthorizedKey(pub)

	return string(pkPem), string(pubBytes), nil
}
Exemplo n.º 4
0
// Run executes the Packer build step that generates SSH key pairs.
func (s *StepCreateSSHKey) Run(state multistep.StateBag) multistep.StepAction {
	ui := state.Get("ui").(packer.Ui)

	ui.Say("Creating temporary SSH key for instance...")
	priv, err := rsa.GenerateKey(rand.Reader, 2048)
	if err != nil {
		err := fmt.Errorf("Error creating temporary ssh key: %s", err)
		state.Put("error", err)
		ui.Error(err.Error())
		return multistep.ActionHalt
	}

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

	pub, err := ssh.NewPublicKey(&priv.PublicKey)
	if err != nil {
		err := fmt.Errorf("Error creating temporary ssh key: %s", err)
		state.Put("error", err)
		ui.Error(err.Error())
		return multistep.ActionHalt
	}

	state.Put("ssh_private_key", string(pem.EncodeToMemory(&priv_blk)))
	state.Put("ssh_public_key", string(ssh.MarshalAuthorizedKey(pub)))
	return multistep.ActionContinue
}
Exemplo n.º 5
0
func rsaPubkeyToSSHPubkey(rsakey rsa.PublicKey) (sshkey ssh.PublicKey, err error) {
	sshkey, err = ssh.NewPublicKey(&rsakey)
	if err != nil {
		return nil, err
	}
	return sshkey, nil
}
Exemplo n.º 6
0
Arquivo: main.go Projeto: kr/runx
func main() {
	log.SetFlags(0)
	maybePrintInfo()
	maybeProxy()
	args := os.Args[1:]
	runxURL, err := getToken()
	if err != nil {
		log.Fatal(err)
	}
	if len(args) > 0 && args[0] == "-d" {
		args = args[1:]
		_, err := herokuRun(strings.Join(args, " "), nil)
		if err != nil {
			log.Fatal(err)
		}
		return
	}
	key, err := rsa.GenerateKey(rand.Reader, 1024)
	if err != nil {
		log.Fatal("keygen", err)
	}
	pub, err := ssh.NewPublicKey(&key.PublicKey)
	if err != nil {
		log.Fatal(err)
	}
	uuid, err := herokuRun(script, map[string]string{
		"RUNX_URL":        runxURL,
		"AUTHORIZED_KEYS": string(ssh.MarshalAuthorizedKey(pub)),
	})
	if err != nil {
		log.Fatal(err)
	}
	log.Fatal(execSSH(runxURL, uuid, key, args))
}
Exemplo n.º 7
0
Arquivo: ssh_test.go Projeto: kr/runx
func TestSSHD(t *testing.T) {
	block, _ := pem.Decode([]byte(testClientPrivateKey))
	rsakey, _ := x509.ParsePKCS1PrivateKey(block.Bytes)
	pub, _ := ssh.NewPublicKey(&rsakey.PublicKey)
	cmd, c, err := startSSHD(ssh.MarshalAuthorizedKey(pub))
	if err != nil {
		t.Fatal(err)
	}
	defer cmd.Wait()
	defer cmd.Process.Kill()
	u, err := user.Current()
	if err != nil {
		t.Fatal(err)
	}
	_ = u
	config := &ssh.ClientConfig{
		User: u.Username,
		Auth: []ssh.ClientAuth{ssh.ClientAuthKeyring(&keyring{rsakey})},
	}
	client, err := ssh.Client(c, config)
	if err != nil {
		t.Fatal(err)
	}
	sess, err := client.NewSession()
	if err != nil {
		t.Fatal(err)
	}
	out, err := sess.Output("echo hello")
	if err != nil {
		t.Fatal(err)
	}
	if string(out) != "hello\n" {
		t.Fatalf("out = %q want %q", string(out), "hello\n")
	}
}
Exemplo n.º 8
0
Arquivo: rsa.go Projeto: 41px/dmz
func GenerateKey() (pkPem []byte, pubkPem []byte, pubSSHAK []byte, err error) {
	pk, err := rsa.GenerateKey(rand.Reader, 2048)
	if err != nil {
		return
	}
	pkDer := x509.MarshalPKCS1PrivateKey(pk)
	pkBlock := pem.Block{
		Type:    "RSA PRIVATE KEY",
		Headers: nil,
		Bytes:   pkDer,
	}
	pkPem = pem.EncodeToMemory(&pkBlock)

	pubk := pk.PublicKey
	pubkDer, err := x509.MarshalPKIXPublicKey(&pubk)
	if err != nil {
		return
	}

	pubkBlock := pem.Block{
		Type:    "PUBLIC KEY",
		Headers: nil,
		Bytes:   pubkDer,
	}
	pubkPem = pem.EncodeToMemory(&pubkBlock)

	pubSSH, err := ssh.NewPublicKey(&pubk)
	if err != nil {
		return
	}
	pubSSHAK = ssh.MarshalAuthorizedKey(pubSSH)

	return
}
Exemplo n.º 9
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))
}
Exemplo n.º 10
0
// helper function that marshalls an RSA Public Key to an SSH
// .authorized_keys format
func MarshalPublicKey(public *rsa.PublicKey) []byte {
	private, err := ssh.NewPublicKey(public)
	if err != nil {
		return []byte{}
	}

	return ssh.MarshalAuthorizedKey(private)
}
Exemplo n.º 11
0
// marshalKey returns two byte slices: one represent the private key in the PEM
// format, and the other representing the public key in the authorized_keys
// format.
func marshalKey(keyPair *rsa.PrivateKey) (privateKey []byte, publicKey []byte, err error) {
	sshPublicKey, err := ssh.NewPublicKey(&keyPair.PublicKey)
	if err != nil {
		return nil, nil, err
	}
	publicKey = ssh.MarshalAuthorizedKey(sshPublicKey)
	block := pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(keyPair)}
	privateKey = pem.EncodeToMemory(&block)
	return privateKey, publicKey, nil
}
Exemplo n.º 12
0
func (k *keychain) Key(i int) (ssh.PublicKey, error) {
	if i != 0 {
		return nil, nil
	}
	pubkey, err := ssh.NewPublicKey(&k.key.PublicKey)
	if err != nil {
		log.Panic(err)
	}
	return pubkey, nil
}
Exemplo n.º 13
0
func (k *Keychain) Key(i int) (key ssh.PublicKey, err error) {
	if i != 0 {
		return nil, nil
	}

	// Transform the rsa key into an ssh key
	ssh_publickey, _ := ssh.NewPublicKey(k.key.PublicKey)

	return ssh_publickey, nil
}
Exemplo n.º 14
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)
}
Exemplo n.º 15
0
func GenerateNewPublicKey() string {
	key, err := rsa.GenerateKey(rand.Reader, 2048)
	if err != nil {
		log.Fatal("Failed to generate new RSA key: ", err)
	}
	pk, err := ssh.NewPublicKey(&key.PublicKey)
	if err != nil {
		log.Fatal("Failed to generate public key: ", err)
	}
	return string(ssh.MarshalAuthorizedKey(pk))
}
Exemplo n.º 16
0
func genSSHKey() (*sshData, error) {
	keyFile, err := ioutil.TempFile("", "")
	if err != nil {
		return nil, err

	}
	defer keyFile.Close()
	rsaKey, err := rsa.GenerateKey(rand.Reader, 2048)
	if err != nil {
		return nil, err
	}
	pem.Encode(keyFile, &pem.Block{
		Type:  "RSA PRIVATE KEY",
		Bytes: x509.MarshalPKCS1PrivateKey(rsaKey),
	})

	pubFile, err := ioutil.TempFile("", "")
	if err != nil {
		return nil, err
	}
	defer pubFile.Close()
	rsaPubKey, err := ssh.NewPublicKey(&rsaKey.PublicKey)
	if err != nil {
		return nil, err
	}
	if _, err := pubFile.Write(ssh.MarshalAuthorizedKey(rsaPubKey)); err != nil {
		return nil, err
	}

	wrapperFile, err := ioutil.TempFile("", "")
	if err != nil {
		return nil, err
	}
	defer wrapperFile.Close()
	if err := sshWrapper.Execute(wrapperFile, map[string]string{"SSHKey": keyFile.Name()}); err != nil {
		return nil, err
	}
	if err := wrapperFile.Chmod(0700); err != nil {
		return nil, err
	}

	return &sshData{
		Key: keyFile.Name(),
		Pub: pubFile.Name(),
		Env: []string{"GIT_SSH=" + wrapperFile.Name()},
		Cleanup: func() {
			os.RemoveAll(keyFile.Name())
			os.RemoveAll(pubFile.Name())
			os.RemoveAll(wrapperFile.Name())
		},
	}, nil
}
Exemplo n.º 17
0
func (keyring *SandhogClientKeyring) Key(i int) (ssh.PublicKey, error) {
	// Only support one key
	if i != 0 {
		return nil, nil
	}

	// Wrap the RSA public key in the SSH package's PublicKey wrapper
	publicKey, err := ssh.NewPublicKey(keyring.key.PublicKey)
	if err != nil {
		return nil, err
	}

	return publicKey, nil
}
Exemplo n.º 18
0
func GeneratePublicKey(privateKey []byte) (string, error) {
	rsaPK, err := ssh.ParseRawPrivateKey(privateKey)
	if err != nil {
		return "", err
	}

	sshPK := rsaPK.(*rsa.PrivateKey)
	sshPubKey, err := ssh.NewPublicKey(&sshPK.PublicKey)
	if err != nil {
		return "", err
	}

	return MarshalPublickKey(sshPubKey), nil
}
Exemplo n.º 19
0
func generateRSAKey(bits int) ([]byte, []byte, error) {
	rsaKey, err := rsa.GenerateKey(rand.Reader, bits)
	if err != nil {
		return nil, nil, err
	}
	pubKey, err := ssh.NewPublicKey(&rsaKey.PublicKey)
	if err != nil {
		return nil, nil, err
	}
	rsaKeyDER := x509.MarshalPKCS1PrivateKey(rsaKey)
	return pem.EncodeToMemory(&pem.Block{
		Type:  "RSA PRIVATE KEY",
		Bytes: rsaKeyDER,
	}), ssh.MarshalAuthorizedKey(pubKey), nil
}
Exemplo n.º 20
0
// Run executes the Packer build step that generates SSH key pairs.
func (s *StepCreateSSHKey) Run(state multistep.StateBag) multistep.StepAction {
	ui := state.Get("ui").(packer.Ui)

	ui.Say("Creating temporary SSH key for instance...")
	priv, err := rsa.GenerateKey(rand.Reader, 2048)
	if err != nil {
		err := fmt.Errorf("Error creating temporary ssh key: %s", err)
		state.Put("error", err)
		ui.Error(err.Error())
		return multistep.ActionHalt
	}

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

	pub, err := ssh.NewPublicKey(&priv.PublicKey)
	if err != nil {
		err := fmt.Errorf("Error creating temporary ssh key: %s", err)
		state.Put("error", err)
		ui.Error(err.Error())
		return multistep.ActionHalt
	}
	state.Put("ssh_private_key", string(pem.EncodeToMemory(&priv_blk)))
	state.Put("ssh_public_key", string(ssh.MarshalAuthorizedKey(pub)))

	if s.Debug {
		ui.Message(fmt.Sprintf("Saving key for debug purposes: %s", s.DebugKeyPath))
		f, err := os.Create(s.DebugKeyPath)
		if err != nil {
			state.Put("error", fmt.Errorf("Error saving debug key: %s", err))
			return multistep.ActionHalt
		}

		// Write out the key
		err = pem.Encode(f, &priv_blk)
		f.Close()
		if err != nil {
			state.Put("error", fmt.Errorf("Error saving debug key: %s", err))
			return multistep.ActionHalt
		}
	}
	return multistep.ActionContinue
}
Exemplo n.º 21
0
func (s *stepCreateSSHKey) Run(state multistep.StateBag) multistep.StepAction {
	client := state.Get("client").(*DigitalOceanClient)
	ui := state.Get("ui").(packer.Ui)

	ui.Say("Creating temporary ssh key for droplet...")

	priv, err := rsa.GenerateKey(rand.Reader, 2014)

	// ASN.1 DER encoded form
	priv_der := x509.MarshalPKCS1PrivateKey(priv)
	priv_blk := pem.Block{
		Type:    "RSA PRIVATE KEY",
		Headers: nil,
		Bytes:   priv_der,
	}

	// Set the private key in the statebag for later
	state.Put("privateKey", string(pem.EncodeToMemory(&priv_blk)))

	// Marshal the public key into SSH compatible format
	// TODO properly handle the public key error
	pub, _ := ssh.NewPublicKey(&priv.PublicKey)
	pub_sshformat := string(ssh.MarshalAuthorizedKey(pub))

	// The name of the public key on DO
	name := fmt.Sprintf("packer-%s", hex.EncodeToString(identifier.NewUUID().Raw()))

	// Create the key!
	keyId, err := client.CreateKey(name, pub_sshformat)
	if err != nil {
		err := fmt.Errorf("Error creating temporary SSH key: %s", err)
		state.Put("error", err)
		ui.Error(err.Error())
		return multistep.ActionHalt
	}

	// We use this to check cleanup
	s.keyId = keyId

	log.Printf("temporary ssh key name: %s", name)

	// Remember some state for the future
	state.Put("ssh_key_id", keyId)

	return multistep.ActionContinue
}
Exemplo n.º 22
0
func generateDSAKey() ([]byte, []byte, error) {
	params := &dsa.Parameters{}
	if err := dsa.GenerateParameters(params, rand.Reader, dsa.L1024N160); err != nil {
		return nil, nil, err
	}
	dsaKey := &dsa.PrivateKey{
		PublicKey: dsa.PublicKey{
			Parameters: *params,
		},
	}
	if err := dsa.GenerateKey(dsaKey, rand.Reader); err != nil {
		return nil, nil, err
	}
	pubKey, err := ssh.NewPublicKey(&dsaKey.PublicKey)
	if err != nil {
		return nil, nil, err
	}
	dsaKeyASN1, err := asn1.Marshal(struct {
		Version       int
		P, Q, G, Y, X *big.Int
	}{
		0,
		dsaKey.P,
		dsaKey.Q,
		dsaKey.G,
		dsaKey.Y,
		dsaKey.X,
	})
	if err != nil {
		return nil, nil, err
	}
	return pem.EncodeToMemory(&pem.Block{
		Type:  "DSA PRIVATE KEY",
		Bytes: dsaKeyASN1,
	}), ssh.MarshalAuthorizedKey(pubKey), nil
}
Exemplo n.º 23
0
func (k *keyring) Key(i int) (ssh.PublicKey, error) {
	if i < 0 || i >= len(k.keys) {
		return nil, nil
	}
	return ssh.NewPublicKey(&k.keys[i].PublicKey)
}
Exemplo n.º 24
0
func (k *keychain) Key(i int) (ssh.PublicKey, error) {
	if i != 0 {
		return nil, nil
	}
	return ssh.NewPublicKey(&k.key.PublicKey)
}