Skip to content

Commit

Permalink
Add sysctl whitelist
Browse files Browse the repository at this point in the history
Signed-off-by: mmirecki <mmirecki@redhat.com>
  • Loading branch information
mmirecki committed Feb 8, 2022
1 parent 27e830b commit 7ef6b59
Showing 1 changed file with 64 additions and 0 deletions.
64 changes: 64 additions & 0 deletions plugins/meta/tuning/tuning.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,14 @@ package main

import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net"
"os"
"path"
"path/filepath"
"regexp"
"strings"

"github.com/vishvananda/netlink"
Expand All @@ -40,6 +42,7 @@ import (
)

const defaultDataDir = "/run/cni/tuning"
const defaultWhitelistFile = "/etc/cni/tuning/whitelist.conf"

// TuningConf represents the network tuning configuration.
type TuningConf struct {
Expand Down Expand Up @@ -305,6 +308,10 @@ func cmdAdd(args *skel.CmdArgs) error {
return err
}

if err = validateSysctlConf(tuningConf); err != nil {
return err
}

// Parse previous result.
if tuningConf.RawPrevResult == nil {
return fmt.Errorf("Required prevResult missing")
Expand Down Expand Up @@ -477,3 +484,60 @@ func cmdCheck(args *skel.CmdArgs) error {

return nil
}

// Validate the sysctls in the tuning config are on the sysctl whitelist file.
// Note that if the whitelist file is missing no validation takes place.
func validateSysctlConf(tuningConf *TuningConf) error {
isPresent, whiteList, err := readWhitelist()
if err != nil {
return err
}
if !isPresent {
return nil
}
for sysctl, _ := range tuningConf.SysCtl {
match, err := contains(sysctl, whiteList)
if err != nil {
return err
}
if !match {
return errors.New(fmt.Sprintf("Sysctl %s is not allowed. Only the following sysctls are allowed: %+v", sysctl, whiteList))
}
}
return nil
}

// Validate the whiteList contains the given sysctl
func contains(sysctl string, whiteList []string) (bool, error) {
for _, whiteListElements := range whiteList {
match, err := regexp.MatchString(whiteListElements, sysctl)
if err != nil {
return false, err
}
if match {
return true, nil
}
}
return false, nil
}

// Read the systctl whitelist from file. Return info if the file is present and the read whiteList if it is
func readWhitelist() (bool, []string, error) {
if _, err := os.Stat(defaultWhitelistFile); os.IsNotExist(err) {
return false, nil, nil
}
dat, err := os.ReadFile(defaultWhitelistFile)
if err != nil {
return false, nil, err
}

lines := strings.Split(string(dat), "\n")
whiteList := []string{}
for _, line := range lines {
line = strings.TrimSpace(line)
if len(line) > 0 {
whiteList = append(whiteList, line)
}
}
return true, whiteList, nil
}

0 comments on commit 7ef6b59

Please sign in to comment.