keys.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. // +build linux
  2. package daemon
  3. import (
  4. "fmt"
  5. "io/ioutil"
  6. "os"
  7. "strconv"
  8. "strings"
  9. )
  10. const (
  11. rootKeyFile = "/proc/sys/kernel/keys/root_maxkeys"
  12. rootBytesFile = "/proc/sys/kernel/keys/root_maxbytes"
  13. rootKeyLimit = 1000000
  14. // it is standard configuration to allocate 25 bytes per key
  15. rootKeyByteMultiplier = 25
  16. )
  17. // ModifyRootKeyLimit checks to see if the root key limit is set to
  18. // at least 1000000 and changes it to that limit along with the maxbytes
  19. // allocated to the keys at a 25 to 1 multiplier.
  20. func ModifyRootKeyLimit() error {
  21. value, err := readRootKeyLimit(rootKeyFile)
  22. if err != nil {
  23. return err
  24. }
  25. if value < rootKeyLimit {
  26. return setRootKeyLimit(rootKeyLimit)
  27. }
  28. return nil
  29. }
  30. func setRootKeyLimit(limit int) error {
  31. keys, err := os.OpenFile(rootKeyFile, os.O_WRONLY, 0)
  32. if err != nil {
  33. return err
  34. }
  35. defer keys.Close()
  36. if _, err := fmt.Fprintf(keys, "%d", limit); err != nil {
  37. return err
  38. }
  39. bytes, err := os.OpenFile(rootBytesFile, os.O_WRONLY, 0)
  40. if err != nil {
  41. return err
  42. }
  43. defer bytes.Close()
  44. _, err = fmt.Fprintf(bytes, "%d", limit*rootKeyByteMultiplier)
  45. return err
  46. }
  47. func readRootKeyLimit(path string) (int, error) {
  48. data, err := ioutil.ReadFile(path)
  49. if err != nil {
  50. return -1, err
  51. }
  52. return strconv.Atoi(strings.Trim(string(data), "\n"))
  53. }