Skip to content
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

Allow REST endpoints to hijack readers to allow file upload and download #12

Draft
wants to merge 3 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
120 changes: 93 additions & 27 deletions cmd/guac/guac.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,46 +9,98 @@ import (
"net/url"
"strconv"

"github.com/gorilla/mux"
"github.com/gorilla/websocket"
"github.com/sirupsen/logrus"
"github.com/wwt/guac"
)

var tunnels map[string]guac.Tunnel

func main() {
logrus.SetLevel(logrus.DebugLevel)

servlet := guac.NewServer(DemoDoConnect)
// servlet := guac.NewServer(DemoDoConnect)
wsServer := guac.NewWebsocketServer(DemoDoConnect)
wsServerIntercept := guac.NewWebsocketServer(DemoDoConnectWithIntercept)

sessions := guac.NewMemorySessionStore()
wsServer.OnConnect = sessions.Add
wsServer.OnDisconnect = sessions.Delete

mux := http.NewServeMux()
mux.Handle("/tunnel", servlet)
mux.Handle("/tunnel/", servlet)
mux.Handle("/websocket-tunnel", wsServer)
mux.HandleFunc("/sessions/", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
wsServerIntercept.OnConnect = sessions.Add
wsServerIntercept.OnDisconnect = sessions.Delete

tunnels = make(map[string]guac.Tunnel)

wsServerIntercept.OnConnectWs = func(s string, _ *websocket.Conn, _ *http.Request, t guac.Tunnel) {
tunnels[s] = t
}

wsServerIntercept.OnDisconnectWs = func(s string, _ *websocket.Conn, _ *http.Request, _ guac.Tunnel) {
delete(tunnels, s)
}

m := mux.NewRouter()

// m.Handle("/", servlet)
m.Handle("/websocket-tunnel", wsServer)
m.Handle("/websocket-tunnel-intercept", wsServerIntercept)

m.HandleFunc("/api/session/tunnels/{tunnel}/streams/{stream}/{file}", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Disposition", "attachment")
t := mux.Vars(r)["tunnel"]

tunnel, ok := tunnels[t]
if !ok {
w.Write([]byte("KO"))
w.WriteHeader(http.StatusInternalServerError)
return
}

sit, ok := tunnel.(*guac.UserTunnel)
if !ok {
w.Write([]byte("Not supported"))
w.WriteHeader(http.StatusBadRequest)
return
}

stream := mux.Vars(r)["stream"]

if err := sit.InterceptOutputStream(stream, w); err != nil {
w.Write([]byte("KO Intercepting output stream"))
}
}).Methods("GET")

m.HandleFunc("/api/session/tunnels/{tunnel}/streams/{stream}/{file}", func(w http.ResponseWriter, r *http.Request) {
t := mux.Vars(r)["tunnel"]
tunnel, ok := tunnels[t]
if !ok {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("KO"))
return
}

sit, ok := tunnel.(*guac.UserTunnel)
if !ok {
w.Write([]byte("Not supported"))
w.WriteHeader(http.StatusBadRequest)
return
}

sessions.RLock()
defer sessions.RUnlock()
stream := mux.Vars(r)["stream"]

type ConnIds struct {
Uuid string `json:"uuid"`
Num int `json:"num"`
if err := sit.InterceptInputStream(stream, r.Body); err != nil {
w.Write([]byte("KO intercepting input stream"))
}
}).Methods("POST")

connIds := make([]*ConnIds, len(sessions.ConnIds))
m.HandleFunc("/api/session/tunnels", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")

i := 0
for id, num := range sessions.ConnIds {
connIds[i] = &ConnIds{
Uuid: id,
Num: num,
}
t := []string{}
for tun := range tunnels {
t = append(t, tun)
}

if err := json.NewEncoder(w).Encode(connIds); err != nil {
if err := json.NewEncoder(w).Encode(t); err != nil {
logrus.Error(err)
}
})
Expand All @@ -57,7 +109,7 @@ func main() {

s := &http.Server{
Addr: "0.0.0.0:4567",
Handler: mux,
Handler: m,
ReadTimeout: guac.SocketTimeout,
WriteTimeout: guac.SocketTimeout,
MaxHeaderBytes: 1 << 20,
Expand All @@ -69,7 +121,7 @@ func main() {
}

// DemoDoConnect creates the tunnel to the remote machine (via guacd)
func DemoDoConnect(request *http.Request) (guac.Tunnel, error) {
func DemoDoConnect(request *http.Request) (_ guac.Tunnel, err error) {
config := guac.NewGuacamoleConfiguration()

var query url.Values
Expand All @@ -93,12 +145,10 @@ func DemoDoConnect(request *http.Request) (guac.Tunnel, error) {
}

config.Protocol = query.Get("scheme")
config.Parameters = map[string]string{}
for k, v := range query {
config.Parameters[k] = v[0]
}

var err error
if query.Get("width") != "" {
config.OptimalScreenHeight, err = strconv.Atoi(query.Get("width"))
if err != nil || config.OptimalScreenHeight == 0 {
Expand All @@ -117,6 +167,10 @@ func DemoDoConnect(request *http.Request) (guac.Tunnel, error) {

logrus.Debug("Connecting to guacd")
addr, err := net.ResolveTCPAddr("tcp", "127.0.0.1:4822")
if err != nil {
logrus.Errorln("error while resolving 127.0.0.1")
return nil, err
}

conn, err := net.DialTCP("tcp", nil, addr)
if err != nil {
Expand All @@ -130,11 +184,23 @@ func DemoDoConnect(request *http.Request) (guac.Tunnel, error) {
if request.URL.Query().Get("uuid") != "" {
config.ConnectionID = request.URL.Query().Get("uuid")
}

logrus.Debugf("Starting handshake with %#v", config)
err = stream.Handshake(config)
if err != nil {
return nil, err
}
logrus.Debug("Socket configured")

return guac.NewSimpleTunnel(stream), nil
}

// DemoDoConnectWithIntercept showcases a use for intercepting streams
func DemoDoConnectWithIntercept(r *http.Request) (guac.Tunnel, error) {
t, err := DemoDoConnect(r)
if err != nil {
return nil, err
}

return guac.NewUserTunnel(t), nil
}
14 changes: 7 additions & 7 deletions config.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,22 +5,22 @@ type Config struct {
// ConnectionID is used to reconnect to an existing session, otherwise leave blank for a new session.
ConnectionID string
// Protocol is the protocol of the connection from guacd to the remote (rdp, ssh, etc).
Protocol string
Protocol string
// Parameters are used to configure protocol specific options like sla for rdp or terminal color schemes.
Parameters map[string]string
Parameters map[string]string

// OptimalScreenWidth is the desired width of the screen
OptimalScreenWidth int
OptimalScreenWidth int
// OptimalScreenHeight is the desired height of the screen
OptimalScreenHeight int
// OptimalResolution is the desired resolution of the screen
OptimalResolution int
OptimalResolution int
// AudioMimetypes is an array of the supported audio types
AudioMimetypes []string
AudioMimetypes []string
// VideoMimetypes is an array of the supported video types
VideoMimetypes []string
VideoMimetypes []string
// ImageMimetypes is an array of the supported image types
ImageMimetypes []string
ImageMimetypes []string
}

// NewGuacamoleConfiguration returns a Config with sane defaults
Expand Down
2 changes: 1 addition & 1 deletion doc.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
/*
Package guac implements a HTTP client and a WebSocket client that connects to an Apache Guacamole server.
*/
*/
package guac
5 changes: 5 additions & 0 deletions filter.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
package guac

type Filter interface {
Filter(*Instruction) (*Instruction, error)
}
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ replace github.com/Sirupsen/logrus v1.4.2 => github.com/sirupsen/logrus v1.4.2

require (
github.com/google/uuid v1.1.1
github.com/gorilla/mux v1.8.0
github.com/gorilla/websocket v1.4.1
github.com/sirupsen/logrus v1.4.2
)
6 changes: 6 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -1,13 +1,19 @@
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/google/uuid v1.1.1 h1:Gkbcsh/GbpXz7lPftLA3P6TYMwjCLYm83jiFQZF/3gY=
github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/gorilla/mux v1.8.0 h1:i40aqfkR1h2SlN9hojwV5ZA91wcXFOvkdNIeFDP5koI=
github.com/gorilla/mux v1.8.0/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB71So=
github.com/gorilla/websocket v1.4.1 h1:q7AeDBpnBk8AogcD4DSag/Ukw/KV+YhzLj2bP5HvKCM=
github.com/gorilla/websocket v1.4.1/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
github.com/konsorten/go-windows-terminal-sequences v1.0.1 h1:mweAR1A6xJ3oS2pRaGiHgQ4OO8tzTaLawm8vnODuwDk=
github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/sirupsen/logrus v1.4.2 h1:SPIRibHv4MatM3XXNO2BJeFLZwZ2LvZgfQ5+UNI2im4=
github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE=
github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.2.2 h1:bSDNvY7ZPG5RlJ8otE/7V6gMiyenm9RtJ7IUVIAoJ1w=
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
golang.org/x/sys v0.0.0-20190422165155-953cdadca894 h1:Cz4ceDQGXuKRnVBDTS23GTn/pU5OE2C0WrNTOYK1Uuc=
golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
Loading