| 1 |
|
| 2 |
|
| 3 |
package chroot |
| 4 |
|
| 5 |
import ( |
| 6 |
"fmt" |
| 7 |
"path/filepath" |
| 8 |
"strings" |
| 9 |
"syscall" |
| 10 |
) |
| 11 |
|
| 12 |
var anchor = "/" |
| 13 |
|
| 14 |
func getAnchor() string { |
| 15 |
return anchor |
| 16 |
} |
| 17 |
|
| 18 |
func rel(path string) (chrootRelativePath string, canAddress bool) { |
| 19 |
p, err := filepath.Rel(Anchor(), path) |
| 20 |
if err != nil || p == "" { |
| 21 |
return "", false |
| 22 |
} |
| 23 |
|
| 24 |
if p == ".." || strings.HasPrefix(p, "../") { |
| 25 |
return "", false |
| 26 |
} |
| 27 |
|
| 28 |
if p == "." { |
| 29 |
return "/", true |
| 30 |
} |
| 31 |
|
| 32 |
return "/" + p, true |
| 33 |
} |
| 34 |
|
| 35 |
|
| 36 |
|
| 37 |
|
| 38 |
func Chroot(path string) error { |
| 39 |
if !filepath.IsAbs(path) { |
| 40 |
return fmt.Errorf("chroot path must be absolute: %v", path) |
| 41 |
} |
| 42 |
|
| 43 |
err := syscall.Chroot(path) |
| 44 |
if err != nil { |
| 45 |
return err |
| 46 |
} |
| 47 |
|
| 48 |
anchor = filepath.Join(anchor, path[1:]) |
| 49 |
return nil |
| 50 |
} |