summaryrefslogtreecommitdiff
path: root/main.go
blob: 269b11e5350d18d5a8a438b6cedd8ef5d29de308 (plain)
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
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
package main

import (
	"encoding/base64"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"log"
	"net"
	"net/http"
	"net/url"
	"regexp"
	"strings"

	"code.crute.me/mcrute/go_ddns_manager/bind"
	"code.crute.me/mcrute/go_ddns_manager/dns"
	"github.com/gin-gonic/gin"
)

const (
	ACME_AUTH_KEY = "ACMEAuthUserID"
	DDNS_AUTH_KEY = "DDNSAuthZone"
)

var (
	cfg      *bind.BINDConfig
	secrets  *Secrets
	ipRegexp = regexp.MustCompile(`(?:\[([0-9a-f:]+)\]|(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})):\d+`)
)

func init() {
	var err error
	cfg, err = bind.ParseBINDConfig("zones.conf")
	if err != nil {
		panic(err)
	}

	fd, err := ioutil.ReadFile("secrets.json")
	if err != nil {
		panic(err)
	}

	secrets = &Secrets{}
	if err = json.Unmarshal(fd, secrets); err != nil {
		panic(err)
	}
}

type Secrets struct {
	DDNS map[string]string
	ACME map[string]map[string]int
}

func (s *Secrets) IsACMEClientAllowed(key, zone string) bool {
	u, ok := s.ACME[key]
	if !ok {
		return false
	}

	p, ok := u[zone]
	if ok && p == 1 {
		return true
	}

	p, ok = u[strings.TrimRight(zone, ".")]
	if ok && p == 1 {
		return true
	}

	return false
}

type DDNSUpdateRequest struct {
	Key string `form:"key" binding:"required"`
}

type ACMEChallenge struct {
	Zone      string `json:"zone" binding:"required"`
	Challenge string `json:"challenge" binding:"required"`
}

type ACMEChallengeID struct {
	Zone      string
	Prefix    string
	Challenge string
}

func joinDomainParts(parts ...string) string {
	p := []string{}
	for _, i := range parts {
		if strings.TrimSpace(i) != "" {
			p = append(p, i)
		}
	}
	return strings.Join(p, ".")
}

// Find the closest zone that we manage by striping dotted components off the
// front of the domain until one matches. If there is a match return the zone
// that matched and any prefix components, if any, as a dotted string. If none
// match then return nil.
func findClosestZone(cfg *bind.BINDConfig, zoneIn, view string) (*bind.Zone, string) {
	suffix := ""
	prefix := []string{}

	zc := strings.Split(zoneIn, ".")
	for i := 0; i <= len(zc)-2; i++ {
		prefix, suffix = zc[:i], strings.Join(zc[i:], ".")
		if zone := cfg.Zone(view, suffix); zone != nil {
			return zone, strings.Join(prefix, ".")
		}
	}

	return nil, ""
}

func makeURL(r *http.Request, path string, subs ...interface{}) *url.URL {
	scheme := "https"

	if r.TLS == nil {
		scheme = "http"
	}

	// Always defer to whatever the proxy told us it was doing because this
	// could be a mullet-VIP in either direction.
	if fwProto := r.Header.Get("X-Forwarded-Proto"); fwProto != "" {
		scheme = fwProto
	}

	return &url.URL{
		Scheme: scheme,
		Host:   r.Host,
		Path:   fmt.Sprintf(path, subs...),
	}
}

func createAcmeChallenge(c *gin.Context) {
	dc := dns.DNSClient{Server: "172.16.18.52:53"}

	var ch ACMEChallenge
	if err := c.ShouldBindJSON(&ch); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"error": err.Error(),
		})
		return
	}

	zone, prefix := findClosestZone(cfg, ch.Zone, "external")
	if zone == nil {
		c.JSON(http.StatusNotFound, gin.H{
			"error": "Zone not found",
		})
		return
	}

	if v := c.GetString(ACME_AUTH_KEY); !secrets.IsACMEClientAllowed(v, zone.Name) {
		c.JSON(http.StatusForbidden, gin.H{
			"error": "Zone update not allowed",
		})
		return
	}

	// Do this first, in-case it fails (even though it should never fail)
	id, err := json.Marshal(ACMEChallengeID{
		Zone:      zone.Name,
		Prefix:    prefix,
		Challenge: ch.Challenge,
	})
	if err != nil {
		log.Printf("error: %s", err)
		c.JSON(http.StatusInternalServerError, gin.H{
			"error": "error encoding ID",
		})
		return
	}

	url := makeURL(c.Request, "/acme/%s", base64.URLEncoding.EncodeToString(id))

	t := &dns.TXT{
		Name: joinDomainParts("_acme-challenge", prefix),
		Ttl:  5,
		Txt:  []string{ch.Challenge},
	}

	// Cleanup any old challenges before adding a new one
	if err := dc.RemoveAll(zone, t); err != nil {
		log.Printf("error RemoveAll: %s", err)
		c.JSON(http.StatusInternalServerError, gin.H{
			"error": err.Error(),
		})
		return
	}

	if err := dc.Insert(zone, t); err != nil {
		log.Printf("error Insert: %s", err)
		c.JSON(http.StatusInternalServerError, gin.H{
			"error": err.Error(),
		})
		return
	}

	c.Writer.Header()["Location"] = []string{url.String()}
	c.JSON(http.StatusCreated, gin.H{
		"created": url.String(),
	})
}

func deleteAcmeChallenge(c *gin.Context) {
	dc := dns.DNSClient{Server: "172.16.18.52:53"}

	rid, err := base64.URLEncoding.DecodeString(c.Param("id"))
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"error": "unable to decode ID",
		})
		return
	}

	var id ACMEChallengeID
	if err = json.Unmarshal(rid, &id); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"error": "unable to decode ID",
		})
		return
	}

	zone := cfg.Zone("external", id.Zone)
	if zone == nil {
		c.JSON(http.StatusNotFound, gin.H{
			"error": "Zone not found",
		})
		return
	}

	if v := c.GetString(ACME_AUTH_KEY); !secrets.IsACMEClientAllowed(v, zone.Name) {
		c.JSON(http.StatusForbidden, gin.H{
			"error": "Zone update not allowed",
		})
		return
	}

	t := &dns.TXT{
		Name: joinDomainParts("_acme-challenge", id.Prefix),
		Ttl:  5,
		Txt:  []string{id.Challenge},
	}

	if err := dc.Remove(zone, t); err != nil {
		log.Printf("error Remove: %s", err)
		c.JSON(http.StatusInternalServerError, gin.H{
			"error": err.Error(),
		})
		return
	}

	c.JSON(http.StatusNoContent, gin.H{})
}

func updateDynamicDNS(c *gin.Context) {
	dc := dns.DNSClient{Server: "172.16.18.52:53"}

	res := c.GetString(DDNS_AUTH_KEY)
	if res == "" {
		log.Println("ddns: Unable to get auth key")
		c.AbortWithStatus(http.StatusForbidden)
		return
	}

	zone, part := findClosestZone(cfg, res, "external")
	if zone == nil {
		log.Println("ddns: Unable to locate zone")
		c.AbortWithStatus(http.StatusNotFound)
		return
	}

	inip := net.ParseIP(strings.Split(c.Request.RemoteAddr, ":")[0])
	xff := c.Request.Header.Get("X-Forwarded-For")
	if xff != "" {
		inip = net.ParseIP(xff)
	}

	if inip == nil {
		log.Println("ddns: Unable to parse IP")
		c.AbortWithStatus(http.StatusInternalServerError)
		return
	}

	t := &dns.A{
		Name: part,
		Ttl:  60,
		A:    inip,
	}

	// Cleanup any old records before adding the new one
	if err := dc.RemoveAll(zone, t); err != nil {
		log.Printf("ddns RemoveAll: %s", err)
		c.AbortWithStatus(http.StatusInternalServerError)
		return
	}

	if err := dc.Insert(zone, t); err != nil {
		log.Printf("ddns Insert: %s", err)
		c.AbortWithStatus(http.StatusInternalServerError)
		return
	}

	c.String(http.StatusAccepted, "")
}

func reflectIP(c *gin.Context) {
	myIp := c.Request.RemoteAddr
	xff := c.Request.Header.Get("X-Forwarded-For")
	if xff != "" {
		myIp = xff
	}

	ips := ipRegexp.FindStringSubmatch(myIp)
	if ips == nil {
		c.AbortWithStatus(http.StatusInternalServerError)
		return
	}

	v6, v4 := ips[1], ips[2]
	if v6 != "" {
		c.String(http.StatusOK, v6)
	} else if v4 != "" {
		c.String(http.StatusOK, v4)
	} else {
		c.AbortWithStatus(http.StatusInternalServerError)
	}
}

func acmeAuth(c *gin.Context) {
	_, pwd, ok := c.Request.BasicAuth()
	if !ok {
		c.Request.Header["WWW-Authenticate"] = []string{`Basic realm="closed site"`}
		c.AbortWithStatus(http.StatusUnauthorized)
		return
	}

	if _, ok := secrets.ACME[pwd]; !ok {
		c.AbortWithStatus(http.StatusForbidden)
		return
	} else {
		c.Set(ACME_AUTH_KEY, pwd)
	}

	c.Next()
}

func ddnsAuth(c *gin.Context) {
	var req DDNSUpdateRequest
	if err := c.ShouldBind(&req); err != nil {
		log.Println("ddnsAuth: No key in request")
		c.AbortWithStatus(http.StatusNotFound)
		return
	}

	res, ok := secrets.DDNS[req.Key]
	if !ok {
		log.Println("ddnsAuth: Unknown secret")
		c.AbortWithStatus(http.StatusNotFound)
		return
	} else {
		c.Set(DDNS_AUTH_KEY, res)
	}

	c.Next()
}

func main() {
	gin.SetMode(gin.DebugMode)

	router := gin.Default()

	router.GET("/reflect-ip", reflectIP)

	ddns := router.Group("/dynamic-dns")
	ddns.Use(ddnsAuth)
	{
		ddns.POST("", updateDynamicDNS)
	}

	acme := router.Group("/acme")
	acme.Use(acmeAuth)
	{
		acme.POST("", createAcmeChallenge)
		acme.DELETE("/:id", deleteAcmeChallenge)
	}

	router.Run()
}