Rework Communication+Link to Connection

This commit is contained in:
Daniel
2020-04-07 17:30:33 +02:00
parent eec0c37101
commit 38f57a8954
21 changed files with 862 additions and 1741 deletions

View File

@@ -33,11 +33,11 @@ func startAPIAuth() {
var err error
_, apiPort, err = parseHostPort(apiListenAddress())
if err != nil {
log.Warningf("firewall: failed to parse API address for improved api auth mechanism: %s", err)
log.Warningf("filter: failed to parse API address for improved api auth mechanism: %s", err)
return
}
apiPortSet = true
log.Tracef("firewall: api port set to %d", apiPort)
log.Tracef("filter: api port set to %d", apiPort)
}
func apiAuthenticator(s *http.Server, r *http.Request) (grantAccess bool, err error) {
@@ -83,7 +83,7 @@ func apiAuthenticator(s *http.Server, r *http.Request) (grantAccess bool, err er
}
}
log.Debugf("firewall: denying api access to %s - also checked %s (trusted root is %s)", procsChecked[0], strings.Join(procsChecked[1:], " "), dataRoot.Path)
log.Debugf("filter: denying api access to %s - also checked %s (trusted root is %s)", procsChecked[0], strings.Join(procsChecked[1:], " "), dataRoot.Path)
return false, nil
}

View File

@@ -2,7 +2,7 @@ package firewall
import (
"context"
"fmt"
"net"
"os"
"sync/atomic"
"time"
@@ -34,7 +34,7 @@ var (
// localNet4 *net.IPNet
// localhost4 = net.IPv4(127, 0, 0, 1)
localhost4 = net.IPv4(127, 0, 0, 1)
// localhost6 = net.IPv6loopback
// tunnelNet4 *net.IPNet
@@ -61,6 +61,8 @@ func init() {
DefaultValue: true,
},
)
network.SetDefaultFirewallHandler(defaultHandler)
}
func prep() (err error) {
@@ -78,16 +80,16 @@ func prep() (err error) {
// // Yes, this would normally be 127.0.0.0/8
// // TODO: figure out any side effects
// if err != nil {
// return fmt.Errorf("firewall: failed to parse cidr 127.0.0.0/24: %s", err)
// return fmt.Errorf("filter: failed to parse cidr 127.0.0.0/24: %s", err)
// }
// _, tunnelNet4, err = net.ParseCIDR("127.17.0.0/16")
// if err != nil {
// return fmt.Errorf("firewall: failed to parse cidr 127.17.0.0/16: %s", err)
// return fmt.Errorf("filter: failed to parse cidr 127.17.0.0/16: %s", err)
// }
// _, tunnelNet6, err = net.ParseCIDR("fd17::/64")
// if err != nil {
// return fmt.Errorf("firewall: failed to parse cidr fd17::/64: %s", err)
// return fmt.Errorf("filter: failed to parse cidr fd17::/64: %s", err)
// }
var pA uint64
@@ -135,7 +137,10 @@ func handlePacket(pkt packet.Packet) {
// }
// allow local dns
if (pkt.Info().DstPort == 53 || pkt.Info().SrcPort == 53) && pkt.Info().Src.Equal(pkt.Info().Dst) {
if (pkt.Info().DstPort == 53 || pkt.Info().SrcPort == 53) &&
(pkt.Info().Src.Equal(pkt.Info().Dst) || // Windows redirects back to same interface
pkt.Info().Src.Equal(localhost4) || // Linux sometimes does 127.0.0.1->127.0.0.53
pkt.Info().Dst.Equal(localhost4)) {
log.Debugf("accepting local dns: %s", pkt)
_ = pkt.PermanentAccept()
return
@@ -180,11 +185,11 @@ func handlePacket(pkt packet.Packet) {
// TODO: Howto handle NetBios?
}
// log.Debugf("firewall: pkt %s has ID %s", pkt, pkt.GetLinkID())
// log.Debugf("filter: pkt %s has ID %s", pkt, pkt.GetLinkID())
// use this to time how long it takes process packet
// timed := time.Now()
// defer log.Tracef("firewall: took %s to process packet %s", time.Now().Sub(timed).String(), pkt)
// defer log.Tracef("filter: took %s to process packet %s", time.Now().Sub(timed).String(), pkt)
// check if packet is destined for tunnel
// switch pkt.IPVersion() {
@@ -201,156 +206,110 @@ func handlePacket(pkt packet.Packet) {
traceCtx, tracer := log.AddTracer(context.Background())
if tracer != nil {
pkt.SetCtx(traceCtx)
tracer.Tracef("firewall: handling packet: %s", pkt)
tracer.Tracef("filter: handling packet: %s", pkt)
}
// associate packet to link and handle
link, created := network.GetOrCreateLinkByPacket(pkt)
if created {
link.SetFirewallHandler(initialHandler)
conn, ok := network.GetConnection(pkt.GetConnectionID())
if ok {
tracer.Tracef("filter: assigned to connection %s", conn.ID)
} else {
conn = network.NewConnectionFromFirstPacket(pkt)
tracer.Tracef("filter: created new connection %s", conn.ID)
conn.SetFirewallHandler(initialHandler)
}
link.HandlePacket(pkt)
// handle packet
conn.HandlePacket(pkt)
}
func initialHandler(pkt packet.Packet, link *network.Link) {
defer func() {
go link.SaveIfNeeded()
}()
log.Tracer(pkt.Ctx()).Trace("firewall: [initial handler]")
func initialHandler(conn *network.Connection, pkt packet.Packet) {
log.Tracer(pkt.Ctx()).Trace("filter: [initial handler]")
// check for internal firewall bypass
ps := getPortStatusAndMarkUsed(pkt.Info().LocalPort())
if ps.isMe {
// connect to comms
comm, err := network.GetOwnComm(pkt)
if err != nil {
// log.Warningf("firewall: could not get own comm: %s", err)
log.Tracer(pkt.Ctx()).Warningf("firewall: could not get own comm: %s", err)
} else {
comm.AddLink(link)
}
// approve
link.Accept("internally approved")
log.Tracer(pkt.Ctx()).Tracef("firewall: internally approved link (via local port %d)", pkt.Info().LocalPort())
conn.Accept("internally approved")
// finish
link.StopFirewallHandler()
issueVerdict(pkt, link, 0, true)
conn.StopFirewallHandler()
issueVerdict(conn, pkt, 0, true)
return
}
// get Communication
comm, err := network.GetCommunicationByFirstPacket(pkt)
if err != nil {
log.Tracer(pkt.Ctx()).Warningf("firewall: could not get process, denying link: %s", err)
// get "unknown" comm
link.Deny(fmt.Sprintf("could not get process: %s", err))
comm, err = network.GetUnknownCommunication(pkt)
if err != nil {
// all failed
log.Tracer(pkt.Ctx()).Errorf("firewall: could not get unknown comm: %s", err)
link.UpdateVerdict(network.VerdictDrop)
link.StopFirewallHandler()
issueVerdict(pkt, link, 0, true)
return
}
}
// add new Link to Communication (and save both)
comm.AddLink(link)
log.Tracer(pkt.Ctx()).Tracef("firewall: link attached to %s", comm)
// reroute dns requests to nameserver
if comm.Process().Pid != os.Getpid() && pkt.IsOutbound() && pkt.Info().DstPort == 53 && !pkt.Info().Src.Equal(pkt.Info().Dst) {
link.UpdateVerdict(network.VerdictRerouteToNameserver)
link.StopFirewallHandler()
issueVerdict(pkt, link, 0, true)
if conn.Process().Pid != os.Getpid() && pkt.IsOutbound() && pkt.Info().DstPort == 53 && !pkt.Info().Src.Equal(pkt.Info().Dst) {
conn.Verdict = network.VerdictRerouteToNameserver
conn.StopFirewallHandler()
issueVerdict(conn, pkt, 0, true)
return
}
log.Tracer(pkt.Ctx()).Trace("firewall: starting decision process")
// TODO: filter lists may have IPs in the future!
DecideOnCommunication(comm)
DecideOnLink(comm, link, pkt)
// TODO: link this to real status
// gate17Active := mode.Client()
log.Tracer(pkt.Ctx()).Trace("filter: starting decision process")
DecideOnConnection(conn, pkt)
conn.Inspecting = false // TODO: enable inspecting again
switch {
// case gate17Active && link.Inspect:
// // tunnel link, but also inspect (after reroute)
// link.Tunneled = true
// link.SetFirewallHandler(inspectThenVerdict)
// verdict(pkt, link.GetVerdict())
// case gate17Active:
// // tunnel link, don't inspect
// link.Tunneled = true
// link.StopFirewallHandler()
// permanentVerdict(pkt, network.VerdictAccept)
case link.Inspect:
log.Tracer(pkt.Ctx()).Trace("firewall: start inspecting")
link.SetFirewallHandler(inspectThenVerdict)
inspectThenVerdict(pkt, link)
case conn.Inspecting:
log.Tracer(pkt.Ctx()).Trace("filter: start inspecting")
conn.SetFirewallHandler(inspectThenVerdict)
inspectThenVerdict(conn, pkt)
default:
link.StopFirewallHandler()
issueVerdict(pkt, link, 0, true)
conn.StopFirewallHandler()
issueVerdict(conn, pkt, 0, true)
}
}
func inspectThenVerdict(pkt packet.Packet, link *network.Link) {
pktVerdict, continueInspection := inspection.RunInspectors(pkt, link)
func defaultHandler(conn *network.Connection, pkt packet.Packet) {
issueVerdict(conn, pkt, 0, true)
}
func inspectThenVerdict(conn *network.Connection, pkt packet.Packet) {
pktVerdict, continueInspection := inspection.RunInspectors(conn, pkt)
if continueInspection {
issueVerdict(pkt, link, pktVerdict, false)
issueVerdict(conn, pkt, pktVerdict, false)
return
}
// we are done with inspecting
link.StopFirewallHandler()
issueVerdict(pkt, link, 0, true)
conn.StopFirewallHandler()
issueVerdict(conn, pkt, 0, true)
}
func issueVerdict(pkt packet.Packet, link *network.Link, verdict network.Verdict, allowPermanent bool) {
link.Lock()
func issueVerdict(conn *network.Connection, pkt packet.Packet, verdict network.Verdict, allowPermanent bool) {
// enable permanent verdict
if allowPermanent && !link.VerdictPermanent {
link.VerdictPermanent = permanentVerdicts()
if link.VerdictPermanent {
link.SaveWhenFinished()
if allowPermanent && !conn.VerdictPermanent {
conn.VerdictPermanent = permanentVerdicts()
if conn.VerdictPermanent {
conn.SaveWhenFinished()
}
}
// do not allow to circumvent link decision: e.g. to ACCEPT packets from a DROP-ed link
if verdict < link.Verdict {
verdict = link.Verdict
// do not allow to circumvent decision: e.g. to ACCEPT packets from a DROP-ed connection
if verdict < conn.Verdict {
verdict = conn.Verdict
}
var err error
switch verdict {
case network.VerdictAccept:
atomic.AddUint64(packetsAccepted, 1)
if link.VerdictPermanent {
if conn.VerdictPermanent {
err = pkt.PermanentAccept()
} else {
err = pkt.Accept()
}
case network.VerdictBlock:
atomic.AddUint64(packetsBlocked, 1)
if link.VerdictPermanent {
if conn.VerdictPermanent {
err = pkt.PermanentBlock()
} else {
err = pkt.Block()
}
case network.VerdictDrop:
atomic.AddUint64(packetsDropped, 1)
if link.VerdictPermanent {
if conn.VerdictPermanent {
err = pkt.PermanentDrop()
} else {
err = pkt.Drop()
@@ -364,13 +323,9 @@ func issueVerdict(pkt packet.Packet, link *network.Link, verdict network.Verdict
err = pkt.Drop()
}
link.Unlock()
if err != nil {
log.Warningf("firewall: failed to apply verdict to pkt %s: %s", pkt, err)
log.Warningf("filter: failed to apply verdict to pkt %s: %s", pkt, err)
}
log.Tracer(pkt.Ctx()).Infof("firewall: %s %s", link.Verdict, link)
}
// func tunnelHandler(pkt packet.Packet) {
@@ -381,7 +336,7 @@ func issueVerdict(pkt packet.Packet, link *network.Link, verdict network.Verdict
// }
//
// entry.CreateTunnel(pkt, tunnelInfo.Domain, tunnelInfo.RRCache.ExportAllARecords())
// log.Tracef("firewall: rerouting %s to tunnel entry point", pkt)
// log.Tracef("filter: rerouting %s to tunnel entry point", pkt)
// pkt.RerouteToTunnel()
// return
// }
@@ -403,7 +358,7 @@ func statLogger() {
case <-module.Stopping():
return
case <-time.After(10 * time.Second):
log.Tracef("firewall: packets accepted %d, blocked %d, dropped %d", atomic.LoadUint64(packetsAccepted), atomic.LoadUint64(packetsBlocked), atomic.LoadUint64(packetsDropped))
log.Tracef("filter: packets accepted %d, blocked %d, dropped %d", atomic.LoadUint64(packetsAccepted), atomic.LoadUint64(packetsBlocked), atomic.LoadUint64(packetsDropped))
atomic.StoreUint64(packetsAccepted, 0)
atomic.StoreUint64(packetsBlocked, 0)
atomic.StoreUint64(packetsDropped, 0)

View File

@@ -12,12 +12,12 @@ const (
DO_NOTHING uint8 = iota
BLOCK_PACKET
DROP_PACKET
BLOCK_LINK
DROP_LINK
BLOCK_CONN
DROP_CONN
STOP_INSPECTING
)
type inspectorFn func(packet.Packet, *network.Link) uint8
type inspectorFn func(*network.Connection, packet.Packet) uint8
var (
inspectors []inspectorFn
@@ -38,20 +38,20 @@ func RegisterInspector(name string, inspector inspectorFn, inspectVerdict networ
}
// RunInspectors runs all the applicable inspectors on the given packet.
func RunInspectors(pkt packet.Packet, link *network.Link) (network.Verdict, bool) {
func RunInspectors(conn *network.Connection, pkt packet.Packet) (network.Verdict, bool) {
// inspectorsLock.Lock()
// defer inspectorsLock.Unlock()
activeInspectors := link.GetActiveInspectors()
activeInspectors := conn.GetActiveInspectors()
if activeInspectors == nil {
activeInspectors = make([]bool, len(inspectors))
link.SetActiveInspectors(activeInspectors)
conn.SetActiveInspectors(activeInspectors)
}
inspectorData := link.GetInspectorData()
inspectorData := conn.GetInspectorData()
if inspectorData == nil {
inspectorData = make(map[uint8]interface{})
link.SetInspectorData(inspectorData)
conn.SetInspectorData(inspectorData)
}
continueInspection := false
@@ -62,12 +62,12 @@ func RunInspectors(pkt packet.Packet, link *network.Link) (network.Verdict, bool
if skip {
continue
}
if link.Verdict > inspectVerdicts[key] {
if conn.Verdict > inspectVerdicts[key] {
activeInspectors[key] = true
continue
}
action := inspectors[key](pkt, link) // Actually run inspector
action := inspectors[key](conn, pkt) // Actually run inspector
switch action {
case DO_NOTHING:
if verdict < network.VerdictAccept {
@@ -82,16 +82,14 @@ func RunInspectors(pkt packet.Packet, link *network.Link) (network.Verdict, bool
case DROP_PACKET:
verdict = network.VerdictDrop
continueInspection = true
case BLOCK_LINK:
link.UpdateVerdict(network.VerdictBlock)
case BLOCK_CONN:
conn.SetVerdict(network.VerdictBlock)
verdict = conn.Verdict
activeInspectors[key] = true
if verdict < network.VerdictBlock {
verdict = network.VerdictBlock
}
case DROP_LINK:
link.UpdateVerdict(network.VerdictDrop)
case DROP_CONN:
conn.SetVerdict(network.VerdictDrop)
verdict = conn.Verdict
activeInspectors[key] = true
verdict = network.VerdictDrop
case STOP_INSPECTING:
activeInspectors[key] = true
}

View File

@@ -51,7 +51,7 @@ func (pkt *Packet) setVerdict(v uint32) (err error) {
}()
pkt.verdict <- v
close(pkt.verdict)
// log.Tracef("firewall: packet %s verdict %d", pkt, v)
// log.Tracef("filter: packet %s verdict %d", pkt, v)
return err
}

View File

@@ -31,91 +31,170 @@ import (
// 4. DecideOnLink
// is called when when the first packet of a link arrives only if communication has verdict UNDECIDED or CANTSAY
// DecideOnCommunicationBeforeDNS makes a decision about a communication before the dns query is resolved and intel is gathered.
func DecideOnCommunicationBeforeDNS(comm *network.Communication) {
// DecideOnConnection makes a decision about a connection.
func DecideOnConnection(conn *network.Connection, pkt packet.Packet) {
// update profiles and check if communication needs reevaluation
if comm.UpdateAndCheck() {
log.Infof("firewall: re-evaluating verdict on %s", comm)
comm.ResetVerdict()
}
// check if need to run
if comm.GetVerdict() != network.VerdictUndecided {
return
if conn.UpdateAndCheck() {
log.Infof("filter: re-evaluating verdict on %s", conn)
conn.Verdict = network.VerdictUndecided
}
// grant self
if comm.Process().Pid == os.Getpid() {
log.Infof("firewall: granting own communication %s", comm)
comm.Accept("")
if conn.Process().Pid == os.Getpid() {
log.Infof("filter: granting own connection %s", conn)
conn.Verdict = network.VerdictAccept
return
}
// check if process is communicating with itself
if pkt != nil {
if conn.Process().Pid >= 0 && pkt.Info().Src.Equal(pkt.Info().Dst) {
// get PID
otherPid, _, err := process.GetPidByEndpoints(
pkt.Info().RemoteIP(),
pkt.Info().RemotePort(),
pkt.Info().LocalIP(),
pkt.Info().LocalPort(),
pkt.Info().Protocol,
)
if err == nil {
// get primary process
otherProcess, err := process.GetOrFindPrimaryProcess(pkt.Ctx(), otherPid)
if err == nil {
if otherProcess.Pid == conn.Process().Pid {
conn.Accept("connection to self")
return
}
}
}
}
}
// get profile
p := comm.Process().Profile()
// check for any network access
if p.BlockScopeInternet() && p.BlockScopeLAN() {
log.Infof("firewall: denying communication %s, accessing Internet or LAN not permitted", comm)
comm.Deny("accessing Internet or LAN not permitted")
p := conn.Process().Profile()
if p == nil {
conn.Block("no profile")
return
}
// continueing with access to either Internet or LAN
// check endpoint list
// FIXME: comm.Entity.Lock()
result, reason := p.MatchEndpoint(comm.Entity)
// FIXME: comm.Entity.Unlock()
// check conn type
switch conn.Scope {
case network.IncomingHost, network.IncomingLAN, network.IncomingInternet, network.IncomingInvalid:
if p.BlockInbound() {
if conn.Scope == network.IncomingHost {
conn.Block("inbound connections blocked")
} else {
conn.Deny("inbound connections blocked")
}
return
}
case network.PeerLAN, network.PeerInternet, network.PeerInvalid:
// Important: PeerHost is and should be missing!
if p.BlockP2P() {
conn.Block("direct connections (P2P) blocked")
return
}
}
// check scopes
if conn.Entity.IP != nil {
classification := netutils.ClassifyIP(conn.Entity.IP)
switch classification {
case netutils.Global, netutils.GlobalMulticast:
if p.BlockScopeInternet() {
conn.Deny("Internet access blocked") // Block Outbound / Drop Inbound
return
}
case netutils.SiteLocal, netutils.LinkLocal, netutils.LocalMulticast:
if p.BlockScopeLAN() {
conn.Block("LAN access blocked") // Block Outbound / Drop Inbound
return
}
case netutils.HostLocal:
if p.BlockScopeLocal() {
conn.Block("Localhost access blocked") // Block Outbound / Drop Inbound
return
}
default: // netutils.Invalid
conn.Deny("invalid IP") // Block Outbound / Drop Inbound
return
}
} else if conn.Entity.Domain != "" {
// DNS Query
// DNS is expected to resolve to LAN or Internet addresses
// TODO: handle domains mapped to localhost
if p.BlockScopeInternet() && p.BlockScopeLAN() {
conn.Block("Internet and LAN access blocked")
return
}
}
// check endpoints list
var result endpoints.EPResult
var reason string
if conn.Inbound {
result, reason = p.MatchServiceEndpoint(conn.Entity)
} else {
result, reason = p.MatchEndpoint(conn.Entity)
}
switch result {
case endpoints.Undeterminable:
comm.UpdateVerdict(network.VerdictUndeterminable)
return
case endpoints.Denied:
log.Infof("firewall: denying communication %s, domain is blacklisted: %s", comm, reason)
comm.Deny(fmt.Sprintf("domain is blacklisted: %s", reason))
conn.Deny("endpoint is blacklisted: " + reason) // Block Outbound / Drop Inbound
return
case endpoints.Permitted:
log.Infof("firewall: permitting communication %s, domain is whitelisted: %s", comm, reason)
comm.Accept(fmt.Sprintf("domain is whitelisted: %s", reason))
conn.Accept("endpoint is whitelisted: " + reason)
return
}
// continuing with result == NoMatch
// implicit default=block for inbound
if conn.Inbound {
conn.Drop("endpoint is not whitelisted (incoming is always default=block)")
return
}
// continueing with result == NoMatch
// check default action
if p.DefaultAction() == profile.DefaultActionPermit {
log.Infof("firewall: permitting communication %s, domain is not blacklisted (default=permit)", comm)
comm.Accept("domain is not blacklisted (default=permit)")
conn.Accept("endpoint is not blacklisted (default=permit)")
return
}
// check relation
if !p.DisableAutoPermit() {
if checkRelation(comm) {
related, reason := checkRelation(conn)
if related {
conn.Accept(reason)
return
}
}
// prompt
if p.DefaultAction() == profile.DefaultActionAsk {
prompt(comm, nil, nil)
prompt(conn, pkt)
return
}
// DefaultAction == DefaultActionBlock
log.Infof("firewall: denying communication %s, domain is not whitelisted (default=block)", comm)
comm.Deny("domain is not whitelisted (default=block)")
conn.Deny("endpoint is not whitelisted (default=block)")
return
}
// FilterDNSResponse filters a dns response according to the application profile and settings.
func FilterDNSResponse(comm *network.Communication, q *resolver.Query, rrCache *resolver.RRCache) *resolver.RRCache { //nolint:gocognit // TODO
func FilterDNSResponse(conn *network.Connection, q *resolver.Query, rrCache *resolver.RRCache) *resolver.RRCache { //nolint:gocognit // TODO
// do not modify own queries - this should not happen anyway
if comm.Process().Pid == os.Getpid() {
if conn.Process().Pid == os.Getpid() {
return rrCache
}
// get profile
p := comm.Process().Profile()
p := conn.Process().Profile()
if p == nil {
conn.Block("no profile")
return nil
}
// check if DNS response filtering is completely turned off
if !p.RemoveOutOfScopeDNS() && !p.RemoveBlockedDNS() {
@@ -201,14 +280,13 @@ func FilterDNSResponse(comm *network.Communication, q *resolver.Query, rrCache *
if addressesRemoved > 0 {
rrCache.Filtered = true
if addressesOk == 0 {
comm.Deny("no addresses returned for this domain are permitted")
log.Infof("firewall: fully dns responses for communication %s", comm)
conn.Block("no addresses returned for this domain are permitted")
return nil
}
}
if rrCache.Filtered {
log.Infof("firewall: filtered DNS replies for %s: %s", comm, strings.Join(rrCache.FilteredEntries, ", "))
log.Infof("filter: filtered DNS replies for %s: %s", conn, strings.Join(rrCache.FilteredEntries, ", "))
}
// TODO: Gate17 integration
@@ -217,231 +295,22 @@ func FilterDNSResponse(comm *network.Communication, q *resolver.Query, rrCache *
return rrCache
}
// DecideOnCommunication makes a decision about a communication with its first packet.
func DecideOnCommunication(comm *network.Communication) {
// update profiles and check if communication needs reevaluation
if comm.UpdateAndCheck() {
log.Infof("firewall: re-evaluating verdict on %s", comm)
comm.ResetVerdict()
// if communicating with a domain entity, re-evaluate with BeforeDNS
if strings.HasSuffix(comm.Scope, ".") {
DecideOnCommunicationBeforeDNS(comm)
}
}
// check if need to run
if comm.GetVerdict() != network.VerdictUndecided {
return
}
// grant self
if comm.Process().Pid == os.Getpid() {
log.Infof("firewall: granting own communication %s", comm)
comm.Accept("")
return
}
// get profile
p := comm.Process().Profile()
// check comm type
switch comm.Scope {
case network.IncomingHost, network.IncomingLAN, network.IncomingInternet, network.IncomingInvalid:
if p.BlockInbound() {
log.Infof("firewall: denying communication %s, not a service", comm)
if comm.Scope == network.IncomingHost {
comm.Block("not a service")
} else {
comm.Deny("not a service")
}
return
}
case network.PeerLAN, network.PeerInternet, network.PeerInvalid:
// Important: PeerHost is and should be missing!
if p.BlockP2P() {
log.Infof("firewall: denying communication %s, peer to peer comms (to an IP) not allowed", comm)
comm.Deny("peer to peer comms (to an IP) not allowed")
return
}
}
// check network scope
switch comm.Scope {
case network.IncomingHost:
if p.BlockScopeLocal() {
log.Infof("firewall: denying communication %s, serving localhost not allowed", comm)
comm.Block("serving localhost not allowed")
return
}
case network.IncomingLAN:
if p.BlockScopeLAN() {
log.Infof("firewall: denying communication %s, serving LAN not allowed", comm)
comm.Deny("serving LAN not allowed")
return
}
case network.IncomingInternet:
if p.BlockScopeInternet() {
log.Infof("firewall: denying communication %s, serving Internet not allowed", comm)
comm.Deny("serving Internet not allowed")
return
}
case network.IncomingInvalid:
log.Infof("firewall: denying communication %s, invalid IP address", comm)
comm.Drop("invalid IP address")
return
case network.PeerHost:
if p.BlockScopeLocal() {
log.Infof("firewall: denying communication %s, accessing localhost not allowed", comm)
comm.Block("accessing localhost not allowed")
return
}
case network.PeerLAN:
if p.BlockScopeLAN() {
log.Infof("firewall: denying communication %s, accessing the LAN not allowed", comm)
comm.Deny("accessing the LAN not allowed")
return
}
case network.PeerInternet:
if p.BlockScopeInternet() {
log.Infof("firewall: denying communication %s, accessing the Internet not allowed", comm)
comm.Deny("accessing the Internet not allowed")
return
}
case network.PeerInvalid:
log.Infof("firewall: denying communication %s, invalid IP address", comm)
comm.Deny("invalid IP address")
return
}
log.Infof("firewall: undeterminable verdict for communication %s", comm)
comm.UpdateVerdict(network.VerdictUndeterminable)
}
// DecideOnLink makes a decision about a link with the first packet.
func DecideOnLink(comm *network.Communication, link *network.Link, pkt packet.Packet) {
// grant self
if comm.Process().Pid == os.Getpid() {
log.Infof("firewall: granting own link %s", comm)
link.Accept("")
return
}
// check if process is communicating with itself
if comm.Process().Pid >= 0 && pkt.Info().Src.Equal(pkt.Info().Dst) {
// get PID
otherPid, _, err := process.GetPidByEndpoints(
pkt.Info().RemoteIP(),
pkt.Info().RemotePort(),
pkt.Info().LocalIP(),
pkt.Info().LocalPort(),
pkt.Info().Protocol,
)
if err == nil {
// get primary process
otherProcess, err := process.GetOrFindPrimaryProcess(pkt.Ctx(), otherPid)
if err == nil {
if otherProcess.Pid == comm.Process().Pid {
log.Infof("firewall: permitting connection to self %s", comm)
link.AddReason("connection to self")
link.Lock()
link.Verdict = network.VerdictAccept
link.SaveWhenFinished()
link.Unlock()
return
}
}
}
}
// check if we aleady have a verdict
switch comm.GetVerdict() {
case network.VerdictUndecided, network.VerdictUndeterminable:
// continue
default:
link.UpdateVerdict(comm.GetVerdict())
return
}
// get profile
p := comm.Process().Profile()
// check endpoints list
var result endpoints.EPResult
var reason string
// FIXME: link.Entity.Lock()
if comm.Direction {
result, reason = p.MatchServiceEndpoint(link.Entity)
} else {
result, reason = p.MatchEndpoint(link.Entity)
}
// FIXME: link.Entity.Unlock()
switch result {
case endpoints.Denied:
log.Infof("firewall: denying link %s, endpoint is blacklisted: %s", link, reason)
link.Deny(fmt.Sprintf("endpoint is blacklisted: %s", reason))
return
case endpoints.Permitted:
log.Infof("firewall: permitting link %s, endpoint is whitelisted: %s", link, reason)
link.Accept(fmt.Sprintf("endpoint is whitelisted: %s", reason))
return
}
// continueing with result == NoMatch
// implicit default=block for incoming
if comm.Direction {
log.Infof("firewall: denying link %s: endpoint is not whitelisted (incoming is always default=block)", link)
link.Deny("endpoint is not whitelisted (incoming is always default=block)")
return
}
// check default action
if p.DefaultAction() == profile.DefaultActionPermit {
log.Infof("firewall: permitting link %s: endpoint is not blacklisted (default=permit)", link)
link.Accept("endpoint is not blacklisted (default=permit)")
return
}
// check relation
if !p.DisableAutoPermit() {
if checkRelation(comm) {
return
}
}
// prompt
if p.DefaultAction() == profile.DefaultActionAsk {
prompt(comm, link, pkt)
return
}
// DefaultAction == DefaultActionBlock
log.Infof("firewall: denying link %s: endpoint is not whitelisted (default=block)", link)
link.Deny("endpoint is not whitelisted (default=block)")
return
}
// checkRelation tries to find a relation between a process and a communication. This is for better out of the box experience and is _not_ meant to thwart intentional malware.
func checkRelation(comm *network.Communication) (related bool) {
if comm.Entity.Domain != "" {
return false
func checkRelation(conn *network.Connection) (related bool, reason string) {
if conn.Entity.Domain != "" {
return false, ""
}
// don't check for unknown processes
if comm.Process().Pid < 0 {
return false
if conn.Process().Pid < 0 {
return false, ""
}
pathElements := strings.Split(comm.Process().Path, string(filepath.Separator))
pathElements := strings.Split(conn.Process().Path, string(filepath.Separator))
// only look at the last two path segments
if len(pathElements) > 2 {
pathElements = pathElements[len(pathElements)-2:]
}
domainElements := strings.Split(comm.Entity.Domain, ".")
domainElements := strings.Split(conn.Entity.Domain, ".")
var domainElement string
var processElement string
@@ -455,21 +324,20 @@ matchLoop:
break matchLoop
}
}
if levenshtein.Match(domainElement, comm.Process().Name, nil) > 0.5 {
if levenshtein.Match(domainElement, conn.Process().Name, nil) > 0.5 {
related = true
processElement = comm.Process().Name
processElement = conn.Process().Name
break matchLoop
}
if levenshtein.Match(domainElement, comm.Process().ExecName, nil) > 0.5 {
if levenshtein.Match(domainElement, conn.Process().ExecName, nil) > 0.5 {
related = true
processElement = comm.Process().ExecName
processElement = conn.Process().ExecName
break matchLoop
}
}
if related {
log.Infof("firewall: permitting communication %s, match to domain was found: %s is related to %s", comm, domainElement, processElement)
comm.Accept(fmt.Sprintf("domain is related to process: %s is related to %s", domainElement, processElement))
reason = fmt.Sprintf("domain is related to process: %s is related to %s", domainElement, processElement)
}
return related
return
}

View File

@@ -50,7 +50,7 @@ func GetPermittedPort() uint16 {
// generate port between 10000 and 65535
rN, err := rng.Number(55535)
if err != nil {
log.Warningf("firewall: failed to generate random port: %s", err)
log.Warningf("filter: failed to generate random port: %s", err)
return 0
}
port := uint16(rN + 10000)

View File

@@ -29,27 +29,17 @@ var (
mtSaveProfile = "save profile"
)
//nolint:gocognit // FIXME
func prompt(comm *network.Communication, link *network.Link, pkt packet.Packet) {
func prompt(conn *network.Connection, pkt packet.Packet) { //nolint:gocognit // TODO
nTTL := time.Duration(promptTimeout()) * time.Second
// first check if there is an existing notification for this.
// build notification ID
var nID string
switch {
case comm.Direction, comm.Entity.Domain == "": // connection to/from IP
if pkt == nil {
log.Error("firewall: could not prompt for incoming/direct connection: missing pkt")
if link != nil {
link.Deny("internal error")
} else {
comm.Deny("internal error")
}
return
}
nID = fmt.Sprintf("firewall-prompt-%d-%s-%s", comm.Process().Pid, comm.Scope, pkt.Info().RemoteIP())
case conn.Inbound, conn.Entity.Domain == "": // connection to/from IP
nID = fmt.Sprintf("firewall-prompt-%d-%s-%s", conn.Process().Pid, conn.Scope, pkt.Info().RemoteIP())
default: // connection to domain
nID = fmt.Sprintf("firewall-prompt-%d-%s", comm.Process().Pid, comm.Scope)
nID = fmt.Sprintf("firewall-prompt-%d-%s", conn.Process().Pid, conn.Scope)
}
n := notifications.Get(nID)
saveResponse := true
@@ -69,8 +59,8 @@ func prompt(comm *network.Communication, link *network.Link, pkt packet.Packet)
// add message and actions
switch {
case comm.Direction: // incoming
n.Message = fmt.Sprintf("Application %s wants to accept connections from %s (%d/%d)", comm.Process(), link.Entity.IP.String(), link.Entity.Protocol, link.Entity.Port)
case conn.Inbound:
n.Message = fmt.Sprintf("Application %s wants to accept connections from %s (%d/%d)", conn.Process(), conn.Entity.IP.String(), conn.Entity.Protocol, conn.Entity.Port)
n.AvailableActions = []*notifications.Action{
{
ID: permitServingIP,
@@ -81,8 +71,8 @@ func prompt(comm *network.Communication, link *network.Link, pkt packet.Packet)
Text: "Deny",
},
}
case comm.Entity.Domain == "": // direct connection
n.Message = fmt.Sprintf("Application %s wants to connect to %s (%d/%d)", comm.Process(), link.Entity.IP.String(), link.Entity.Protocol, link.Entity.Port)
case conn.Entity.Domain == "": // direct connection
n.Message = fmt.Sprintf("Application %s wants to connect to %s (%d/%d)", conn.Process(), conn.Entity.IP.String(), conn.Entity.Protocol, conn.Entity.Port)
n.AvailableActions = []*notifications.Action{
{
ID: permitIP,
@@ -94,10 +84,10 @@ func prompt(comm *network.Communication, link *network.Link, pkt packet.Packet)
},
}
default: // connection to domain
if link != nil {
n.Message = fmt.Sprintf("Application %s wants to connect to %s (%s %d/%d)", comm.Process(), comm.Entity.Domain, link.Entity.IP.String(), link.Entity.Protocol, link.Entity.Port)
if pkt != nil {
n.Message = fmt.Sprintf("Application %s wants to connect to %s (%s %d/%d)", conn.Process(), conn.Entity.Domain, conn.Entity.IP.String(), conn.Entity.Protocol, conn.Entity.Port)
} else {
n.Message = fmt.Sprintf("Application %s wants to connect to %s", comm.Process(), comm.Entity.Domain)
n.Message = fmt.Sprintf("Application %s wants to connect to %s", conn.Process(), conn.Entity.Domain)
}
n.AvailableActions = []*notifications.Action{
{
@@ -123,17 +113,9 @@ func prompt(comm *network.Communication, link *network.Link, pkt packet.Packet)
case promptResponse := <-n.Response():
switch promptResponse {
case permitDomainAll, permitDomainDistinct, permitIP, permitServingIP:
if link != nil {
link.Accept("permitted by user")
} else {
comm.Accept("permitted by user")
}
conn.Accept("permitted by user")
default: // deny
if link != nil {
link.Accept("denied by user")
} else {
comm.Accept("denied by user")
}
conn.Deny("denied by user")
}
// end here if we won't save the response to the profile
@@ -142,42 +124,43 @@ func prompt(comm *network.Communication, link *network.Link, pkt packet.Packet)
}
// get profile
p := comm.Process().Profile()
p := conn.Process().Profile()
var ep endpoints.Endpoint
switch promptResponse {
case permitDomainAll:
ep = &endpoints.EndpointDomain{
EndpointBase: endpoints.EndpointBase{Permitted: true},
Domain: "." + comm.Entity.Domain,
Domain: "." + conn.Entity.Domain,
}
case permitDomainDistinct:
ep = &endpoints.EndpointDomain{
EndpointBase: endpoints.EndpointBase{Permitted: true},
Domain: comm.Entity.Domain,
Domain: conn.Entity.Domain,
}
case denyDomainAll:
ep = &endpoints.EndpointDomain{
EndpointBase: endpoints.EndpointBase{Permitted: false},
Domain: "." + comm.Entity.Domain,
Domain: "." + conn.Entity.Domain,
}
case denyDomainDistinct:
ep = &endpoints.EndpointDomain{
EndpointBase: endpoints.EndpointBase{Permitted: false},
Domain: comm.Entity.Domain,
Domain: conn.Entity.Domain,
}
case permitIP, permitServingIP:
ep = &endpoints.EndpointIP{
EndpointBase: endpoints.EndpointBase{Permitted: true},
IP: comm.Entity.IP,
IP: conn.Entity.IP,
}
case denyIP, denyServingIP:
ep = &endpoints.EndpointIP{
EndpointBase: endpoints.EndpointBase{Permitted: false},
IP: comm.Entity.IP,
IP: conn.Entity.IP,
}
default:
log.Warningf("filter: unknown prompt response: %s", promptResponse)
return
}
switch promptResponse {
@@ -188,10 +171,6 @@ func prompt(comm *network.Communication, link *network.Link, pkt packet.Packet)
}
case <-n.Expired():
if link != nil {
link.Deny("no response to prompt")
} else {
comm.Deny("no response to prompt")
}
conn.Deny("no response to prompt")
}
}