// DockerCleanup cleans all containers created by ssh2docker func DockerCleanup() error { containers, err := DockerListContainers(false) if err != nil { return err } for _, cid := range containers { if err = DockerKill(cid); err != nil { log.Warnf("Failed to kill container %q: %v", cid, err) } } containers, err = DockerListContainers(true) if err != nil { return err } for _, cid := range containers { if err = DockerRemove(cid); err != nil { log.Warnf("Failed to remove container %q: %v", cid, err) } } return nil }
// Init initializes server func (s *Server) Init() error { // Initialize only once if s.initialized { return nil } // disable password authentication if s.PasswordAuthScript == "" && s.PublicKeyAuthScript != "" { s.SshConfig.PasswordCallback = nil } // cleanup old containers if s.CleanOnStartup { err := dockerhelper.DockerCleanup() if err != nil { log.Warnf("Failed to cleanup docker containers: %v", err) } } s.initialized = true return nil }
// CheckConfig checks if the ClientConfig has access func (s *Server) CheckConfig(config *ClientConfig) error { if !config.Allowed && (s.PasswordAuthScript != "" || s.PublicKeyAuthScript != "") { log.Debugf("config.Allowed = false") return fmt.Errorf("Access not allowed") } if s.AllowedImages != nil { allowed := false for _, image := range s.AllowedImages { if image == config.ImageName { allowed = true break } } if !allowed { log.Warnf("Image is not allowed: %q", config.ImageName) return fmt.Errorf("Image not allowed") } } return nil }
func main() { log.SetHandler(cli.New(os.Stdout)) log.SetLevel(log.DebugLevel) s, err := config.LoadConfig(ConfigurationFileName) if err != nil { log.Warnf("Unable to read configuration file: %s", err.Error()) } d, err := store.Init(s.Location.Database, 2500) if err != nil { log.Fatalf("Unable to connect to data store at %s: %s", s.Location.Database, err.Error()) } r := gin.New() // If redirects to the secure are enabled, attach the secure middleware helper if s.Bind.Redirect { log.Debug("Secure redirects enabled") r.Use(secure.RedirectToSecureByProxy(s.Domain, s.Bind.Ports.Secure, s.Bind.Proxy.Secure)) } r.Use(gin.Logger()) r.Use(gin.Recovery()) // Add out own Middleware r.Use(store.Connect(d)) // Connect the relevant modules to the router alive.Init(r) log.Debug("Starting Run()") err = r.Run(s.Bind.Address + ":" + strconv.FormatInt(int64(s.Bind.Ports.Standard), 10)) if err != nil { log.Fatalf("Fatal error during Run: %s", err.Error()) } }
func (c *Client) runCommand(channel ssh.Channel, entrypoint string, command []string) { var cmd *exec.Cmd var err error if c.Config.IsLocal { cmd = exec.Command(entrypoint, command...) } else { // checking if a container already exists for this user existingContainer := "" if !c.Server.NoJoin { cmd = exec.Command("docker", "ps", "--filter=label=ssh2docker", fmt.Sprintf("--filter=label=image=%s", c.Config.ImageName), fmt.Sprintf("--filter=label=user=%s", c.Config.RemoteUser), "--quiet", "--no-trunc") cmd.Env = c.Config.Env.List() buf, err := cmd.CombinedOutput() if err != nil { log.Warnf("docker ps ... failed: %v", err) channel.Close() return } existingContainer = strings.TrimSpace(string(buf)) } // Opening Docker process if existingContainer != "" { // Attaching to an existing container args := []string{"exec"} if len(c.Config.DockerExecArgs) > 0 { args = append(args, c.Config.DockerExecArgs...) if err := c.alterArgs(args); err != nil { log.Errorf("Failed to execute template on args: %v", err) return } } else { inlineExec, err := c.alterArg(c.Server.DockerExecArgsInline) if err != nil { log.Errorf("Failed to execute template on arg: %v", err) return } execArgs, err := shlex.Split(inlineExec) if err != nil { log.Errorf("Failed to split arg %q: %v", inlineExec, err) return } args = append(args, execArgs...) } args = append(args, existingContainer) if entrypoint != "" { args = append(args, entrypoint) } args = append(args, command...) log.Debugf("Executing 'docker %s'", strings.Join(args, " ")) cmd = exec.Command("docker", args...) cmd.Env = c.Config.Env.List() } else { // Creating and attaching to a new container args := []string{"run"} if len(c.Config.DockerRunArgs) > 0 { args = append(args, c.Config.DockerRunArgs...) if err := c.alterArgs(args); err != nil { log.Errorf("Failed to execute template on args: %v", err) return } } else { inlineRun, err := c.alterArg(c.Server.DockerRunArgsInline) if err != nil { log.Errorf("Failed to execute template on arg: %v", err) return } runArgs, err := shlex.Split(inlineRun) if err != nil { log.Errorf("Failed to split arg %q: %v", inlineRun, err) return } args = append(args, runArgs...) } args = append(args, "--label=ssh2docker", fmt.Sprintf("--label=user=%s", c.Config.RemoteUser), fmt.Sprintf("--label=image=%s", c.Config.ImageName)) if c.Config.User != "" { args = append(args, "-u", c.Config.User) } if entrypoint != "" { args = append(args, "--entrypoint", entrypoint) } args = append(args, c.Config.ImageName) args = append(args, command...) log.Debugf("Executing 'docker %s'", strings.Join(args, " ")) cmd = exec.Command("docker", args...) cmd.Env = c.Config.Env.List() } } if c.Server.Banner != "" { banner := c.Server.Banner banner = strings.Replace(banner, "\r", "", -1) banner = strings.Replace(banner, "\n", "\n\r", -1) fmt.Fprintf(channel, "%s\n\r", banner) } cmd.Stdout = channel cmd.Stdin = channel cmd.Stderr = channel var wg sync.WaitGroup if c.Config.UseTTY { cmd.Stdout = c.Tty cmd.Stdin = c.Tty cmd.Stderr = c.Tty wg.Add(1) go func() { io.Copy(channel, c.Pty) wg.Done() }() wg.Add(1) go func() { io.Copy(c.Pty, channel) wg.Done() }() defer wg.Wait() } cmd.SysProcAttr = &syscall.SysProcAttr{ Setctty: c.Config.UseTTY, Setsid: true, } err = cmd.Start() if err != nil { log.Warnf("cmd.Start failed: %v", err) channel.Close() return } if err := cmd.Wait(); err != nil { log.Warnf("cmd.Wait failed: %v", err) } channel.Close() log.Debugf("cmd.Wait done") }
// Warnf level formatted message. func Warnf(msg string, v ...interface{}) { apexlog.Warnf(msg, v...) }
// KeyboardInteractiveCallback is called after PublicKeyCallback func (s *Server) KeyboardInteractiveCallback(conn ssh.ConnMetadata, challenge ssh.KeyboardInteractiveChallenge) (*ssh.Permissions, error) { username := conn.User() clientID := conn.RemoteAddr().String() log.Debugf("KeyboardInteractiveCallback: %q", username) config := s.ClientConfigs[clientID] if config == nil { s.ClientConfigs[clientID] = &ClientConfig{ RemoteUser: username, ImageName: username, Keys: []string{}, AuthenticationMethod: "noauth", AuthenticationAttempts: 0, AuthenticationComment: "", Env: make(envhelper.Environment, 0), } } config = s.ClientConfigs[clientID] if len(config.Keys) == 0 { log.Warnf("No user keys, continuing with password authentication") return nil, s.CheckConfig(config) } if s.PublicKeyAuthScript == "" { log.Debugf("%d keys received, but no hook script, continuing", len(config.Keys)) return nil, s.CheckConfig(config) } config.AuthenticationAttempts++ log.Debugf("%d keys received, trying to authenticate using publickey hook", len(config.Keys)) var output []byte switch { case strings.HasPrefix(s.PublicKeyAuthScript, "http://"), strings.HasPrefix(s.PublicKeyAuthScript, "https://"): input := struct { Username string `json:"username"` Publickeys []string `json:"publickeys"` }{ Username: username, Publickeys: config.Keys, } resp, body, errs := gorequest.New().Type("json").Post(s.PublicKeyAuthScript).Send(input).End() if len(errs) > 0 { return nil, fmt.Errorf("gorequest errs: %v", errs) } if resp.StatusCode != 200 { return nil, fmt.Errorf("invalid status code: %d", resp.StatusCode) } output = []byte(body) default: script, err := homedir.Expand(s.PublicKeyAuthScript) if err != nil { log.Warnf("Failed to expandUser: %v", err) return nil, err } cmd := exec.Command(script, append([]string{username}, config.Keys...)...) cmd.Env = config.Env.List() // FIXME: redirect stderr to log cmd.Stderr = os.Stderr output, err = cmd.Output() if err != nil { log.Warnf("Failed to execute publickey-auth-script: %v", err) return nil, err } } if err := json.Unmarshal(output, &config); err != nil { log.Warnf("Failed to unmarshal json %q: %v", string(output), err) return nil, err } if err := s.CheckConfig(config); err != nil { return nil, err } // success config.AuthenticationMethod = "publickey" return nil, nil }
// PasswordCallback is called when the user tries to authenticate using a password func (s *Server) PasswordCallback(conn ssh.ConnMetadata, password []byte) (*ssh.Permissions, error) { username := conn.User() clientID := conn.RemoteAddr().String() log.Debugf("PasswordCallback: %q %q", username, password) // map config in the memory config := s.ClientConfigs[clientID] if config == nil { s.ClientConfigs[clientID] = &ClientConfig{ //Allowed: true, RemoteUser: username, ImageName: username, Keys: []string{}, AuthenticationMethod: "noauth", AuthenticationAttempts: 0, AuthenticationComment: "", Env: make(envhelper.Environment, 0), } config = s.ClientConfigs[clientID] } // if there is a password callback if s.PasswordAuthScript == "" { return nil, s.CheckConfig(config) } config.AuthenticationAttempts++ var output []byte switch { case strings.HasPrefix(s.PasswordAuthScript, "http://"), strings.HasPrefix(s.PasswordAuthScript, "https://"): input := struct { Username string `json:"username"` Password string `json:"password"` }{ Username: username, Password: string(password), } resp, body, errs := gorequest.New().Type("json").Post(s.PasswordAuthScript).Send(input).End() if len(errs) > 0 { return nil, fmt.Errorf("gorequest errs: %v", errs) } if resp.StatusCode != 200 { return nil, fmt.Errorf("invalid status code: %d", resp.StatusCode) } output = []byte(body) default: script, err := homedir.Expand(s.PasswordAuthScript) if err != nil { log.Warnf("Failed to expandUser: %v", err) return nil, err } cmd := exec.Command(script, username, string(password)) cmd.Env = config.Env.List() // FIXME: redirect stderr to log cmd.Stderr = os.Stderr output, err = cmd.Output() if err != nil { log.Warnf("Failed to execute password-auth-script: %v", err) return nil, err } } if err := json.Unmarshal(output, &config); err != nil { log.Warnf("Failed to unmarshal json %q: %v", string(output), err) return nil, err } if err := s.CheckConfig(config); err != nil { return nil, err } // success config.AuthenticationMethod = "password" return nil, nil }