-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmain.go
115 lines (92 loc) · 2.38 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
package main
import (
"flag"
"fmt"
"io"
"log/slog"
"net"
"os"
"github.com/jeroenrinzema/psql-wire/pkg/buffer"
)
var listening = flag.String("l", ":2345", "port the proxy is listening on")
var dial = flag.String("d", "127.0.0.1:5432", "PostgreSQL server target")
var tls = flag.Bool("tls", false, "this flag has to be set whenever the server is supporting TLS connections")
func main() {
flag.Parse()
err := run()
if err != nil {
fmt.Println(err)
os.Exit(1)
}
}
func run() error {
listener, err := net.Listen("tcp", *listening)
if err != nil {
return err
}
slog.Info("proxy listening", slog.String("address", *listening))
for {
client, err := listener.Accept()
if err != nil {
return err
}
slog.Info("incoming connection, dialing PostgreSQL server!")
db, err := net.Dial("tcp", *dial)
if err != nil {
return err
}
go sniffer(client, db)
}
}
func sniffer(client, db net.Conn) {
to := io.TeeReader(client, db)
from := io.TeeReader(db, client)
slog.Info("starting sniffing the PSQL packages")
go func() {
reader := buffer.NewReader(slog.Default(), to, 0)
_, err := reader.ReadUntypedMsg()
if err != nil {
slog.Error("unexpected error while reading the client version", slog.String("err", err.Error()))
return
}
version, _ := reader.GetUint32()
slog.Info("-->", slog.Uint64("version", uint64(version)))
if !*tls {
// NOTE: we have to read a untyped message twice if TLS is disabled (check handshake)
reader.ReadUntypedMsg()
}
for {
t, _, err := reader.ReadTypedMsg()
if err == io.EOF {
return
}
if err != nil {
slog.Error("unexpected error while reading a typed client message", slog.String("err", err.Error()))
return
}
slog.Info("->>", slog.String("type", string(t)), slog.String("msg", string(reader.Msg)))
}
}()
go func() {
if !*tls {
bb := make([]byte, 1)
_, err := from.Read(bb)
if err != nil {
slog.Error("unexpected error while reading the tls response", slog.String("err", err.Error()))
return
}
}
reader := buffer.NewReader(slog.Default(), from, 0)
for {
t, _, err := reader.ReadTypedMsg()
if err == io.EOF {
return
}
if err != nil {
slog.Error("unexpected error while reading the server response", slog.String("err", err.Error()))
return
}
slog.Info("<<-", slog.String("type", string(t)), slog.String("msg", string(reader.Msg)))
}
}()
}