Beispiel #1
0
func (ih *InputHandler) createSession(config *InputEntry) (session *ssh.Session, err error) {

	var authMethod []ssh.AuthMethod
	var key *ssh.Signer
	if !config.Cred.IsPasswordAuth() {
		key, err = ih.parsePrivateKey(config.Cred.Identity)
		if err != nil {
			return
		}
		authMethod = []ssh.AuthMethod{ssh.PublicKeys(*key)}
	} else {
		authMethod = []ssh.AuthMethod{ssh.Password(config.Cred.Pass)}
	}

	sshConfig := new(ssh.ClientConfig)
	sshConfig.User = config.Cred.User
	sshConfig.Auth = authMethod

	port := uint16(22)
	if config.Port != 0 {
		port = config.Port
	}
	hostNameString := fmt.Sprintf("%s:%d", config.Host, port)
	client, err := ssh.Dial("tcp", hostNameString, sshConfig)
	if err != nil {
		return
	}

	session, err = client.NewSession()
	return
}
Beispiel #2
0
func sshClientConfig(user string, checker *HostKeyChecker, addr string) (*gossh.ClientConfig, error) {
	agentClient, err := SSHAgentClient()
	if err != nil {
		return nil, err
	}

	signers, err := agentClient.Signers()
	if err != nil {
		return nil, err
	}

	cfg := gossh.ClientConfig{
		User: user,
		Auth: []gossh.AuthMethod{
			gossh.PublicKeys(signers...),
		},
	}

	if checker != nil {
		cfg.HostKeyCallback = checker.Check
		cfg.HostKeyAlgorithms = checker.GetHostKeyAlgorithms(addr)
	}

	return &cfg, nil
}
Beispiel #3
0
func TestServer(t *testing.T) {
	shellScript := `#!/bin/sh
echo $*
exit
`
	shell, err := ioutil.TempFile("", "govcs-ssh-shell")
	if err != nil {
		t.Fatal(err)
	}
	shell.WriteString(shellScript)
	if err := shell.Chmod(0700); err != nil {
		t.Fatal(err)
	}
	if err := shell.Close(); err != nil {
		t.Fatal(err)
	}
	defer os.RemoveAll(shell.Name())

	s, err := NewServer(shell.Name(), "/tmp", PrivateKey(SamplePrivKey))
	if err != nil {
		t.Fatal(err)
	}
	if err := s.Start(); err != nil {
		t.Fatal(err)
	}

	// Client
	cauth, err := clientAuth(SamplePrivKey)
	if err != nil {
		t.Fatal(err)
	}
	cconf := ssh.ClientConfig{User: "******"}
	cconf.Auth = append(cconf.Auth, cauth)
	sshc, err := ssh.Dial(s.l.Addr().Network(), s.l.Addr().String(), &cconf)
	if err != nil {
		t.Fatal(err)
	}
	defer sshc.Close()

	session, err := sshc.NewSession()
	if err != nil {
		t.Fatal(err)
	}
	defer session.Close()

	out, err := session.CombinedOutput("git-upload-pack 'foo'")
	if err != nil {
		t.Fatal(err)
	}
	if got, want := string(out), "-c git-upload-pack 'foo'\n"; got != want {
		t.Errorf("got ssh session output %q, want %q", got, want)
	}
}
Beispiel #4
0
func openLog(path string) (io.WriteCloser, error) {
	m := scpPathRe.FindStringSubmatch(path)
	if m == nil {
		return os.OpenFile(path, os.O_WRONLY|os.O_CREATE, 0600)
	} else {
		user, pass, host, port, path := m[1], m[2], m[3], m[4], m[5]
		if path == "" {
			return nil, errors.New("blank remote file path")
		}
		if port == "" {
			port = "22"
		} else {
			port = port[1:]
		}
		config := ssh.ClientConfig{
			User: user,
			Auth: []ssh.AuthMethod{ssh.KeyboardInteractive(sshKeyboardAuth)},
		}
		if pass != "" {
			config.Auth = append([]ssh.AuthMethod{ssh.Password(pass[1:])}, config.Auth...)
		} else {
			config.Auth = append([]ssh.AuthMethod{ssh.PasswordCallback(func() (string, error) {
				fmt.Printf("Password: "******"tcp", net.JoinHostPort(host, port), &config)
		if err != nil {
			return nil, err
		}
		session, err := client.NewSession()
		if err != nil {
			return nil, err
		}
		inputStream, err := session.StdinPipe()
		if err != nil {
			session.Close()
			return nil, err
		}
		cmd := fmt.Sprintf("cat > %s", shellEscape(path))
		if err := session.Start(cmd); err != nil {
			session.Close()
			return nil, err
		}
		return inputStream, nil
	}
}
Beispiel #5
0
func (ssc *SSHConfig) Connect() (err tree_lib.TreeError) {
	var (
		client_conf ssh.ClientConfig
	)
	err.From = tree_lib.FROM_SSH_CONNECT
	client_conf.User = ssc.Username
	if len(ssc.Password) > 0 {
		client_conf.Auth = []ssh.AuthMethod{ssh.Password(ssc.Password)}
	} else {
		client_conf.Auth = []ssh.AuthMethod{ssh_agent()}
	}

	ssc.conn, err.Err = ssh.Dial("tcp", fmt.Sprintf("%s:%d", ssc.Host, ssc.Port), &client_conf)
	return
}
Beispiel #6
0
func AddSSHIdentity(sshConfig *ssh.ClientConfig, p string) error {
	a, err := parsePrivateKeyFile(p)
	if err != nil {
		return err
	}
	sshConfig.Auth = append(sshConfig.Auth, a)
	return nil
}
Beispiel #7
0
func TestAuth(t *testing.T) {
	a, b, err := netPipe()
	if err != nil {
		t.Fatalf("netPipe: %v", err)
	}

	defer a.Close()
	defer b.Close()

	agent, _, cleanup := startAgent(t)
	defer cleanup()

	if err := agent.Add(AddedKey{PrivateKey: testPrivateKeys["rsa"], Comment: "comment"}); err != nil {
		t.Errorf("Add: %v", err)
	}

	serverConf := ssh.ServerConfig{}
	serverConf.AddHostKey(testSigners["rsa"])
	serverConf.PublicKeyCallback = func(c ssh.ConnMetadata, key ssh.PublicKey) (*ssh.Permissions, error) {
		if bytes.Equal(key.Marshal(), testPublicKeys["rsa"].Marshal()) {
			return nil, nil
		}

		return nil, errors.New("pubkey rejected")
	}

	go func() {
		conn, _, _, err := ssh.NewServerConn(a, &serverConf)
		if err != nil {
			t.Fatalf("Server: %v", err)
		}
		conn.Close()
	}()

	conf := ssh.ClientConfig{}
	conf.Auth = append(conf.Auth, ssh.PublicKeysCallback(agent.Signers))
	conn, _, _, err := ssh.NewClientConn(b, "", &conf)
	if err != nil {
		t.Fatalf("NewClientConn: %v", err)
	}
	conn.Close()
}
Beispiel #8
0
func sshConfig(state multistep.StateBag) (*ssh.ClientConfig, error) {
	config := state.Get("config").(Config)
	clientConfig := ssh.ClientConfig{User: config.SSHUsername}
	if config.OsSnapshot == "" && config.IpxeUrl == "" {
		// default case where vultr generated the password
		password := state.Get("default_password").(string)
		clientConfig.Auth = []ssh.AuthMethod{ssh.Password(password)}
	} else if config.SSHPassword != "" {
		// special case but we got a password
		clientConfig.Auth = []ssh.AuthMethod{ssh.Password(config.SSHPassword)}
	} else {
		// special case and we got a key
		signer, err := ssh.ParsePrivateKey([]byte(config.SSHPrivateKey))
		if err != nil {
			return nil, fmt.Errorf("Error setting up SSH config: %s", err)
		}
		clientConfig.Auth = []ssh.AuthMethod{ssh.PublicKeys(signer)}
	}
	return &clientConfig, nil
}
Beispiel #9
0
func clientDo() error {
	var cc ssh.ClientConfig
	cc.User = string(testUser)
	cc.Auth = append(cc.Auth, ssh.Password(string(testPass)))
	conn, e := ssh.Dial("tcp4", "127.0.0.1:2022", &cc)
	if e != nil {
		return e
	}
	defer conn.Close()
	cl, e := client.NewClient(conn)
	if e != nil {
		return e
	}
	cl.Mkdir("/D")
	cl.Chmod("/D", 0700)
	cl.Remove("/D")
	rs, e := cl.ReadDir("/")
	if e != nil {
		return e
	}
	tdebug(rs)
	return nil
}
Beispiel #10
0
var _ = Describe("SSH proxy", func() {
	var (
		fakeBBS *ghttp.Server
		fakeUAA *ghttp.Server
		fakeCC  *ghttp.Server
		runner  ifrit.Runner
		process ifrit.Process

		address                     string
		bbsAddress                  string
		ccAPIURL                    string
		diegoCredentials            string
		enableCFAuth                bool
		enableDiegoAuth             bool
		hostKey                     string
		hostKeyFingerprint          string
		skipCertVerify              bool
		uaaTokenURL                 string
		uaaPassword                 string
		uaaUsername                 string
		allowedCiphers              string
		allowedMACs                 string
		allowedKeyExchanges         string
		expectedGetActualLRPRequest *models.ActualLRPGroupByProcessGuidAndIndexRequest
		actualLRPGroupResponse      *models.ActualLRPGroupResponse
		getDesiredLRPRequest        *models.DesiredLRPByProcessGuidRequest
		desiredLRPResponse          *models.DesiredLRPResponse

		processGuid  string
		clientConfig *ssh.ClientConfig
	)
Beispiel #11
0
func (d *timeoutDialer) Dial(network, addr string, config *ssh.ClientConfig) (*ssh.Client, error) {
	config.Timeout = d.timeout
	return d.dialer.Dial(network, addr, config)
}
Beispiel #12
0
func TestServer(t *testing.T) {
	var shellScript string

	if runtime.GOOS == "windows" {
		shellScript = `@echo off
	set flag=%1
	set flag=%flag:"=%
	set args=%2
	set args=%args:"=%
	echo %flag% %args%
`
	} else {
		shellScript = `#!/bin/sh
echo $*
exit
`
	}

	shell, dir, err := internal.ScriptFile("govcs-ssh-shell")
	if err != nil {
		t.Fatal(err)
	}
	defer os.Remove(shell)
	if dir != "" {
		defer os.RemoveAll(dir)
	}

	err = internal.WriteFileWithPermissions(shell, []byte(shellScript), 0700)
	if err != nil {
		t.Fatal(err)
	}

	s, err := NewServer(shell, os.TempDir(), PrivateKey(SamplePrivKey))
	if err != nil {
		t.Fatal(err)
	}
	if err := s.Start(); err != nil {
		t.Fatal(err)
	}

	// Client
	cauth, err := clientAuth(SamplePrivKey)
	if err != nil {
		t.Fatal(err)
	}
	cconf := ssh.ClientConfig{User: "******"}
	cconf.Auth = append(cconf.Auth, cauth)
	sshc, err := ssh.Dial(s.l.Addr().Network(), s.l.Addr().String(), &cconf)
	if err != nil {
		t.Fatal(err)
	}
	defer sshc.Close()

	session, err := sshc.NewSession()
	if err != nil {
		t.Fatal(err)
	}
	defer session.Close()

	out, err := session.CombinedOutput("git-upload-pack 'foo'")
	if err != nil {
		t.Fatal(err)
	}
	if got, want := strings.TrimSpace(string(out)), "-c git-upload-pack 'foo'"; got != want {
		t.Errorf("got ssh session output %q, want %q", got, want)
	}
}
Beispiel #13
0
		Context("when the cc URL cannot be parsed", func() {
			BeforeEach(func() {
				ccAPIURL = ":://goober-swallow#yuck"
			})

			It("reports the problem and terminates", func() {
				Expect(runner).To(gbytes.Say("failed-to-parse-cc-api-url"))
				Expect(runner).NotTo(gexec.Exit(0))
			})
		})
	})

	Describe("execution", func() {
		var (
			clientConfig *ssh.ClientConfig
			processGuid  string
		)

		BeforeEach(func() {
			processGuid = "process-guid"
			clientConfig = &ssh.ClientConfig{
				User: "******",
				Auth: []ssh.AuthMethod{ssh.Password("")},
			}
		})

		JustBeforeEach(func() {
			sshRoute := routes.SSHRoute{
				ContainerPort:   9999,
				PrivateKey:      privateKeyPem,
				HostFingerprint: hostKeyFingerprint,