security_linux.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. //go:build linux
  2. package ims
  3. import (
  4. "context"
  5. "errors"
  6. "fmt"
  7. "os/exec"
  8. "strings"
  9. "sync"
  10. )
  11. type linuxIPSecInstaller struct {
  12. ipCommand string
  13. }
  14. func defaultIPSecInstaller() IPSecSAInstaller {
  15. return linuxIPSecInstaller{ipCommand: "ip"}
  16. }
  17. type linuxIPSecHandle struct {
  18. mu sync.Mutex
  19. ipCommand string
  20. config IPSecSAConfig
  21. closed bool
  22. }
  23. func (installer linuxIPSecInstaller) Install(ctx context.Context, config IPSecSAConfig) (IPSecSAHandle, error) {
  24. command := installer.ipCommand
  25. if command == "" {
  26. command = "ip"
  27. }
  28. if _, err := exec.LookPath(command); err != nil {
  29. return nil, errors.New("ims: Linux iproute2 is required for ipsec-3gpp")
  30. }
  31. install, err := buildXFRMInstallPlan(config)
  32. if err != nil {
  33. return nil, err
  34. }
  35. handle := &linuxIPSecHandle{
  36. ipCommand: command,
  37. config: cloneIPSecSAConfig(config),
  38. }
  39. for _, operation := range install {
  40. if err := runIPCommand(ctx, command, operation); err != nil {
  41. _ = handle.cleanup(context.Background())
  42. zeroBytes(handle.config.EncryptionKey)
  43. zeroBytes(handle.config.IntegrityKey)
  44. return nil, fmt.Errorf("%w: %v", ErrIPSecInstall, err)
  45. }
  46. }
  47. zeroBytes(handle.config.EncryptionKey)
  48. zeroBytes(handle.config.IntegrityKey)
  49. return handle, nil
  50. }
  51. func (handle *linuxIPSecHandle) Close(ctx context.Context) error {
  52. handle.mu.Lock()
  53. defer handle.mu.Unlock()
  54. if handle.closed {
  55. return nil
  56. }
  57. handle.closed = true
  58. return handle.cleanup(ctx)
  59. }
  60. func (handle *linuxIPSecHandle) cleanup(ctx context.Context) error {
  61. var cleanupErrors []error
  62. for _, operation := range buildXFRMCleanupPlan(handle.config) {
  63. if err := runIPCommand(ctx, handle.ipCommand, operation); err != nil {
  64. cleanupErrors = append(cleanupErrors, err)
  65. }
  66. }
  67. return errors.Join(cleanupErrors...)
  68. }
  69. func runIPCommand(ctx context.Context, command string, operation xfrmOperation) error {
  70. output, err := exec.CommandContext(ctx, command, operation.arguments...).CombinedOutput()
  71. if err == nil {
  72. return nil
  73. }
  74. message := strings.TrimSpace(string(output))
  75. if message == "" {
  76. message = err.Error()
  77. }
  78. // Operation descriptions contain no SPI keys or subscriber identity.
  79. return fmt.Errorf("%s: %s", operation.description, message)
  80. }