-
Notifications
You must be signed in to change notification settings - Fork 1.8k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
SSH connection hand-over #38545
SSH connection hand-over #38545
Changes from 7 commits
68b5f58
226decc
4b4eb5a
71cabe8
56c74ec
cfbec5f
63794f5
50e4b60
0608afd
44c62fa
fa81fa6
a2924f2
aefbc45
3f14a35
da39989
347ca06
f434358
006bd9e
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,112 @@ | ||
// Teleport | ||
// Copyright (C) 2024 Gravitational, Inc. | ||
// | ||
// This program is free software: you can redistribute it and/or modify | ||
// it under the terms of the GNU Affero General Public License as published by | ||
// the Free Software Foundation, either version 3 of the License, or | ||
// (at your option) any later version. | ||
// | ||
// This program is distributed in the hope that it will be useful, | ||
// but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
// GNU Affero General Public License for more details. | ||
// | ||
// You should have received a copy of the GNU Affero General Public License | ||
// along with this program. If not, see <http://www.gnu.org/licenses/>. | ||
|
||
package resumption | ||
|
||
import ( | ||
"context" | ||
"io" | ||
"net" | ||
"net/netip" | ||
"time" | ||
|
||
"github.com/gravitational/trace" | ||
|
||
"github.com/gravitational/teleport/lib/multiplexer" | ||
"github.com/gravitational/teleport/lib/utils" | ||
) | ||
|
||
func (r *SSHServerWrapper) attemptHandover(conn *multiplexer.Conn, token resumptionToken) { | ||
handoverConn, err := r.dialHandover(token) | ||
if err != nil { | ||
if trace.IsNotFound(err) { | ||
r.log.Debug("Resumable connection not found or already deleted.") | ||
_, _ = conn.Write([]byte{notFoundServerExchangeTag}) | ||
return | ||
} | ||
r.log.WithError(err).Error("Error while connecting to handover socket.") | ||
return | ||
} | ||
defer handoverConn.Close() | ||
|
||
var remoteIP netip.Addr | ||
if t, _ := conn.RemoteAddr().(*net.TCPAddr); t != nil { | ||
remoteIP, _ = netip.AddrFromSlice(t.IP) | ||
} | ||
remoteIP16 := remoteIP.As16() | ||
|
||
if _, err := handoverConn.Write(remoteIP16[:]); err != nil { | ||
if !utils.IsOKNetworkError(err) { | ||
r.log.WithError(err).Error("Error while forwarding remote address to handover socket.") | ||
} | ||
return | ||
} | ||
|
||
r.log.Debug("Forwarding resuming connection to handover socket.") | ||
_ = utils.ProxyConn(context.Background(), conn, handoverConn) | ||
espadolini marked this conversation as resolved.
Show resolved
Hide resolved
|
||
} | ||
|
||
func (r *SSHServerWrapper) setupHandoverListener(ctx context.Context, token resumptionToken, entry *connEntry) error { | ||
ibeckermayer marked this conversation as resolved.
Show resolved
Hide resolved
|
||
l, err := r.listenHandover(token) | ||
espadolini marked this conversation as resolved.
Show resolved
Hide resolved
|
||
if err != nil { | ||
return trace.Wrap(err) | ||
} | ||
|
||
go r.runHandoverListener(l, entry) | ||
context.AfterFunc(ctx, func() { _ = l.Close() }) | ||
|
||
return nil | ||
} | ||
|
||
func (r *SSHServerWrapper) runHandoverListener(l net.Listener, entry *connEntry) { | ||
defer l.Close() | ||
|
||
var tempDelay time.Duration | ||
for { | ||
c, err := l.Accept() | ||
if err == nil { | ||
tempDelay = 0 | ||
go r.handleHandoverConnection(c, entry) | ||
continue | ||
} | ||
|
||
if tempErr, ok := err.(interface{ Temporary() bool }); !ok || !tempErr.Temporary() { | ||
if !utils.IsOKNetworkError(err) { | ||
r.log.WithError(err).Warn("Accept error in handover listener.") | ||
} | ||
return | ||
} | ||
|
||
tempDelay = max(5*time.Millisecond, min(2*tempDelay, time.Second)) | ||
r.log.WithError(err).WithField("delay", tempDelay).Warn("Temporary accept error in handover listener, continuing after delay.") | ||
time.Sleep(tempDelay) | ||
ibeckermayer marked this conversation as resolved.
Show resolved
Hide resolved
|
||
} | ||
} | ||
|
||
func (r *SSHServerWrapper) handleHandoverConnection(conn net.Conn, entry *connEntry) { | ||
defer conn.Close() | ||
|
||
var remoteIP16 [16]byte | ||
if _, err := io.ReadFull(conn, remoteIP16[:]); err != nil { | ||
if !utils.IsOKNetworkError(err) { | ||
r.log.WithError(err).Error("Error while reading remote address from handover socket.") | ||
} | ||
return | ||
} | ||
remoteIP := netip.AddrFrom16(remoteIP16).Unmap() | ||
|
||
r.resumeConnection(entry, conn, remoteIP) | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,40 @@ | ||
//go:build !unix | ||
|
||
// Teleport | ||
// Copyright (C) 2024 Gravitational, Inc. | ||
// | ||
// This program is free software: you can redistribute it and/or modify | ||
// it under the terms of the GNU Affero General Public License as published by | ||
// the Free Software Foundation, either version 3 of the License, or | ||
// (at your option) any later version. | ||
// | ||
// This program is distributed in the hope that it will be useful, | ||
// but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
// GNU Affero General Public License for more details. | ||
// | ||
// You should have received a copy of the GNU Affero General Public License | ||
// along with this program. If not, see <http://www.gnu.org/licenses/>. | ||
|
||
package resumption | ||
|
||
import ( | ||
"context" | ||
"net" | ||
|
||
"github.com/gravitational/trace" | ||
) | ||
|
||
func (r *SSHServerWrapper) listenHandover(token resumptionToken) (net.Listener, error) { | ||
return nil, trace.NotImplemented("handover is not implemented for the current platform") | ||
} | ||
|
||
func (r *SSHServerWrapper) dialHandover(token resumptionToken) (net.Conn, error) { | ||
return nil, trace.NotFound("handover is not implemented for the current platform") | ||
} | ||
|
||
// HandoverCleanup does nothing, because on this platform we don't support | ||
// hand-over sockets, so there can't be anything to clean up. | ||
func (r *SSHServerWrapper) HandoverCleanup(context.Context) error { | ||
return nil | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,173 @@ | ||
//go:build unix | ||
|
||
// Teleport | ||
// Copyright (C) 2024 Gravitational, Inc. | ||
// | ||
// This program is free software: you can redistribute it and/or modify | ||
// it under the terms of the GNU Affero General Public License as published by | ||
// the Free Software Foundation, either version 3 of the License, or | ||
// (at your option) any later version. | ||
// | ||
// This program is distributed in the hope that it will be useful, | ||
// but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
// GNU Affero General Public License for more details. | ||
// | ||
// You should have received a copy of the GNU Affero General Public License | ||
// along with this program. If not, see <http://www.gnu.org/licenses/>. | ||
|
||
package resumption | ||
|
||
import ( | ||
"context" | ||
"crypto/sha256" | ||
"encoding/base64" | ||
"errors" | ||
"net" | ||
"os" | ||
"path/filepath" | ||
"strings" | ||
"syscall" | ||
"time" | ||
|
||
"github.com/gravitational/trace" | ||
) | ||
|
||
const sockSuffix = ".sock" | ||
|
||
func sockPath(dataDir string, token resumptionToken) string { | ||
hash := sha256.Sum256(token[:]) | ||
// unix domain sockets are limited to 108 or 104 characters, so the full | ||
// sha256 hash is a bit too much (64 bytes in hex or 44 in b64); truncating | ||
// the hash to 128 bits still gives us more than enough headroom to just | ||
// assume that we'll have no collisions (a probability of one in a | ||
// quintillion with 26 billion concurrent connections) | ||
return filepath.Join(dataDir, "handover", base64.RawURLEncoding.EncodeToString(hash[:16])+sockSuffix) | ||
} | ||
|
||
func sockDir(dataDir string) string { | ||
return filepath.Join(dataDir, "handover") | ||
} | ||
|
||
var errNoDataDir error = &trace.NotFoundError{Message: "data dir not configured"} | ||
|
||
func (r *SSHServerWrapper) listenHandover(token resumptionToken) (net.Listener, error) { | ||
if r.dataDir == "" { | ||
return nil, trace.Wrap(errNoDataDir) | ||
} | ||
|
||
_ = os.MkdirAll(sockDir(r.dataDir), 0o700) | ||
ibeckermayer marked this conversation as resolved.
Show resolved
Hide resolved
|
||
l, err := net.Listen("unix", sockPath(r.dataDir, token)) | ||
if err != nil { | ||
return nil, trace.ConvertSystemError(err) | ||
} | ||
return l, nil | ||
} | ||
|
||
func (r *SSHServerWrapper) dialHandover(token resumptionToken) (net.Conn, error) { | ||
if r.dataDir == "" { | ||
return nil, trace.Wrap(errNoDataDir) | ||
} | ||
|
||
c, err := net.DialTimeout("unix", sockPath(r.dataDir, token), time.Second) | ||
if err != nil { | ||
return nil, trace.ConvertSystemError(err) | ||
} | ||
return c, nil | ||
} | ||
|
||
func filterNonConnectableSockets(ctx context.Context, paths []string) (filtered []string, lastErr error) { | ||
filtered = paths[:0] | ||
|
||
var d net.Dialer | ||
for _, path := range paths { | ||
c, err := d.DialContext(ctx, "unix", path) | ||
if err == nil { | ||
_ = c.Close() | ||
continue | ||
} | ||
|
||
if errors.Is(err, os.ErrNotExist) { | ||
continue | ||
} | ||
|
||
if errors.Is(err, syscall.ECONNREFUSED) { | ||
filtered = append(filtered, path) | ||
continue | ||
} | ||
|
||
lastErr = trace.ConvertSystemError(err) | ||
} | ||
|
||
return filtered, lastErr | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. It looks like we only return There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I don't think it'd be super useful to collect all the errors, this is basically just to log the error to identify potential issues during cleanup (say, after changing the user that runs Teleport or something like that). That's why I'm only keeping the last one that occurred. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. That reasoning doesn't really make sense to me, if we want to identify potential issues during cleanup then we'd want to see all the errors in case there were multiple different ones. If you're adamant that this is the correct approach then I won't fight you further, but you should at least add a comment explaining why you're doing something non-standard. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I'm just not sure of what'll happen when we aggregate a potentially unbound amount of errors; I'm already kind of spooked by the potential for weirdness as we aggregate errors for all the There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I've capped the amount of errors when aggregating in f434358, in both retainNonConnectableSockets and handoverCleanup. WDYT? |
||
} | ||
|
||
type cleanupDelayContextKey struct{} | ||
|
||
// HandoverCleanup deletes hand-over sockets that were left over from previous | ||
// runs of Teleport that failed to clean up after themselves (because of an | ||
// uncatchable signal or a system crash). It will exhaustively clean up the | ||
// current left over sockets, so it's sufficient to call it once per process. | ||
func (r *SSHServerWrapper) HandoverCleanup(ctx context.Context) error { | ||
if r.dataDir == "" { | ||
return nil | ||
} | ||
ibeckermayer marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
dir := sockDir(r.dataDir) | ||
entries, err := os.ReadDir(dir) | ||
if err != nil { | ||
if errors.Is(err, os.ErrNotExist) { | ||
return nil | ||
} | ||
return trace.ConvertSystemError(err) | ||
} | ||
|
||
paths := make([]string, 0, len(entries)) | ||
for _, entry := range entries { | ||
if strings.HasSuffix(entry.Name(), sockSuffix) { | ||
paths = append(paths, filepath.Join(dir, entry.Name())) | ||
} | ||
} | ||
|
||
paths, firstErr := filterNonConnectableSockets(ctx, paths) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Got tripped up by the function naming here, which to me sounds like you're filtering out non-connectable sockets, consider chnaging to There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Shouldn't we check There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. We return (and then log |
||
|
||
if len(paths) < 1 { | ||
return trace.Wrap(firstErr) | ||
} | ||
|
||
// unix domain sockets exist on disk between bind() and listen() but | ||
// connecting before listen() results in ECONNREFUSED, so we just wait a | ||
// little bit before testing them again; the first check lets us be done | ||
// with the check immediately in the happy case where there's no | ||
// unconnectable sockets | ||
r.log.WithField("sockets", len(paths)).Debug("Found some unconnectable handover sockets, waiting before checking them again.") | ||
ibeckermayer marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
cleanupDelay := time.Second | ||
if d, ok := ctx.Value((*cleanupDelayContextKey)(nil)).(time.Duration); ok { | ||
cleanupDelay = d | ||
} | ||
espadolini marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
select { | ||
case <-ctx.Done(): | ||
return trace.NewAggregate(firstErr, ctx.Err()) | ||
case <-time.After(cleanupDelay): | ||
} | ||
|
||
paths, secondErr := filterNonConnectableSockets(ctx, paths) | ||
|
||
if len(paths) < 1 { | ||
r.log.Debug("Found no unconnectable handover socket after waiting.") | ||
return trace.NewAggregate(firstErr, secondErr) | ||
} | ||
|
||
r.log.WithField("sockets", len(paths)).Info("Cleaning up some non-connectable handover sockets, left over from previous Teleport instances.") | ||
|
||
errs := []error{firstErr, secondErr} | ||
for _, path := range paths { | ||
if err := trace.ConvertSystemError(os.Remove(path)); err != nil { | ||
errs = append(errs, err) | ||
} | ||
} | ||
|
||
return trace.NewAggregate(errs...) | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I'm comfortable leaving the remote IP slice as all zeroes and let the server decide if that's good enough or not, rather than prohibit it in the client side.