func (s *SSHCommandSuite) TestCommandEnablePTY(c *gc.C) { var opts ssh.Options opts.EnablePTY() s.assertCommandArgs(c, s.commandOptions([]string{"echo", "123"}, &opts), s.fakessh+" -o StrictHostKeyChecking no -o PasswordAuthentication no -t -t localhost echo 123", ) }
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)) }
func (s *SSHCommandSuite) TestCommandIdentities(c *gc.C) { var opts ssh.Options opts.SetIdentities("x", "y") s.assertCommandArgs(c, s.commandOptions([]string{"echo", "123"}, &opts), s.fakessh+" -o StrictHostKeyChecking no -o PasswordAuthentication no -i x -i y localhost echo 123", ) }
func (s *SSHCommandSuite) TestCopy(c *gc.C) { var opts ssh.Options opts.EnablePTY() opts.AllowPasswordAuthentication() opts.SetIdentities("x", "y") opts.SetPort(2022) err := s.client.Copy([]string{"/tmp/blah", "[email protected]:baz"}, &opts) c.Assert(err, gc.IsNil) out, err := ioutil.ReadFile(s.fakescp + ".args") c.Assert(err, gc.IsNil) // EnablePTY has no effect for Copy c.Assert(string(out), gc.Equals, s.fakescp+" -o StrictHostKeyChecking no -i x -i y -P 2022 /tmp/blah [email protected]:baz\n") // Try passing extra args err = s.client.Copy([]string{"/tmp/blah", "[email protected]:baz", "-r", "-v"}, &opts) c.Assert(err, gc.IsNil) out, err = ioutil.ReadFile(s.fakescp + ".args") c.Assert(err, gc.IsNil) c.Assert(string(out), gc.Equals, s.fakescp+" -o StrictHostKeyChecking no -i x -i y -P 2022 /tmp/blah [email protected]:baz -r -v\n") // Try interspersing extra args err = s.client.Copy([]string{"-r", "/tmp/blah", "-v", "[email protected]:baz"}, &opts) c.Assert(err, gc.IsNil) out, err = ioutil.ReadFile(s.fakescp + ".args") c.Assert(err, gc.IsNil) c.Assert(string(out), gc.Equals, s.fakescp+" -o StrictHostKeyChecking no -i x -i y -P 2022 -r /tmp/blah -v [email protected]:baz\n") }
// setProxyCommand sets the proxy command option. func (c *SSHCommon) setProxyCommand(options *ssh.Options) error { apiServerHost, _, err := net.SplitHostPort(c.apiAddr) if err != nil { return fmt.Errorf("failed to get proxy address: %v", err) } juju, err := getJujuExecutable() if err != nil { return fmt.Errorf("failed to get juju executable path: %v", err) } options.SetProxyCommand(juju, "ssh", "--proxy=false", "--pty=false", apiServerHost, "nc", "-q0", "%h", "%p") return nil }
func (s *SSHCommandSuite) TestCommandClientKeys(c *gc.C) { defer overrideGenerateKey(c).Restore() clientKeysDir := c.MkDir() defer ssh.ClearClientKeys() err := ssh.LoadClientKeys(clientKeysDir) c.Assert(err, gc.IsNil) ck := filepath.Join(clientKeysDir, "juju_id_rsa") var opts ssh.Options opts.SetIdentities("x", "y") s.assertCommandArgs(c, s.commandOptions([]string{"echo", "123"}, &opts), s.fakessh+" -o StrictHostKeyChecking no -o PasswordAuthentication no -i x -i y -i "+ck+" localhost echo 123", ) }
// getSSHOptions configures and returns SSH options and proxy settings. func (c *SSHCommon) getSSHOptions(enablePty bool) (*ssh.Options, error) { var options ssh.Options if enablePty { options.EnablePTY() } var err error if c.proxy, err = c.proxySSH(); err != nil { return nil, err } else if c.proxy { if err := c.setProxyCommand(&options); err != nil { return nil, err } } return &options, nil }
func (s *SSHCommandSuite) TestCommandDefaultIdentities(c *gc.C) { var opts ssh.Options tempdir := c.MkDir() def1 := filepath.Join(tempdir, "def1") def2 := filepath.Join(tempdir, "def2") s.PatchValue(ssh.DefaultIdentities, []string{def1, def2}) // If no identities are specified, then the defaults aren't added. s.assertCommandArgs(c, s.commandOptions([]string{"echo", "123"}, &opts), s.fakessh+" -o StrictHostKeyChecking no -o PasswordAuthentication no localhost echo 123", ) // If identities are specified, then the defaults are must added. // Only the defaults that exist on disk will be added. err := ioutil.WriteFile(def2, nil, 0644) c.Assert(err, gc.IsNil) opts.SetIdentities("x", "y") s.assertCommandArgs(c, s.commandOptions([]string{"echo", "123"}, &opts), s.fakessh+" -o StrictHostKeyChecking no -o PasswordAuthentication no -i x -i y -i "+def2+" localhost echo 123", ) }
// InitUbuntuUser adds the ubuntu user if it doesn't // already exist, updates its ~/.ssh/authorized_keys, // and enables passwordless sudo for it. // // InitUbuntuUser will initially attempt to login as // the ubuntu user, and verify that passwordless sudo // is enabled; only if this is false will there be an // attempt with the specified login. // // authorizedKeys may be empty, in which case the file // will be created and left empty. // // stdin and stdout will be used for remote sudo prompts, // if the ubuntu user must be created/updated. func InitUbuntuUser(host, login, authorizedKeys string, stdin io.Reader, stdout io.Writer) error { logger.Infof("initialising %q, user %q", host, login) // To avoid unnecessary prompting for the specified login, // initUbuntuUser will first attempt to ssh to the machine // as "ubuntu" with password authentication disabled, and // ensure that it can use sudo without a password. // // Note that we explicitly do not allocate a PTY, so we // get a failure if sudo prompts. cmd := ssh.Command("ubuntu@"+host, []string{"sudo", "-n", "true"}, nil) if cmd.Run() == nil { logger.Infof("ubuntu user is already initialised") return nil } // Failed to login as ubuntu (or passwordless sudo is not enabled). // Use specified login, and execute the initUbuntuScript below. if login != "" { host = login + "@" + host } script := fmt.Sprintf(initUbuntuScript, utils.ShQuote(authorizedKeys)) var options ssh.Options options.AllowPasswordAuthentication() options.EnablePTY() cmd = ssh.Command(host, []string{"sudo", "/bin/bash -c " + utils.ShQuote(script)}, &options) var stderr bytes.Buffer cmd.Stdin = stdin cmd.Stdout = stdout // for sudo prompt cmd.Stderr = &stderr if err := cmd.Run(); err != nil { if stderr.Len() != 0 { err = fmt.Errorf("%v (%v)", err, strings.TrimSpace(stderr.String())) } return err } return nil }
func (s *SSHGoCryptoCommandSuite) TestCommand(c *gc.C) { 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 opts.SetPort(server.Addr().(*net.TCPAddr).Port) cmd := client.Command("127.0.0.1", testCommand, &opts) checkedKey := false server.cfg.PublicKeyCallback = func(conn *cryptossh.ServerConn, user, algo string, pubkey []byte) bool { c.Check(pubkey, gc.DeepEquals, cryptossh.MarshalPublicKey(key.PublicKey())) checkedKey = true 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) c.Assert(checkedKey, jc.IsTrue) }