Esempio n. 1
0
File: scp.go Progetto: nrolans/netb
func (h *SCPHandler) SinkRequest(conn ssh.ServerConn, parameters scp.Parameter, pattern string) bool {

	h.conn = conn

	// Remote address lookup
	var err error
	h.name, err = lookupIP(conn.RemoteAddr().String())
	if err != nil {
		log.Println("Failed to lookup IP: %s", err)
		return false
	}

	log.Println("Accepting SCP request from %s", h.name)
	return true
}
Esempio n. 2
0
func NewSession(gateway *Gateway, connection *ssh.ServerConn) (*Session, error) {
	glog.V(1).Infof("new session: user = %s, remote = %v", connection.User(), connection.RemoteAddr())

	return &Session{
		gateway:        gateway,
		connection:     connection,
		user:           connection.User(),
		remoteAddr:     connection.RemoteAddr(),
		localAddr:      connection.LocalAddr(),
		services:       make(map[string]map[uint16]bool),
		lock:           &sync.Mutex{},
		active:         true,
		created:        time.Now(),
		used:           time.Now(),
		channelsClosed: 0,
		bytesRead:      0,
		bytesWritten:   0,
	}, nil
}
Esempio n. 3
0
// NewClient initializes a new client
func NewClient(conn *ssh.ServerConn, chans <-chan ssh.NewChannel, reqs <-chan *ssh.Request, server *Server) *Client {
	client := Client{
		Idx:        clientCounter,
		ClientID:   conn.RemoteAddr().String(),
		ChannelIdx: 0,
		Conn:       conn,
		Chans:      chans,
		Reqs:       reqs,
		Server:     server,

		// Default ClientConfig, will be overwritten if a hook is used
		Config: &ClientConfig{
			ImageName:              strings.Replace(conn.User(), "_", "/", -1),
			RemoteUser:             "******",
			AuthenticationMethod:   "noauth",
			AuthenticationComment:  "",
			AuthenticationAttempts: 0,
			Env:     envhelper.Environment{},
			Command: make([]string, 0),
		},
	}

	if server.LocalUser != "" {
		client.Config.IsLocal = client.Config.ImageName == server.LocalUser
	}

	if _, found := server.ClientConfigs[client.ClientID]; !found {
		server.ClientConfigs[client.ClientID] = client.Config
	}

	client.Config = server.ClientConfigs[conn.RemoteAddr().String()]
	client.Config.Env.ApplyDefaults()

	clientCounter++

	remoteAddr := strings.Split(client.ClientID, ":")
	log.Infof("Accepted %s for %s from %s port %s ssh2: %s", client.Config.AuthenticationMethod, conn.User(), remoteAddr[0], remoteAddr[1], client.Config.AuthenticationComment)
	return &client
}
Esempio n. 4
0
/* connectionLogger opens a log file for the authenticated connection in the
given logDir.  It returns the logger itself, as well as the name of the
logfile and the session directory.  Should look like
	logdir/address/sessiontime/log
The returned *os.File must be closed when it's no longer needed to prevent
memory/fd leakage.
*/
func connectionLogger(
	sc *ssh.ServerConn,
	logDir string,
) (lg *log.Logger, name, dir string, file *os.File, err error) {
	/* Each host gets its own directory */
	addrDir, _, err := net.SplitHostPort(sc.RemoteAddr().String())
	if nil != err {
		log.Printf(
			"Address:%v Unable to split host from port: %v",
			sc.RemoteAddr().String(),
			err,
		)
		addrDir = sc.RemoteAddr().String() + "err"
	}

	/* Each authenticated session does, as well */
	sessionDir := filepath.Join(
		logDir,
		addrDir,
		time.Now().Format(LOGFORMAT),
	)
	if err := os.MkdirAll(sessionDir, 0700); nil != err {
		return nil, "", "", nil, err
	}
	/* Open the main logfile */
	logName := filepath.Join(sessionDir, LOGNAME)
	lf, err := os.OpenFile(
		logName,
		os.O_WRONLY|os.O_APPEND|os.O_CREATE|os.O_EXCL,
		0600,
	)
	if nil != err {
		return nil, "", "", nil, err
	}

	/* Logify it. */
	return log.New(
		//lf,
		io.MultiWriter(lf, os.Stderr), /* DEBUG */
		"",
		log.LstdFlags|log.Lmicroseconds,
	), logName, sessionDir, lf, nil
}
Esempio n. 5
0
File: sshd.go Progetto: bachue/pages
func (server *Server) handleChannel(newChannel ssh.NewChannel, conn *ssh.ServerConn) {
	channelType := newChannel.ChannelType()
	if channelType != "session" {
		newChannel.Reject(ssh.UnknownChannelType,
			fmt.Sprintf("Unknown SSH Channel Type: %s, only `session` is supported", channelType))
		server.Logger.Errorf("Rejected SSH Channel Request from %s due to unknown channel type: %s",
			conn.RemoteAddr().String(), newChannel.ChannelType())
		return
	}
	channel, requests, err := newChannel.Accept()
	if err != nil {
		newChannel.Reject(ssh.ConnectionFailed, "Failed to accept SSH Channel Request, developers are working on it.")
		server.Logger.Errorf("Rejected SSH Channel Request from %s due to accept request failure: %s",
			conn.RemoteAddr().String(), err)
		return
	}
	server.Logger.Debugf("Accepted new SSH Channel Request from %s", conn.RemoteAddr().String())

	server.handleRequest(channel, requests, conn)
}
Esempio n. 6
0
File: sshd.go Progetto: bachue/pages
func (server *Server) handleRequest(channel ssh.Channel, requests <-chan *ssh.Request, conn *ssh.ServerConn) {
	defer func() {
		err := channel.Close()
		if err != nil {
			server.Logger.Errorf("Failed to close SSH Channel from %s due to %s",
				conn.RemoteAddr().String(), err)
		}
		server.Logger.Debugf("Close SSH Channel from %s", conn.RemoteAddr().String())
	}()
	for req := range requests {
		server.Logger.Debugf("Received new SSH Request (type = %s) from %s", req.Type, conn.RemoteAddr().String())

		switch req.Type {
		case "exec":
			server.handleExecRequest(channel, req, conn)
		default:
			var err error
			if req.Type == "env" {
				_, err = channel.Stderr().Write([]byte("error: Pages does not support SendEnv.\n"))
			} else {
				_, err = channel.Write([]byte("You've successfully authenticated, but Pages does not provide shell access.\n"))
			}
			if err != nil && err != io.EOF {
				server.Logger.Errorf("Failed to Talk to SSH Request due to %s", err)
			}
			err = req.Reply(false, nil)
			if err != nil && err != io.EOF {
				server.Logger.Errorf("Failed to Reply false to SSH Request due to %s", err)
			}
			err = channel.Close()
			if err != nil && err != io.EOF {
				server.Logger.Errorf("Failed to close SSH Request due to %s", err)
			}
			server.Logger.Errorf("Close SSH Request due to unsupported SSH Request type: %s", req.Type)
		}
		return
	}
}
Esempio n. 7
0
func newAttacker(conn *ssh.ServerConn, username string, password string) *Attacker {
	addr := conn.RemoteAddr().String()
	addr = ipAddrFromRemoteAddr(addr)
	return &Attacker{addr, username, password}
}
Esempio n. 8
0
File: sshd.go Progetto: bachue/pages
func (server *Server) handleExecRequest(channel ssh.Channel, request *ssh.Request, conn *ssh.ServerConn) {
	doReply := func(ok bool) {
		err := request.Reply(ok, nil)
		if err != nil {
			server.Logger.Errorf("Failed to reply %t to SSH Request from %s due to %s",
				ok, conn.RemoteAddr().String(), err)
		}
		server.Logger.Debugf("Reply to SSH Request `%t` from %s", ok, conn.RemoteAddr().String())
	}
	if len(request.Payload) < 4 {
		server.Logger.Errorf("Payload must not be shorter than 4 bytes, but only %d bytes", len(request.Payload))
		doReply(false)
		return
	}
	header := request.Payload[:4]
	cmdLen := int64(binary.BigEndian.Uint32(header))
	if int64(len(request.Payload)) < 4+cmdLen {
		server.Logger.Errorf("Payload must not be shorter than %d bytes, but only %d bytes", 4+cmdLen, len(request.Payload))
		doReply(false)
		return
	}
	cmd := request.Payload[4 : 4+cmdLen]
	server.Logger.Debugf("Execute command `%s` via SSH from %s",
		string(cmd), conn.RemoteAddr().String())

	shellCmd := exec.Command(server.Config.ShellPath, "-c", string(cmd))

	stdinPipe, err := shellCmd.StdinPipe()
	if err != nil {
		server.Logger.Errorf("Failed to create STDIN pipe error for command: %s", err)
		doReply(false)
		return
	}
	defer stdinPipe.Close()

	stdoutPipe, err := shellCmd.StdoutPipe()
	if err != nil {
		server.Logger.Errorf("Failed to create STDOUT pipe error for command: %s", err)
		doReply(false)
		return
	}
	defer stdoutPipe.Close()

	stderrPipe, err := shellCmd.StderrPipe()
	if err != nil {
		server.Logger.Errorf("Failed to create STDERR pipe error for command: %s", err)
		doReply(false)
		return
	}
	defer stderrPipe.Close()

	sendExitStatus := func() {
		channel.SendRequest("exit-status", false, []byte{0, 0, 0, 0})
		server.Logger.Debugf("Sent exit status 0 to %s", conn.RemoteAddr().String())
	}

	var once sync.Once

	go func() {
		io.Copy(stdinPipe, channel)
		once.Do(sendExitStatus)
	}()
	go func() {
		io.Copy(channel, stdoutPipe)
		once.Do(sendExitStatus)
	}()
	go func() {
		io.Copy(channel.Stderr(), stderrPipe)
		once.Do(sendExitStatus)
	}()

	err = shellCmd.Start()
	if err != nil {
		server.Logger.Errorf("Close SSH Channel from %s due to command error: %s", conn.RemoteAddr().String(), err)
		doReply(false)
		return
	}

	doReply(true)
	_, err = shellCmd.Process.Wait()
	if err != nil {
		_, ok := err.(*exec.ExitError)
		if !ok {
			server.Logger.Errorf("Failed to wait command(PID = %d) due to %s", shellCmd.Process.Pid, err)
		}
		return
	}
}
Esempio n. 9
0
File: sshd.go Progetto: bachue/pages
func (server *Server) handleChannels(chans <-chan ssh.NewChannel, conn *ssh.ServerConn) {
	// Service the incoming Channel channel in go routine
	for newChannel := range chans {
		server.Logger.Debugf("New SSH Channel Request %s from %s", newChannel.ChannelType(), conn.RemoteAddr().String())
		// TODO: Find Channel ID to log
		go server.handleChannel(newChannel, conn)
	}
}