A feature-rich RADIUS library for Go. This is a significantly refactored version (v2) of the original library, optimized for clarity and ease of use.
This project forks from https://github.com/bronze1man/radius
- Simplified API: Clean and intuitive Go-native interfaces.
- Dictionary Support: Full support for FreeRADIUS-style dictionary files.
- Builtin Dictionary: Minimal standard attributes included out-of-the-box.
- Template System: Pre-resolve attributes and VSAs for packet construction.
- Lazy Decoding: Zero-allocation iterator-based decoding for high-performance use cases.
- Allocation Pooling: Use
sync.PoolforPacketstructs to reach absolute zero-allocation. - Enhanced Testing: Comprehensive test suite including "golden data" verification.
go get github.com/sergle/radius/v2This library supports FreeRADIUS-style dictionary files, including $INCLUDE, VENDOR, BEGIN-VENDOR, vendor-specific attributes (VSAs) and tlv attributes (ParseTLV, GetTLV).
Create a small top-level dictionary file that includes the base dictionary plus any vendor dictionaries you need.
Example dictionary file:
$INCLUDE /path/to/freeradius/dictionary
$INCLUDE /path/to/freeradius/dictionary.cisco
$INCLUDE /path/to/freeradius/dictionary.microsoft
Then load it in Go:
dict := radius.NewDictionary()
if err := dict.LoadFile("/path/to/your/dictionary"); err != nil {
log.Fatal(err)
}
// Optional: make this dictionary the default for package-level lookups.
radius.SetDefaultDictionary(dict)
// Example: pre-resolve a reply template with a Cisco VSA for reuse.
replyTemplate, _ := dict.CreateRequestTemplate(radius.AccessAccept, "Reply-Message")
replyTemplate.AddVSAAttribute(dict, "Cisco", "h323-remote-address")You can also call dict.LoadFile(...) multiple times (for example, once per vendor file). Using a root dictionary with $INCLUDE is usually easier to manage and matches how FreeRADIUS dictionaries are commonly organized.
package main
import (
"context"
"log"
"github.com/sergle/radius/v2"
)
func main() {
handler := radius.HandlerFunc(func(ctx context.Context, request *radius.Packet) *radius.Packet {
log.Printf("Received %s from %s", request.Code, request.ClientAddr)
if request.Code == radius.AccessRequest {
if request.GetUsername() == "admin" && request.GetPassword() == "secret" {
return request.ReplyAccept()
}
return request.ReplyReject()
}
return nil
})
// Option A: single shared secret for all clients
srv := radius.NewServer(":1812", "shared-secret", handler)
// Option B: per-client shared secrets (lookup by remote host IP)
// clients := radius.NewClientList([]radius.Client{
// radius.NewClient("192.0.2.10", "secret-a"),
// radius.NewClient("192.0.2.11", "secret-b"),
// })
// srv := radius.NewServerWithClientList(":1812", clients, handler)
log.Fatal(srv.ListenAndServe())
}package main
import (
"context"
"log"
"github.com/sergle/radius/v2"
)
func main() {
client := radius.NewRadClient("127.0.0.1:1812", "shared-secret")
req := client.NewRequest(radius.AccessRequest)
req.AddAVP(radius.AVP{Type: radius.AttrUserName, Value: []byte("admin")})
if err := req.AddPassword("secret"); err != nil {
log.Fatal(err)
}
// Context-aware request with timeout
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
reply, err := client.SendContext(ctx, req)
if err != nil {
log.Fatal(err)
}
log.Printf("Reply: %s", reply.Code)
}CHAP sends a challenge and a response derived from the password: (response = MD5(chapID || password || challenge)).
package main
import (
"context"
"crypto/rand"
"log"
"time"
"github.com/sergle/radius/v2"
)
func main() {
client := radius.NewRadClient("127.0.0.1:1812", "shared-secret")
req := client.NewRequest(radius.AccessRequest)
req.AddAVP(radius.AVP{Type: radius.AttrUserName, Value: []byte("admin")})
chapID := uint8(1)
challenge := make([]byte, 16) // RFC 2865: 5..253 bytes, random
if _, err := rand.Read(challenge); err != nil {
log.Fatal(err)
}
if err := req.SetCHAPPasswordFromSecret(chapID, "secret", challenge); err != nil {
log.Fatal(err)
}
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
reply, err := client.SendContext(ctx, req)
if err != nil {
log.Fatal(err)
}
log.Printf("Reply: %s", reply.Code)
}On the server, request.VerifyCHAP(password) checks the response; without CHAP-Challenge the Request Authenticator is used as the challenge. A challenge under 5 bytes is refused (ErrInvalidCHAPChallengeLength). The NAS picks the challenge, so a replayed request can't be detected; require Message-Authenticator (SetRequireMessageAuthenticator), since CHAP doesn't use the shared secret.
MS-CHAPv2 travels in Microsoft VSAs, so load a dictionary that includes dictionary.microsoft (see Dictionaries). The client sends MS-CHAP-Challenge and MS-CHAP2-Response; the server checks the NT-Response and answers with MS-CHAP2-Success, which proves to the client that the server knows the password too, and the MPPE keys (RFC 3079).
Client (NAS) side:
package main
import (
"context"
"crypto/rand"
"crypto/subtle"
"log"
"time"
"github.com/sergle/radius/v2"
)
func main() {
dict := radius.NewDictionary()
if err := dict.LoadFile("/path/to/your/dictionary"); err != nil {
log.Fatal(err)
}
const user, password = "admin", "secret"
authChallenge := make([]byte, 16) // sent by the NAS to the peer
peerChallenge := make([]byte, 16) // chosen by the peer
rand.Read(authChallenge)
rand.Read(peerChallenge)
ntResponse, err := radius.MSCHAPv2NTResponse(authChallenge, peerChallenge, user, password)
if err != nil {
log.Fatal(err)
}
// MS-CHAP2-Response: Ident(1) Flags(1) Peer-Challenge(16) Reserved(8) NT-Response(24)
resp := make([]byte, 50)
resp[0] = 1 // Ident
copy(resp[2:18], peerChallenge)
copy(resp[26:], ntResponse)
client := radius.NewRadClient("127.0.0.1:1812", "shared-secret")
req := client.NewAccessRequest()
req.AddAVP(radius.AVP{Type: radius.AttrUserName, Value: []byte(user)})
for _, a := range [][2]string{
{"MS-CHAP-Challenge", string(authChallenge)},
{"MS-CHAP2-Response", string(resp)},
} {
vsa, err := dict.ParseVSA("Microsoft", a[0], a[1])
if err == nil {
err = req.AddVSA(vsa)
}
if err != nil {
log.Fatal(err)
}
}
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
reply, err := client.SendContext(ctx, req)
if err != nil {
log.Fatal(err)
}
if reply.Code != radius.AccessAccept {
log.Fatalf("Reply: %s", reply.Code)
}
// MS-CHAP2-Success: Ident(1) "S=<40 hex digits>"
want := radius.MSCHAPv2AuthenticatorResponse(authChallenge, peerChallenge, ntResponse, user, password)
success, ok := dict.GetVSA(reply, "Microsoft", "MS-CHAP2-Success")
if !ok || len(success) == 0 || subtle.ConstantTimeCompare(success[1:], []byte(want)) != 1 {
log.Fatal("server failed to authenticate")
}
sendKey, _ := dict.GetVSA(reply, "Microsoft", "MS-MPPE-Send-Key") // decrypted
recvKey, _ := dict.GetVSA(reply, "Microsoft", "MS-MPPE-Recv-Key")
log.Printf("Accepted, send key %x, recv key %x", sendKey, recvKey)
}Server side (dict loaded as above, lookupPassword is your user store):
handler := radius.HandlerFunc(func(ctx context.Context, request *radius.Packet) *radius.Packet {
if request.Code != radius.AccessRequest {
return nil
}
user := request.GetUsername()
password, ok := lookupPassword(user)
challenge, _ := dict.GetVSA(request, "Microsoft", "MS-CHAP-Challenge")
resp, _ := dict.GetVSA(request, "Microsoft", "MS-CHAP2-Response")
if !ok || len(challenge) != 16 || len(resp) != 50 {
return request.ReplyReject()
}
ident, peerChallenge, ntResponse := string(resp[:1]), resp[2:18], resp[26:]
want, err := radius.MSCHAPv2NTResponse(challenge, peerChallenge, user, password)
if err != nil || subtle.ConstantTimeCompare(ntResponse, want) != 1 {
reply := request.ReplyReject()
if vsa, err := dict.ParseVSA("Microsoft", "MS-CHAP-Error", ident+"E=691 R=0"); err == nil {
reply.AddVSA(vsa)
}
return reply
}
// Encrypted attributes need the request's authenticator: use request.Reply*()
reply := request.ReplyAccept()
sendKey, recvKey := radius.MSCHAPv2MPPEKeys(ntResponse, password)
for _, a := range [][2]string{
{"MS-CHAP2-Success", ident + radius.MSCHAPv2AuthenticatorResponse(challenge, peerChallenge, ntResponse, user, password)},
{"MS-MPPE-Send-Key", string(sendKey)},
{"MS-MPPE-Recv-Key", string(recvKey)},
} {
vsa, err := dict.ParseVSA("Microsoft", a[0], a[1])
if err == nil {
err = reply.AddVSA(vsa)
}
if err != nil {
log.Printf("MS-CHAPv2 reply: %v", err)
return request.ReplyReject()
}
}
return reply
})Tunnel attributes (Tunnel-Type, Tunnel-Medium-Type, Tunnel-Private-Group-ID, ...) carry a tag (1–31) that groups attributes of the same tunnel. Dictionaries mark them with has_tag. Set the tag with the Name:tag syntax; without it the tag is 0:
dict := radius.GetDefaultDictionary()
reply := request.ReplyAccept()
// Tunnel-Type:1 = VLAN, Tunnel-Medium-Type:1 = 802, Tunnel-Private-Group-ID:1 = "100"
for _, a := range [][2]string{
{"Tunnel-Type:1", "VLAN"},
{"Tunnel-Medium-Type:1", "802"},
{"Tunnel-Private-Group-ID:1", "100"},
} {
avp, err := dict.ParseAVP(a[0], a[1])
if err != nil {
log.Fatal(err) // unknown attribute, tag on an untagged attribute, bad value
}
reply.AddAVP(avp)
}
// Templates accept the same syntax
tmpl, _ := dict.CreateRequestTemplate(radius.AccessAccept, "Tunnel-Type:2", "Tunnel-Private-Group-ID:2")
tmpl.Fill(reply, "VLAN", "200")Decoding strips the tag; tagged values are accepted with or without one:
vlan, ok := reply.GetVLAN() // 100, true
tt := reply.GetAVP(radius.AttrTunnelType)
log.Print(tt.Decode(reply)) // 13 (VLAN), tag removed
log.Print(dict.DecodeAVPValue(reply, *tt)) // "VLAN (tag 1)"Attributes of type tlv (e.g. 3GPP2, FreeRADIUS EAP-FAST) hold sub-attributes, declared with dotted ids (59.1) or BEGIN-TLV blocks. Build them with ParseTLV, which returns a *TLV builder, add sub-attributes with Add, and add the result with Packet.AddTLV. Read them with GetTLV/GetTLVString; DecodeAVPValue renders them:
tlv, err := dict.ParseTLV("3GPP2", "3GPP2-Remote-IP-Address")
err = tlv.Add("3GPP2-Remote-IP-Address-Value", "10.1.2.3")
err = tlv.Add("3GPP2-Remote-IP-Qualifier", "1")
err = req.AddTLV(tlv)
q, ok := dict.GetTLVString(p, "3GPP2", "3GPP2-Remote-IP-Qualifier") // "1", trueNotes:
-
Addtakes sub-attributes at any depth, checks the name, type, VALUE names and length, and returns the error right away. -
Sub-attributes of a nested TLV go into its last instance.
AddTLV(name)starts a new instance and returns a builder for it:n, err := tlv.AddTLV("Example-Nested") err = n.Add("Example-Nested-Name", "b")
-
Packet.AddTLVdoesn't change the builder, so oneTLVcan go into several packets. It splits a long value over several attributes for WiMAX and long extended attributes (245, 246).ToAVPreturns the value as one attribute without a packet; it logs a warning and returns the zero AVP if the value doesn't fit one attribute or needs encryption. -
Sub-attributes whose type has no handler (e.g.
abinary) are shown as raw bytes and can't be built. -
Encrypted sub-attributes (
encrypt=1orencrypt=2in the dictionary, e.g.WiMAX-hDHCP-DHCP-RK) need the packet's secret and authenticator.Addkeeps their plaintext, andPacket.AddTLVencrypts them. For a reply, create the packet withrequest.Reply()(orReplyAccept()etc.) first, otherwisePacket.AddTLV(likeAddTunnelPassword) returnsErrNoRequestAuthenticator. Accounting, CoA and Disconnect requests hide values with an all-zero authenticator (RFC 2866, RFC 5176).encrypt=2values (like Tunnel-Password, RFC 2868) can't go in an Access-Request or Status-Server:Packet.AddTLVandAddTunnelPasswordreturnErrTunnelPasswordInRequest. A failingPacket.AddTLVleaves the packet unchanged. For example:tlv, err := dict.ParseTLV("WiMAX", "WiMAX-hDHCP-Server-Parameters") err = tlv.Add("WiMAX-hDHCP-DHCP-RK", string(key)) err = tlv.Add("WiMAX-hDHCP-DHCP-RK-Key-Id", "1") reply := req.ReplyAccept() err = reply.AddTLV(tlv)
GetTLV,GetTLVString,DecodeAVPValueandPacket.Stringdecrypt them with the packet they are given.Packet.StringMasked,AVP.StringMaskedandDecodeAVPValueMaskedshow them as*****, for logs. If the ciphertext is malformed,GetTLVdoesn't find it and the others show the raw bytes;DecodeAVPValue(nil, …)shows the raw bytes too (GetTLVandGetTLVStringfind nothing in a nil packet). A wrong secret or authenticator isn't detected: it decrypts to garbage. Onlyencrypt=1onstringsub-attributes andencrypt=2on non-TLV ones are supported. Those others, andencrypt=3, are loaded with a warning but can't be built (ErrUnsupportedAttributeType) or decrypted: they are shown as raw bytes andGetTLVdoesn't find them (nor the sub-attributes of such an encrypted TLV). -
Not supported yet: sub-attributes of vendors with a format other than
1,1or1,1,c(WiMAX).
Attributes 241–246 hold "extended" attributes, e.g. Frag-Status (241.1) or the IP-Port TLVs (241.5–241.7). 245 and 246 use the "long" format: a value over 251 bytes is split over several attributes. Vendors can define attributes there too (Extended-Vendor-Specific, BEGIN-VENDOR ... format=Extended-Vendor-Specific-N in FreeRADIUS dictionaries).
Use them by name, as other attributes:
avp, err := dict.ParseAVP("Frag-Status", "More-Data-Pending") // fits one attribute
req.AddAVP(avp)
e, err := dict.ParseExtended("FreeRADIUS", "FreeRADIUS-802.1X-EAPoL-Key-Msg", longValue) // "" for standard ones
req.AddExtended(e) // splits a long value
v, ok := dict.GetExtended(p, "", "Frag-Status") // the whole value, fragments joinedTemplates (CreateRequestTemplate, AddVSAAttribute for vendor ones) accept extended names, ParseTLV/GetTLV work for TLVs among them, and DecodeAVPValue/Packet.String show them by name. Notes:
- The builtin dictionary declares 241–246 only; load the FreeRADIUS dictionaries for the attributes in them.
ParseAVPreturns one attribute, so it refuses a value too long for it; useParseExtendedandAddExtended.Packet.AddTLVsplits a long-extended TLV value over several attributes.- Values can't be empty (RFC 6929).
- Fragments are joined only if they follow each other; a broken chain is ignored.
DecodeAVPValueshows each fragment separately and marks the ones after the first asContinued. - The only
BEGIN-VENDORoption isformat=(orparent=) naming an Extended-Vendor-Specific attribute; anything else is a load error.
Most vendors use the standard VSA layout: a 1-byte attribute number and a 1-byte length. Some declare another layout in the dictionary with VENDOR ... format=T,L[,c], and the library follows it:
T: attribute number size, 1, 2 or 4 bytes (e.g. Lucent and Starent use 2, USR uses 4).L: length field size, 0, 1 or 2 bytes.c: WiMAX continuation byte, which lets a long value span several attributes.
ParseVSA, templates and TLV builders encode with the vendor's format, and DecodeAVPValue and ToVSA decode with it. For WiMAX, AddVSA splits a long value over several Vendor-Specific attributes, and GetVSA/GetTLV join it back:
vsa, _ := dict.ParseVSA("WiMAX", "WiMAX-Hotline-Indicator", longValue)
req.AddVSA(vsa) // adds several attributes if the value is long
v, ok := dict.GetVSA(p, "WiMAX
B665
", "WiMAX-Hotline-Indicator") // the whole valueDecodeAVPValue (and so Packet.String) still shows each WiMAX fragment separately.
A VSA built by hand uses the standard layout unless you set Format, e.g. Format: dict.VendorFormat(vendorID). If the format is invalid (see VendorFormat.Valid) or the attribute number is too big for it, ParseVSA and templates return ErrInvalidVendorFormat, and ToAVP/ToAVPList log a warning and return nothing. ToVSA fills in Format and, for WiMAX, leaves the continuation byte out of Value.
The only VENDOR option is format=T,L[,c]; anything else is a load error.
Vendor attributes declared with encrypt=1 (as User-Password) or encrypt=2 (with has_tag as Tunnel-Password, without it as MS-MPPE-Send-Key, RFC 2548) are encrypted by AddVSA with the packet's secret and authenticator. ParseVSA keeps the plaintext, so add the result with AddVSA and check its error:
reply := request.ReplyAccept()
sendKey, _ := radius.MSCHAPv2MPPEKeys(ntResponse, password) // RFC 3079
vsa, err := dict.ParseVSA("Microsoft", "MS-MPPE-Send-Key", string(sendKey))
if err == nil {
err = reply.AddVSA(vsa)
}
key, ok := dict.GetVSA(p, "Microsoft", "MS-MPPE-Send-Key") // decryptedAddVSA returns ErrNoRequestAuthenticator for a reply not made with request.Reply(), and ErrTunnelPasswordInRequest for encrypt=2 in an Access-Request or Status-Server; the packet is unchanged on error. ToAVP/ToAVPList refuse such a VSA (log a warning and return nothing), so it never goes out unencrypted. GetVSA, DecodeAVPValue and Packet.String decrypt them.
For high-load proxies or filters where performance is critical, use lazy decoding to avoid unnecessary allocations.
// Decode without parsing attributes upfront
packet, _ := radius.DecodeRequestLazy(secret, buf)
// Attributes are parsed on-demand when using GetAVP or EachAVP
username := packet.GetUsername()
// Iterate over all attributes without heap allocations
packet.EachAVP(func(attr radius.AVP) bool {
log.Printf("Found AVP: %d", attr.Type)
return true
})The lazy decoders don't check attribute lengths by default: accessors stop at a malformed attribute, so the ones after it are hidden (also from the Message-Authenticator check) while Encode forwards them. Proxies and other code that forwards packets should set ValidateAttributes, which rejects such a packet with ErrInvalidAttributeLength and doesn't allocate:
packet, err := radius.DecodeRequestLazyWithOptions(secret, buf, &radius.DecodeOptions{ValidateAttributes: true})RADIUS "Response Authenticator" integrity is based on an MD5 construction that is vulnerable to modern collision attacks in certain on-path (MITM) threat models (CVE-2024-3596, see BLAST RADIUS – Attack Details).
This library generates and verifies Message-Authenticator (HMAC-MD5, RFC 3579) and includes it as the first attribute on Access- packets it encodes*, which is the recommended mitigation.
Client: RadClient rejects Access-* replies without Message-Authenticator (radius.ErrMessageAuthenticatorMissing). For legacy servers that don't send one:
client.SetRequireMessageAuthenticator(false)Server: set these before Listen/Serve:
srv.SetLimitProxyState(true) // default: drop Access-Requests with Proxy-State but no Message-Authenticator
srv.SetRequireMessageAuthenticator(false) // default: set true to drop every Access-Request without oneDecoding directly: Message-Authenticator is optional by default for compatibility; opt in to reject Access-* packets that omit it:
packet, err := radius.DecodeRequestWithOptions(secret, buf, &radius.DecodeOptions{
RequireMessageAuthenticator: true,
})
if err != nil {
// err == radius.ErrMessageAuthenticatorMissing when absent on Access-*
log.Fatal(err)
}
_ = packetFor the absolute highest performance, use sync.Pool and direct buffer encoding.
// Acquire a packet from the internal pool (Zero B/op)
packet, err := radius.DecodeRequestPooled(secret, buf)
if err != nil {
log.Fatal(err)
}
defer packet.Release() // Crucial: Return packet to the pool
log.Printf("User: %s", packet.GetUsername())DecodeRequestLazyPooled/DecodeReplyLazyPooled combine pooling with lazy decoding: attributes stay in RawAVPs and are read on access.
// Encode directly into a provided buffer, avoiding allocations
buf := make([]byte, 4096)
n, err := packet.EncodeTo(buf)The library is silent by default. Diagnostics (skipped dictionary entries, dropped server packets, ...) go to an optional log/slog logger:
radius.SetLogger(slog.Default())To log packets, use StringMasked (or slog.Any("packet", p), which logs it): String and DecodeAVPValue decrypt passwords and keys. StringMasked shows encrypted values, CHAP-Password, Digest-Response, Digest-HA1 and the MS-CHAP responses as *****, and EAP data other than Identity, Notification and Nak only as its length. The shared secret is left out of JSON, slog and %#v output of Packet and DefaultClient.
- Import Path: Change
github.com/sergle/radiustogithub.com/sergle/radius/v2. - Attribute Names: Standard attributes are now prefixed with
Attr(e.g.,UserName->AttrUserName). - Server API: The
Serviceinterface now returns*Packetdirectly. UseHandlerFuncfor simple closures. - Packet Creation: Use
client.NewRequest(code)orradius.Request(code, secret)for more control.
- EAP MS-CHAPv2 packet format: http://tools.ietf.org/id/draft-kamath-pppext-eap-mschapv2-01.txt
- EAP MS-CHAPv2: https://tools.ietf.org/html/rfc2759
- RADIUS Access-Request: https://tools.ietf.org/html/rfc2865
- RADIUS Accounting-Request: https://tools.ietf.org/html/rfc2866
- RADIUS Support For EAP: https://tools.ietf.org/html/rfc3579
- RADIUS Implementation Issues: https://tools.ietf.org/html/rfc5080
MIT License. See LICENSE for details.