-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapiban.go
264 lines (222 loc) · 6.23 KB
/
apiban.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
/*
* Copyright (C) 2020-2021 Fred Posner (palner.com)
*
* This file is part of APIBAN.org.
*
* apiban is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version
*
* apiban is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
package golib
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"strings"
)
var (
// RootURL is the base URI of the APIBAN.org API server
RootURL = "https://apiban.org/api/"
)
// ErrBadRequest indicates a 400 response was received;
//
// NOTE: this is used by the server to indicate both that an IP address is not
// blocked (when calling Check) and that the list is complete (when calling
// Banned)
var ErrBadRequest = errors.New("bad request")
// Entry describes a set of blocked IP addresses from APIBAN.org
type Entry struct {
// ID is the timestamp of the next Entry
ID string `json:"ID"`
// IPs is the list of blocked IP addresses in this entry
IPs []string `json:"ipaddress"`
}
type ApiGetJson struct {
SetType string `json:"set"`
ID string `json:"id"`
}
type ApiGetCheck struct {
SetType string `json:"set"`
IP string `json:"ipaddress"`
}
// Banned returns a set of banned addresses, optionally limited to the
// specified startFrom ID. If no startFrom is supplied, the entire current list will
// be pulled.
func Banned(key string, startFrom string, set string) (*Entry, error) {
if key == "" {
return nil, errors.New("API Key is required")
}
if key == "MY API KEY" {
return nil, errors.New("API Key is required")
}
if startFrom == "" {
startFrom = "100" // NOTE: arbitrary ID copied from reference source
}
if set == "" {
set = "sip"
}
p := &ApiGetJson{
ID: startFrom,
SetType: set,
}
p_json, err := json.Marshal(p)
if err != nil {
return nil, errors.New("error making json payload")
}
out := &Entry{
ID: startFrom,
}
url := RootURL + "get"
e, err := queryServerv2(key, p_json, url)
if err != nil {
return nil, err
}
if e.ID == "none" {
// List complete
return out, nil
}
if e.ID == "" {
return nil, errors.New("empty ID received")
}
// Set the next ID
out.ID = e.ID
// Aggregate the received IPs
out.IPs = append(out.IPs, e.IPs...)
return out, nil
}
// Check queries APIBAN.org to see if the provided IP address is blocked.
func Check(key string, ip string, set string) (bool, error) {
if key == "" {
return false, errors.New("API Key is required")
}
if ip == "" {
return false, errors.New("IP address is required")
}
if set == "" {
set = "sip"
}
p := &ApiGetCheck{
IP: ip,
SetType: set,
}
p_json, err := json.Marshal(p)
if err != nil {
return false, errors.New("error making json payload")
}
url := RootURL + "check"
entry, err := queryServerv2(key, p_json, url)
if err == ErrBadRequest {
// Not blocked
return false, nil
}
if err != nil {
return false, err
}
if entry == nil {
return false, errors.New("empty entry received")
} else if len(entry.IPs) == 1 {
if entry.IPs[0] == "not blocked" {
// Not blocked
return false, nil
}
}
// IP address is blocked
return true, nil
}
func queryServerv2(key string, p_json []byte, url string) (*Entry, error) {
sendbody := strings.NewReader(string(p_json))
bearer := "Bearer " + key
req, err := http.NewRequest("POST", url, sendbody)
req.Header.Add("Authorization", bearer)
if err != nil {
// handle err
return nil, err
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, fmt.Errorf("query error: %s", err.Error())
}
defer resp.Body.Close()
switch {
case resp.StatusCode == http.StatusBadRequest ||
resp.StatusCode == http.StatusNotFound ||
resp.StatusCode == http.StatusForbidden:
return processBadRequest(resp)
case resp.StatusCode == http.StatusOK:
break
case resp.StatusCode > 400 && resp.StatusCode < 500:
return nil, fmt.Errorf("client error (%d) from apiban.org: %s from %q", resp.StatusCode, resp.Status, url)
case resp.StatusCode >= 500:
return nil, fmt.Errorf("server error (%d) from apiban.org: %s from %q", resp.StatusCode, resp.Status, url)
case resp.StatusCode > 299:
return nil, fmt.Errorf("unhandled error (%d) from apiban.org: %s from %q", resp.StatusCode, resp.Status, url)
}
entry := new(Entry)
if err = json.NewDecoder(resp.Body).Decode(entry); err != nil {
return nil, fmt.Errorf("failed to decode server response: %s", err.Error())
}
return entry, nil
}
func processBadRequest(resp *http.Response) (*Entry, error) {
var buf bytes.Buffer
if _, err := buf.ReadFrom(resp.Body); err != nil {
return nil, fmt.Errorf("failed to read response body: %w", err)
}
// Read the bytes buffer into a new bytes.Reader
r := bytes.NewReader(buf.Bytes())
// First, try decoding as a normal entry
e := new(Entry)
if err := json.NewDecoder(r).Decode(e); err == nil {
// Successfully decoded normal entry
switch e.ID {
case "none":
// non-error case
case "unauthorized":
return nil, errors.New("unauthorized")
default:
// unhandled case
return nil, ErrBadRequest
}
if len(e.IPs) > 0 {
switch e.IPs[0] {
case "no new bans":
return e, nil
}
}
// Unhandled case
return nil, ErrBadRequest
}
// Next, try decoding as an errorEntry
if _, err := r.Seek(0, io.SeekStart); err != nil {
return nil, fmt.Errorf("failed to re-seek to beginning of response buffer: %w", err)
}
type errorEntry struct {
AddressCode string `json:"ipaddress"`
IDCode string `json:"ID"`
}
ee := new(errorEntry)
if err := json.NewDecoder(r).Decode(ee); err != nil {
return nil, fmt.Errorf("failed to decode Bad Request response: %s", err.Error())
}
switch ee.AddressCode {
case "rate limit exceeded":
return nil, errors.New("rate limit exceeded")
default:
// unhandled case
return nil, ErrBadRequest
}
}