forked from boringproxy/boringproxy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtunnel_manager.go
247 lines (190 loc) · 5.31 KB
/
tunnel_manager.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
package boringproxy
import (
"context"
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"errors"
"fmt"
"github.com/caddyserver/certmagic"
"golang.org/x/crypto/ssh"
"io/ioutil"
"log"
"os"
"os/user"
"strings"
"sync"
)
type TunnelManager struct {
config *Config
db *Database
mutex *sync.Mutex
certConfig *certmagic.Config
user *user.User
}
func NewTunnelManager(config *Config, db *Database, certConfig *certmagic.Config) *TunnelManager {
user, err := user.Current()
if err != nil {
log.Fatalf("Unable to get current user: %v", err)
}
if config.autoCerts {
for domainName, tun := range db.GetTunnels() {
if tun.TlsTermination == "server" || tun.TlsTermination == "server-tls" {
err = certConfig.ManageSync(context.Background(), []string{domainName})
if err != nil {
log.Println("CertMagic error at startup")
log.Println(err)
}
}
}
}
mutex := &sync.Mutex{}
return &TunnelManager{config, db, mutex, certConfig, user}
}
func (m *TunnelManager) GetTunnels() map[string]Tunnel {
return m.db.GetTunnels()
}
func (m *TunnelManager) RequestCreateTunnel(tunReq Tunnel) (Tunnel, error) {
if tunReq.Domain == "" {
return Tunnel{}, errors.New("Domain required")
}
if tunReq.Owner == "" {
return Tunnel{}, errors.New("Owner required")
}
if tunReq.TlsTermination == "server" || tunReq.TlsTermination == "server-tls" {
if m.config.autoCerts {
err := m.certConfig.ManageSync(context.Background(), []string{tunReq.Domain})
if err != nil {
return Tunnel{}, errors.New("Failed to get cert")
}
}
}
m.mutex.Lock()
defer m.mutex.Unlock()
if tunReq.TunnelPort == 0 {
var err error
tunReq.TunnelPort, err = randomOpenPort()
if err != nil {
return Tunnel{}, err
}
}
for _, tun := range m.db.GetTunnels() {
if tunReq.Domain == tun.Domain {
return Tunnel{}, errors.New("Tunnel domain already in use")
}
if tunReq.TunnelPort == tun.TunnelPort {
return Tunnel{}, errors.New("Tunnel port already in use")
}
}
privKey, err := m.addToAuthorizedKeys(tunReq.Domain, tunReq.TunnelPort, tunReq.AllowExternalTcp)
if err != nil {
return Tunnel{}, err
}
tunReq.ServerPublicKey = ""
tunReq.Username = m.user.Username
tunReq.TunnelPrivateKey = privKey
m.db.SetTunnel(tunReq.Domain, tunReq)
return tunReq, nil
}
func (m *TunnelManager) DeleteTunnel(domain string) error {
m.mutex.Lock()
defer m.mutex.Unlock()
tunnel, exists := m.db.GetTunnel(domain)
if !exists {
return errors.New("Tunnel doesn't exist")
}
m.db.DeleteTunnel(domain)
authKeysPath := fmt.Sprintf("%s/.ssh/authorized_keys", m.user.HomeDir)
akBytes, err := ioutil.ReadFile(authKeysPath)
if err != nil {
return err
}
akStr := string(akBytes)
lines := strings.Split(akStr, "\n")
tunnelId := fmt.Sprintf("boringproxy-%s-%d", domain, tunnel.TunnelPort)
outLines := []string{}
for _, line := range lines {
if strings.Contains(line, tunnelId) {
continue
}
outLines = append(outLines, line)
}
outStr := strings.Join(outLines, "\n")
err = ioutil.WriteFile(authKeysPath, []byte(outStr), 0600)
if err != nil {
return err
}
return nil
}
func (m *TunnelManager) GetPort(domain string) (int, error) {
tunnel, exists := m.db.GetTunnel(domain)
if !exists {
return 0, errors.New("Doesn't exist")
}
return tunnel.TunnelPort, nil
}
func (m *TunnelManager) addToAuthorizedKeys(domain string, port int, allowExternalTcp bool) (string, error) {
authKeysPath := fmt.Sprintf("%s/.ssh/authorized_keys", m.user.HomeDir)
akFile, err := os.OpenFile(authKeysPath, os.O_RDWR|os.O_CREATE, 0600)
if err != nil {
return "", err
}
defer akFile.Close()
akBytes, err := ioutil.ReadAll(akFile)
if err != nil {
return "", err
}
akStr := string(akBytes)
var privKey string
var pubKey string
pubKey, privKey, err = MakeSSHKeyPair()
if err != nil {
return "", err
}
pubKey = strings.TrimSpace(pubKey)
bindAddr := "127.0.0.1"
if allowExternalTcp {
bindAddr = "0.0.0.0"
}
options := fmt.Sprintf(`command="echo This key permits tunnels only",permitopen="fakehost:1",permitlisten="%s:%d"`, bindAddr, port)
tunnelId := fmt.Sprintf("boringproxy-%s-%d", domain, port)
newAk := fmt.Sprintf("%s%s %s %s\n", akStr, options, pubKey, tunnelId)
// Clear the file
err = akFile.Truncate(0)
if err != nil {
return "", err
}
_, err = akFile.Seek(0, 0)
if err != nil {
return "", err
}
_, err = akFile.Write([]byte(newAk))
if err != nil {
return "", err
}
return privKey, nil
}
// Adapted from https://stackoverflow.com/a/34347463/943814
// MakeSSHKeyPair make a pair of public and private keys for SSH access.
// Public key is encoded in the format for inclusion in an OpenSSH authorized_keys file.
// Private Key generated is PEM encoded
func MakeSSHKeyPair() (string, string, error) {
privateKey, err := rsa.GenerateKey(rand.Reader, 1024)
if err != nil {
return "", "", err
}
// generate and write private key as PEM
var privKeyBuf strings.Builder
privateKeyPEM := &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(privateKey)}
if err := pem.Encode(&privKeyBuf, privateKeyPEM); err != nil {
return "", "", err
}
// generate and write public key
pub, err := ssh.NewPublicKey(&privateKey.PublicKey)
if err != nil {
return "", "", err
}
pubKey := string(ssh.MarshalAuthorizedKey(pub))
return pubKey, privKeyBuf.String(), nil
}