-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
214 lines (179 loc) · 4.65 KB
/
main.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
/*
* Copyright 2021 Spæren, Teodor <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package main
import (
"bufio"
"context"
"fmt"
"io"
"log"
"net"
"net/http"
"os"
"strings"
"sync"
"time"
"github.com/google/renameio/v2"
)
const (
IPv4ListUrl = "https://www.team-cymru.org/Services/Bogons/fullbogons-ipv4.txt"
IPv6ListUrl = "https://www.team-cymru.org/Services/Bogons/fullbogons-ipv6.txt"
)
// Data is the data passed to the tmplText
type Data struct {
Date time.Time
IPv4s []net.IPNet
IPv6s []net.IPNet
}
func main() {
if len(os.Args) != 2 {
log.Fatalf("We require one argument, that being the filename")
}
fd, err := renameio.NewPendingFile(os.Args[1],
renameio.WithExistingPermissions(),
renameio.WithPermissions(0644),
)
if err != nil {
log.Fatalf("new pending file: %v", err)
}
defer fd.Cleanup()
// We can't wait all day!
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Minute)
defer cancel()
data := Data{Date: time.Now()}
var wg sync.WaitGroup
// IPv4
wg.Add(1)
go func() {
defer wg.Done()
ips, err := fetchIpList(ctx, ValidIPv4, IPv4ListUrl)
if err != nil {
log.Fatalf("fetch ipv4 list: %v", err)
}
data.IPv4s = ips
}()
// IPv6
wg.Add(1)
go func() {
defer wg.Done()
ips, err := fetchIpList(ctx, ValidIPv6, IPv6ListUrl)
if err != nil {
log.Fatalf("fetch ipv6 list: %v", err)
}
data.IPv6s = ips
}()
wg.Wait()
if err := writeDefFile(fd, data); err != nil {
log.Fatalf("writeDefFile: %v", err)
}
if err := fd.CloseAtomicallyReplace(); err != nil {
log.Fatalf("closing file atomically: %v", err)
}
}
// writeDefFile writes the tempalte to the given writer based on the
// data in d
func writeDefFile(w io.Writer, d Data) error {
bw := bufio.NewWriter(w)
// Write the header
if _, err := fmt.Fprintf(bw, strings.TrimSpace(`
# Generated by fullbogons-nftables-gen at %s
# Based on https://team-cymru.com/community-services/bogon-reference/
# Source at https://github.com/rhermes/fullbogons-nftables-gen
`), d.Date.Format("2006-01-02 15:04:05Z07:00")); err != nil {
return err
}
// newline
if _, err := fmt.Fprintln(bw, "\n"); err != nil {
return err
}
// Write IPV4_BOGONS
if err := writeIpList(bw, "IPV4_BOGONS", d.IPv4s); err != nil {
return err
}
// newline
if _, err := fmt.Fprintln(bw, ""); err != nil {
return err
}
// Write IPV6_BOGONS
if err := writeIpList(bw, "IPV6_BOGONS", d.IPv6s); err != nil {
return err
}
// remember to flush the buffer
return bw.Flush()
}
// writeIpList writes
func writeIpList(w io.Writer, name string, ips []net.IPNet) error {
if _, err := fmt.Fprintf(w, "define %s = {", name); err != nil {
return err
}
for i, ip := range ips {
s := " %s,\n"
if i == 0 {
s = "\n %s,\n"
}
if _, err := fmt.Fprintf(w, s, ip.String()); err != nil {
return err
}
}
if _, err := fmt.Fprintln(w, "}"); err != nil {
return err
}
return nil
}
// fetchIpList fetches the IP list and validates the contents
func fetchIpList(ctx context.Context, validator IpValidator, listUrl string) ([]net.IPNet, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, listUrl, http.NoBody)
if err != nil {
return nil, err
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
ips := make([]net.IPNet, 0)
scanner := bufio.NewScanner(resp.Body)
for scanner.Scan() {
line := scanner.Text()
// Skip comments
if strings.HasPrefix(line, "#") {
continue
}
// Parse line
_, ip, err := net.ParseCIDR(line)
if err != nil {
return nil, err
}
if !validator(ip) {
return nil, fmt.Errorf("invalid ip by validator: %s", ip.String())
}
ips = append(ips, *ip)
}
if err := scanner.Err(); err != nil {
return nil, err
}
return ips, nil
}
// An IpValidator returns if the ip is a valid ip for the context.
type IpValidator func(ip *net.IPNet) bool
// Taken from https://github.com/asaskevich/govalidator
func ValidIPv4(ip *net.IPNet) bool {
return ip != nil && strings.Contains(ip.IP.String(), ".")
}
// Taken from https://github.com/asaskevich/govalidator
func ValidIPv6(ip *net.IPNet) bool {
return ip != nil && strings.Contains(ip.IP.String(), ":")
}