2020-03-19 15:17:40 -04:00
package worker
import (
"context"
2020-09-20 23:09:42 -04:00
"net"
2020-03-19 15:17:40 -04:00
"net/http"
2020-09-20 23:09:42 -04:00
"strconv"
2020-03-19 15:17:40 -04:00
2020-08-10 17:15:02 -04:00
"github.com/hashicorp/boundary/globals"
2020-09-20 12:51:08 -04:00
pbs "github.com/hashicorp/boundary/internal/gen/controller/servers/services"
2020-09-10 23:25:40 -04:00
"github.com/hashicorp/boundary/internal/proxy"
2020-08-12 16:12:45 -04:00
"github.com/hashicorp/shared-secure-libs/configutil"
2020-09-03 13:24:34 -04:00
"nhooyr.io/websocket"
2020-09-10 23:25:40 -04:00
"nhooyr.io/websocket/wspb"
2020-03-19 15:17:40 -04:00
)
type HandlerProperties struct {
ListenerConfig * configutil . Listener
}
// Handler returns an http.Handler for the API. This can be used on
2020-09-25 00:55:06 +08:00
// its own to mount the Worker API within another web server.
2020-09-03 13:24:34 -04:00
func ( w * Worker ) handler ( props HandlerProperties ) http . Handler {
2020-03-19 15:17:40 -04:00
// Create the muxer to handle the actual endpoints
mux := http . NewServeMux ()
2020-09-03 13:24:34 -04:00
mux . Handle ( "/v1/proxy" , w . handleProxy ())
2020-03-19 15:17:40 -04:00
2020-09-03 13:24:34 -04:00
genericWrappedHandler := w . wrapGenericHandler ( mux , props )
2020-03-19 15:17:40 -04:00
return genericWrappedHandler
}
2020-09-03 13:24:34 -04:00
func ( w * Worker ) handleProxy () http . HandlerFunc {
return http . HandlerFunc ( func ( wr http . ResponseWriter , r * http . Request ) {
if r . TLS == nil {
w . logger . Error ( "no request TLS information found" )
wr . WriteHeader ( http . StatusInternalServerError )
return
}
2020-09-19 00:18:17 -04:00
sessionId := r . TLS . ServerName
2020-09-03 13:24:34 -04:00
2020-09-20 23:09:42 -04:00
clientIp , clientPort , err := net . SplitHostPort ( r . RemoteAddr )
if err != nil {
2020-10-16 13:45:47 -04:00
w . logger . Error ( "unable to understand remote address" , "error" , err , "remote_addr" , r . RemoteAddr )
2020-09-20 23:09:42 -04:00
wr . WriteHeader ( http . StatusInternalServerError )
return
}
numPort , err := strconv . Atoi ( clientPort )
if err != nil {
w . logger . Error ( "unable to understand remote port" , "error" , err )
wr . WriteHeader ( http . StatusInternalServerError )
return
}
clientAddr := & net . TCPAddr {
IP : net . ParseIP ( clientIp ),
Port : numPort ,
}
2020-09-19 00:18:17 -04:00
w . logger . Trace ( "received TLS connection" )
2020-09-20 12:51:08 -04:00
siRaw , valid := w . sessionInfoMap . Load ( sessionId )
2020-09-03 13:24:34 -04:00
if ! valid {
2020-09-19 00:18:17 -04:00
w . logger . Error ( "session not found in info map" , "session_id" , sessionId )
2020-09-03 13:24:34 -04:00
wr . WriteHeader ( http . StatusInternalServerError )
return
}
2020-09-20 12:51:08 -04:00
si := siRaw .( * sessionInfo )
si . RLock ()
expiration := si . lookupSessionResponse . GetExpiration ()
tofuToken := si . lookupSessionResponse . GetTofuToken ()
version := si . lookupSessionResponse . GetVersion ()
endpoint := si . lookupSessionResponse . GetEndpoint ()
2021-01-07 10:02:32 -05:00
// userId := si.lookupSessionResponse.GetAuthorization()
2020-09-20 12:51:08 -04:00
sessStatus := si . status
si . RUnlock ()
2020-09-19 00:18:17 -04:00
w . logger . Trace ( "found session in session info map" )
2020-09-03 13:24:34 -04:00
opts := & websocket . AcceptOptions {
Subprotocols : [] string { globals . TcpProxyV1 },
}
conn , err := websocket . Accept ( wr , r , opts )
if err != nil {
w . logger . Error ( "error during websocket upgrade" , "error" , err )
wr . WriteHeader ( http . StatusInternalServerError )
return
}
// Later calls will cause this to noop if they return a different status
defer conn . Close ( websocket . StatusNormalClosure , "done" )
2020-09-19 00:18:17 -04:00
w . logger . Trace ( "websocket upgrade done" )
2020-09-20 12:51:08 -04:00
connCtx , connCancel := context . WithDeadline ( r . Context (), expiration . AsTime ())
defer connCancel ()
2020-09-03 13:24:34 -04:00
2020-09-19 00:18:17 -04:00
var handshake proxy . ClientHandshake
2020-09-10 23:25:40 -04:00
if err := wspb . Read ( connCtx , conn , & handshake ); err != nil {
2020-09-19 00:18:17 -04:00
w . logger . Error ( "error reading handshake from client" , "error" , err )
conn . Close ( websocket . StatusPolicyViolation , "invalid handshake received" )
2020-09-10 23:25:40 -04:00
return
}
if len ( handshake . GetTofuToken ()) < 20 {
w . logger . Error ( "invalid tofu token" )
2020-09-19 00:18:17 -04:00
conn . Close ( websocket . StatusUnsupportedData , "invalid tofu token" )
return
}
w . logger . Trace ( "proxy handshake finished" )
2020-09-20 12:51:08 -04:00
if tofuToken != "" {
if tofuToken != handshake . GetTofuToken () {
2020-09-19 00:18:17 -04:00
w . logger . Error ( "WARNING: mismatched tofu token" , "session_id" , sessionId )
conn . Close ( websocket . StatusPolicyViolation , "tofu token not allowed" )
return
}
} else {
2020-09-20 12:51:08 -04:00
if sessStatus != pbs . SESSIONSTATUS_SESSIONSTATUS_PENDING {
w . logger . Error ( "no tofu token but not in correct session state" , "error" , err )
conn . Close ( websocket . StatusInternalError , "refusing to activate session" )
return
}
2020-12-16 17:14:47 -05:00
if handshake . Command == proxy . HANDSHAKECOMMAND_HANDSHAKECOMMAND_UNSPECIFIED {
w . logger . Trace ( "activating session" )
sessStatus , err = w . activateSession ( r . Context (), sessionId , handshake . GetTofuToken (), version )
if err != nil {
w . logger . Error ( "unable to validate session" , "error" , err )
conn . Close ( websocket . StatusInternalError , "unable to activate session" )
return
}
}
}
if handshake . Command == proxy . HANDSHAKECOMMAND_HANDSHAKECOMMAND_SESSION_CANCEL {
w . logger . Trace ( "canceling session at client request" )
_ , err := w . cancelSession ( r . Context (), sessionId )
2020-09-20 12:51:08 -04:00
if err != nil {
2020-12-16 17:14:47 -05:00
w . logger . Error ( "unable to cancel session" , "error" , err )
conn . Close ( websocket . StatusInternalError , "unable to cancel session" )
2020-09-19 00:18:17 -04:00
return
}
2020-12-16 17:14:47 -05:00
conn . Close ( websocket . StatusNormalClosure , "session canceled" )
return
2020-09-19 00:18:17 -04:00
}
2020-09-20 12:51:08 -04:00
var ci * connInfo
2020-09-20 16:28:00 -04:00
var connsLeft int32
ci , connsLeft , err = w . authorizeConnection ( r . Context (), sessionId )
2020-09-20 12:51:08 -04:00
if err != nil {
2020-09-24 14:12:34 -04:00
w . logger . Error ( "unable to authorize connection" , "error" , err )
2020-09-20 12:51:08 -04:00
conn . Close ( websocket . StatusInternalError , "unable to authorize connection" )
return
}
2020-09-21 00:09:50 -04:00
defer func () {
connectionId := ci . id
2020-09-21 02:22:59 -04:00
if err := w . closeConnections ( r . Context (), map [ string ] string {
connectionId : si . id ,
}); err != nil {
2020-09-21 00:09:50 -04:00
w . logger . Error ( "error marking connection closed" , "error" , err , "connection_id" , connectionId )
}
}()
2020-09-20 12:51:08 -04:00
si . Lock ()
ci . connCtx = connCtx
ci . connCancel = connCancel
si . connInfoMap [ ci . id ] = ci
si . status = sessStatus
2020-09-20 21:18:07 -04:00
connectionLimit := si . lookupSessionResponse . GetConnectionLimit ()
2020-09-20 12:51:08 -04:00
si . Unlock ()
w . logger . Trace ( "authorized connection" , "connection_id" , ci . id )
2020-09-19 13:51:50 -04:00
handshakeResult := & proxy . HandshakeResult {
2020-09-20 16:28:00 -04:00
Expiration : expiration ,
2020-09-20 21:18:07 -04:00
ConnectionLimit : connectionLimit ,
2020-09-20 16:28:00 -04:00
ConnectionsLeft : connsLeft ,
2020-09-19 13:51:50 -04:00
}
if err := wspb . Write ( connCtx , conn , handshakeResult ); err != nil {
2020-09-19 00:18:17 -04:00
w . logger . Error ( "error sending handshake result to client" , "error" , err )
conn . Close ( websocket . StatusProtocolError , "unable to send handshake result" )
2020-09-10 23:25:40 -04:00
return
}
2020-09-03 13:24:34 -04:00
switch conn . Subprotocol () {
case globals . TcpProxyV1 :
2020-09-20 23:09:42 -04:00
w . handleTcpProxyV1 ( connCtx , clientAddr , conn , si , ci . id , endpoint )
2020-09-03 13:24:34 -04:00
default :
conn . Close ( websocket . StatusProtocolError , "unsupported-protocol" )
return
}
2020-03-19 15:17:40 -04:00
})
}
2020-09-03 13:24:34 -04:00
func ( w * Worker ) wrapGenericHandler ( h http . Handler , props HandlerProperties ) http . Handler {
return http . HandlerFunc ( func ( wr http . ResponseWriter , r * http . Request ) {
2020-03-19 15:17:40 -04:00
// Set the Cache-Control header for all responses returned
2020-09-03 13:24:34 -04:00
wr . Header (). Set ( "Cache-Control" , "no-store" )
h . ServeHTTP ( wr , r )
2020-03-19 15:17:40 -04:00
})
}
/*
func WrapForwardedForHandler(h http.Handler, authorizedAddrs []*sockaddr.SockAddrMarshaler, rejectNotPresent, rejectNonAuthz bool, hopSkips int) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
headers, headersOK := r.Header[textproto.CanonicalMIMEHeaderKey("X-Forwarded-For")]
if !headersOK || len(headers) == 0 {
if !rejectNotPresent {
h.ServeHTTP(w, r)
return
}
respondError(w, http.StatusBadRequest, fmt.Errorf("missing x-forwarded-for header and configured to reject when not present"))
return
}
host, port, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
// If not rejecting treat it like we just don't have a valid
// header because we can't do a comparison against an address we
// can't understand
if !rejectNotPresent {
h.ServeHTTP(w, r)
return
}
respondError(w, http.StatusBadRequest, errwrap.Wrapf("error parsing client hostport: {{err}}", err))
return
}
addr, err := sockaddr.NewIPAddr(host)
if err != nil {
// We treat this the same as the case above
if !rejectNotPresent {
h.ServeHTTP(w, r)
return
}
respondError(w, http.StatusBadRequest, errwrap.Wrapf("error parsing client address: {{err}}", err))
return
}
var found bool
for _, authz := range authorizedAddrs {
if authz.Contains(addr) {
found = true
break
}
}
if !found {
// If we didn't find it and aren't configured to reject, simply
// don't trust it
if !rejectNonAuthz {
h.ServeHTTP(w, r)
return
}
respondError(w, http.StatusBadRequest, fmt.Errorf("client address not authorized for x-forwarded-for and configured to reject connection"))
return
}
// At this point we have at least one value and it's authorized
// Split comma separated ones, which are common. This brings it in line
// to the multiple-header case.
var acc []string
for _, header := range headers {
vals := strings.Split(header, ",")
for _, v := range vals {
acc = append(acc, strings.TrimSpace(v))
}
}
indexToUse := len(acc) - 1 - hopSkips
if indexToUse < 0 {
// This is likely an error in either configuration or other
// infrastructure. We could either deny the request, or we
// could simply not trust the value. Denying the request is
// "safer" since if this logic is configured at all there may
// be an assumption it can always be trusted. Given that we can
// deny accepting the request at all if it's not from an
// authorized address, if we're at this point the address is
// authorized (or we've turned off explicit rejection) and we
// should assume that what comes in should be properly
// formatted.
respondError(w, http.StatusBadRequest, fmt.Errorf("malformed x-forwarded-for configuration or request, hops to skip (%d) would skip before earliest chain link (chain length %d)", hopSkips, len(headers)))
return
}
r.RemoteAddr = net.JoinHostPort(acc[indexToUse], port)
h.ServeHTTP(w, r)
return
})
}
*/