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

152
protocol/arp/arp.go Normal file
View File

@@ -0,0 +1,152 @@
package arp
import (
"fmt"
"git.darknebu.la/maride/pancap/common"
"git.darknebu.la/maride/pancap/output"
"github.com/google/gopacket"
"github.com/google/gopacket/layers"
"log"
"net"
)
var (
arpStatsList []arpStats
devices []arpDevice
)
type Protocol struct {}
// Checks if the given packet is an ARP packet we can process
func (p *Protocol) CanAnalyze(packet gopacket.Packet) bool {
return packet.Layer(layers.LayerTypeARP) != nil
}
// Analyzes the given ARP packet
func (p *Protocol) Analyze(packet gopacket.Packet) error {
var arppacket layers.ARP
// Decode raw packet into ARP
decodeErr := arppacket.DecodeFromBytes(packet.Layer(layers.LayerTypeARP).LayerContents(), gopacket.NilDecodeFeedback)
if decodeErr != nil {
// Encountered an error during decoding, most likely a broken packet
return decodeErr
}
// Convert MAC address byte array to string
sourceAddr := net.HardwareAddr(arppacket.SourceHwAddress).String()
participant := p.getStatOrCreate(sourceAddr)
// Raise stats
if arppacket.Operation == layers.ARPRequest {
// Request packet
participant.asked++
participant.askedList = common.AppendIfUnique(net.IP(arppacket.DstProtAddress).String(), participant.askedList)
// Add device entry
p.addDeviceEntry(sourceAddr, net.IP(arppacket.SourceProtAddress).String())
} else {
// Response packet
participant.answered++
participant.answeredList = common.AppendIfUnique(net.IP(arppacket.SourceProtAddress).String(), participant.answeredList)
// Add device entry
p.addDeviceEntry(sourceAddr, net.IP(arppacket.SourceProtAddress).String())
}
return nil
}
// Print a summary after all packets are processed
func (p *Protocol) PrintSummary() {
output.PrintBlock("ARP traffic summary", p.generateTrafficStats())
output.PrintBlock("ARP LAN overview", p.generateLANOverview())
}
// Generates an answer regarding the ARP traffic
func (p *Protocol) generateTrafficStats() string {
var tmparr []string
// Iterate over all participants
for _, p := range arpStatsList {
// produce a meaningful output
if p.asked > 0 {
// device asked at least for one IP
if p.answered > 0 {
// and also answered requests
tmparr = append(tmparr, fmt.Sprintf("%s asked for %d addresses and answered %d requests", p.macaddr, p.asked, p.answered))
} else {
// only asked, never answered
tmparr = append(tmparr, fmt.Sprintf("%s asked for %d addresses", p.macaddr, p.asked))
}
} else {
// Answered, but never asked for any addresses
tmparr = append(tmparr, fmt.Sprintf("%s answered %d requests", p.macaddr, p.answered))
}
}
// And print it as a tree
return common.GenerateTree(tmparr)
}
// Generates an overview over all connected devices in the LAN
func (p *Protocol) generateLANOverview() string {
var tmparr []string
// iterate over all devices
for _, d := range devices {
tmparr = append(tmparr, fmt.Sprintf("%s got address %s", d.macaddr, d.ipaddr))
}
// And print it as a tree
return common.GenerateTree(tmparr)
}
// Returns the arpStats object for the given MAC address, or creates a new one
func (p *Protocol) getStatOrCreate(macaddr string) *arpStats {
// Try to find the given macaddr
for i := 0; i < len(arpStatsList); i++ {
if arpStatsList[i].macaddr == macaddr {
// Found, return it
return &arpStatsList[i]
}
}
// None found yet, we need to create a new one
arpStatsList = append(arpStatsList, arpStats{
macaddr: macaddr,
})
// And return it
return &arpStatsList[len(arpStatsList)-1]
}
// Adds a new entry to the devices array, checking if there may be a collision (=ARP Spoofing)
func (p *Protocol) addDeviceEntry(macaddr string, ipaddr string) {
if ipaddr == "0.0.0.0" {
// Possible ARP request if sender doesn't have an IP address yet. Ignore.
return
}
for i := 0; i < len(devices); i++ {
// check if we found a collision (possible ARP spoofing)
if (devices[i].macaddr == macaddr) != (devices[i].ipaddr == ipaddr) {
// this operation is practically XOR (which golang doesn't provide e.g. with ^)
log.Printf("Found possible ARP spoofing! Old: (MAC=%s, IP=%s), New: (MAC=%s, IP=%s). Overriding...", devices[i].macaddr, devices[i].ipaddr, macaddr, ipaddr)
devices[i].macaddr = macaddr
devices[i].ipaddr = ipaddr
return
}
if devices[i].macaddr == macaddr && devices[i].ipaddr == ipaddr {
// Found collision, but no ARP spoofing (both values are identical)
return
}
}
// No device found, add a new entry
devices = append(devices, arpDevice{
macaddr: macaddr,
ipaddr: ipaddr,
})
}

View File

@@ -0,0 +1,6 @@
package arp
type arpDevice struct {
macaddr string
ipaddr string
}

9
protocol/arp/arpStats.go Normal file
View File

@@ -0,0 +1,9 @@
package arp
type arpStats struct {
macaddr string
asked int
answered int
askedList []string
answeredList []string
}

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,
})
}

92
protocol/dns/answer.go Normal file
View File

@@ -0,0 +1,92 @@
package dns
import (
"fmt"
"git.darknebu.la/maride/pancap/common"
"github.com/google/gopacket/layers"
"golang.org/x/net/publicsuffix"
"log"
)
var (
numAnswers int
answerDomains []string
answerBaseDomains []string
answerPrivateDomains []string
answerType = make(map[layers.DNSType]int)
answerPublicIPv4 []string
answerPrivateIPv4 []string
)
// Called on every DNS packet to process response(s)
func (p *Protocol) processDNSAnswer(answers []layers.DNSResourceRecord) {
for _, answer := range answers {
// Raise stats
numAnswers++
// Add answer to answers array
name := string(answer.Name)
basename, basenameErr := publicsuffix.EffectiveTLDPlusOne(name)
if basenameErr != nil {
// Encountered error while checking for the basename
log.Printf("Encountered error while checking '%s' domain for its basename: %s", name, basenameErr.Error())
continue
}
// Process type answers
p.processType(answerType, answer.Type)
// Append full domain and base domain
answerDomains = common.AppendIfUnique(name, answerDomains)
// Check if we need to add the base name to the private list
_, icannManaged := publicsuffix.PublicSuffix(name)
if icannManaged {
// TLD is managed by ICANN, add to the base list
answerBaseDomains = common.AppendIfUnique(basename, answerBaseDomains)
} else {
// it's not managed by ICANN, so it's private - add it to the private list
answerPrivateDomains = common.AppendIfUnique(name, answerPrivateDomains)
}
// Check if we got an A record answer
if answer.Type == layers.DNSTypeA {
// A record, check IP for being private
if ipIsPrivate(answer.IP) {
answerPrivateIPv4 = common.AppendIfUnique(answer.IP.String(), answerPrivateIPv4)
} else {
answerPublicIPv4 = common.AppendIfUnique(answer.IP.String(), answerPublicIPv4)
}
}
}
}
// Generates a summary of all DNS answers
func (p *Protocol) generateDNSAnswerSummary() string {
summary := ""
// Overall question stats
summary = fmt.Sprintf("%s%d DNS answers in total\n", summary, numAnswers)
summary = fmt.Sprintf("%s%s records\n", summary, p.generateDNSTypeSummary(answerType))
summary = fmt.Sprintf("%s%d unique domains of %d base domains, of which are %d private (non-ICANN) TLDs.\n", summary, len(answerDomains), len(answerBaseDomains), len(answerPrivateDomains))
// Output base domains answered with
if len(answerBaseDomains) > 0 {
summary = fmt.Sprintf("Answered with these base domains:\n%s", common.GenerateTree(answerBaseDomains))
}
// Output private domains
if len(answerPrivateDomains) > 0 {
summary = fmt.Sprintf("%sAnswered with these private (non-ICANN managed) domains:\n%s", summary, common.GenerateTree(answerPrivateDomains))
}
// Check for public and private IPs
summary = fmt.Sprintf("%sAnswered with %d public IP addresses and %d private IP addresses\n", summary, len(answerPublicIPv4), len(answerPrivateIPv4))
if len(answerPrivateIPv4) > 0 {
summary = fmt.Sprintf("%sPrivate IP addresses in answer:\n%s", summary, common.GenerateTree(answerPrivateIPv4))
}
// Return summary
return summary
}

71
protocol/dns/common.go Normal file
View File

@@ -0,0 +1,71 @@
package dns
import (
"fmt"
"github.com/google/gopacket/layers"
"net"
)
var (
privateBlocks = []net.IPNet{
{net.IPv4(10, 0, 0, 0), net.IPv4Mask(255, 0, 0, 0)}, // 10.0.0.0/8
{net.IPv4(172, 16, 0, 0), net.IPv4Mask(255, 240, 0, 0)}, // 172.16.0.0/12
{net.IPv4(192, 168, 0, 0), net.IPv4Mask(255, 255, 0, 0)}, // 192.168.0.0/24
{net.IPv4(100, 64, 0, 0), net.IPv4Mask(255, 192, 0, 0)}, // 100.64.0.0/10
{net.IPv4(169, 254, 0, 0), net.IPv4Mask(255, 255, 0, 0)}, // 169.254.0.0/16
}
)
// Processes the given dnstype and raises its stats in the given array
func (p *Protocol) processType(typearr map[layers.DNSType]int, dnstype layers.DNSType) {
typearr[dnstype]++
}
// Checks if the given IP is in a private range or not
func ipIsPrivate(ip net.IP) bool {
// check every private IP block for our IP
for _, block := range privateBlocks {
if block.Contains(ip) {
// found, is a private IP
return true
}
}
// Not in any of the private blocks, not private
return false
}
// Generates a summary string for DNS types in the given array
func (p *Protocol) generateDNSTypeSummary(typearr map[layers.DNSType]int) string {
var answerarr []string
// Iterate over all possible DNS types
for iter, typeelem := range typearr {
// Read amount of type hits for this type
answerarr = append(answerarr, fmt.Sprintf("%d %s", typeelem, iter.String()))
}
// Check if we even processed a single type
if len(answerarr) == 0 {
// we didn't, strange.
return "(no types encountered)"
}
// now, glue all array elements together
answerstr := ""
for iter, elem := range answerarr {
// Check if we need to apply to proper sentence rules
if iter == 0 {
// We don't need to append yet
answerstr = elem
} else if iter == len(answerarr) - 1 {
// Last element, use "and" instead of a comma
answerstr = fmt.Sprintf("%s and %s", answerstr, elem)
} else {
// Some entry, just add it with a comma
answerstr = fmt.Sprintf("%s, %s", answerstr, elem)
}
}
return answerstr
}

38
protocol/dns/dns.go Normal file
View File

@@ -0,0 +1,38 @@
package dns
import (
"git.darknebu.la/maride/pancap/output"
"github.com/google/gopacket"
"github.com/google/gopacket/layers"
)
type Protocol struct {}
func (p *Protocol) CanAnalyze(packet gopacket.Packet) bool {
return packet.Layer(layers.LayerTypeDNS) != nil
}
// Analyzes the given DHCP packet
func (p *Protocol) Analyze(packet gopacket.Packet) error {
var dnspacket layers.DNS
// Decode raw packet into DNS
decodeErr := dnspacket.DecodeFromBytes(packet.ApplicationLayer().LayerContents(), gopacket.NilDecodeFeedback)
if decodeErr != nil {
// Encountered an error during decoding, most likely a broken packet
return decodeErr
}
// Further process the packet
p.processDNSQuestion(dnspacket.Questions)
p.processDNSAnswer(dnspacket.Answers)
// No error encountered, return clean
return nil
}
// Print a summary after all DNS packets were processed
func (p *Protocol) PrintSummary() {
output.PrintBlock("DNS Request Summary", p.generateDNSQuestionSummary())
output.PrintBlock("DNS Response Summary", p.generateDNSAnswerSummary())
}

75
protocol/dns/question.go Normal file
View File

@@ -0,0 +1,75 @@
package dns
import (
"fmt"
"git.darknebu.la/maride/pancap/common"
"github.com/google/gopacket/layers"
"golang.org/x/net/publicsuffix"
"log"
)
var (
numQuestions int
questionDomains []string
questionBaseDomains []string
questionPrivateDomains []string
questionType = make(map[layers.DNSType]int)
)
// Called on every DNS packet to process questions
func (p *Protocol) processDNSQuestion(questions []layers.DNSQuestion) {
// Iterate over all questions
for _, question := range questions {
// Raise stats
numQuestions++
// Add question to questions array
name := string(question.Name)
basename, basenameErr := publicsuffix.EffectiveTLDPlusOne(name)
if basenameErr != nil {
// Encountered error while checking for the basename
log.Printf("Encountered error while checking '%s' domain for its basename: %s", name, basenameErr.Error())
continue
}
// Process type questions
p.processType(questionType, question.Type)
// Append full domain and base domain
questionDomains = common.AppendIfUnique(name, questionDomains)
// Check if we need to add the base name to the private list
_, icannManaged := publicsuffix.PublicSuffix(name)
if icannManaged {
// TLD is managed by ICANN, add to the base list
questionBaseDomains = common.AppendIfUnique(basename, questionBaseDomains)
} else {
// it's not managed by ICANN, so it's private - add it to the private list
questionPrivateDomains = common.AppendIfUnique(name, questionPrivateDomains)
}
}
}
// Generates a summary of all DNS questions
func (p *Protocol) generateDNSQuestionSummary() string {
summary := ""
// Overall question stats
summary = fmt.Sprintf("%s%d DNS questions in total\n", summary, numQuestions)
summary = fmt.Sprintf("%s%s records\n", summary, p.generateDNSTypeSummary(questionType))
summary = fmt.Sprintf("%s%d unique domains of %d base domains, of which are %d private (non-ICANN) TLDs.\n", summary, len(questionDomains), len(questionBaseDomains), len(questionPrivateDomains))
// Output base domains asked for
if len(questionBaseDomains) > 0 {
summary = fmt.Sprintf("%sAsked for these base domains:\n%s", summary, common.GenerateTree(questionBaseDomains))
}
// Output private domains
if len(questionPrivateDomains) > 0 {
summary = fmt.Sprintf("%sAsked for these private (non-ICANN managed) domains:\n%s", summary, common.GenerateTree(questionPrivateDomains))
}
// And return summary
return summary
}

15
protocol/index.go Normal file
View File

@@ -0,0 +1,15 @@
package protocol
import (
"git.darknebu.la/maride/pancap/protocol/arp"
"git.darknebu.la/maride/pancap/protocol/dhcpv4"
"git.darknebu.la/maride/pancap/protocol/dns"
)
var (
Protocols = []Protocol{
&arp.Protocol{},
&dhcpv4.Protocol{},
&dns.Protocol{},
}
)

9
protocol/protocol.go Normal file
View File

@@ -0,0 +1,9 @@
package protocol
import "github.com/google/gopacket"
type Protocol interface {
CanAnalyze(gopacket.Packet) bool
Analyze(gopacket.Packet) error
PrintSummary()
}