diff --git a/felix/iptables/actions.go b/felix/iptables/actions.go index f1382f85936..387909d8e96 100644 --- a/felix/iptables/actions.go +++ b/felix/iptables/actions.go @@ -21,6 +21,8 @@ import ( "github.com/projectcalico/calico/felix/generictables" ) +var shellUnsafe = regexp.MustCompile(`[^\w @%+=:,./-]`) + func Actions() generictables.ActionFactory { return &actionFactory{} } @@ -189,7 +191,7 @@ type LogAction struct { } func (g LogAction) ToFragment(features *environment.Features) string { - return fmt.Sprintf(`--jump LOG --log-prefix "%s: " --log-level 5`, g.Prefix) + return fmt.Sprintf(`--jump LOG --log-prefix "%s: " --log-level 5`, escapeLogPrefix(g.Prefix)) } func (g LogAction) String() string { @@ -375,3 +377,9 @@ func (c SetConnMarkAction) ToFragment(features *environment.Features) string { func (c SetConnMarkAction) String() string { return fmt.Sprintf("SetConnMarkWithMask:%#x/%#x", c.Mark, c.Mask) } + +// escapeLogPrefix replaces anything other than "safe" shell characters with an +// underscore (_) and truncates to 27 characters. +func escapeLogPrefix(s string) string { + return shellUnsafe.ReplaceAllString(s, "_")[:27] +} diff --git a/felix/nftables/actions.go b/felix/nftables/actions.go index 65186aae749..c49bee75da9 100644 --- a/felix/nftables/actions.go +++ b/felix/nftables/actions.go @@ -24,6 +24,8 @@ import ( "github.com/projectcalico/calico/felix/generictables" ) +var shellUnsafe = regexp.MustCompile(`[^\w @%+=:,./-]`) + type namespaceable interface { Namespace(string) generictables.Action } @@ -229,7 +231,7 @@ type LogAction struct { } func (g LogAction) ToFragment(features *environment.Features) string { - return fmt.Sprintf(`log prefix %s level info`, g.Prefix) + return fmt.Sprintf(`log prefix "%s" level info`, escapeLogPrefix(g.Prefix)) } func (g LogAction) String() string { @@ -406,3 +408,10 @@ func (c SetConnMarkAction) ToFragment(features *environment.Features) string { func (c SetConnMarkAction) String() string { return fmt.Sprintf("SetConnMarkWithMask:%#x/%#x", c.Mark, c.Mask) } + + +// escapeLogPrefix replaces anything other than "safe" shell characters with an +// underscore (_). +func escapeLogPrefix(s string) string { + return shellUnsafe.ReplaceAllString(s, "_") +} \ No newline at end of file diff --git a/felix/rules/policy.go b/felix/rules/policy.go index bcd7023ccc8..603e1bc5cfe 100644 --- a/felix/rules/policy.go +++ b/felix/rules/policy.go @@ -544,7 +544,11 @@ func (r *DefaultRuleRenderer) CalculateActions(pRule *proto.Rule, ipVersion uint actions = append(actions, r.IptablesFilterDenyAction()) case "log": // This rule should log. - actions = append(actions, r.Log(r.LogPrefix)) + prefix, ok := pRule.Metadata.Annotations["projectcalico.org/LogPrefix"] + if ! ok { + prefix = r.LogPrefix + } + actions = append(actions, r.Log(prefix)) default: log.WithField("action", pRule.Action).Panic("Unknown rule action") }