/
controller.go
369 lines (287 loc) · 9.12 KB
/
controller.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
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
package local
import (
"context"
"io"
"os"
"path"
"strings"
"time"
"github.com/cockroachdb/errors"
log "github.com/sirupsen/logrus"
"k8s.io/apimachinery/pkg/util/runtime"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/client-go/tools/cache"
"k8s.io/client-go/util/workqueue"
config "github.com/bugfest/tor-controller/agents/tor/config"
v1alpha2 "github.com/bugfest/tor-controller/apis/tor/v1alpha2"
)
const (
authorizedClientsDir = "/run/tor/service/authorized_clients"
torFilePath = "/run/tor/torfile"
torServiceDir = "/run/tor/service/"
defaultUnixPermission = 0o600
)
type Controller struct {
indexer cache.Indexer
queue workqueue.RateLimitingInterface
informer cache.Controller
localManager *Manager
}
func NewController(queue workqueue.RateLimitingInterface, informer cache.SharedIndexInformer, localManager *Manager) *Controller {
return &Controller{
informer: informer,
indexer: informer.GetIndexer(),
queue: queue,
localManager: localManager,
}
}
func (c *Controller) processNextItem() bool {
key, quit := c.queue.Get()
if quit {
log.Info("Queue quits")
return false
}
defer c.queue.Done(key)
keyString, ok := key.(string)
if !ok {
log.Errorf("Key is not a string: %v", key)
return false
}
err := c.sync(keyString)
c.handleErr(err, key)
return true
}
//nolint:gocognit,nestif // this function is long for a reason
func (c *Controller) sync(key string) error {
log.Infof("Getting key %s", key)
// Get the OnionService resource with this key
obj, exists, err := c.indexer.GetByKey(key)
if err != nil {
log.Errorf("Fetching object with key %s from store failed with %v", key, err)
return errors.Wrap(err, "fetching object from store")
}
if !exists {
log.Warnf("OnionService %s does not exist anymore", key)
return nil
}
log.Debugf("%v", obj)
onionService, err := parseOnionService(obj)
if err != nil {
log.Errorf("Error in parseOnionService: %s", err)
return errors.Wrap(err, "parsing onion service")
}
// torfile
torConfig, err := config.TorConfigForService(&onionService)
if err != nil {
log.Errorf("Generating config failed with %v", err)
return errors.Wrap(err, "generating config")
}
reload := false
torfile, err := os.ReadFile(torFilePath)
switch {
case os.IsNotExist(err):
reload = true
case err != nil:
return errors.Wrap(err, "reading torfile")
case string(torfile) != torConfig:
reload = true
}
if reload {
err = serviceReload(&onionService, []byte(torConfig))
if err != nil {
log.Errorf("Reloading service failed with %v", err)
return errors.Wrap(err, "reloading service")
}
}
// update hostname
err = copyIfNotExist(
"/run/tor/service/key/hostname",
"/run/tor/service/hostname",
)
if err != nil {
log.Errorf("Updating hostname failed with %v", err)
}
// update private and public keys
publicKeyFileName := "hs_ed25519_public_key"
privateKeyFileName := "hs_ed25519_secret_key"
if onionService.Spec.GetVersion() == 2 {
publicKeyFileName = "public_key"
privateKeyFileName = "private_key"
}
err = copyIfNotExist(
path.Join(torServiceDir, "key", publicKeyFileName),
path.Join(torServiceDir, publicKeyFileName),
)
if err != nil {
log.Errorf("Updating public key failed with %v", err)
}
err = copyIfNotExist(
path.Join(torServiceDir, "key", privateKeyFileName),
path.Join(torServiceDir, privateKeyFileName),
)
if err != nil {
log.Errorf("Updating private key failed with %v", err)
}
// copy authorized keys to the correct directory (/run/tor/service/authorized_keys)
// as Tor requires this directory to be only accessible for the current user (0700)
// and k8s does not allow to set the permissions of the directory where the projected
// secrets are mounted
files, err := os.ReadDir("/run/tor/service/.authorized_clients/")
if err != nil {
log.Info("No authorized keys found")
} else {
// Create `authorized_clients_dir` directory if it does not exist
if _, err := os.Stat(authorizedClientsDir); errors.Is(err, os.ErrNotExist) {
err := os.Mkdir(authorizedClientsDir, 0o700)
if err != nil {
log.Fatalf("Creating directory %s failed with %v", authorizedClientsDir, err)
}
}
// Copy *.auth files from mounted secrets into `authorized_clients_dir` directory
for _, file := range files {
if !file.IsDir() && strings.HasSuffix(file.Name(), ".auth") {
err = copyIfNotExist(
path.Join("/run/tor/service/.authorized_clients/", file.Name()),
path.Join("/run/tor/service/authorized_clients/", file.Name()),
)
if err != nil {
log.Errorf("Copying authorized keys failed with %v", err)
}
}
}
}
// ob_config needs to be created if this Hidden Service have a Master one in front
if len(onionService.Spec.MasterOnionAddress) > 0 {
obConfig, err := config.ObConfigForService(&onionService)
if err != nil {
log.Errorf("Generating ob_config failed with %v", err)
return errors.Wrap(err, "generating ob_config")
}
obfile, err := os.ReadFile("/run/tor/service/ob_config")
switch {
case os.IsNotExist(err):
reload = true
case err != nil:
return errors.Wrap(err, "reading ob_config")
case string(obfile) != obConfig:
reload = true
}
if reload {
log.Infof("Updating onionbalance config for %s/%s", onionService.Namespace, onionService.Name)
err = os.WriteFile("/run/tor/service/ob_config", []byte(obConfig), defaultUnixPermission)
if err != nil {
log.Errorf("Writing config failed with %v", err)
return errors.Wrap(err, "writing ob_config")
}
}
}
if reload {
c.localManager.daemon.Reload()
}
err = c.updateOnionServiceStatus(&onionService)
if err != nil {
log.Errorf("Updating status failed with %v", err)
return errors.Wrap(err, "updating status")
}
return nil
}
func (c *Controller) updateOnionServiceStatus(onionService *v1alpha2.OnionService) error {
hostname, err := os.ReadFile("/run/tor/service/hostname")
if err != nil {
log.Errorf("Got this error when trying to find hostname: %v", err)
return errors.Wrap(err, "reading hostname")
}
newHostname := strings.TrimSpace(string(hostname))
if newHostname != onionService.Status.Hostname {
log.Infof("Got new hostname: %s", newHostname)
onionService.Status.Hostname = newHostname
log.Debugf("Updating onionService to: %v", onionService)
err = c.localManager.kclient.Status().Update(context.Background(), onionService)
if err != nil {
log.Errorf("Error updating onionService: %s", err)
return errors.Wrap(err, "updating onionService")
}
}
return nil
}
// handleErr checks if an error happened and makes sure we will retry later.
func (c *Controller) handleErr(err error, key interface{}) {
if err == nil {
c.queue.Forget(key)
return
}
// This controller retries 5 times if something goes wrong. After that, it stops trying.
//nolint:gomnd // 5 is a reasonable number of retries
if c.queue.NumRequeues(key) < 5 {
log.Errorf("Error syncing onionservice %v: %v", key, err)
// Re-enqueue the key rate limited. Based on the rate limiter on the
// queue and the re-enqueue history, the key will be processed later again.
// c.queue.AddRateLimited(key)
c.queue.AddAfter(key, 3*time.Second)
return
}
c.queue.Forget(key)
// Report to an external entity that, even after several retries, we could not successfully process this key
runtime.HandleError(err)
log.Infof("Dropping onionservice %q out of the queue: %v", key, err)
}
func (c *Controller) Run(threadiness int, stopCh chan struct{}) {
defer runtime.HandleCrash()
// Let the workers stop when we are done
defer c.queue.ShutDown()
log.Info("Starting controller")
go c.informer.Run(stopCh)
// Wait for all involved caches to be synced, before processing items from the queue is started
if !cache.WaitForCacheSync(stopCh, c.informer.HasSynced) {
runtime.HandleError(errors.New("timed out waiting for caches to sync"))
return
}
for i := 0; i < threadiness; i++ {
go wait.Until(c.runWorker, time.Second, stopCh)
}
<-stopCh
log.Info("Stopping controller")
}
func (c *Controller) runWorker() {
for c.processNextItem() {
}
}
func copyIfNotExist(src, dst string) error {
_, err := os.Stat(dst)
if !os.IsNotExist(err) {
return errors.Wrap(err, "checking if file exists")
}
log.Infof("Creating copy of %s at %s", src, dst)
srcfd, err := os.Open(src)
if err != nil {
return errors.Wrap(err, "opening source file")
}
defer srcfd.Close()
dstfd, err := os.Create(dst)
if err != nil {
return errors.Wrap(err, "creating destination file")
}
defer dstfd.Close()
_, err = io.Copy(dstfd, srcfd)
if err != nil {
return errors.Wrap(err, "copying file")
}
srcinfo, err := os.Stat(src)
if err != nil {
return errors.Wrap(err, "getting source file info")
}
err = dstfd.Chmod(srcinfo.Mode())
if err != nil {
return errors.Wrap(err, "setting destination file mode")
}
return nil
}
func serviceReload(onionService *v1alpha2.OnionService, configData []byte) error {
log.Infof("Updating tor config for %s/%s", onionService.Namespace, onionService.Name)
err := os.WriteFile(torFilePath, configData, defaultUnixPermission)
if err != nil {
log.Errorf("Writing config failed with %v", err)
return errors.Wrap(err, "writing config")
}
return nil
}