add_seccomp.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. package python
  2. import (
  3. "os"
  4. "strconv"
  5. "strings"
  6. "syscall"
  7. "github.com/langgenius/dify-sandbox/internal/core/lib"
  8. "github.com/langgenius/dify-sandbox/internal/static/python_syscall"
  9. )
  10. //var allow_syscalls = []int{}
  11. func InitSeccomp(uid int, gid int, enable_network bool) error {
  12. err := syscall.Chroot(".")
  13. if err != nil {
  14. return err
  15. }
  16. err = syscall.Chdir("/")
  17. if err != nil {
  18. return err
  19. }
  20. lib.SetNoNewPrivs()
  21. allowed_syscalls := []int{}
  22. allowed_not_kill_syscalls := []int{}
  23. allowed_not_kill_syscalls = append(allowed_not_kill_syscalls, python_syscall.ALLOW_ERROR_SYSCALLS...)
  24. allowed_syscall := os.Getenv("ALLOWED_SYSCALLS")
  25. if allowed_syscall != "" {
  26. nums := strings.Split(allowed_syscall, ",")
  27. for num := range nums {
  28. syscall, err := strconv.Atoi(nums[num])
  29. if err != nil {
  30. continue
  31. }
  32. allowed_syscalls = append(allowed_syscalls, syscall)
  33. }
  34. } else {
  35. allowed_syscalls = append(allowed_syscalls, python_syscall.ALLOW_SYSCALLS...)
  36. if enable_network {
  37. allowed_syscalls = append(allowed_syscalls, python_syscall.ALLOW_NETWORK_SYSCALLS...)
  38. }
  39. }
  40. err = lib.Seccomp(allowed_syscalls, allowed_not_kill_syscalls)
  41. if err != nil {
  42. return err
  43. }
  44. // setuid
  45. err = syscall.Setuid(uid)
  46. if err != nil {
  47. return err
  48. }
  49. // setgid
  50. err = syscall.Setgid(gid)
  51. if err != nil {
  52. return err
  53. }
  54. return nil
  55. }