Get rid of LinkType-style branching: different LinkTypes may use the same Protocol modules.

This commit is contained in:
2019-12-09 12:14:01 +01:00
parent c2aa435a6d
commit f0b5ab140e
20 changed files with 182 additions and 173 deletions

74
protocol/dhcpv4/dhcp.go Normal file
View File

@@ -0,0 +1,74 @@
package dhcpv4
import (
"git.darknebu.la/maride/pancap/output"
"github.com/google/gopacket"
"github.com/google/gopacket/layers"
)
type Protocol struct {
hostnames []hostname
networkSetup map[layers.DHCPOpt][]byte
requestMAC []string
responses []dhcpResponse
}
// Checks if the given packet is a DHCP packet we can process
func (p *Protocol) CanAnalyze(packet gopacket.Packet) bool {
return packet.Layer(layers.LayerTypeDHCPv4) != nil && packet.Layer(layers.LayerTypeEthernet) != nil && packet.Layers()[2].LayerPayload() != nil
}
// Analyzes the given DHCP packet
func (p *Protocol) Analyze(packet gopacket.Packet) error {
var dhcppacket layers.DHCPv4
var ethernetpacket layers.Ethernet
// Check if it's the first run - init networkSetup map then
if p.networkSetup == nil {
p.networkSetup = make(map[layers.DHCPOpt][]byte)
}
// For some reason I can't find an explanation for,
// packet.Layer(layers.LayerTypeDHCPv4).LayerContents(), which effectively is
// packet.Layers()[3].layerContents(), is empty, but
// packet.Layers()[2].layerPayload() contains the correct DHCP packet.
// ... although both calls should return the same bytes.
// TODO: Open an Issue on github.com/google/gopacket
// Decode raw packet into DHCPv4
decodeDHCPErr := dhcppacket.DecodeFromBytes(packet.Layers()[2].LayerPayload(), gopacket.NilDecodeFeedback)
if decodeDHCPErr != nil {
// Encountered an error during decoding, most likely a broken packet
return decodeDHCPErr
}
// And decode raw packet into Ethernet
decodeEthernetErr := ethernetpacket.DecodeFromBytes(packet.Layer(layers.LayerTypeEthernet).LayerContents(), gopacket.NilDecodeFeedback)
if decodeEthernetErr != nil {
// Encountered an error during decoding, most likely a broken packet
return decodeEthernetErr
}
// Examine packet further
if dhcppacket.Operation == layers.DHCPOpRequest {
// Request packet
p.processRequestPacket(dhcppacket)
} else {
// Response/Offer packet
p.processResponsePacket(dhcppacket, ethernetpacket)
}
// Check for Hostname DHCP option (12)
p.checkForHostname(dhcppacket)
p.checkForNetworkInfos(dhcppacket)
return nil
}
// Print summary after all packets are processed
func (p *Protocol) PrintSummary() {
output.PrintBlock("DHCP Network Overview", p.generateNetworkSummary())
output.PrintBlock("DHCP Requests", p.generateRequestSummary())
output.PrintBlock("DHCP Responses/Offers", p.generateResponseSummary())
output.PrintBlock("DHCP Hostnames", p.generateHostnamesSummary())
}

View File

@@ -0,0 +1,9 @@
package dhcpv4
type dhcpResponse struct {
destMACAddr string
newIPAddr string
serverMACAddr string
askedFor bool
}

View File

@@ -0,0 +1,8 @@
package dhcpv4
type hostname struct {
hostname string
requestedByMAC string
granted bool
deniedHostname string
}

View File

@@ -0,0 +1,114 @@
package dhcpv4
import (
"fmt"
"git.darknebu.la/maride/pancap/common"
"github.com/google/gopacket/layers"
"log"
)
func (p *Protocol) checkForHostname(dhcppacket layers.DHCPv4) {
// Search for "Hostname" option (ID 12) in DHCP Packet Options
for _, o := range dhcppacket.Options {
if o.Type == layers.DHCPOptHostname {
// found it. Let's see if it's a request or response
if dhcppacket.Operation == layers.DHCPOpRequest {
// request, not granted yet.
p.addHostname(hostname{
hostname: string(o.Data),
requestedByMAC: dhcppacket.ClientHWAddr.String(),
granted: false,
})
} else {
// Response, DHCP issued this hostname
p.addHostname(hostname{
hostname: string(o.Data),
requestedByMAC: "",
granted: true,
})
}
return
}
}
// None found, means client or server doesn't support Hostname option field. Ignore.
}
// Generates the list of all hostnames encountered.
func (p *Protocol) generateHostnamesSummary() string {
var tmparr []string
// Construct meaningful text
for _, h := range p.hostnames {
answer := ""
// check what kind of answer we need to construct
if h.deniedHostname == "" {
// Hostname was not denied, let's check if it was officially accepted
if h.granted {
// it was. Yay.
answer = fmt.Sprintf("%s has hostname %s, granted by the DHCP server", h.requestedByMAC, h.hostname)
} else {
// it was neither denied nor accepted, either missing the DHCP answer in capture file or misconfigured DHCP server
answer = fmt.Sprintf("%s has hostname %s, without a response from DHCP server", h.requestedByMAC, h.hostname)
}
} else {
// Hostname was denied, let's check if we captured the request
if h.hostname == "" {
// we didn't.
answer = fmt.Sprintf("%s was forced to have hostname %s by DHCP server,", h.requestedByMAC, h.hostname)
} else {
// we did, print desired and de-facto hostname
answer = fmt.Sprintf("%s asked for hostname %s, but got hostname %s from DHCP server.", h.requestedByMAC, h.deniedHostname, h.hostname)
}
}
tmparr = append(tmparr, answer)
}
// and print it as a tree.
return common.GenerateTree(tmparr)
}
// Adds the given hostname to the hostname array, or patches an existing entry if found
func (p *Protocol) addHostname(tmph hostname) {
// see if we have an existing entry for this hostname
for i := 0; i < len(p.hostnames); i++ {
// get ith hostname in the list
h := p.hostnames[i]
// ... and check if it's the one requested
if h.hostname == tmph.hostname {
// Found hostname, check different possible cases
if tmph.requestedByMAC != "" {
// Already got that hostname in the list, but received another request for it
if tmph.requestedByMAC == h.requestedByMAC {
// Same client asked for the same hostname - that's ok. Ignore.
} else {
// Different devices asked for the same hostname - log it.
log.Printf("Multiple clients (%s, %s) asked for the same hostname (%s)", h.requestedByMAC, tmph.requestedByMAC, h.hostname)
}
} else {
// Received a response for this hostname, check if it was granted
if h.hostname == tmph.hostname {
// granted, everything is fine.
p.hostnames[i].granted = true
} else {
// Received a different hostname than the one requested by the MAC. Report that.
log.Printf("Client %s asked for hostname '%s' but was given '%s' by DHCP server", h.requestedByMAC, tmph.hostname, h.hostname)
p.hostnames[i].deniedHostname = p.hostnames[i].hostname
p.hostnames[i].hostname = tmph.hostname
p.hostnames[i].granted = false
}
// in either case, it's a response by the DHCP server - hostname is granted in this context
}
return
}
}
// We didn't find the desired hostname, append given object to the list
p.hostnames = append(p.hostnames, tmph)
}

153
protocol/dhcpv4/network.go Normal file
View File

@@ -0,0 +1,153 @@
package dhcpv4
import (
"bytes"
"encoding/binary"
"fmt"
"github.com/fatih/color"
"github.com/google/gopacket/layers"
"log"
"net"
)
var (
watchedOpts = []layers.DHCPOpt{
layers.DHCPOptSubnetMask, // Option 1
layers.DHCPOptRouter, // Option 3
layers.DHCPOptDNS, // Option 6
layers.DHCPOptBroadcastAddr, // Option 28
layers.DHCPOptNTPServers, // Option 42
layers.DHCPOptLeaseTime, // Option 51
layers.DHCPOptT1, // Option 58
}
)
// Generates the summary of relevant DHCP options
func (p *Protocol) generateNetworkSummary() string {
// It's also possible to use strings.Builder here, but it produces code which is longer than this solution :shrug:
summary := fmt.Sprintf("Subnet Mask: %s\n", formatIP(p.networkSetup[layers.DHCPOptSubnetMask]))
summary = fmt.Sprintf("%sBroadcast: %s\n", summary, formatIP(p.networkSetup[layers.DHCPOptBroadcastAddr]))
summary = fmt.Sprintf("%sRouter: %s\n", summary, formatIP(p.networkSetup[layers.DHCPOptRouter]))
summary = fmt.Sprintf("%sDNS Server: %s\n", summary, formatIP(p.networkSetup[layers.DHCPOptDNS]))
summary = fmt.Sprintf("%sNTP Server: %s\n", summary, formatIP(p.networkSetup[layers.DHCPOptNTPServers]))
summary = fmt.Sprintf( "%sLease Time: %s\n", summary, formatDate(p.networkSetup[layers.DHCPOptLeaseTime]))
summary = fmt.Sprintf("%sRenewal Time: %s\n", summary, formatDate(p.networkSetup[layers.DHCPOptT1]))
return summary
}
// Looks for information specifying the setup of the network. This includes
// - Option 1: Subnet Mask
// - Option 3: Router address
// - Option 6: Domain Name Server address
// - Option 28: Broadcast address
// - Option 42: NTP Server address
// - Option 51: IP Address Lease time
// - Option 58: IP Renewal time
func (p *Protocol) checkForNetworkInfos(dhcppacket layers.DHCPv4) {
// Check if it is a DHCP request
if dhcppacket.Operation == layers.DHCPOpRequest {
// We can ignore requests, they won't help us here
return
}
// Search for different options (1, 3, 6, 28, 42, 51, 58) in DHCP Packet Options
for _, o := range dhcppacket.Options {
if isRelevantOption(o) {
// Found DHCP option to be watched, let's watch it
p.saveOption(o)
}
}
}
// Saves the given option in the networkSetup map, and informs the user if the value changes
func (p *Protocol) saveOption(opt layers.DHCPOption) {
// check if we already stored this value
if p.networkSetup[opt.Type] != nil {
// We already stored a value, let's check if it's the same as the new one
if !bytes.Equal(p.networkSetup[opt.Type], opt.Data) {
// Already stored a value and it's different from our new value - inform user and overwrite value later
log.Printf("Received different values for DHCP Option %s (ID %d). (Old: %s, New. %s)", opt.Type.String(), opt.Type, p.networkSetup[opt.Type], opt.Data)
} else {
// Exactly this value was already stored, no need to overwrite it
return
}
}
p.networkSetup[opt.Type] = opt.Data
}
// Checks if the given DHCPOption is part of the watchlist
func isRelevantOption(opt layers.DHCPOption) bool {
// Iterate over all DHCP options in our watchlist
for _, o := range watchedOpts {
if o == opt.Type {
// Found.
return true
}
}
// This option is not on our watchlist.
return false
}
// Formats the given byte array as string representing the IP address, or returns an error (as string)
func formatIP(rawIP []byte) string {
// Check if we even have an IP
if rawIP == nil {
// We don't have an IP, construct an error message (as string)
error := color.New(color.FgRed)
return error.Sprint("(not found)")
}
// Return formatted IP
return net.IP(rawIP).String()
}
func formatDate(rawDate []byte) string {
// Check if we even have a date
if rawDate == nil {
// We don't have a date, construct an error message (as string)
error := color.New(color.FgRed)
return error.Sprint("(not found)")
}
// Actually format date
intDate := binary.LittleEndian.Uint32(rawDate)
seconds := intDate % 60
minutes := intDate / 60 % 60
hours := intDate / 60 / 60 % 60
formattedDate := ""
// Check which words we need to pick
// ... regarding hours
if hours > 0 {
formattedDate = fmt.Sprintf("%d hours", hours)
}
// ... regarding minutes
if minutes > 0 {
// check if we got a previous string we need to take care of
if len(formattedDate) > 0 {
// yes, append our information to existing string
formattedDate = fmt.Sprintf("%s, %d minutes", formattedDate, minutes)
} else {
// no, use our string
formattedDate = fmt.Sprintf("%d minutes", minutes)
}
}
// ... regarding seconds
if seconds > 0 {
// check if we got a previous string we need to take care of
if len(formattedDate) > 0 {
// yes, append our information to existing string
formattedDate = fmt.Sprintf("%s, %d seconds", formattedDate, seconds)
} else {
// no, use our string
formattedDate = fmt.Sprintf("%d seconds", seconds)
}
}
return formattedDate
}

View File

@@ -0,0 +1,17 @@
package dhcpv4
import (
"fmt"
"git.darknebu.la/maride/pancap/common"
"github.com/google/gopacket/layers"
)
// Processes the DHCP request packet handed over
func (p *Protocol) processRequestPacket(dhcppacket layers.DHCPv4) {
p.requestMAC = common.AppendIfUnique(dhcppacket.ClientHWAddr.String(), p.requestMAC)
}
// Generates the summary of all DHCP request packets
func (p *Protocol) generateRequestSummary() string {
return fmt.Sprintf("%d unique DHCP requests\n%s", len(p.requestMAC), common.GenerateTree(p.requestMAC))
}

View File

@@ -0,0 +1,76 @@
package dhcpv4
import (
"fmt"
"git.darknebu.la/maride/pancap/common"
"github.com/google/gopacket/layers"
"log"
)
func (p *Protocol) processResponsePacket(dhcppacket layers.DHCPv4, ethernetpacket layers.Ethernet) {
p.addResponseEntry(dhcppacket.ClientIP.String(), dhcppacket.YourClientIP.String(), dhcppacket.ClientHWAddr.String(), ethernetpacket.SrcMAC.String())
}
// Generates the summary of all DHCP offer packets
func (p *Protocol) generateResponseSummary() string {
var tmpaddr []string
// Iterate over all responses
for _, r := range p.responses {
addition := ""
if r.askedFor {
addition = " which the client explicitly asked for."
}
tmpaddr = append(tmpaddr, fmt.Sprintf("%s offered %s IP address %s%s", r.serverMACAddr, r.destMACAddr, r.newIPAddr, addition))
}
// Draw as tree
return common.GenerateTree(tmpaddr)
}
// Adds a new response entry. If an IP address was already issued or a MAC asks multiple times for DNS, the case is examined further
func (p *Protocol) addResponseEntry(newIP string, yourIP string, destMAC string, serverMAC string) {
// Check if client asked for a specific address (which was granted by the DHCP server)
askedFor := false
if newIP == "0.0.0.0" {
// Yes, client asked for a specific address. Most likely not the first time in this network.
newIP = yourIP
askedFor = true
}
for _, r := range p.responses {
// Check for interesting cases
if r.destMACAddr == destMAC {
// The same client device received multiple IP addresses, let's examine further
if r.newIPAddr == newIP {
// the handed IP is the same - this is ok, just badly configured
if r.serverMACAddr == serverMAC {
// Same DHCP server answered.
log.Printf("MAC address %s received the same IP address multiple times via DHCP by the same server.", destMAC)
} else {
// Different DHCP servers answered, but with the same address - strange network, but ok...
log.Printf("MAC address %s received the same IP address multiple times via DHCP by different servers.", destMAC)
}
} else {
// far more interesting - one client received multiple addresses
if r.serverMACAddr == serverMAC {
// Same DHCP server answered.
log.Printf("MAC address %s received different IP addresses (%s, %s) multiple times via DHCP by the same server.", destMAC, r.newIPAddr, newIP)
} else {
// Different DHCP servers answered, with different addresses - possibly an attempt to build up MitM
log.Printf("MAC address %s received different IP addresses (%s, %s) multiple times via DHCP by different servers (%s, %s).", destMAC, r.newIPAddr, newIP, r.serverMACAddr, serverMAC)
}
}
}
}
// Add a response entry - even if we found some "strange" behavior before.
p.responses = append(p.responses, dhcpResponse{
destMACAddr: destMAC,
newIPAddr: newIP,
serverMACAddr: serverMAC,
askedFor: askedFor,
})
}