selinux_linux.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840
  1. // +build selinux,linux
  2. package selinux
  3. import (
  4. "bufio"
  5. "bytes"
  6. "crypto/rand"
  7. "encoding/binary"
  8. "fmt"
  9. "io"
  10. "io/ioutil"
  11. "os"
  12. "path"
  13. "path/filepath"
  14. "regexp"
  15. "strconv"
  16. "strings"
  17. "sync"
  18. "syscall"
  19. "github.com/pkg/errors"
  20. "golang.org/x/sys/unix"
  21. )
  22. const (
  23. // Enforcing constant indicate SELinux is in enforcing mode
  24. Enforcing = 1
  25. // Permissive constant to indicate SELinux is in permissive mode
  26. Permissive = 0
  27. // Disabled constant to indicate SELinux is disabled
  28. Disabled = -1
  29. selinuxDir = "/etc/selinux/"
  30. selinuxConfig = selinuxDir + "config"
  31. selinuxfsMount = "/sys/fs/selinux"
  32. selinuxTypeTag = "SELINUXTYPE"
  33. selinuxTag = "SELINUX"
  34. xattrNameSelinux = "security.selinux"
  35. stRdOnly = 0x01
  36. )
  37. type selinuxState struct {
  38. enabledSet bool
  39. enabled bool
  40. selinuxfsOnce sync.Once
  41. selinuxfs string
  42. mcsList map[string]bool
  43. sync.Mutex
  44. }
  45. var (
  46. // ErrMCSAlreadyExists is returned when trying to allocate a duplicate MCS.
  47. ErrMCSAlreadyExists = errors.New("MCS label already exists")
  48. // ErrEmptyPath is returned when an empty path has been specified.
  49. ErrEmptyPath = errors.New("empty path")
  50. // InvalidLabel is returned when an invalid label is specified.
  51. InvalidLabel = errors.New("Invalid Label")
  52. assignRegex = regexp.MustCompile(`^([^=]+)=(.*)$`)
  53. roFileLabel string
  54. state = selinuxState{
  55. mcsList: make(map[string]bool),
  56. }
  57. // for attrPath()
  58. attrPathOnce sync.Once
  59. haveThreadSelf bool
  60. )
  61. // Context is a representation of the SELinux label broken into 4 parts
  62. type Context map[string]string
  63. func (s *selinuxState) setEnable(enabled bool) bool {
  64. s.Lock()
  65. defer s.Unlock()
  66. s.enabledSet = true
  67. s.enabled = enabled
  68. return s.enabled
  69. }
  70. func (s *selinuxState) getEnabled() bool {
  71. s.Lock()
  72. enabled := s.enabled
  73. enabledSet := s.enabledSet
  74. s.Unlock()
  75. if enabledSet {
  76. return enabled
  77. }
  78. enabled = false
  79. if fs := getSelinuxMountPoint(); fs != "" {
  80. if con, _ := CurrentLabel(); con != "kernel" {
  81. enabled = true
  82. }
  83. }
  84. return s.setEnable(enabled)
  85. }
  86. // SetDisabled disables selinux support for the package
  87. func SetDisabled() {
  88. state.setEnable(false)
  89. }
  90. func verifySELinuxfsMount(mnt string) bool {
  91. var buf syscall.Statfs_t
  92. for {
  93. err := syscall.Statfs(mnt, &buf)
  94. if err == nil {
  95. break
  96. }
  97. if err == syscall.EAGAIN {
  98. continue
  99. }
  100. return false
  101. }
  102. if uint32(buf.Type) != uint32(unix.SELINUX_MAGIC) {
  103. return false
  104. }
  105. if (buf.Flags & stRdOnly) != 0 {
  106. return false
  107. }
  108. return true
  109. }
  110. func findSELinuxfs() string {
  111. // fast path: check the default mount first
  112. if verifySELinuxfsMount(selinuxfsMount) {
  113. return selinuxfsMount
  114. }
  115. // check if selinuxfs is available before going the slow path
  116. fs, err := ioutil.ReadFile("/proc/filesystems")
  117. if err != nil {
  118. return ""
  119. }
  120. if !bytes.Contains(fs, []byte("\tselinuxfs\n")) {
  121. return ""
  122. }
  123. // slow path: try to find among the mounts
  124. f, err := os.Open("/proc/self/mountinfo")
  125. if err != nil {
  126. return ""
  127. }
  128. defer f.Close()
  129. scanner := bufio.NewScanner(f)
  130. for {
  131. mnt := findSELinuxfsMount(scanner)
  132. if mnt == "" { // error or not found
  133. return ""
  134. }
  135. if verifySELinuxfsMount(mnt) {
  136. return mnt
  137. }
  138. }
  139. }
  140. // findSELinuxfsMount returns a next selinuxfs mount point found,
  141. // if there is one, or an empty string in case of EOF or error.
  142. func findSELinuxfsMount(s *bufio.Scanner) string {
  143. for s.Scan() {
  144. txt := s.Bytes()
  145. // The first field after - is fs type.
  146. // Safe as spaces in mountpoints are encoded as \040
  147. if !bytes.Contains(txt, []byte(" - selinuxfs ")) {
  148. continue
  149. }
  150. const mPos = 5 // mount point is 5th field
  151. fields := bytes.SplitN(txt, []byte(" "), mPos+1)
  152. if len(fields) < mPos+1 {
  153. continue
  154. }
  155. return string(fields[mPos-1])
  156. }
  157. return ""
  158. }
  159. func (s *selinuxState) getSELinuxfs() string {
  160. s.selinuxfsOnce.Do(func() {
  161. s.selinuxfs = findSELinuxfs()
  162. })
  163. return s.selinuxfs
  164. }
  165. // getSelinuxMountPoint returns the path to the mountpoint of an selinuxfs
  166. // filesystem or an empty string if no mountpoint is found. Selinuxfs is
  167. // a proc-like pseudo-filesystem that exposes the selinux policy API to
  168. // processes. The existence of an selinuxfs mount is used to determine
  169. // whether selinux is currently enabled or not.
  170. func getSelinuxMountPoint() string {
  171. return state.getSELinuxfs()
  172. }
  173. // GetEnabled returns whether selinux is currently enabled.
  174. func GetEnabled() bool {
  175. return state.getEnabled()
  176. }
  177. func readConfig(target string) string {
  178. var (
  179. val, key string
  180. bufin *bufio.Reader
  181. )
  182. in, err := os.Open(selinuxConfig)
  183. if err != nil {
  184. return ""
  185. }
  186. defer in.Close()
  187. bufin = bufio.NewReader(in)
  188. for done := false; !done; {
  189. var line string
  190. if line, err = bufin.ReadString('\n'); err != nil {
  191. if err != io.EOF {
  192. return ""
  193. }
  194. done = true
  195. }
  196. line = strings.TrimSpace(line)
  197. if len(line) == 0 {
  198. // Skip blank lines
  199. continue
  200. }
  201. if line[0] == ';' || line[0] == '#' {
  202. // Skip comments
  203. continue
  204. }
  205. if groups := assignRegex.FindStringSubmatch(line); groups != nil {
  206. key, val = strings.TrimSpace(groups[1]), strings.TrimSpace(groups[2])
  207. if key == target {
  208. return strings.Trim(val, "\"")
  209. }
  210. }
  211. }
  212. return ""
  213. }
  214. func getSELinuxPolicyRoot() string {
  215. return filepath.Join(selinuxDir, readConfig(selinuxTypeTag))
  216. }
  217. func isProcHandle(fh *os.File) error {
  218. var buf unix.Statfs_t
  219. err := unix.Fstatfs(int(fh.Fd()), &buf)
  220. if err != nil {
  221. return fmt.Errorf("statfs(%q) failed: %v", fh.Name(), err)
  222. }
  223. if buf.Type != unix.PROC_SUPER_MAGIC {
  224. return fmt.Errorf("file %q is not on procfs", fh.Name())
  225. }
  226. return nil
  227. }
  228. func readCon(fpath string) (string, error) {
  229. if fpath == "" {
  230. return "", ErrEmptyPath
  231. }
  232. in, err := os.Open(fpath)
  233. if err != nil {
  234. return "", err
  235. }
  236. defer in.Close()
  237. if err := isProcHandle(in); err != nil {
  238. return "", err
  239. }
  240. var retval string
  241. if _, err := fmt.Fscanf(in, "%s", &retval); err != nil {
  242. return "", err
  243. }
  244. return strings.Trim(retval, "\x00"), nil
  245. }
  246. // SetFileLabel sets the SELinux label for this path or returns an error.
  247. func SetFileLabel(fpath string, label string) error {
  248. if fpath == "" {
  249. return ErrEmptyPath
  250. }
  251. if err := lsetxattr(fpath, xattrNameSelinux, []byte(label), 0); err != nil {
  252. return errors.Wrapf(err, "failed to set file label on %s", fpath)
  253. }
  254. return nil
  255. }
  256. // FileLabel returns the SELinux label for this path or returns an error.
  257. func FileLabel(fpath string) (string, error) {
  258. if fpath == "" {
  259. return "", ErrEmptyPath
  260. }
  261. label, err := lgetxattr(fpath, xattrNameSelinux)
  262. if err != nil {
  263. return "", err
  264. }
  265. // Trim the NUL byte at the end of the byte buffer, if present.
  266. if len(label) > 0 && label[len(label)-1] == '\x00' {
  267. label = label[:len(label)-1]
  268. }
  269. return string(label), nil
  270. }
  271. /*
  272. SetFSCreateLabel tells kernel the label to create all file system objects
  273. created by this task. Setting label="" to return to default.
  274. */
  275. func SetFSCreateLabel(label string) error {
  276. return writeAttr("fscreate", label)
  277. }
  278. /*
  279. FSCreateLabel returns the default label the kernel which the kernel is using
  280. for file system objects created by this task. "" indicates default.
  281. */
  282. func FSCreateLabel() (string, error) {
  283. return readAttr("fscreate")
  284. }
  285. // CurrentLabel returns the SELinux label of the current process thread, or an error.
  286. func CurrentLabel() (string, error) {
  287. return readAttr("current")
  288. }
  289. // PidLabel returns the SELinux label of the given pid, or an error.
  290. func PidLabel(pid int) (string, error) {
  291. return readCon(fmt.Sprintf("/proc/%d/attr/current", pid))
  292. }
  293. /*
  294. ExecLabel returns the SELinux label that the kernel will use for any programs
  295. that are executed by the current process thread, or an error.
  296. */
  297. func ExecLabel() (string, error) {
  298. return readAttr("exec")
  299. }
  300. func writeCon(fpath, val string) error {
  301. if fpath == "" {
  302. return ErrEmptyPath
  303. }
  304. if val == "" {
  305. if !GetEnabled() {
  306. return nil
  307. }
  308. }
  309. out, err := os.OpenFile(fpath, os.O_WRONLY, 0)
  310. if err != nil {
  311. return err
  312. }
  313. defer out.Close()
  314. if err := isProcHandle(out); err != nil {
  315. return err
  316. }
  317. if val != "" {
  318. _, err = out.Write([]byte(val))
  319. } else {
  320. _, err = out.Write(nil)
  321. }
  322. if err != nil {
  323. return errors.Wrapf(err, "failed to set %s on procfs", fpath)
  324. }
  325. return nil
  326. }
  327. func attrPath(attr string) string {
  328. // Linux >= 3.17 provides this
  329. const threadSelfPrefix = "/proc/thread-self/attr"
  330. attrPathOnce.Do(func() {
  331. st, err := os.Stat(threadSelfPrefix)
  332. if err == nil && st.Mode().IsDir() {
  333. haveThreadSelf = true
  334. }
  335. })
  336. if haveThreadSelf {
  337. return path.Join(threadSelfPrefix, attr)
  338. }
  339. return path.Join("/proc/self/task/", strconv.Itoa(syscall.Gettid()), "/attr/", attr)
  340. }
  341. func readAttr(attr string) (string, error) {
  342. return readCon(attrPath(attr))
  343. }
  344. func writeAttr(attr, val string) error {
  345. return writeCon(attrPath(attr), val)
  346. }
  347. /*
  348. CanonicalizeContext takes a context string and writes it to the kernel
  349. the function then returns the context that the kernel will use. This function
  350. can be used to see if two contexts are equivalent
  351. */
  352. func CanonicalizeContext(val string) (string, error) {
  353. return readWriteCon(filepath.Join(getSelinuxMountPoint(), "context"), val)
  354. }
  355. func readWriteCon(fpath string, val string) (string, error) {
  356. if fpath == "" {
  357. return "", ErrEmptyPath
  358. }
  359. f, err := os.OpenFile(fpath, os.O_RDWR, 0)
  360. if err != nil {
  361. return "", err
  362. }
  363. defer f.Close()
  364. _, err = f.Write([]byte(val))
  365. if err != nil {
  366. return "", err
  367. }
  368. var retval string
  369. if _, err := fmt.Fscanf(f, "%s", &retval); err != nil {
  370. return "", err
  371. }
  372. return strings.Trim(retval, "\x00"), nil
  373. }
  374. /*
  375. SetExecLabel sets the SELinux label that the kernel will use for any programs
  376. that are executed by the current process thread, or an error.
  377. */
  378. func SetExecLabel(label string) error {
  379. return writeAttr("exec", label)
  380. }
  381. /*
  382. SetTaskLabel sets the SELinux label for the current thread, or an error.
  383. This requires the dyntransition permission.
  384. */
  385. func SetTaskLabel(label string) error {
  386. return writeAttr("current", label)
  387. }
  388. // SetSocketLabel takes a process label and tells the kernel to assign the
  389. // label to the next socket that gets created
  390. func SetSocketLabel(label string) error {
  391. return writeAttr("sockcreate", label)
  392. }
  393. // SocketLabel retrieves the current socket label setting
  394. func SocketLabel() (string, error) {
  395. return readAttr("sockcreate")
  396. }
  397. // PeerLabel retrieves the label of the client on the other side of a socket
  398. func PeerLabel(fd uintptr) (string, error) {
  399. return unix.GetsockoptString(int(fd), syscall.SOL_SOCKET, syscall.SO_PEERSEC)
  400. }
  401. // SetKeyLabel takes a process label and tells the kernel to assign the
  402. // label to the next kernel keyring that gets created
  403. func SetKeyLabel(label string) error {
  404. err := writeCon("/proc/self/attr/keycreate", label)
  405. if os.IsNotExist(err) {
  406. return nil
  407. }
  408. if label == "" && os.IsPermission(err) {
  409. return nil
  410. }
  411. return err
  412. }
  413. // KeyLabel retrieves the current kernel keyring label setting
  414. func KeyLabel() (string, error) {
  415. return readCon("/proc/self/attr/keycreate")
  416. }
  417. // Get returns the Context as a string
  418. func (c Context) Get() string {
  419. if c["level"] != "" {
  420. return fmt.Sprintf("%s:%s:%s:%s", c["user"], c["role"], c["type"], c["level"])
  421. }
  422. return fmt.Sprintf("%s:%s:%s", c["user"], c["role"], c["type"])
  423. }
  424. // NewContext creates a new Context struct from the specified label
  425. func NewContext(label string) (Context, error) {
  426. c := make(Context)
  427. if len(label) != 0 {
  428. con := strings.SplitN(label, ":", 4)
  429. if len(con) < 3 {
  430. return c, InvalidLabel
  431. }
  432. c["user"] = con[0]
  433. c["role"] = con[1]
  434. c["type"] = con[2]
  435. if len(con) > 3 {
  436. c["level"] = con[3]
  437. }
  438. }
  439. return c, nil
  440. }
  441. // ClearLabels clears all reserved labels
  442. func ClearLabels() {
  443. state.Lock()
  444. state.mcsList = make(map[string]bool)
  445. state.Unlock()
  446. }
  447. // ReserveLabel reserves the MLS/MCS level component of the specified label
  448. func ReserveLabel(label string) {
  449. if len(label) != 0 {
  450. con := strings.SplitN(label, ":", 4)
  451. if len(con) > 3 {
  452. mcsAdd(con[3])
  453. }
  454. }
  455. }
  456. func selinuxEnforcePath() string {
  457. return path.Join(getSelinuxMountPoint(), "enforce")
  458. }
  459. // EnforceMode returns the current SELinux mode Enforcing, Permissive, Disabled
  460. func EnforceMode() int {
  461. var enforce int
  462. enforceB, err := ioutil.ReadFile(selinuxEnforcePath())
  463. if err != nil {
  464. return -1
  465. }
  466. enforce, err = strconv.Atoi(string(enforceB))
  467. if err != nil {
  468. return -1
  469. }
  470. return enforce
  471. }
  472. /*
  473. SetEnforceMode sets the current SELinux mode Enforcing, Permissive.
  474. Disabled is not valid, since this needs to be set at boot time.
  475. */
  476. func SetEnforceMode(mode int) error {
  477. return ioutil.WriteFile(selinuxEnforcePath(), []byte(strconv.Itoa(mode)), 0644)
  478. }
  479. /*
  480. DefaultEnforceMode returns the systems default SELinux mode Enforcing,
  481. Permissive or Disabled. Note this is is just the default at boot time.
  482. EnforceMode tells you the systems current mode.
  483. */
  484. func DefaultEnforceMode() int {
  485. switch readConfig(selinuxTag) {
  486. case "enforcing":
  487. return Enforcing
  488. case "permissive":
  489. return Permissive
  490. }
  491. return Disabled
  492. }
  493. func mcsAdd(mcs string) error {
  494. if mcs == "" {
  495. return nil
  496. }
  497. state.Lock()
  498. defer state.Unlock()
  499. if state.mcsList[mcs] {
  500. return ErrMCSAlreadyExists
  501. }
  502. state.mcsList[mcs] = true
  503. return nil
  504. }
  505. func mcsDelete(mcs string) {
  506. if mcs == "" {
  507. return
  508. }
  509. state.Lock()
  510. defer state.Unlock()
  511. state.mcsList[mcs] = false
  512. }
  513. func intToMcs(id int, catRange uint32) string {
  514. var (
  515. SETSIZE = int(catRange)
  516. TIER = SETSIZE
  517. ORD = id
  518. )
  519. if id < 1 || id > 523776 {
  520. return ""
  521. }
  522. for ORD > TIER {
  523. ORD = ORD - TIER
  524. TIER--
  525. }
  526. TIER = SETSIZE - TIER
  527. ORD = ORD + TIER
  528. return fmt.Sprintf("s0:c%d,c%d", TIER, ORD)
  529. }
  530. func uniqMcs(catRange uint32) string {
  531. var (
  532. n uint32
  533. c1, c2 uint32
  534. mcs string
  535. )
  536. for {
  537. binary.Read(rand.Reader, binary.LittleEndian, &n)
  538. c1 = n % catRange
  539. binary.Read(rand.Reader, binary.LittleEndian, &n)
  540. c2 = n % catRange
  541. if c1 == c2 {
  542. continue
  543. } else {
  544. if c1 > c2 {
  545. c1, c2 = c2, c1
  546. }
  547. }
  548. mcs = fmt.Sprintf("s0:c%d,c%d", c1, c2)
  549. if err := mcsAdd(mcs); err != nil {
  550. continue
  551. }
  552. break
  553. }
  554. return mcs
  555. }
  556. /*
  557. ReleaseLabel will unreserve the MLS/MCS Level field of the specified label.
  558. Allowing it to be used by another process.
  559. */
  560. func ReleaseLabel(label string) {
  561. if len(label) != 0 {
  562. con := strings.SplitN(label, ":", 4)
  563. if len(con) > 3 {
  564. mcsDelete(con[3])
  565. }
  566. }
  567. }
  568. // ROFileLabel returns the specified SELinux readonly file label
  569. func ROFileLabel() string {
  570. return roFileLabel
  571. }
  572. /*
  573. ContainerLabels returns an allocated processLabel and fileLabel to be used for
  574. container labeling by the calling process.
  575. */
  576. func ContainerLabels() (processLabel string, fileLabel string) {
  577. var (
  578. val, key string
  579. bufin *bufio.Reader
  580. )
  581. if !GetEnabled() {
  582. return "", ""
  583. }
  584. lxcPath := fmt.Sprintf("%s/contexts/lxc_contexts", getSELinuxPolicyRoot())
  585. in, err := os.Open(lxcPath)
  586. if err != nil {
  587. return "", ""
  588. }
  589. defer in.Close()
  590. bufin = bufio.NewReader(in)
  591. for done := false; !done; {
  592. var line string
  593. if line, err = bufin.ReadString('\n'); err != nil {
  594. if err == io.EOF {
  595. done = true
  596. } else {
  597. goto exit
  598. }
  599. }
  600. line = strings.TrimSpace(line)
  601. if len(line) == 0 {
  602. // Skip blank lines
  603. continue
  604. }
  605. if line[0] == ';' || line[0] == '#' {
  606. // Skip comments
  607. continue
  608. }
  609. if groups := assignRegex.FindStringSubmatch(line); groups != nil {
  610. key, val = strings.TrimSpace(groups[1]), strings.TrimSpace(groups[2])
  611. if key == "process" {
  612. processLabel = strings.Trim(val, "\"")
  613. }
  614. if key == "file" {
  615. fileLabel = strings.Trim(val, "\"")
  616. }
  617. if key == "ro_file" {
  618. roFileLabel = strings.Trim(val, "\"")
  619. }
  620. }
  621. }
  622. if processLabel == "" || fileLabel == "" {
  623. return "", ""
  624. }
  625. if roFileLabel == "" {
  626. roFileLabel = fileLabel
  627. }
  628. exit:
  629. scon, _ := NewContext(processLabel)
  630. if scon["level"] != "" {
  631. mcs := uniqMcs(1024)
  632. scon["level"] = mcs
  633. processLabel = scon.Get()
  634. scon, _ = NewContext(fileLabel)
  635. scon["level"] = mcs
  636. fileLabel = scon.Get()
  637. }
  638. return processLabel, fileLabel
  639. }
  640. // SecurityCheckContext validates that the SELinux label is understood by the kernel
  641. func SecurityCheckContext(val string) error {
  642. return ioutil.WriteFile(path.Join(getSelinuxMountPoint(), "context"), []byte(val), 0644)
  643. }
  644. /*
  645. CopyLevel returns a label with the MLS/MCS level from src label replaced on
  646. the dest label.
  647. */
  648. func CopyLevel(src, dest string) (string, error) {
  649. if src == "" {
  650. return "", nil
  651. }
  652. if err := SecurityCheckContext(src); err != nil {
  653. return "", err
  654. }
  655. if err := SecurityCheckContext(dest); err != nil {
  656. return "", err
  657. }
  658. scon, err := NewContext(src)
  659. if err != nil {
  660. return "", err
  661. }
  662. tcon, err := NewContext(dest)
  663. if err != nil {
  664. return "", err
  665. }
  666. mcsDelete(tcon["level"])
  667. mcsAdd(scon["level"])
  668. tcon["level"] = scon["level"]
  669. return tcon.Get(), nil
  670. }
  671. // Prevent users from relabing system files
  672. func badPrefix(fpath string) error {
  673. if fpath == "" {
  674. return ErrEmptyPath
  675. }
  676. badPrefixes := []string{"/usr"}
  677. for _, prefix := range badPrefixes {
  678. if strings.HasPrefix(fpath, prefix) {
  679. return fmt.Errorf("relabeling content in %s is not allowed", prefix)
  680. }
  681. }
  682. return nil
  683. }
  684. // Chcon changes the `fpath` file object to the SELinux label `label`.
  685. // If `fpath` is a directory and `recurse`` is true, Chcon will walk the
  686. // directory tree setting the label.
  687. func Chcon(fpath string, label string, recurse bool) error {
  688. if fpath == "" {
  689. return ErrEmptyPath
  690. }
  691. if label == "" {
  692. return nil
  693. }
  694. if err := badPrefix(fpath); err != nil {
  695. return err
  696. }
  697. callback := func(p string, info os.FileInfo, err error) error {
  698. e := SetFileLabel(p, label)
  699. if os.IsNotExist(e) {
  700. return nil
  701. }
  702. return e
  703. }
  704. if recurse {
  705. return filepath.Walk(fpath, callback)
  706. }
  707. return SetFileLabel(fpath, label)
  708. }
  709. // DupSecOpt takes an SELinux process label and returns security options that
  710. // can be used to set the SELinux Type and Level for future container processes.
  711. func DupSecOpt(src string) ([]string, error) {
  712. if src == "" {
  713. return nil, nil
  714. }
  715. con, err := NewContext(src)
  716. if err != nil {
  717. return nil, err
  718. }
  719. if con["user"] == "" ||
  720. con["role"] == "" ||
  721. con["type"] == "" {
  722. return nil, nil
  723. }
  724. dup := []string{"user:" + con["user"],
  725. "role:" + con["role"],
  726. "type:" + con["type"],
  727. }
  728. if con["level"] != "" {
  729. dup = append(dup, "level:"+con["level"])
  730. }
  731. return dup, nil
  732. }
  733. // DisableSecOpt returns a security opt that can be used to disable SELinux
  734. // labeling support for future container processes.
  735. func DisableSecOpt() []string {
  736. return []string{"disable"}
  737. }