Esempio n. 1
0
func init() {
	template.Must(configTmpl.Parse(sshd_config))

	var err error
	hostKey, err = ssh.ParsePrivateKey([]byte(keys["ssh_host_rsa_key"]))
	if err != nil {
		panic("ParsePrivateKey: " + err.Error())
	}
	privateKey, err = ssh.ParsePrivateKey([]byte(testClientPrivateKey))
	if err != nil {
		panic("ParsePrivateKey: " + err.Error())
	}
}
Esempio n. 2
0
// Start listening for SSH connections
func StartSSH() {
	PEM_KEY := LoadPrivKeyFromFile("./id_rsa")
	private, err := ssh.ParsePrivateKey(PEM_KEY)
	if err != nil {
		log.Fatal("Key failed to parse.")
	}

	SSHConfig := &ssh.ServerConfig{
		PasswordCallback: func(conn ssh.ConnMetadata, pass []byte) (*ssh.Permissions, error) {
			perms := ssh.Permissions{}
			return &perms, nil
		},
		PublicKeyCallback: func(conn ssh.ConnMetadata, key ssh.PublicKey) (*ssh.Permissions, error) {
			perms := ssh.Permissions{}
			return &perms, nil
		},
	}

	SSHConfig.AddHostKey(private)

	listener, err := net.Listen("tcp", "0.0.0.0:2222")
	if err != nil {
		log.Fatalln("Could not start TCP listening on 0.0.0.0:2222")
	}
	log.Println("Waiting for TCP conns on 0.0.0.0:2222")

	for {
		nConn, err := listener.Accept()
		if err != nil {
			log.Println("WARNING - Failed to Accept TCP conn. RSN: %s / %s", err.Error(), err)
			continue
		}
		go HandleIncomingSSHConn(nConn, SSHConfig)
	}
}
Esempio n. 3
0
func (s *SSHGoCryptoCommandSuite) TestProxyCommand(c *gc.C) {
	realNetcat, err := exec.LookPath("nc")
	if err != nil {
		c.Skip("skipping test, couldn't find netcat: %v")
		return
	}
	netcat := filepath.Join(c.MkDir(), "nc")
	err = ioutil.WriteFile(netcat, []byte("#!/bin/sh\necho $0 \"$@\" > $0.args && exec "+realNetcat+" \"$@\""), 0755)
	c.Assert(err, gc.IsNil)

	private, _, err := ssh.GenerateKey("test-server")
	c.Assert(err, gc.IsNil)
	key, err := cryptossh.ParsePrivateKey([]byte(private))
	client, err := ssh.NewGoCryptoClient(key)
	c.Assert(err, gc.IsNil)
	server := newServer(c)
	var opts ssh.Options
	port := server.listener.Addr().(*net.TCPAddr).Port
	opts.SetProxyCommand(netcat, "-q0", "%h", "%p")
	opts.SetPort(port)
	cmd := client.Command("127.0.0.1", testCommand, &opts)
	server.cfg.PublicKeyCallback = func(_ cryptossh.ConnMetadata, pubkey cryptossh.PublicKey) (*cryptossh.Permissions, error) {
		return nil, nil
	}
	go server.run(c)
	out, err := cmd.Output()
	c.Assert(err, gc.IsNil)
	c.Assert(string(out), gc.Equals, "abc value\n")
	// Ensure the proxy command was executed with the appropriate arguments.
	data, err := ioutil.ReadFile(netcat + ".args")
	c.Assert(err, gc.IsNil)
	c.Assert(string(data), gc.Equals, fmt.Sprintf("%s -q0 127.0.0.1 %v\n", netcat, port))
}
Esempio n. 4
0
func (self *Server) ParsePrivateKey(filePath string) error {
	if filePath == "" {
		return nil
	}

	keyBytes, err := ioutil.ReadFile(filePath)

	if err != nil {
		err = errors.New(fmt.Sprintf("Could not read ssh key \"%s\" : %s ", filePath, err.Error()))
		self.Error = err
		self.ErrorMsg = err.Error()
		return err
	}

	signer, err := ssh.ParsePrivateKey(keyBytes)

	if err != nil {
		err = errors.New(fmt.Sprintf("Could not parse ssh key \"%s\" : %s ", filePath, err.Error()))
		self.Error = err
		self.ErrorMsg = err.Error()
		return err
	}

	self.PrivateKeyPath = filePath
	self.AuthMethods = append(self.AuthMethods, ssh.PublicKeys(signer))

	return nil
}
Esempio n. 5
0
func newWorkerListener(listener net.Listener, secret []byte) connListener {
	key, err := ssh.ParsePrivateKey(secret)
	if err != nil {
		return newTCPListener(listener, secret)
	}
	return newSSHListener(listener, key)
}
Esempio n. 6
0
//TODO 某种认证方法只有一个会被使用,需要多次猜测
func DialInConsole(addr string, username string) (client *ssh.Client, err error) {
	//find cert file
	pathList := certFilePathList()
	authList := []ssh.AuthMethod{}
	for _, path := range pathList {
		clientKeyBytes, err := ioutil.ReadFile(path)
		if err != nil {
			if !os.IsNotExist(err) {
				return nil, fmt.Errorf("[DialInConsole] ioutil.ReadFile() err:%s", err)
			}
		} else {
			signer, err := ssh.ParsePrivateKey(clientKeyBytes)
			if err != nil {
				return nil, fmt.Errorf("[DialInConsole] ssh.ParsePrivateKey err:%s", err)
			}
			//clientKey := &keychain{signer}
			authList = append(authList, ssh.PublicKeys(signer))
		}
	}
	authList = append(authList, ssh.PasswordCallback(func() (secret string, err error) {
		fmt.Printf("[ssh] password for %s@%s", username, addr)
		secret = string(gopass.GetPasswd())
		return
	}))
	clientConfig := &ssh.ClientConfig{
		User: username,
		Auth: authList,
	}
	client, err = ssh.Dial("tcp", addr, clientConfig)
	if err != nil {
		return nil, fmt.Errorf("[DialInConsole] Failed to dial: %s", err.Error())
	}
	return
}
Esempio n. 7
0
func newTestServer() (Server, error) {

	// Create a new backend object.
	b := redis.New("test", "tcp", "127.0.0.1:6379")

	// Create a new crypter.
	c, err := crypto.NewRandomCrypter()
	if err != nil {
		return nil, err
	}

	private, _ := ssh.ParsePrivateKey(ServerTestPrivateKey)
	if err != nil {
		return nil, err
	}

	s := NewServer(b, c, private)

	for _, publicKey := range ServerTestPublicKeys {
		publicKeyParsed, _, _, _, err := ssh.ParseAuthorizedKey([]byte(publicKey))
		if err != nil {
			return s, err
		}

		s.AddReadKey(publicKeyParsed)
		s.AddWriteKey(publicKeyParsed)
	}

	return s, nil
}
Esempio n. 8
0
func getSftpClient(conf Config) []*sftp.Client {
	// process the keyfile
	buf, err := ioutil.ReadFile(conf.KeyFile)
	if err != nil {
		log.Fatalf("error in reading private key file %s\n", err)
	}
	key, err := ssh.ParsePrivateKey(buf)
	if err != nil {
		log.Fatalf("error in parsing private key %s\n", key)
	}
	// client config
	config := &ssh.ClientConfig{
		User: conf.User,
		Auth: []ssh.AuthMethod{ssh.PublicKeys(key)},
	}
	// connection
	clients := make([]*sftp.Client, 0)
	for _, r := range conf.Remotes {
		c, err := ssh.Dial("tcp", r, config)
		if err != nil {
			log.Fatalf("error in ssh connection %s\n", err)
		}
		// sftp handler
		sftp, err := sftp.NewClient(c)
		if err != nil {
			log.Fatalf("error in sftp connection %s\n", err)
		}
		clients = append(clients, sftp)
	}
	return clients
}
Esempio n. 9
0
func (s *SSHGoCryptoCommandSuite) TestProxyCommand(c *gc.C) {
	realNetcat, err := exec.LookPath("nc")
	if err != nil {
		c.Skip("skipping test, couldn't find netcat: %v")
		return
	}
	netcat := filepath.Join(c.MkDir(), "nc")
	err = ioutil.WriteFile(netcat, []byte("#!/bin/sh\necho $0 \"$@\" > $0.args && exec "+realNetcat+" \"$@\""), 0755)
	c.Assert(err, gc.IsNil)

	private, _, err := ssh.GenerateKey("test-server")
	c.Assert(err, gc.IsNil)
	key, err := cryptossh.ParsePrivateKey([]byte(private))
	client, err := ssh.NewGoCryptoClient(key)
	c.Assert(err, gc.IsNil)
	server := newServer(c)
	var opts ssh.Options
	port := server.Addr().(*net.TCPAddr).Port
	opts.SetProxyCommand(netcat, "-q0", "%h", "%p")
	opts.SetPort(port)
	cmd := client.Command("127.0.0.1", testCommand, &opts)
	server.cfg.PublicKeyCallback = func(conn *cryptossh.ServerConn, user, algo string, pubkey []byte) bool {
		return true
	}
	go server.run(c)
	out, err := cmd.Output()
	c.Assert(err, gc.ErrorMatches, "ssh: could not execute command.*")
	// TODO(axw) when gosshnew is ready, expect reply from server.
	c.Assert(out, gc.IsNil)
	// Ensure the proxy command was executed with the appropriate arguments.
	data, err := ioutil.ReadFile(netcat + ".args")
	c.Assert(err, gc.IsNil)
	c.Assert(string(data), gc.Equals, fmt.Sprintf("%s -q0 127.0.0.1 %v\n", netcat, port))
}
Esempio n. 10
0
func (c *SftpClient) GetKey(sKeyPath string) (key ssh.Signer, err error) {
	buf, err := ioutil.ReadFile(sKeyPath)
	if err != nil {
		return nil, err
	}
	return ssh.ParsePrivateKey(buf)
}
Esempio n. 11
0
// FileSigner returns an ssh.Signer for a key file.
func FileSigner(path string) (ssh.Signer, error) {
	f, err := os.Open(path)
	if err != nil {
		return nil, err
	}
	defer f.Close()

	keyBytes, err := ioutil.ReadAll(f)
	if err != nil {
		return nil, err
	}

	// We parse the private key on our own first so that we can
	// show a nicer error if the private key has a password.
	block, _ := pem.Decode(keyBytes)
	if block == nil {
		return nil, fmt.Errorf(
			"Failed to read key '%s': no key found", path)
	}
	if block.Headers["Proc-Type"] == "4,ENCRYPTED" {
		return nil, fmt.Errorf(
			"Failed to read key '%s': password protected keys are\n"+
				"not supported. Please decrypt the key prior to use.", path)
	}

	signer, err := ssh.ParsePrivateKey(keyBytes)
	if err != nil {
		return nil, fmt.Errorf("Error setting up SSH config: %s", err)
	}

	return signer, nil
}
Esempio n. 12
0
func CreateServer(webhost string) (srv *Server, err error) {
	srv = &Server{
		scss:    make(map[net.Addr]SshConnServer, 0),
		webhost: webhost,
		cnt:     CreateCounter(CONN_PROTECT),
	}
	srv.srvcfg = &ssh.ServerConfig{
		PublicKeyCallback: srv.authUser,
	}

	v := &url.Values{}
	err = srv.GetJson("/l/cfg", false, v, &srv.WebConfig)
	if err != nil {
		panic(err.Error())
	}
	log.Debug("config: %#v", srv.WebConfig)

	private, err := ssh.ParsePrivateKey([]byte(srv.WebConfig.Hostkey))
	if err != nil {
		log.Error("failed to parse keyfile: %s", err.Error())
		return
	}
	srv.srvcfg.AddHostKey(private)

	return
}
Esempio n. 13
0
// PrepareConfig is used to turn the *SSHConfig provided into a
// usable *Config for client initialization.
func PrepareConfig(conf *SSHConfig) (*Config, error) {
	sshConf := &ssh.ClientConfig{
		User: conf.User,
	}
	if conf.KeyFile != "" {
		key, err := ioutil.ReadFile(conf.KeyFile)
		if err != nil {
			return nil, fmt.Errorf("Failed to read key file '%s': %v", conf.KeyFile, err)
		}
		signer, err := ssh.ParsePrivateKey(key)
		if err != nil {
			return nil, fmt.Errorf("Failed to parse key file '%s': %v", conf.KeyFile, err)
		}
		sshConf.Auth = append(sshConf.Auth, ssh.PublicKeys(signer))
	}
	if conf.Password != "" {
		sshConf.Auth = append(sshConf.Auth,
			ssh.Password(conf.Password))
		sshConf.Auth = append(sshConf.Auth,
			ssh.KeyboardInteractive(PasswordKeyboardInteractive(conf.Password)))
	}
	host := fmt.Sprintf("%s:%d", conf.Host, conf.Port)
	config := &Config{
		SSHConfig:  sshConf,
		Connection: ConnectFunc("tcp", host),
	}
	return config, nil
}
Esempio n. 14
0
func getTestPublicKey(t *testing.T) ssh.PublicKey {
	priv, err := ssh.ParsePrivateKey([]byte(testClientPrivateKey))
	if err != nil {
		t.Fatalf("ParsePrivateKey: %v", err)
	}

	return priv.PublicKey()
}
Esempio n. 15
0
func init() {
	// Parse and set the private key of the server, required to accept connections
	signer, err := ssh.ParsePrivateKey([]byte(testServerPrivateKey))
	if err != nil {
		panic("unable to parse private key: " + err.Error())
	}
	serverConfig.AddHostKey(signer)
}
func (s *Command) getSSHKey(identityFile string) (key ssh.Signer, err error) {
	buf, err := ioutil.ReadFile(identityFile)
	if err != nil {
		return nil, err
	}
	key, err = ssh.ParsePrivateKey(buf)
	return key, err
}
Esempio n. 17
0
func newWorkerDialer(secret []byte) connDialer {
	key, err := ssh.ParsePrivateKey(secret)
	if err != nil {
		return newTCPDialer(secret)
	}

	return newSSHDialer(key)
}
Esempio n. 18
0
func serverRun(cmd *Command, args []string) {

	c, err := crypto.NewCrypterFromFile(serverConfig.SecretFilepath)
	if err != nil {
		log.Fatal(err)
	}

	b, err := backend.NewBackend(serverConfig.Backend, serverConfig.BackendNamespace, serverConfig.BackendProtocol, serverConfig.BackendAddress)
	if err != nil {
		log.Fatal(err)
	}

	privateBytes, err := ioutil.ReadFile(serverConfig.PrivateFilepath)
	if err != nil {
		log.Fatal("failed to load private key")
	}

	private, err := ssh.ParsePrivateKey(privateBytes)
	if err != nil {
		log.Fatal("failed to parse private key")
	}

	// Create a new server using the specified Backend and Crypter.
	server := auth.NewServer(b, c, private)

	// Check if a URL was provided to pull reader keys from.
	if serverConfig.ReadersURL != "" {

		// Fetch the reader keys.
		readers, err := serverFetchPublicKeys(serverConfig.ReadersURL)
		if err != nil {
			log.Fatal(err)
		}

		// Add the reader keys to the server.
		for _, reader := range readers {
			server.AddReadKey(reader)
		}
	}

	// Check if a URL was provided to pull writer keys from.
	if serverConfig.WritersURL != "" {

		// Fetch the writer keys.
		writers, err := serverFetchPublicKeys(serverConfig.WritersURL)
		if err != nil {
			log.Fatal(err)
		}

		// Add the writer keys to the server.
		for _, writer := range writers {
			server.AddWriteKey(writer)
		}
	}

	// Start the server.
	log.Fatal(server.ListenAndServe(serverConfig.Address))
}
Esempio n. 19
0
func (s *SSHGoCryptoCommandSuite) TestNewGoCryptoClient(c *gc.C) {
	_, err := ssh.NewGoCryptoClient()
	c.Assert(err, gc.IsNil)
	private, _, err := ssh.GenerateKey("test-client")
	c.Assert(err, gc.IsNil)
	key, err := cryptossh.ParsePrivateKey([]byte(private))
	c.Assert(err, gc.IsNil)
	_, err = ssh.NewGoCryptoClient(key)
	c.Assert(err, gc.IsNil)
}
Esempio n. 20
0
func (k *Keychain) Add(privateKey []byte) error {
	key, err := ssh.ParsePrivateKey(privateKey)

	if err != nil {
		return err
	}

	k.keys = append(k.keys, key)

	return nil
}
Esempio n. 21
0
func loadPEM(file string) (ssh.Signer, error) {
	buf, err := ioutil.ReadFile(file)
	if err != nil {
		return nil, err
	}
	key, err := ssh.ParsePrivateKey(buf)
	if err != nil {
		return nil, err
	}
	return key, nil
}
func init() {
	template.Must(configTmpl.Parse(sshd_config))

	for n, k := range map[string]*ssh.Signer{
		"ssh_host_ecdsa_key": &hostKeyECDSA,
		"ssh_host_rsa_key":   &hostKeyRSA,
		"ssh_host_dsa_key":   &hostKeyDSA,
	} {
		var err error
		*k, err = ssh.ParsePrivateKey([]byte(keys[n]))
		if err != nil {
			panic(fmt.Sprintf("ParsePrivateKey(%q): %v", n, err))
		}
	}

	var err error
	privateKey, err = ssh.ParsePrivateKey([]byte(testClientPrivateKey))
	if err != nil {
		panic(fmt.Sprintf("ParsePrivateKey: %v", err))
	}
}
Esempio n. 23
0
func (k *KeyChain) LoadPEM(file string) error {
	buf, err := ioutil.ReadFile(file)
	if err != nil {
		return err
	}
	key, err := ssh.ParsePrivateKey(buf)
	if err != nil {
		return err
	}
	k.keys = append(k.keys, key)
	return nil
}
Esempio n. 24
0
func (k *keychain) loadPEM(file string) error {
	buf, err := ioutil.ReadFile(file)
	if err != nil {
		return err
	}
	key, err := ssh.ParsePrivateKey(buf)
	if err != nil {
		return err
	}
	k.add(key)
	return nil
}
Esempio n. 25
0
func (self *Script) Execute(host *Host, out io.Writer) error {
	usr, err := user.Current()
	if err != nil {
		return err
	}
	if host.User == "" {
		host.User = usr.Username
	}
	cfg := &ssh.ClientConfig{
		User: host.User,
	}
	if host.Password != "" {
		cfg.Auth = []ssh.AuthMethod{
			ssh.Password(host.Password),
		}
	} else {
		content, err := ioutil.ReadFile(usr.HomeDir + "/.ssh/id_rsa")
		if err != nil {
			content, err = ioutil.ReadFile(usr.HomeDir + "/.ssh/id_dsa")
			if err != nil {
				return err
			}
		}
		key, err := ssh.ParsePrivateKey(content)
		if err != nil {
			return err
		}
		cfg.Auth = []ssh.AuthMethod{ssh.PublicKeys(key)}
	}
	client, err := ssh.Dial("tcp", host.Name+":"+strconv.Itoa(host.Port), cfg)
	if err != nil {
		fmt.Fprintln(out, err.Error())
		return err
	}
	session, err := client.NewSession()
	if err != nil {
		fmt.Fprintln(out, err.Error())
		return err
	}
	defer session.Close()
	session.Stdout = out
	session.Stderr = out
	if !self.HideBoundaries {
		fmt.Fprintln(out, "---------------------- script started ----------------------")
	}
	if err := session.Run(self.Content); err != nil {
		return err
	}
	if !self.HideBoundaries {
		fmt.Fprintln(out, "---------------------- script finished ----------------------")
	}
	return nil
}
Esempio n. 26
0
// This function is used to get the pulic ssh key to make password-less
// connection to a remote machine.
func getKeyFile() (key ssh.Signer, err error) {
	file := os.Getenv("HOME") + "/.ssh/id_rsa"
	buf, err := ioutil.ReadFile(file)
	if err != nil {
		return
	}
	key, err = ssh.ParsePrivateKey(buf)
	if err != nil {
		return
	}
	return
}
Esempio n. 27
0
File: loom.go Progetto: euforia/loom
// parsekey is a private function that reads in a keyfile containing a private key and parses it.
func parsekey(file string) (ssh.Signer, error) {
	var private ssh.Signer
	privateBytes, err := ioutil.ReadFile(file)
	if err != nil {
		return nil, err
	}

	private, err = ssh.ParsePrivateKey(privateBytes)
	if err != nil {
		return nil, err
	}
	return private, nil
}
Esempio n. 28
0
func getPrivateKeys(job *engine.Job) ssh.Signer {
	privateBytes, err := ioutil.ReadFile(os.Getenv("HOME") + "/.ssh/id_rsa")

	if err != nil {
		job.Errorf("Failed to load private key")
	}
	private, err := ssh.ParsePrivateKey(privateBytes)
	if err != nil {
		job.Errorf("Failed to parse private key")
	}

	return private
}
Esempio n. 29
0
func newServer(c *gc.C) *sshServer {
	private, _, err := ssh.GenerateKey("test-server")
	c.Assert(err, gc.IsNil)
	key, err := cryptossh.ParsePrivateKey([]byte(private))
	c.Assert(err, gc.IsNil)
	server := &sshServer{
		cfg: &cryptossh.ServerConfig{},
	}
	server.cfg.AddHostKey(key)
	server.listener, err = net.Listen("tcp", "127.0.0.1:0")
	c.Assert(err, gc.IsNil)
	return server
}
Esempio n. 30
0
func getKeyFile() (key ssh.Signer, err error) {
	usr, _ := user.Current()
	file := usr.HomeDir + "/.ssh/jai_rsa"
	buf, err := ioutil.ReadFile(file)
	if err != nil {
		panic(err)
	}
	key, err = ssh.ParsePrivateKey(buf)
	if err != nil {
		panic(err)
	}
	return
}