-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathgoradius.go
331 lines (262 loc) · 7.55 KB
/
goradius.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
package goradius
import (
"encoding/json"
"fmt"
"github.com/alouca/goconfig"
"github.com/alouca/gologger"
"io/ioutil"
"net"
)
var (
l *logger.Logger
c *config.Config
// Various Maps necessary for Marshalling/unmarshalling data
radiusMap map[int]RadiusDictionary
vendorMap map[int]VendorDictionary
parserMap map[string]ContentParser
marshalMap map[string]MarshalHelper
)
// Radius Content Parser Function Signature
type ContentParser func([]byte, *RadiusPacket) interface{}
// Marshaller signature
type MarshalHelper func(AttributeValuePair, *RadiusPacket) []byte
// Radius Shared-Secret Provider Signature
type SharedSecretProvider func(string) string
/*
* Dictionary Structure Definitions
*/
// RADIUS Dictionary (RFC2865 + RFC2866)
type RadiusDictionary struct {
Attribute int
Name string
ContentType string
}
// Vendor-Specific Attribute Dictionary
type VendorDictionary struct {
VendorID int
Name string
TLVs []TLV
TLVMap map[int]TLV
}
// Type-Length-Value Structure
type TLV struct {
Type uint8
Name string
ContentType string
}
type GoRadius struct {
SharedSecret SharedSecretProvider
conn *net.UDPConn
}
/*
* Create a new RADIUS parser, providing the RADIUS & Vendor-Specific TLV Dictionary JSON files.
* Option to enable debug & verbose output to aid in troubleshooting
*/
func NewGoRadius(radDictFile, vendorDictFile string, debug, verbose bool) *GoRadius {
l = logger.CreateLogger(verbose, debug)
radDict, err := ioutil.ReadFile(radDictFile)
if err != nil {
l.Fatal("Unable to read RADIUS Dictionary file: %s\n", err.Error())
return nil
}
vendorDict, err := ioutil.ReadFile(vendorDictFile)
if err != nil {
l.Fatal("Unable to read Vendor Dictionary file: %s\n", err.Error())
return nil
}
var vendorData []VendorDictionary
var radiusData []RadiusDictionary
// Parse dictionaries
err = json.Unmarshal(vendorDict, &vendorData)
if err != nil {
l.Fatal("Unable to unmarshal JSON Vendor Dictionary: %s\n", err.Error())
return nil
}
err = json.Unmarshal(radDict, &radiusData)
if err != nil {
l.Fatal("Unable to unmarshal JSON RADIUS Dictionary: %s\n", err.Error())
return nil
}
r := new(GoRadius)
radiusMap = make(map[int]RadiusDictionary)
vendorMap = make(map[int]VendorDictionary)
// Register default-parsers
parserMap = map[string]ContentParser{
"VSA": VendorParser,
"IP": IPParser,
"Acct-Status-Type": AcctStatusTypeParser,
"uint16": ParseUint16,
"uint32": ParseUint32,
"string": ParseString,
"userpassword": ParseUserPassword,
"uvarint": ParseUvarint,
"fallback": FallbackParser,
}
marshalMap = map[string]MarshalHelper{
"string": StringMarshaller,
}
// Load dictionaries
for _, attr := range radiusData {
radiusMap[attr.Attribute] = attr
}
for _, vsa := range vendorData {
vsa.TLVMap = make(map[int]TLV)
for _, tlv := range vsa.TLVs {
vsa.TLVMap[int(tlv.Type)] = tlv
}
vendorMap[vsa.VendorID] = vsa
}
return r
}
func (r *GoRadius) SendPacket(p *RadiusPacket) error {
rawPacket := p.Marshal()
r.SendRawPacket(rawPacket, p.Originator)
l.Debug("Sent response to %s (Data len: %d)\n", p.Originator.String(), len(rawPacket))
return nil
}
func (r *GoRadius) SendRawPacket(data []byte, dest *net.UDPAddr) error {
if r.conn != nil {
n, err := r.conn.WriteToUDP(data, dest)
if err != nil {
fmt.Errorf("Error writing to destination: %s\n", err.Error())
} else {
l.Debug("Wrote %d bytes to destination %s\n", n, dest.String())
return nil
}
}
return fmt.Errorf("No UDP Server started\n")
}
// Registers a new AVP Parser
func RegisterParser(name string, parser ContentParser) error {
if _, ok := parserMap[name]; ok {
return fmt.Errorf("Parser with name %s is already registered\n", name)
}
if parser == nil {
return fmt.Errorf("Parser function cannot be null\n")
}
parserMap[name] = parser
return nil
}
func (r *GoRadius) StartUDPServer(port int, ssp SharedSecretProvider) (chan *RadiusPacket, error) {
udpAddr, err := net.ResolveUDPAddr("udp", fmt.Sprintf(":%d", port))
if err != nil {
return nil, fmt.Errorf("Unable to resolve UDP Address: %s\n", err.Error())
}
conn, err := net.ListenUDP("udp", udpAddr)
if err != nil {
return nil, fmt.Errorf("Error on listen: %s\n", err.Error())
}
r.SharedSecret = ssp
r.conn = conn
c := make(chan *RadiusPacket, 10000)
go func() {
for {
b := make([]byte, 1500)
n, raddr, err := conn.ReadFromUDP(b)
if err != nil {
l.Error("Error reading data: %s\n", err.Error())
} else {
l.Debug("Read %d bytes from %s\n", n, raddr.IP.String())
go func() {
data := r.ParseRadiusPacket(raddr, b[0:n])
l.Debug("Parsed total of %d AVPs\n", len(data.AVPS))
c <- data
}()
}
}
}()
return c, nil
}
// RADIUS Packet Parser
// Returns an array of parsed Attribute-Value Pairs
func (r *GoRadius) ParseRadiusPacket(source *net.UDPAddr, data []byte) *RadiusPacket {
p := new(RadiusPacket)
p.Raw = data
p.Originator = source
// Parse the header
// First byte is the Code
l.Debug("Packet Code: %d\n", uint(data[0]))
p.Code = uint(data[0])
// Set string packet code
if packetCode, ok := packetCodes[p.Code]; ok {
p.PacketType = packetCode
} else {
p.PacketType = "Unknown"
}
// Second byte is the Identifier
l.Debug("Packet Identifier: %d\n", uint(data[1]))
p.PacketId = uint(data[1])
// Find the packet length
pl := uint16(data[2])<<8 | uint16(data[3])
l.Debug("Packet length: %d\n", pl)
if int(pl) != len(data) {
l.Fatal("Packet length and provided data do not match %d vs %d", int(pl), len(data))
}
p.Authenticator = data[4:20]
l.Debug("Authenticator: %x\n", p.Authenticator)
// Get the shared-secret from provided call-back
p.SharedSecret = r.SharedSecret(source.IP.String())
// start decoding AVPs from byte 20
cursor := 20
pairs := make([]AttributeValuePair, 0, 10)
for cursor < len(data) {
avpType := uint8(data[cursor])
cursor++
avpLength := uint8(data[cursor])
cursor++
//fmt.Printf("AVP Length: %d\n", avpLength)
read := int(avpLength) + cursor - 2
avpContent := data[cursor:read]
cursor += int(avpLength) - 2
var parsedContent interface{}
var name, ctype string
if avp, ok := radiusMap[int(avpType)]; ok {
// Parse the content
parser := parserMap[avp.ContentType]
l.Debug("Type: %s(%d), Length: %d, Content-Type: %s\n", avp.Name, avpType, avpLength, avp.ContentType)
parsedContent = parser(avpContent, p)
name = avp.Name
ctype = avp.ContentType
} else {
l.Debug("Unknown Type %d, Length %d\n", avpType, avpLength)
parser := parserMap["fallback"]
name = "unknown"
ctype = "fallback"
parsedContent = parser(avpContent, p)
}
pairs = append(pairs, AttributeValuePair{name, ctype, avpLength, parsedContent})
}
p.AVPS = pairs
return p
}
// parseInt64 treats the given bytes as a big-endian, signed integer and
// returns the result.
func parseInt64(bytes []byte) (ret int64, err error) {
if len(bytes) > 8 {
// We'll overflow an int64 in this case.
err = fmt.Errorf("integer too large")
return
}
for bytesRead := 0; bytesRead < len(bytes); bytesRead++ {
ret <<= 8
ret |= int64(bytes[bytesRead])
}
// Shift up and down in order to sign extend the result.
ret <<= 64 - uint8(len(bytes))*8
ret >>= 64 - uint8(len(bytes))*8
return
}
func Uvarint(buf []byte) (x uint64) {
for i, b := range buf {
x = x<<8 + uint64(b)
if i == 7 {
return
}
}
return
}
func HelperParseUint16(content []byte) int {
number := uint8(content[1]) | uint8(content[0])<<8
//fmt.Printf("\t%d\n", number)
return int(number)
}