selinux_linux.go 24 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097
  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. "github.com/opencontainers/selinux/pkg/pwalk"
  19. "github.com/pkg/errors"
  20. "github.com/willf/bitset"
  21. "golang.org/x/sys/unix"
  22. )
  23. const (
  24. minSensLen = 2
  25. contextFile = "/usr/share/containers/selinux/contexts"
  26. selinuxDir = "/etc/selinux/"
  27. selinuxConfig = selinuxDir + "config"
  28. selinuxfsMount = "/sys/fs/selinux"
  29. selinuxTypeTag = "SELINUXTYPE"
  30. selinuxTag = "SELINUX"
  31. xattrNameSelinux = "security.selinux"
  32. )
  33. type selinuxState struct {
  34. enabledSet bool
  35. enabled bool
  36. selinuxfsOnce sync.Once
  37. selinuxfs string
  38. mcsList map[string]bool
  39. sync.Mutex
  40. }
  41. type level struct {
  42. sens uint
  43. cats *bitset.BitSet
  44. }
  45. type mlsRange struct {
  46. low *level
  47. high *level
  48. }
  49. type levelItem byte
  50. const (
  51. sensitivity levelItem = 's'
  52. category levelItem = 'c'
  53. )
  54. var (
  55. assignRegex = regexp.MustCompile(`^([^=]+)=(.*)$`)
  56. readOnlyFileLabel string
  57. state = selinuxState{
  58. mcsList: make(map[string]bool),
  59. }
  60. // for attrPath()
  61. attrPathOnce sync.Once
  62. haveThreadSelf bool
  63. )
  64. func (s *selinuxState) setEnable(enabled bool) bool {
  65. s.Lock()
  66. defer s.Unlock()
  67. s.enabledSet = true
  68. s.enabled = enabled
  69. return s.enabled
  70. }
  71. func (s *selinuxState) getEnabled() bool {
  72. s.Lock()
  73. enabled := s.enabled
  74. enabledSet := s.enabledSet
  75. s.Unlock()
  76. if enabledSet {
  77. return enabled
  78. }
  79. enabled = false
  80. if fs := getSelinuxMountPoint(); fs != "" {
  81. if con, _ := CurrentLabel(); con != "kernel" {
  82. enabled = true
  83. }
  84. }
  85. return s.setEnable(enabled)
  86. }
  87. // setDisabled disables SELinux support for the package
  88. func setDisabled() {
  89. state.setEnable(false)
  90. }
  91. func verifySELinuxfsMount(mnt string) bool {
  92. var buf unix.Statfs_t
  93. for {
  94. err := unix.Statfs(mnt, &buf)
  95. if err == nil {
  96. break
  97. }
  98. if err == unix.EAGAIN {
  99. continue
  100. }
  101. return false
  102. }
  103. if uint32(buf.Type) != uint32(unix.SELINUX_MAGIC) {
  104. return false
  105. }
  106. if (buf.Flags & unix.ST_RDONLY) != 0 {
  107. return false
  108. }
  109. return true
  110. }
  111. func findSELinuxfs() string {
  112. // fast path: check the default mount first
  113. if verifySELinuxfsMount(selinuxfsMount) {
  114. return selinuxfsMount
  115. }
  116. // check if selinuxfs is available before going the slow path
  117. fs, err := ioutil.ReadFile("/proc/filesystems")
  118. if err != nil {
  119. return ""
  120. }
  121. if !bytes.Contains(fs, []byte("\tselinuxfs\n")) {
  122. return ""
  123. }
  124. // slow path: try to find among the mounts
  125. f, err := os.Open("/proc/self/mountinfo")
  126. if err != nil {
  127. return ""
  128. }
  129. defer f.Close()
  130. scanner := bufio.NewScanner(f)
  131. for {
  132. mnt := findSELinuxfsMount(scanner)
  133. if mnt == "" { // error or not found
  134. return ""
  135. }
  136. if verifySELinuxfsMount(mnt) {
  137. return mnt
  138. }
  139. }
  140. }
  141. // findSELinuxfsMount returns a next selinuxfs mount point found,
  142. // if there is one, or an empty string in case of EOF or error.
  143. func findSELinuxfsMount(s *bufio.Scanner) string {
  144. for s.Scan() {
  145. txt := s.Bytes()
  146. // The first field after - is fs type.
  147. // Safe as spaces in mountpoints are encoded as \040
  148. if !bytes.Contains(txt, []byte(" - selinuxfs ")) {
  149. continue
  150. }
  151. const mPos = 5 // mount point is 5th field
  152. fields := bytes.SplitN(txt, []byte(" "), mPos+1)
  153. if len(fields) < mPos+1 {
  154. continue
  155. }
  156. return string(fields[mPos-1])
  157. }
  158. return ""
  159. }
  160. func (s *selinuxState) getSELinuxfs() string {
  161. s.selinuxfsOnce.Do(func() {
  162. s.selinuxfs = findSELinuxfs()
  163. })
  164. return s.selinuxfs
  165. }
  166. // getSelinuxMountPoint returns the path to the mountpoint of an selinuxfs
  167. // filesystem or an empty string if no mountpoint is found. Selinuxfs is
  168. // a proc-like pseudo-filesystem that exposes the SELinux policy API to
  169. // processes. The existence of an selinuxfs mount is used to determine
  170. // whether SELinux is currently enabled or not.
  171. func getSelinuxMountPoint() string {
  172. return state.getSELinuxfs()
  173. }
  174. // getEnabled returns whether SELinux is currently enabled.
  175. func getEnabled() bool {
  176. return state.getEnabled()
  177. }
  178. func readConfig(target string) string {
  179. var (
  180. val, key string
  181. bufin *bufio.Reader
  182. )
  183. in, err := os.Open(selinuxConfig)
  184. if err != nil {
  185. return ""
  186. }
  187. defer in.Close()
  188. bufin = bufio.NewReader(in)
  189. for done := false; !done; {
  190. var line string
  191. if line, err = bufin.ReadString('\n'); err != nil {
  192. if err != io.EOF {
  193. return ""
  194. }
  195. done = true
  196. }
  197. line = strings.TrimSpace(line)
  198. if len(line) == 0 {
  199. // Skip blank lines
  200. continue
  201. }
  202. if line[0] == ';' || line[0] == '#' {
  203. // Skip comments
  204. continue
  205. }
  206. if groups := assignRegex.FindStringSubmatch(line); groups != nil {
  207. key, val = strings.TrimSpace(groups[1]), strings.TrimSpace(groups[2])
  208. if key == target {
  209. return strings.Trim(val, "\"")
  210. }
  211. }
  212. }
  213. return ""
  214. }
  215. func getSELinuxPolicyRoot() string {
  216. return filepath.Join(selinuxDir, readConfig(selinuxTypeTag))
  217. }
  218. func isProcHandle(fh *os.File) error {
  219. var buf unix.Statfs_t
  220. err := unix.Fstatfs(int(fh.Fd()), &buf)
  221. if err != nil {
  222. return errors.Wrapf(err, "statfs(%q) failed", fh.Name())
  223. }
  224. if buf.Type != unix.PROC_SUPER_MAGIC {
  225. return errors.Errorf("file %q is not on procfs", fh.Name())
  226. }
  227. return nil
  228. }
  229. func readCon(fpath string) (string, error) {
  230. if fpath == "" {
  231. return "", ErrEmptyPath
  232. }
  233. in, err := os.Open(fpath)
  234. if err != nil {
  235. return "", err
  236. }
  237. defer in.Close()
  238. if err := isProcHandle(in); err != nil {
  239. return "", err
  240. }
  241. var retval string
  242. if _, err := fmt.Fscanf(in, "%s", &retval); err != nil {
  243. return "", err
  244. }
  245. return strings.Trim(retval, "\x00"), nil
  246. }
  247. // classIndex returns the int index for an object class in the loaded policy,
  248. // or -1 and an error
  249. func classIndex(class string) (int, error) {
  250. permpath := fmt.Sprintf("class/%s/index", class)
  251. indexpath := filepath.Join(getSelinuxMountPoint(), permpath)
  252. indexB, err := ioutil.ReadFile(indexpath)
  253. if err != nil {
  254. return -1, err
  255. }
  256. index, err := strconv.Atoi(string(indexB))
  257. if err != nil {
  258. return -1, err
  259. }
  260. return index, nil
  261. }
  262. // setFileLabel sets the SELinux label for this path or returns an error.
  263. func setFileLabel(fpath string, label string) error {
  264. if fpath == "" {
  265. return ErrEmptyPath
  266. }
  267. if err := unix.Lsetxattr(fpath, xattrNameSelinux, []byte(label), 0); err != nil {
  268. return errors.Wrapf(err, "failed to set file label on %s", fpath)
  269. }
  270. return nil
  271. }
  272. // fileLabel returns the SELinux label for this path or returns an error.
  273. func fileLabel(fpath string) (string, error) {
  274. if fpath == "" {
  275. return "", ErrEmptyPath
  276. }
  277. label, err := lgetxattr(fpath, xattrNameSelinux)
  278. if err != nil {
  279. return "", err
  280. }
  281. // Trim the NUL byte at the end of the byte buffer, if present.
  282. if len(label) > 0 && label[len(label)-1] == '\x00' {
  283. label = label[:len(label)-1]
  284. }
  285. return string(label), nil
  286. }
  287. // setFSCreateLabel tells kernel the label to create all file system objects
  288. // created by this task. Setting label="" to return to default.
  289. func setFSCreateLabel(label string) error {
  290. return writeAttr("fscreate", label)
  291. }
  292. // fsCreateLabel returns the default label the kernel which the kernel is using
  293. // for file system objects created by this task. "" indicates default.
  294. func fsCreateLabel() (string, error) {
  295. return readAttr("fscreate")
  296. }
  297. // currentLabel returns the SELinux label of the current process thread, or an error.
  298. func currentLabel() (string, error) {
  299. return readAttr("current")
  300. }
  301. // pidLabel returns the SELinux label of the given pid, or an error.
  302. func pidLabel(pid int) (string, error) {
  303. return readCon(fmt.Sprintf("/proc/%d/attr/current", pid))
  304. }
  305. // ExecLabel returns the SELinux label that the kernel will use for any programs
  306. // that are executed by the current process thread, or an error.
  307. func execLabel() (string, error) {
  308. return readAttr("exec")
  309. }
  310. func writeCon(fpath, val string) error {
  311. if fpath == "" {
  312. return ErrEmptyPath
  313. }
  314. if val == "" {
  315. if !getEnabled() {
  316. return nil
  317. }
  318. }
  319. out, err := os.OpenFile(fpath, os.O_WRONLY, 0)
  320. if err != nil {
  321. return err
  322. }
  323. defer out.Close()
  324. if err := isProcHandle(out); err != nil {
  325. return err
  326. }
  327. if val != "" {
  328. _, err = out.Write([]byte(val))
  329. } else {
  330. _, err = out.Write(nil)
  331. }
  332. if err != nil {
  333. return errors.Wrapf(err, "failed to set %s on procfs", fpath)
  334. }
  335. return nil
  336. }
  337. func attrPath(attr string) string {
  338. // Linux >= 3.17 provides this
  339. const threadSelfPrefix = "/proc/thread-self/attr"
  340. attrPathOnce.Do(func() {
  341. st, err := os.Stat(threadSelfPrefix)
  342. if err == nil && st.Mode().IsDir() {
  343. haveThreadSelf = true
  344. }
  345. })
  346. if haveThreadSelf {
  347. return path.Join(threadSelfPrefix, attr)
  348. }
  349. return path.Join("/proc/self/task/", strconv.Itoa(unix.Gettid()), "/attr/", attr)
  350. }
  351. func readAttr(attr string) (string, error) {
  352. return readCon(attrPath(attr))
  353. }
  354. func writeAttr(attr, val string) error {
  355. return writeCon(attrPath(attr), val)
  356. }
  357. // canonicalizeContext takes a context string and writes it to the kernel
  358. // the function then returns the context that the kernel will use. Use this
  359. // function to check if two contexts are equivalent
  360. func canonicalizeContext(val string) (string, error) {
  361. return readWriteCon(filepath.Join(getSelinuxMountPoint(), "context"), val)
  362. }
  363. // computeCreateContext requests the type transition from source to target for
  364. // class from the kernel.
  365. func computeCreateContext(source string, target string, class string) (string, error) {
  366. classidx, err := classIndex(class)
  367. if err != nil {
  368. return "", err
  369. }
  370. return readWriteCon(filepath.Join(getSelinuxMountPoint(), "create"), fmt.Sprintf("%s %s %d", source, target, classidx))
  371. }
  372. // catsToBitset stores categories in a bitset.
  373. func catsToBitset(cats string) (*bitset.BitSet, error) {
  374. bitset := &bitset.BitSet{}
  375. catlist := strings.Split(cats, ",")
  376. for _, r := range catlist {
  377. ranges := strings.SplitN(r, ".", 2)
  378. if len(ranges) > 1 {
  379. catstart, err := parseLevelItem(ranges[0], category)
  380. if err != nil {
  381. return nil, err
  382. }
  383. catend, err := parseLevelItem(ranges[1], category)
  384. if err != nil {
  385. return nil, err
  386. }
  387. for i := catstart; i <= catend; i++ {
  388. bitset.Set(i)
  389. }
  390. } else {
  391. cat, err := parseLevelItem(ranges[0], category)
  392. if err != nil {
  393. return nil, err
  394. }
  395. bitset.Set(cat)
  396. }
  397. }
  398. return bitset, nil
  399. }
  400. // parseLevelItem parses and verifies that a sensitivity or category are valid
  401. func parseLevelItem(s string, sep levelItem) (uint, error) {
  402. if len(s) < minSensLen || levelItem(s[0]) != sep {
  403. return 0, ErrLevelSyntax
  404. }
  405. val, err := strconv.ParseUint(s[1:], 10, 32)
  406. if err != nil {
  407. return 0, err
  408. }
  409. return uint(val), nil
  410. }
  411. // parseLevel fills a level from a string that contains
  412. // a sensitivity and categories
  413. func (l *level) parseLevel(levelStr string) error {
  414. lvl := strings.SplitN(levelStr, ":", 2)
  415. sens, err := parseLevelItem(lvl[0], sensitivity)
  416. if err != nil {
  417. return errors.Wrap(err, "failed to parse sensitivity")
  418. }
  419. l.sens = sens
  420. if len(lvl) > 1 {
  421. cats, err := catsToBitset(lvl[1])
  422. if err != nil {
  423. return errors.Wrap(err, "failed to parse categories")
  424. }
  425. l.cats = cats
  426. }
  427. return nil
  428. }
  429. // rangeStrToMLSRange marshals a string representation of a range.
  430. func rangeStrToMLSRange(rangeStr string) (*mlsRange, error) {
  431. mlsRange := &mlsRange{}
  432. levelSlice := strings.SplitN(rangeStr, "-", 2)
  433. switch len(levelSlice) {
  434. // rangeStr that has a low and a high level, e.g. s4:c0.c1023-s6:c0.c1023
  435. case 2:
  436. mlsRange.high = &level{}
  437. if err := mlsRange.high.parseLevel(levelSlice[1]); err != nil {
  438. return nil, errors.Wrapf(err, "failed to parse high level %q", levelSlice[1])
  439. }
  440. fallthrough
  441. // rangeStr that is single level, e.g. s6:c0,c3,c5,c30.c1023
  442. case 1:
  443. mlsRange.low = &level{}
  444. if err := mlsRange.low.parseLevel(levelSlice[0]); err != nil {
  445. return nil, errors.Wrapf(err, "failed to parse low level %q", levelSlice[0])
  446. }
  447. }
  448. if mlsRange.high == nil {
  449. mlsRange.high = mlsRange.low
  450. }
  451. return mlsRange, nil
  452. }
  453. // bitsetToStr takes a category bitset and returns it in the
  454. // canonical selinux syntax
  455. func bitsetToStr(c *bitset.BitSet) string {
  456. var str string
  457. i, e := c.NextSet(0)
  458. len := 0
  459. for e {
  460. if len == 0 {
  461. if str != "" {
  462. str += ","
  463. }
  464. str += "c" + strconv.Itoa(int(i))
  465. }
  466. next, e := c.NextSet(i + 1)
  467. if e {
  468. // consecutive cats
  469. if next == i+1 {
  470. len++
  471. i = next
  472. continue
  473. }
  474. }
  475. if len == 1 {
  476. str += ",c" + strconv.Itoa(int(i))
  477. } else if len > 1 {
  478. str += ".c" + strconv.Itoa(int(i))
  479. }
  480. if !e {
  481. break
  482. }
  483. len = 0
  484. i = next
  485. }
  486. return str
  487. }
  488. func (l1 *level) equal(l2 *level) bool {
  489. if l2 == nil || l1 == nil {
  490. return l1 == l2
  491. }
  492. if l1.sens != l2.sens {
  493. return false
  494. }
  495. return l1.cats.Equal(l2.cats)
  496. }
  497. // String returns an mlsRange as a string.
  498. func (m mlsRange) String() string {
  499. low := "s" + strconv.Itoa(int(m.low.sens))
  500. if m.low.cats != nil && m.low.cats.Count() > 0 {
  501. low += ":" + bitsetToStr(m.low.cats)
  502. }
  503. if m.low.equal(m.high) {
  504. return low
  505. }
  506. high := "s" + strconv.Itoa(int(m.high.sens))
  507. if m.high.cats != nil && m.high.cats.Count() > 0 {
  508. high += ":" + bitsetToStr(m.high.cats)
  509. }
  510. return low + "-" + high
  511. }
  512. func max(a, b uint) uint {
  513. if a > b {
  514. return a
  515. }
  516. return b
  517. }
  518. func min(a, b uint) uint {
  519. if a < b {
  520. return a
  521. }
  522. return b
  523. }
  524. // calculateGlbLub computes the glb (greatest lower bound) and lub (least upper bound)
  525. // of a source and target range.
  526. // The glblub is calculated as the greater of the low sensitivities and
  527. // the lower of the high sensitivities and the and of each category bitset.
  528. func calculateGlbLub(sourceRange, targetRange string) (string, error) {
  529. s, err := rangeStrToMLSRange(sourceRange)
  530. if err != nil {
  531. return "", err
  532. }
  533. t, err := rangeStrToMLSRange(targetRange)
  534. if err != nil {
  535. return "", err
  536. }
  537. if s.high.sens < t.low.sens || t.high.sens < s.low.sens {
  538. /* these ranges have no common sensitivities */
  539. return "", ErrIncomparable
  540. }
  541. outrange := &mlsRange{low: &level{}, high: &level{}}
  542. /* take the greatest of the low */
  543. outrange.low.sens = max(s.low.sens, t.low.sens)
  544. /* take the least of the high */
  545. outrange.high.sens = min(s.high.sens, t.high.sens)
  546. /* find the intersecting categories */
  547. if s.low.cats != nil && t.low.cats != nil {
  548. outrange.low.cats = s.low.cats.Intersection(t.low.cats)
  549. }
  550. if s.high.cats != nil && t.high.cats != nil {
  551. outrange.high.cats = s.high.cats.Intersection(t.high.cats)
  552. }
  553. return outrange.String(), nil
  554. }
  555. func readWriteCon(fpath string, val string) (string, error) {
  556. if fpath == "" {
  557. return "", ErrEmptyPath
  558. }
  559. f, err := os.OpenFile(fpath, os.O_RDWR, 0)
  560. if err != nil {
  561. return "", err
  562. }
  563. defer f.Close()
  564. _, err = f.Write([]byte(val))
  565. if err != nil {
  566. return "", err
  567. }
  568. var retval string
  569. if _, err := fmt.Fscanf(f, "%s", &retval); err != nil {
  570. return "", err
  571. }
  572. return strings.Trim(retval, "\x00"), nil
  573. }
  574. // setExecLabel sets the SELinux label that the kernel will use for any programs
  575. // that are executed by the current process thread, or an error.
  576. func setExecLabel(label string) error {
  577. return writeAttr("exec", label)
  578. }
  579. // setTaskLabel sets the SELinux label for the current thread, or an error.
  580. // This requires the dyntransition permission.
  581. func setTaskLabel(label string) error {
  582. return writeAttr("current", label)
  583. }
  584. // setSocketLabel takes a process label and tells the kernel to assign the
  585. // label to the next socket that gets created
  586. func setSocketLabel(label string) error {
  587. return writeAttr("sockcreate", label)
  588. }
  589. // socketLabel retrieves the current socket label setting
  590. func socketLabel() (string, error) {
  591. return readAttr("sockcreate")
  592. }
  593. // peerLabel retrieves the label of the client on the other side of a socket
  594. func peerLabel(fd uintptr) (string, error) {
  595. return unix.GetsockoptString(int(fd), unix.SOL_SOCKET, unix.SO_PEERSEC)
  596. }
  597. // setKeyLabel takes a process label and tells the kernel to assign the
  598. // label to the next kernel keyring that gets created
  599. func setKeyLabel(label string) error {
  600. err := writeCon("/proc/self/attr/keycreate", label)
  601. if os.IsNotExist(errors.Cause(err)) {
  602. return nil
  603. }
  604. if label == "" && os.IsPermission(errors.Cause(err)) {
  605. return nil
  606. }
  607. return err
  608. }
  609. // keyLabel retrieves the current kernel keyring label setting
  610. func keyLabel() (string, error) {
  611. return readCon("/proc/self/attr/keycreate")
  612. }
  613. // get returns the Context as a string
  614. func (c Context) get() string {
  615. if c["level"] != "" {
  616. return fmt.Sprintf("%s:%s:%s:%s", c["user"], c["role"], c["type"], c["level"])
  617. }
  618. return fmt.Sprintf("%s:%s:%s", c["user"], c["role"], c["type"])
  619. }
  620. // newContext creates a new Context struct from the specified label
  621. func newContext(label string) (Context, error) {
  622. c := make(Context)
  623. if len(label) != 0 {
  624. con := strings.SplitN(label, ":", 4)
  625. if len(con) < 3 {
  626. return c, InvalidLabel
  627. }
  628. c["user"] = con[0]
  629. c["role"] = con[1]
  630. c["type"] = con[2]
  631. if len(con) > 3 {
  632. c["level"] = con[3]
  633. }
  634. }
  635. return c, nil
  636. }
  637. // clearLabels clears all reserved labels
  638. func clearLabels() {
  639. state.Lock()
  640. state.mcsList = make(map[string]bool)
  641. state.Unlock()
  642. }
  643. // reserveLabel reserves the MLS/MCS level component of the specified label
  644. func reserveLabel(label string) {
  645. if len(label) != 0 {
  646. con := strings.SplitN(label, ":", 4)
  647. if len(con) > 3 {
  648. mcsAdd(con[3])
  649. }
  650. }
  651. }
  652. func selinuxEnforcePath() string {
  653. return path.Join(getSelinuxMountPoint(), "enforce")
  654. }
  655. // enforceMode returns the current SELinux mode Enforcing, Permissive, Disabled
  656. func enforceMode() int {
  657. var enforce int
  658. enforceB, err := ioutil.ReadFile(selinuxEnforcePath())
  659. if err != nil {
  660. return -1
  661. }
  662. enforce, err = strconv.Atoi(string(enforceB))
  663. if err != nil {
  664. return -1
  665. }
  666. return enforce
  667. }
  668. // setEnforceMode sets the current SELinux mode Enforcing, Permissive.
  669. // Disabled is not valid, since this needs to be set at boot time.
  670. func setEnforceMode(mode int) error {
  671. return ioutil.WriteFile(selinuxEnforcePath(), []byte(strconv.Itoa(mode)), 0644)
  672. }
  673. // defaultEnforceMode returns the systems default SELinux mode Enforcing,
  674. // Permissive or Disabled. Note this is is just the default at boot time.
  675. // EnforceMode tells you the systems current mode.
  676. func defaultEnforceMode() int {
  677. switch readConfig(selinuxTag) {
  678. case "enforcing":
  679. return Enforcing
  680. case "permissive":
  681. return Permissive
  682. }
  683. return Disabled
  684. }
  685. func mcsAdd(mcs string) error {
  686. if mcs == "" {
  687. return nil
  688. }
  689. state.Lock()
  690. defer state.Unlock()
  691. if state.mcsList[mcs] {
  692. return ErrMCSAlreadyExists
  693. }
  694. state.mcsList[mcs] = true
  695. return nil
  696. }
  697. func mcsDelete(mcs string) {
  698. if mcs == "" {
  699. return
  700. }
  701. state.Lock()
  702. defer state.Unlock()
  703. state.mcsList[mcs] = false
  704. }
  705. func intToMcs(id int, catRange uint32) string {
  706. var (
  707. SETSIZE = int(catRange)
  708. TIER = SETSIZE
  709. ORD = id
  710. )
  711. if id < 1 || id > 523776 {
  712. return ""
  713. }
  714. for ORD > TIER {
  715. ORD = ORD - TIER
  716. TIER--
  717. }
  718. TIER = SETSIZE - TIER
  719. ORD = ORD + TIER
  720. return fmt.Sprintf("s0:c%d,c%d", TIER, ORD)
  721. }
  722. func uniqMcs(catRange uint32) string {
  723. var (
  724. n uint32
  725. c1, c2 uint32
  726. mcs string
  727. )
  728. for {
  729. binary.Read(rand.Reader, binary.LittleEndian, &n)
  730. c1 = n % catRange
  731. binary.Read(rand.Reader, binary.LittleEndian, &n)
  732. c2 = n % catRange
  733. if c1 == c2 {
  734. continue
  735. } else {
  736. if c1 > c2 {
  737. c1, c2 = c2, c1
  738. }
  739. }
  740. mcs = fmt.Sprintf("s0:c%d,c%d", c1, c2)
  741. if err := mcsAdd(mcs); err != nil {
  742. continue
  743. }
  744. break
  745. }
  746. return mcs
  747. }
  748. // releaseLabel un-reserves the MLS/MCS Level field of the specified label,
  749. // allowing it to be used by another process.
  750. func releaseLabel(label string) {
  751. if len(label) != 0 {
  752. con := strings.SplitN(label, ":", 4)
  753. if len(con) > 3 {
  754. mcsDelete(con[3])
  755. }
  756. }
  757. }
  758. // roFileLabel returns the specified SELinux readonly file label
  759. func roFileLabel() string {
  760. return readOnlyFileLabel
  761. }
  762. func openContextFile() (*os.File, error) {
  763. if f, err := os.Open(contextFile); err == nil {
  764. return f, nil
  765. }
  766. lxcPath := filepath.Join(getSELinuxPolicyRoot(), "/contexts/lxc_contexts")
  767. return os.Open(lxcPath)
  768. }
  769. var labels = loadLabels()
  770. func loadLabels() map[string]string {
  771. var (
  772. val, key string
  773. bufin *bufio.Reader
  774. )
  775. labels := make(map[string]string)
  776. in, err := openContextFile()
  777. if err != nil {
  778. return labels
  779. }
  780. defer in.Close()
  781. bufin = bufio.NewReader(in)
  782. for done := false; !done; {
  783. var line string
  784. if line, err = bufin.ReadString('\n'); err != nil {
  785. if err == io.EOF {
  786. done = true
  787. } else {
  788. break
  789. }
  790. }
  791. line = strings.TrimSpace(line)
  792. if len(line) == 0 {
  793. // Skip blank lines
  794. continue
  795. }
  796. if line[0] == ';' || line[0] == '#' {
  797. // Skip comments
  798. continue
  799. }
  800. if groups := assignRegex.FindStringSubmatch(line); groups != nil {
  801. key, val = strings.TrimSpace(groups[1]), strings.TrimSpace(groups[2])
  802. labels[key] = strings.Trim(val, "\"")
  803. }
  804. }
  805. return labels
  806. }
  807. // kvmContainerLabels returns the default processLabel and mountLabel to be used
  808. // for kvm containers by the calling process.
  809. func kvmContainerLabels() (string, string) {
  810. processLabel := labels["kvm_process"]
  811. if processLabel == "" {
  812. processLabel = labels["process"]
  813. }
  814. return addMcs(processLabel, labels["file"])
  815. }
  816. // initContainerLabels returns the default processLabel and file labels to be
  817. // used for containers running an init system like systemd by the calling process.
  818. func initContainerLabels() (string, string) {
  819. processLabel := labels["init_process"]
  820. if processLabel == "" {
  821. processLabel = labels["process"]
  822. }
  823. return addMcs(processLabel, labels["file"])
  824. }
  825. // containerLabels returns an allocated processLabel and fileLabel to be used for
  826. // container labeling by the calling process.
  827. func containerLabels() (processLabel string, fileLabel string) {
  828. if !getEnabled() {
  829. return "", ""
  830. }
  831. processLabel = labels["process"]
  832. fileLabel = labels["file"]
  833. readOnlyFileLabel = labels["ro_file"]
  834. if processLabel == "" || fileLabel == "" {
  835. return "", fileLabel
  836. }
  837. if readOnlyFileLabel == "" {
  838. readOnlyFileLabel = fileLabel
  839. }
  840. return addMcs(processLabel, fileLabel)
  841. }
  842. func addMcs(processLabel, fileLabel string) (string, string) {
  843. scon, _ := NewContext(processLabel)
  844. if scon["level"] != "" {
  845. mcs := uniqMcs(CategoryRange)
  846. scon["level"] = mcs
  847. processLabel = scon.Get()
  848. scon, _ = NewContext(fileLabel)
  849. scon["level"] = mcs
  850. fileLabel = scon.Get()
  851. }
  852. return processLabel, fileLabel
  853. }
  854. // securityCheckContext validates that the SELinux label is understood by the kernel
  855. func securityCheckContext(val string) error {
  856. return ioutil.WriteFile(path.Join(getSelinuxMountPoint(), "context"), []byte(val), 0644)
  857. }
  858. // copyLevel returns a label with the MLS/MCS level from src label replaced on
  859. // the dest label.
  860. func copyLevel(src, dest string) (string, error) {
  861. if src == "" {
  862. return "", nil
  863. }
  864. if err := SecurityCheckContext(src); err != nil {
  865. return "", err
  866. }
  867. if err := SecurityCheckContext(dest); err != nil {
  868. return "", err
  869. }
  870. scon, err := NewContext(src)
  871. if err != nil {
  872. return "", err
  873. }
  874. tcon, err := NewContext(dest)
  875. if err != nil {
  876. return "", err
  877. }
  878. mcsDelete(tcon["level"])
  879. mcsAdd(scon["level"])
  880. tcon["level"] = scon["level"]
  881. return tcon.Get(), nil
  882. }
  883. // Prevent users from relabeling system files
  884. func badPrefix(fpath string) error {
  885. if fpath == "" {
  886. return ErrEmptyPath
  887. }
  888. badPrefixes := []string{"/usr"}
  889. for _, prefix := range badPrefixes {
  890. if strings.HasPrefix(fpath, prefix) {
  891. return errors.Errorf("relabeling content in %s is not allowed", prefix)
  892. }
  893. }
  894. return nil
  895. }
  896. // chcon changes the fpath file object to the SELinux label label.
  897. // If fpath is a directory and recurse is true, then chcon walks the
  898. // directory tree setting the label.
  899. func chcon(fpath string, label string, recurse bool) error {
  900. if fpath == "" {
  901. return ErrEmptyPath
  902. }
  903. if label == "" {
  904. return nil
  905. }
  906. if err := badPrefix(fpath); err != nil {
  907. return err
  908. }
  909. if !recurse {
  910. return SetFileLabel(fpath, label)
  911. }
  912. return pwalk.Walk(fpath, func(p string, info os.FileInfo, err error) error {
  913. e := SetFileLabel(p, label)
  914. // Walk a file tree can race with removal, so ignore ENOENT
  915. if os.IsNotExist(errors.Cause(e)) {
  916. return nil
  917. }
  918. return e
  919. })
  920. }
  921. // dupSecOpt takes an SELinux process label and returns security options that
  922. // can be used to set the SELinux Type and Level for future container processes.
  923. func dupSecOpt(src string) ([]string, error) {
  924. if src == "" {
  925. return nil, nil
  926. }
  927. con, err := NewContext(src)
  928. if err != nil {
  929. return nil, err
  930. }
  931. if con["user"] == "" ||
  932. con["role"] == "" ||
  933. con["type"] == "" {
  934. return nil, nil
  935. }
  936. dup := []string{"user:" + con["user"],
  937. "role:" + con["role"],
  938. "type:" + con["type"],
  939. }
  940. if con["level"] != "" {
  941. dup = append(dup, "level:"+con["level"])
  942. }
  943. return dup, nil
  944. }
  945. // disableSecOpt returns a security opt that can be used to disable SELinux
  946. // labeling support for future container processes.
  947. func disableSecOpt() []string {
  948. return []string{"disable"}
  949. }