forked from SenseUnit/dumbproxy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.go
302 lines (271 loc) · 6.09 KB
/
utils.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
package main
import (
"bufio"
"context"
"crypto/tls"
"crypto/x509"
"errors"
"fmt"
"io"
"io/ioutil"
"log"
"net"
"net/http"
"os"
"strings"
"sync"
"time"
"golang.org/x/crypto/bcrypt"
"golang.org/x/crypto/ssh/terminal"
)
const COPY_BUF = 128 * 1024
func proxy(ctx context.Context, left, right net.Conn) {
wg := sync.WaitGroup{}
cpy := func(dst, src net.Conn) {
defer wg.Done()
io.Copy(dst, src)
dst.Close()
}
wg.Add(2)
go cpy(left, right)
go cpy(right, left)
groupdone := make(chan struct{}, 1)
go func() {
wg.Wait()
groupdone <- struct{}{}
}()
select {
case <-ctx.Done():
left.Close()
right.Close()
case <-groupdone:
return
}
<-groupdone
return
}
func proxyh2(ctx context.Context, leftreader io.ReadCloser, leftwriter io.Writer, right net.Conn) {
wg := sync.WaitGroup{}
ltr := func(dst net.Conn, src io.Reader) {
defer wg.Done()
io.Copy(dst, src)
dst.Close()
}
rtl := func(dst io.Writer, src io.Reader) {
defer wg.Done()
copyBody(dst, src)
}
wg.Add(2)
go ltr(right, leftreader)
go rtl(leftwriter, right)
groupdone := make(chan struct{}, 1)
go func() {
wg.Wait()
groupdone <- struct{}{}
}()
select {
case <-ctx.Done():
leftreader.Close()
right.Close()
case <-groupdone:
return
}
<-groupdone
return
}
// Hop-by-hop headers. These are removed when sent to the backend.
// http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html
var hopHeaders = []string{
"Connection",
"Keep-Alive",
"Proxy-Authenticate",
"Proxy-Connection",
"Proxy-Authorization",
"Te", // canonicalized version of "TE"
"Trailers",
"Transfer-Encoding",
"Upgrade",
}
func copyHeader(dst, src http.Header) {
for k, vv := range src {
for _, v := range vv {
dst.Add(k, v)
}
}
}
func delHopHeaders(header http.Header) {
for _, h := range hopHeaders {
header.Del(h)
}
}
func hijack(hijackable interface{}) (net.Conn, *bufio.ReadWriter, error) {
hj, ok := hijackable.(http.Hijacker)
if !ok {
return nil, nil, errors.New("Connection doesn't support hijacking")
}
conn, rw, err := hj.Hijack()
if err != nil {
return nil, nil, err
}
var emptytime time.Time
err = conn.SetDeadline(emptytime)
if err != nil {
conn.Close()
return nil, nil, err
}
return conn, rw, nil
}
func flush(flusher interface{}) bool {
f, ok := flusher.(http.Flusher)
if !ok {
return false
}
f.Flush()
return true
}
func copyBody(wr io.Writer, body io.Reader) {
buf := make([]byte, COPY_BUF)
for {
bread, read_err := body.Read(buf)
var write_err error
if bread > 0 {
_, write_err = wr.Write(buf[:bread])
flush(wr)
}
if read_err != nil || write_err != nil {
break
}
}
}
func makeServerTLSConfig(certfile, keyfile, cafile, ciphers string) (*tls.Config, error) {
var cfg tls.Config
cert, err := tls.LoadX509KeyPair(certfile, keyfile)
if err != nil {
return nil, err
}
cfg.Certificates = []tls.Certificate{cert}
if cafile != "" {
roots := x509.NewCertPool()
certs, err := ioutil.ReadFile(cafile)
if err != nil {
return nil, err
}
if ok := roots.AppendCertsFromPEM(certs); !ok {
return nil, errors.New("Failed to load CA certificates")
}
cfg.ClientCAs = roots
cfg.ClientAuth = tls.VerifyClientCertIfGiven
}
cfg.CipherSuites = makeCipherList(ciphers)
return &cfg, nil
}
func updateServerTLSConfig(cfg *tls.Config, cafile, ciphers string) (*tls.Config, error) {
if cafile != "" {
roots := x509.NewCertPool()
certs, err := ioutil.ReadFile(cafile)
if err != nil {
return nil, err
}
if ok := roots.AppendCertsFromPEM(certs); !ok {
return nil, errors.New("Failed to load CA certificates")
}
cfg.ClientCAs = roots
cfg.ClientAuth = tls.VerifyClientCertIfGiven
}
cfg.CipherSuites = makeCipherList(ciphers)
return cfg, nil
}
func makeCipherList(ciphers string) []uint16 {
if ciphers == "" {
return nil
}
cipherIDs := make(map[string]uint16)
for _, cipher := range tls.CipherSuites() {
cipherIDs[cipher.Name] = cipher.ID
}
cipherNameList := strings.Split(ciphers, ":")
cipherIDList := make([]uint16, 0, len(cipherNameList))
for _, name := range cipherNameList {
id, ok := cipherIDs[name]
if !ok {
log.Printf("WARNING: Unknown cipher \"%s\"", name)
}
cipherIDList = append(cipherIDList, id)
}
return cipherIDList
}
func list_ciphers() {
for _, cipher := range tls.CipherSuites() {
fmt.Println(cipher.Name)
}
}
func passwd(filename string, cost int, args ...string) error {
var (
username, password, password2 string
err error
)
if len(args) > 0 {
username = args[0]
} else {
username, err = prompt("Enter username: ", false)
if err != nil {
return fmt.Errorf("can't get username: %w", err)
}
}
if len(args) > 1 {
password = args[1]
} else {
password, err = prompt("Enter password: ", true)
if err != nil {
return fmt.Errorf("can't get password: %w", err)
}
password2, err = prompt("Repeat password: ", true)
if err != nil {
return fmt.Errorf("can't get password (repeat): %w", err)
}
if password != password2 {
return fmt.Errorf("passwords do not match")
}
}
hash, err := bcrypt.GenerateFromPassword([]byte(password), cost)
if err != nil {
return fmt.Errorf("can't generate password hash: %w", err)
}
f, err := os.OpenFile(filename, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0600)
if err != nil {
return fmt.Errorf("can't open file: %w", err)
}
defer f.Close()
_, err = f.WriteString(fmt.Sprintf("%s:%s\n", username, hash))
if err != nil {
return fmt.Errorf("can't write to file: %w", err)
}
return nil
}
func fileModTime(filename string) (time.Time, error) {
f, err := os.Open(filename)
if err != nil {
return time.Time{}, fmt.Errorf("fileModTime(): can't open file %q: %w", filename, err)
}
defer f.Close()
fi, err := f.Stat()
if err != nil {
return time.Time{}, fmt.Errorf("fileModTime(): can't stat file %q: %w", filename, err)
}
return fi.ModTime(), nil
}
func prompt(prompt string, secure bool) (string, error) {
var input string
fmt.Print(prompt)
if secure {
b, err := terminal.ReadPassword(int(os.Stdin.Fd()))
if err != nil {
return "", err
}
input = string(b)
fmt.Println()
} else {
fmt.Scanln(&input)
}
return input, nil
}