/
pbproxy.go
312 lines (280 loc) · 7.62 KB
/
pbproxy.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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
package main
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"crypto/sha256"
"flag"
"io"
"io/ioutil"
"log"
"net"
"os"
"time"
"golang.org/x/crypto/pbkdf2"
)
var (
pFlag *string
lFlag *string
dstHost = ""
dstPort = ""
address = ""
passphrase = ""
)
// Channel to store bytes written
type Channel struct {
bytes uint64
}
func main() {
// Logging the operations in info.log file
file, err := os.OpenFile("info.log", os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
if err != nil {
log.Fatal(err)
}
defer file.Close()
log.SetOutput(file)
// Parsing command line args
pFlag = flag.String("p", "", "File containing the ASCII text keyphrase ")
lFlag = flag.String("l", "", "Specify the listening port which serves as reverse proxy")
flag.Parse()
if len(flag.Args()) != 2 {
panic("must provide destination and port in the format : go run pbproxy.go [-l port] -p <passphrase file> <destination> <port>")
}
if *pFlag != "" {
// Reading the passphrase
pwdBytes, err := ioutil.ReadFile(*pFlag)
if err != nil {
panic(err)
} else {
if len(pwdBytes) == 0 {
panic("passphrase file must contain a passphrase and not be empty")
}
passphrase = string(pwdBytes)
}
} else {
panic("password file containing the passphrase must be passed")
}
// Get destination host and port
dstHost = flag.Arg(0)
dstPort = flag.Arg(1)
// Storing the destination address
address = dstHost + ":" + dstPort
/*
If listen flag is enabled then run as server accepting client connections
Else act as client and connect to mentioned address
*/
if *lFlag != "" {
runServer()
} else {
runClient()
}
}
func runServer() {
// Get the proxy server port
port := *lFlag
// Listen to incoming client connections in proxy server port
listener, err := net.Listen("tcp", ":"+port)
if err != nil {
panic(err)
}
log.Printf("Proxy server is listening for connections on %s", listener.Addr().String())
for {
// Accepting incoming client connections
conn, err := listener.Accept()
if err != nil {
log.Fatalf("error accepting connection from client: %s\n", err)
} else {
// Connecting to service and handling the particular connection
connLocalHost, errLocalHost := net.Dial("tcp", address)
if errLocalHost != nil {
log.Println(errLocalHost)
continue
}
go handleDataServerLocalHost(conn, connLocalHost)
}
}
}
// Running as client and connecting to mentioned address
func runClient() {
con, err := net.Dial("tcp", address)
if err != nil {
log.Fatalln(err)
}
log.Println("Connected to ", address)
con.SetDeadline(time.Now().Add(time.Second * 60))
defer func() {
con.Close()
}()
handleDataClient(con)
}
func handleDataClient(con net.Conn) {
log.Println("Inside handle client function")
channelDataStructure := make(chan Channel)
copy := func(readCloser io.ReadCloser, writeCloser io.WriteCloser) {
defer func() {
readCloser.Close()
writeCloser.Close()
}()
if readCloser == os.Stdin {
log.Println("Inside os.Stdin reader closer")
var written uint64 = 0
bytes := make([]byte, 64*4096)
for {
read, err := readCloser.Read(bytes)
if err != nil {
if err, ok := err.(net.Error); ok && err.Timeout() {
con.Close()
log.Fatalln("connection closed")
}
}
if read != 0 {
data := bytes[:read]
encryptedData := encrypt(string(data))
write, err := writeCloser.Write(encryptedData)
con.SetWriteDeadline(time.Now().Add(time.Second * 300))
if err != nil {
log.Printf("Found error %s in connection %s\n", err, con.RemoteAddr())
}
written += uint64(write)
}
}
channelDataStructure <- Channel{bytes: written}
} else {
log.Println("Inside client conn reader closer")
var written uint64 = 0
bytes := make([]byte, 64*4096)
for {
read, err := readCloser.Read(bytes)
if err != nil {
if err, ok := err.(net.Error); ok && err.Timeout() {
con.Close()
log.Fatalln("connection closed")
}
}
if read != 0 {
data := bytes[:read]
con.SetReadDeadline(time.Now().Add(time.Second * 300))
decryptedData := decrypt(string(data))
write, err := writeCloser.Write(decryptedData)
if err != nil {
log.Printf("Found error %s in connection %s\n", err, con.RemoteAddr())
}
written += uint64(write)
}
}
channelDataStructure <- Channel{bytes: written}
}
}
go copy(con, os.Stdout)
go copy(os.Stdin, con)
channel := <-channelDataStructure
log.Println("Data received (bytes ) : ", channel.bytes)
channel = <-channelDataStructure
log.Println("Data sent (bytes) : ", channel.bytes)
}
func handleDataServerLocalHost(conn net.Conn, connLocalHost net.Conn) {
log.Println("Inside handle server function")
channelDataStructure := make(chan Channel)
copy := func(readCloser io.ReadCloser, writeCloser io.WriteCloser) {
defer func() {
readCloser.Close()
writeCloser.Close()
}()
if readCloser == connLocalHost {
log.Println("Inside connLocalHost reader closer")
var written uint64 = 0
bytes := make([]byte, 64*4096)
for {
read, err := readCloser.Read(bytes)
if err != nil {
if err, ok := err.(net.Error); ok && err.Timeout() {
conn.Close()
}
}
if read != 0 {
data := bytes[:read]
encryptedData := encrypt(string(data))
write, err := writeCloser.Write(encryptedData)
if err != nil {
log.Printf("Found error %s in connection %s\n", err, conn.RemoteAddr())
}
written += uint64(write)
}
}
channelDataStructure <- Channel{bytes: written}
} else {
var written uint64 = 0
bytes := make([]byte, 64*4096)
for {
log.Println("Inside server conn reader closer")
read, err := readCloser.Read(bytes)
if err != nil {
if err, ok := err.(net.Error); ok && err.Timeout() {
conn.Close()
}
}
if read != 0 {
data := bytes[:read]
decryptedData := decrypt(string(data))
write, err := writeCloser.Write(decryptedData)
if err != nil {
log.Printf("Found error %s in connection %s\n", err, conn.RemoteAddr())
}
written += uint64(write)
}
}
channelDataStructure <- Channel{bytes: written}
}
}
go copy(conn, connLocalHost)
go copy(connLocalHost, conn)
channel := <-channelDataStructure
log.Println("Data received (bytes) : ", channel.bytes)
channel = <-channelDataStructure
log.Println("Data sent (bytes) : ", channel.bytes)
}
// Encrypting the data
func encrypt(content string) []byte {
// Generating key
keyBytes := make([]byte, 32)
if _, err := rand.Read(keyBytes); err != nil {
panic(err.Error())
}
key := pbkdf2.Key([]byte(passphrase), keyBytes, 4096, sha256.Size, sha256.New)
block, err := aes.NewCipher(key)
if err != nil {
log.Fatalln(err.Error())
}
// Generating nonce
nonce := make([]byte, 12)
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
panic(err.Error())
}
aesgcm, err := cipher.NewGCM(block)
if err != nil {
log.Fatalln(err.Error())
}
// Encrypting the data
ciphertext := aesgcm.Seal(append(nonce, key...), nonce, []byte(content), nil)
log.Println("Encrypted data sent : ", string(ciphertext))
return ciphertext
}
// Decrypting the data
func decrypt(encryptedData string) []byte {
log.Println("Encrypted data received : ", encryptedData)
// Splitting the nonce, key and ciphertext
nonce, key, ciphertext := encryptedData[:12], []byte(encryptedData[12:44]), encryptedData[44:]
block, err := aes.NewCipher(key)
if err != nil {
log.Fatalln(err.Error())
}
gcm, err := cipher.NewGCM(block)
if err != nil {
log.Fatalln(err.Error())
}
plaintext, err := gcm.Open(nil, []byte(nonce), []byte(ciphertext), nil)
if err != nil {
log.Fatalln(err.Error())
}
return plaintext
}