selinux_linux.go 29 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295
  1. package selinux
  2. import (
  3. "bufio"
  4. "bytes"
  5. "crypto/rand"
  6. "encoding/binary"
  7. "errors"
  8. "fmt"
  9. "io"
  10. "io/fs"
  11. "math/big"
  12. "os"
  13. "os/user"
  14. "path/filepath"
  15. "strconv"
  16. "strings"
  17. "sync"
  18. "github.com/opencontainers/selinux/pkg/pwalkdir"
  19. "golang.org/x/sys/unix"
  20. )
  21. const (
  22. minSensLen = 2
  23. contextFile = "/usr/share/containers/selinux/contexts"
  24. selinuxDir = "/etc/selinux/"
  25. selinuxUsersDir = "contexts/users"
  26. defaultContexts = "contexts/default_contexts"
  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. mcsList map[string]bool
  35. selinuxfs string
  36. selinuxfsOnce sync.Once
  37. enabledSet bool
  38. enabled bool
  39. sync.Mutex
  40. }
  41. type level struct {
  42. cats *big.Int
  43. sens uint
  44. }
  45. type mlsRange struct {
  46. low *level
  47. high *level
  48. }
  49. type defaultSECtx struct {
  50. userRdr io.Reader
  51. verifier func(string) error
  52. defaultRdr io.Reader
  53. user, level, scon string
  54. }
  55. type levelItem byte
  56. const (
  57. sensitivity levelItem = 's'
  58. category levelItem = 'c'
  59. )
  60. var (
  61. readOnlyFileLabel string
  62. state = selinuxState{
  63. mcsList: make(map[string]bool),
  64. }
  65. // for attrPath()
  66. attrPathOnce sync.Once
  67. haveThreadSelf bool
  68. // for policyRoot()
  69. policyRootOnce sync.Once
  70. policyRootVal string
  71. // for label()
  72. loadLabelsOnce sync.Once
  73. labels map[string]string
  74. )
  75. func policyRoot() string {
  76. policyRootOnce.Do(func() {
  77. policyRootVal = filepath.Join(selinuxDir, readConfig(selinuxTypeTag))
  78. })
  79. return policyRootVal
  80. }
  81. func (s *selinuxState) setEnable(enabled bool) bool {
  82. s.Lock()
  83. defer s.Unlock()
  84. s.enabledSet = true
  85. s.enabled = enabled
  86. return s.enabled
  87. }
  88. func (s *selinuxState) getEnabled() bool {
  89. s.Lock()
  90. enabled := s.enabled
  91. enabledSet := s.enabledSet
  92. s.Unlock()
  93. if enabledSet {
  94. return enabled
  95. }
  96. enabled = false
  97. if fs := getSelinuxMountPoint(); fs != "" {
  98. if con, _ := CurrentLabel(); con != "kernel" {
  99. enabled = true
  100. }
  101. }
  102. return s.setEnable(enabled)
  103. }
  104. // setDisabled disables SELinux support for the package
  105. func setDisabled() {
  106. state.setEnable(false)
  107. }
  108. func verifySELinuxfsMount(mnt string) bool {
  109. var buf unix.Statfs_t
  110. for {
  111. err := unix.Statfs(mnt, &buf)
  112. if err == nil {
  113. break
  114. }
  115. if err == unix.EAGAIN || err == unix.EINTR { //nolint:errorlint // unix errors are bare
  116. continue
  117. }
  118. return false
  119. }
  120. if uint32(buf.Type) != uint32(unix.SELINUX_MAGIC) {
  121. return false
  122. }
  123. if (buf.Flags & unix.ST_RDONLY) != 0 {
  124. return false
  125. }
  126. return true
  127. }
  128. func findSELinuxfs() string {
  129. // fast path: check the default mount first
  130. if verifySELinuxfsMount(selinuxfsMount) {
  131. return selinuxfsMount
  132. }
  133. // check if selinuxfs is available before going the slow path
  134. fs, err := os.ReadFile("/proc/filesystems")
  135. if err != nil {
  136. return ""
  137. }
  138. if !bytes.Contains(fs, []byte("\tselinuxfs\n")) {
  139. return ""
  140. }
  141. // slow path: try to find among the mounts
  142. f, err := os.Open("/proc/self/mountinfo")
  143. if err != nil {
  144. return ""
  145. }
  146. defer f.Close()
  147. scanner := bufio.NewScanner(f)
  148. for {
  149. mnt := findSELinuxfsMount(scanner)
  150. if mnt == "" { // error or not found
  151. return ""
  152. }
  153. if verifySELinuxfsMount(mnt) {
  154. return mnt
  155. }
  156. }
  157. }
  158. // findSELinuxfsMount returns a next selinuxfs mount point found,
  159. // if there is one, or an empty string in case of EOF or error.
  160. func findSELinuxfsMount(s *bufio.Scanner) string {
  161. for s.Scan() {
  162. txt := s.Bytes()
  163. // The first field after - is fs type.
  164. // Safe as spaces in mountpoints are encoded as \040
  165. if !bytes.Contains(txt, []byte(" - selinuxfs ")) {
  166. continue
  167. }
  168. const mPos = 5 // mount point is 5th field
  169. fields := bytes.SplitN(txt, []byte(" "), mPos+1)
  170. if len(fields) < mPos+1 {
  171. continue
  172. }
  173. return string(fields[mPos-1])
  174. }
  175. return ""
  176. }
  177. func (s *selinuxState) getSELinuxfs() string {
  178. s.selinuxfsOnce.Do(func() {
  179. s.selinuxfs = findSELinuxfs()
  180. })
  181. return s.selinuxfs
  182. }
  183. // getSelinuxMountPoint returns the path to the mountpoint of an selinuxfs
  184. // filesystem or an empty string if no mountpoint is found. Selinuxfs is
  185. // a proc-like pseudo-filesystem that exposes the SELinux policy API to
  186. // processes. The existence of an selinuxfs mount is used to determine
  187. // whether SELinux is currently enabled or not.
  188. func getSelinuxMountPoint() string {
  189. return state.getSELinuxfs()
  190. }
  191. // getEnabled returns whether SELinux is currently enabled.
  192. func getEnabled() bool {
  193. return state.getEnabled()
  194. }
  195. func readConfig(target string) string {
  196. in, err := os.Open(selinuxConfig)
  197. if err != nil {
  198. return ""
  199. }
  200. defer in.Close()
  201. scanner := bufio.NewScanner(in)
  202. for scanner.Scan() {
  203. line := bytes.TrimSpace(scanner.Bytes())
  204. if len(line) == 0 {
  205. // Skip blank lines
  206. continue
  207. }
  208. if line[0] == ';' || line[0] == '#' {
  209. // Skip comments
  210. continue
  211. }
  212. fields := bytes.SplitN(line, []byte{'='}, 2)
  213. if len(fields) != 2 {
  214. continue
  215. }
  216. if bytes.Equal(fields[0], []byte(target)) {
  217. return string(bytes.Trim(fields[1], `"`))
  218. }
  219. }
  220. return ""
  221. }
  222. func isProcHandle(fh *os.File) error {
  223. var buf unix.Statfs_t
  224. for {
  225. err := unix.Fstatfs(int(fh.Fd()), &buf)
  226. if err == nil {
  227. break
  228. }
  229. if err != unix.EINTR { //nolint:errorlint // unix errors are bare
  230. return &os.PathError{Op: "fstatfs", Path: fh.Name(), Err: err}
  231. }
  232. }
  233. if buf.Type != unix.PROC_SUPER_MAGIC {
  234. return fmt.Errorf("file %q is not on procfs", fh.Name())
  235. }
  236. return nil
  237. }
  238. func readCon(fpath string) (string, error) {
  239. if fpath == "" {
  240. return "", ErrEmptyPath
  241. }
  242. in, err := os.Open(fpath)
  243. if err != nil {
  244. return "", err
  245. }
  246. defer in.Close()
  247. if err := isProcHandle(in); err != nil {
  248. return "", err
  249. }
  250. return readConFd(in)
  251. }
  252. func readConFd(in *os.File) (string, error) {
  253. data, err := io.ReadAll(in)
  254. if err != nil {
  255. return "", err
  256. }
  257. return string(bytes.TrimSuffix(data, []byte{0})), nil
  258. }
  259. // classIndex returns the int index for an object class in the loaded policy,
  260. // or -1 and an error
  261. func classIndex(class string) (int, error) {
  262. permpath := fmt.Sprintf("class/%s/index", class)
  263. indexpath := filepath.Join(getSelinuxMountPoint(), permpath)
  264. indexB, err := os.ReadFile(indexpath)
  265. if err != nil {
  266. return -1, err
  267. }
  268. index, err := strconv.Atoi(string(indexB))
  269. if err != nil {
  270. return -1, err
  271. }
  272. return index, nil
  273. }
  274. // lSetFileLabel sets the SELinux label for this path, not following symlinks,
  275. // or returns an error.
  276. func lSetFileLabel(fpath string, label string) error {
  277. if fpath == "" {
  278. return ErrEmptyPath
  279. }
  280. for {
  281. err := unix.Lsetxattr(fpath, xattrNameSelinux, []byte(label), 0)
  282. if err == nil {
  283. break
  284. }
  285. if err != unix.EINTR { //nolint:errorlint // unix errors are bare
  286. return &os.PathError{Op: "lsetxattr", Path: fpath, Err: err}
  287. }
  288. }
  289. return nil
  290. }
  291. // setFileLabel sets the SELinux label for this path, following symlinks,
  292. // or returns an error.
  293. func setFileLabel(fpath string, label string) error {
  294. if fpath == "" {
  295. return ErrEmptyPath
  296. }
  297. for {
  298. err := unix.Setxattr(fpath, xattrNameSelinux, []byte(label), 0)
  299. if err == nil {
  300. break
  301. }
  302. if err != unix.EINTR { //nolint:errorlint // unix errors are bare
  303. return &os.PathError{Op: "setxattr", Path: fpath, Err: err}
  304. }
  305. }
  306. return nil
  307. }
  308. // fileLabel returns the SELinux label for this path, following symlinks,
  309. // or returns an error.
  310. func fileLabel(fpath string) (string, error) {
  311. if fpath == "" {
  312. return "", ErrEmptyPath
  313. }
  314. label, err := getxattr(fpath, xattrNameSelinux)
  315. if err != nil {
  316. return "", &os.PathError{Op: "getxattr", Path: fpath, Err: err}
  317. }
  318. // Trim the NUL byte at the end of the byte buffer, if present.
  319. if len(label) > 0 && label[len(label)-1] == '\x00' {
  320. label = label[:len(label)-1]
  321. }
  322. return string(label), nil
  323. }
  324. // lFileLabel returns the SELinux label for this path, not following symlinks,
  325. // or returns an error.
  326. func lFileLabel(fpath string) (string, error) {
  327. if fpath == "" {
  328. return "", ErrEmptyPath
  329. }
  330. label, err := lgetxattr(fpath, xattrNameSelinux)
  331. if err != nil {
  332. return "", &os.PathError{Op: "lgetxattr", Path: fpath, Err: err}
  333. }
  334. // Trim the NUL byte at the end of the byte buffer, if present.
  335. if len(label) > 0 && label[len(label)-1] == '\x00' {
  336. label = label[:len(label)-1]
  337. }
  338. return string(label), nil
  339. }
  340. func setFSCreateLabel(label string) error {
  341. return writeCon(attrPath("fscreate"), label)
  342. }
  343. // fsCreateLabel returns the default label the kernel which the kernel is using
  344. // for file system objects created by this task. "" indicates default.
  345. func fsCreateLabel() (string, error) {
  346. return readCon(attrPath("fscreate"))
  347. }
  348. // currentLabel returns the SELinux label of the current process thread, or an error.
  349. func currentLabel() (string, error) {
  350. return readCon(attrPath("current"))
  351. }
  352. // pidLabel returns the SELinux label of the given pid, or an error.
  353. func pidLabel(pid int) (string, error) {
  354. return readCon(fmt.Sprintf("/proc/%d/attr/current", pid))
  355. }
  356. // ExecLabel returns the SELinux label that the kernel will use for any programs
  357. // that are executed by the current process thread, or an error.
  358. func execLabel() (string, error) {
  359. return readCon(attrPath("exec"))
  360. }
  361. func writeCon(fpath, val string) error {
  362. if fpath == "" {
  363. return ErrEmptyPath
  364. }
  365. if val == "" {
  366. if !getEnabled() {
  367. return nil
  368. }
  369. }
  370. out, err := os.OpenFile(fpath, os.O_WRONLY, 0)
  371. if err != nil {
  372. return err
  373. }
  374. defer out.Close()
  375. if err := isProcHandle(out); err != nil {
  376. return err
  377. }
  378. if val != "" {
  379. _, err = out.Write([]byte(val))
  380. } else {
  381. _, err = out.Write(nil)
  382. }
  383. if err != nil {
  384. return err
  385. }
  386. return nil
  387. }
  388. func attrPath(attr string) string {
  389. // Linux >= 3.17 provides this
  390. const threadSelfPrefix = "/proc/thread-self/attr"
  391. attrPathOnce.Do(func() {
  392. st, err := os.Stat(threadSelfPrefix)
  393. if err == nil && st.Mode().IsDir() {
  394. haveThreadSelf = true
  395. }
  396. })
  397. if haveThreadSelf {
  398. return filepath.Join(threadSelfPrefix, attr)
  399. }
  400. return filepath.Join("/proc/self/task", strconv.Itoa(unix.Gettid()), "attr", attr)
  401. }
  402. // canonicalizeContext takes a context string and writes it to the kernel
  403. // the function then returns the context that the kernel will use. Use this
  404. // function to check if two contexts are equivalent
  405. func canonicalizeContext(val string) (string, error) {
  406. return readWriteCon(filepath.Join(getSelinuxMountPoint(), "context"), val)
  407. }
  408. // computeCreateContext requests the type transition from source to target for
  409. // class from the kernel.
  410. func computeCreateContext(source string, target string, class string) (string, error) {
  411. classidx, err := classIndex(class)
  412. if err != nil {
  413. return "", err
  414. }
  415. return readWriteCon(filepath.Join(getSelinuxMountPoint(), "create"), fmt.Sprintf("%s %s %d", source, target, classidx))
  416. }
  417. // catsToBitset stores categories in a bitset.
  418. func catsToBitset(cats string) (*big.Int, error) {
  419. bitset := new(big.Int)
  420. catlist := strings.Split(cats, ",")
  421. for _, r := range catlist {
  422. ranges := strings.SplitN(r, ".", 2)
  423. if len(ranges) > 1 {
  424. catstart, err := parseLevelItem(ranges[0], category)
  425. if err != nil {
  426. return nil, err
  427. }
  428. catend, err := parseLevelItem(ranges[1], category)
  429. if err != nil {
  430. return nil, err
  431. }
  432. for i := catstart; i <= catend; i++ {
  433. bitset.SetBit(bitset, int(i), 1)
  434. }
  435. } else {
  436. cat, err := parseLevelItem(ranges[0], category)
  437. if err != nil {
  438. return nil, err
  439. }
  440. bitset.SetBit(bitset, int(cat), 1)
  441. }
  442. }
  443. return bitset, nil
  444. }
  445. // parseLevelItem parses and verifies that a sensitivity or category are valid
  446. func parseLevelItem(s string, sep levelItem) (uint, error) {
  447. if len(s) < minSensLen || levelItem(s[0]) != sep {
  448. return 0, ErrLevelSyntax
  449. }
  450. val, err := strconv.ParseUint(s[1:], 10, 32)
  451. if err != nil {
  452. return 0, err
  453. }
  454. return uint(val), nil
  455. }
  456. // parseLevel fills a level from a string that contains
  457. // a sensitivity and categories
  458. func (l *level) parseLevel(levelStr string) error {
  459. lvl := strings.SplitN(levelStr, ":", 2)
  460. sens, err := parseLevelItem(lvl[0], sensitivity)
  461. if err != nil {
  462. return fmt.Errorf("failed to parse sensitivity: %w", err)
  463. }
  464. l.sens = sens
  465. if len(lvl) > 1 {
  466. cats, err := catsToBitset(lvl[1])
  467. if err != nil {
  468. return fmt.Errorf("failed to parse categories: %w", err)
  469. }
  470. l.cats = cats
  471. }
  472. return nil
  473. }
  474. // rangeStrToMLSRange marshals a string representation of a range.
  475. func rangeStrToMLSRange(rangeStr string) (*mlsRange, error) {
  476. r := &mlsRange{}
  477. l := strings.SplitN(rangeStr, "-", 2)
  478. switch len(l) {
  479. // rangeStr that has a low and a high level, e.g. s4:c0.c1023-s6:c0.c1023
  480. case 2:
  481. r.high = &level{}
  482. if err := r.high.parseLevel(l[1]); err != nil {
  483. return nil, fmt.Errorf("failed to parse high level %q: %w", l[1], err)
  484. }
  485. fallthrough
  486. // rangeStr that is single level, e.g. s6:c0,c3,c5,c30.c1023
  487. case 1:
  488. r.low = &level{}
  489. if err := r.low.parseLevel(l[0]); err != nil {
  490. return nil, fmt.Errorf("failed to parse low level %q: %w", l[0], err)
  491. }
  492. }
  493. if r.high == nil {
  494. r.high = r.low
  495. }
  496. return r, nil
  497. }
  498. // bitsetToStr takes a category bitset and returns it in the
  499. // canonical selinux syntax
  500. func bitsetToStr(c *big.Int) string {
  501. var str string
  502. length := 0
  503. for i := int(c.TrailingZeroBits()); i < c.BitLen(); i++ {
  504. if c.Bit(i) == 0 {
  505. continue
  506. }
  507. if length == 0 {
  508. if str != "" {
  509. str += ","
  510. }
  511. str += "c" + strconv.Itoa(i)
  512. }
  513. if c.Bit(i+1) == 1 {
  514. length++
  515. continue
  516. }
  517. if length == 1 {
  518. str += ",c" + strconv.Itoa(i)
  519. } else if length > 1 {
  520. str += ".c" + strconv.Itoa(i)
  521. }
  522. length = 0
  523. }
  524. return str
  525. }
  526. func (l *level) equal(l2 *level) bool {
  527. if l2 == nil || l == nil {
  528. return l == l2
  529. }
  530. if l2.sens != l.sens {
  531. return false
  532. }
  533. if l2.cats == nil || l.cats == nil {
  534. return l2.cats == l.cats
  535. }
  536. return l.cats.Cmp(l2.cats) == 0
  537. }
  538. // String returns an mlsRange as a string.
  539. func (m mlsRange) String() string {
  540. low := "s" + strconv.Itoa(int(m.low.sens))
  541. if m.low.cats != nil && m.low.cats.BitLen() > 0 {
  542. low += ":" + bitsetToStr(m.low.cats)
  543. }
  544. if m.low.equal(m.high) {
  545. return low
  546. }
  547. high := "s" + strconv.Itoa(int(m.high.sens))
  548. if m.high.cats != nil && m.high.cats.BitLen() > 0 {
  549. high += ":" + bitsetToStr(m.high.cats)
  550. }
  551. return low + "-" + high
  552. }
  553. func max(a, b uint) uint {
  554. if a > b {
  555. return a
  556. }
  557. return b
  558. }
  559. func min(a, b uint) uint {
  560. if a < b {
  561. return a
  562. }
  563. return b
  564. }
  565. // calculateGlbLub computes the glb (greatest lower bound) and lub (least upper bound)
  566. // of a source and target range.
  567. // The glblub is calculated as the greater of the low sensitivities and
  568. // the lower of the high sensitivities and the and of each category bitset.
  569. func calculateGlbLub(sourceRange, targetRange string) (string, error) {
  570. s, err := rangeStrToMLSRange(sourceRange)
  571. if err != nil {
  572. return "", err
  573. }
  574. t, err := rangeStrToMLSRange(targetRange)
  575. if err != nil {
  576. return "", err
  577. }
  578. if s.high.sens < t.low.sens || t.high.sens < s.low.sens {
  579. /* these ranges have no common sensitivities */
  580. return "", ErrIncomparable
  581. }
  582. outrange := &mlsRange{low: &level{}, high: &level{}}
  583. /* take the greatest of the low */
  584. outrange.low.sens = max(s.low.sens, t.low.sens)
  585. /* take the least of the high */
  586. outrange.high.sens = min(s.high.sens, t.high.sens)
  587. /* find the intersecting categories */
  588. if s.low.cats != nil && t.low.cats != nil {
  589. outrange.low.cats = new(big.Int)
  590. outrange.low.cats.And(s.low.cats, t.low.cats)
  591. }
  592. if s.high.cats != nil && t.high.cats != nil {
  593. outrange.high.cats = new(big.Int)
  594. outrange.high.cats.And(s.high.cats, t.high.cats)
  595. }
  596. return outrange.String(), nil
  597. }
  598. func readWriteCon(fpath string, val string) (string, error) {
  599. if fpath == "" {
  600. return "", ErrEmptyPath
  601. }
  602. f, err := os.OpenFile(fpath, os.O_RDWR, 0)
  603. if err != nil {
  604. return "", err
  605. }
  606. defer f.Close()
  607. _, err = f.Write([]byte(val))
  608. if err != nil {
  609. return "", err
  610. }
  611. return readConFd(f)
  612. }
  613. // peerLabel retrieves the label of the client on the other side of a socket
  614. func peerLabel(fd uintptr) (string, error) {
  615. l, err := unix.GetsockoptString(int(fd), unix.SOL_SOCKET, unix.SO_PEERSEC)
  616. if err != nil {
  617. return "", &os.PathError{Op: "getsockopt", Path: "fd " + strconv.Itoa(int(fd)), Err: err}
  618. }
  619. return l, nil
  620. }
  621. // setKeyLabel takes a process label and tells the kernel to assign the
  622. // label to the next kernel keyring that gets created
  623. func setKeyLabel(label string) error {
  624. err := writeCon("/proc/self/attr/keycreate", label)
  625. if errors.Is(err, os.ErrNotExist) {
  626. return nil
  627. }
  628. if label == "" && errors.Is(err, os.ErrPermission) {
  629. return nil
  630. }
  631. return err
  632. }
  633. // get returns the Context as a string
  634. func (c Context) get() string {
  635. if l := c["level"]; l != "" {
  636. return c["user"] + ":" + c["role"] + ":" + c["type"] + ":" + l
  637. }
  638. return c["user"] + ":" + c["role"] + ":" + c["type"]
  639. }
  640. // newContext creates a new Context struct from the specified label
  641. func newContext(label string) (Context, error) {
  642. c := make(Context)
  643. if len(label) != 0 {
  644. con := strings.SplitN(label, ":", 4)
  645. if len(con) < 3 {
  646. return c, ErrInvalidLabel
  647. }
  648. c["user"] = con[0]
  649. c["role"] = con[1]
  650. c["type"] = con[2]
  651. if len(con) > 3 {
  652. c["level"] = con[3]
  653. }
  654. }
  655. return c, nil
  656. }
  657. // clearLabels clears all reserved labels
  658. func clearLabels() {
  659. state.Lock()
  660. state.mcsList = make(map[string]bool)
  661. state.Unlock()
  662. }
  663. // reserveLabel reserves the MLS/MCS level component of the specified label
  664. func reserveLabel(label string) {
  665. if len(label) != 0 {
  666. con := strings.SplitN(label, ":", 4)
  667. if len(con) > 3 {
  668. _ = mcsAdd(con[3])
  669. }
  670. }
  671. }
  672. func selinuxEnforcePath() string {
  673. return filepath.Join(getSelinuxMountPoint(), "enforce")
  674. }
  675. // isMLSEnabled checks if MLS is enabled.
  676. func isMLSEnabled() bool {
  677. enabledB, err := os.ReadFile(filepath.Join(getSelinuxMountPoint(), "mls"))
  678. if err != nil {
  679. return false
  680. }
  681. return bytes.Equal(enabledB, []byte{'1'})
  682. }
  683. // enforceMode returns the current SELinux mode Enforcing, Permissive, Disabled
  684. func enforceMode() int {
  685. var enforce int
  686. enforceB, err := os.ReadFile(selinuxEnforcePath())
  687. if err != nil {
  688. return -1
  689. }
  690. enforce, err = strconv.Atoi(string(enforceB))
  691. if err != nil {
  692. return -1
  693. }
  694. return enforce
  695. }
  696. // setEnforceMode sets the current SELinux mode Enforcing, Permissive.
  697. // Disabled is not valid, since this needs to be set at boot time.
  698. func setEnforceMode(mode int) error {
  699. //nolint:gosec // ignore G306: permissions to be 0600 or less.
  700. return os.WriteFile(selinuxEnforcePath(), []byte(strconv.Itoa(mode)), 0o644)
  701. }
  702. // defaultEnforceMode returns the systems default SELinux mode Enforcing,
  703. // Permissive or Disabled. Note this is just the default at boot time.
  704. // EnforceMode tells you the systems current mode.
  705. func defaultEnforceMode() int {
  706. switch readConfig(selinuxTag) {
  707. case "enforcing":
  708. return Enforcing
  709. case "permissive":
  710. return Permissive
  711. }
  712. return Disabled
  713. }
  714. func mcsAdd(mcs string) error {
  715. if mcs == "" {
  716. return nil
  717. }
  718. state.Lock()
  719. defer state.Unlock()
  720. if state.mcsList[mcs] {
  721. return ErrMCSAlreadyExists
  722. }
  723. state.mcsList[mcs] = true
  724. return nil
  725. }
  726. func mcsDelete(mcs string) {
  727. if mcs == "" {
  728. return
  729. }
  730. state.Lock()
  731. defer state.Unlock()
  732. state.mcsList[mcs] = false
  733. }
  734. func intToMcs(id int, catRange uint32) string {
  735. var (
  736. SETSIZE = int(catRange)
  737. TIER = SETSIZE
  738. ORD = id
  739. )
  740. if id < 1 || id > 523776 {
  741. return ""
  742. }
  743. for ORD > TIER {
  744. ORD -= TIER
  745. TIER--
  746. }
  747. TIER = SETSIZE - TIER
  748. ORD += TIER
  749. return fmt.Sprintf("s0:c%d,c%d", TIER, ORD)
  750. }
  751. func uniqMcs(catRange uint32) string {
  752. var (
  753. n uint32
  754. c1, c2 uint32
  755. mcs string
  756. )
  757. for {
  758. _ = binary.Read(rand.Reader, binary.LittleEndian, &n)
  759. c1 = n % catRange
  760. _ = binary.Read(rand.Reader, binary.LittleEndian, &n)
  761. c2 = n % catRange
  762. if c1 == c2 {
  763. continue
  764. } else if c1 > c2 {
  765. c1, c2 = c2, c1
  766. }
  767. mcs = fmt.Sprintf("s0:c%d,c%d", c1, c2)
  768. if err := mcsAdd(mcs); err != nil {
  769. continue
  770. }
  771. break
  772. }
  773. return mcs
  774. }
  775. // releaseLabel un-reserves the MLS/MCS Level field of the specified label,
  776. // allowing it to be used by another process.
  777. func releaseLabel(label string) {
  778. if len(label) != 0 {
  779. con := strings.SplitN(label, ":", 4)
  780. if len(con) > 3 {
  781. mcsDelete(con[3])
  782. }
  783. }
  784. }
  785. // roFileLabel returns the specified SELinux readonly file label
  786. func roFileLabel() string {
  787. return readOnlyFileLabel
  788. }
  789. func openContextFile() (*os.File, error) {
  790. if f, err := os.Open(contextFile); err == nil {
  791. return f, nil
  792. }
  793. return os.Open(filepath.Join(policyRoot(), "contexts", "lxc_contexts"))
  794. }
  795. func loadLabels() {
  796. labels = make(map[string]string)
  797. in, err := openContextFile()
  798. if err != nil {
  799. return
  800. }
  801. defer in.Close()
  802. scanner := bufio.NewScanner(in)
  803. for scanner.Scan() {
  804. line := bytes.TrimSpace(scanner.Bytes())
  805. if len(line) == 0 {
  806. // Skip blank lines
  807. continue
  808. }
  809. if line[0] == ';' || line[0] == '#' {
  810. // Skip comments
  811. continue
  812. }
  813. fields := bytes.SplitN(line, []byte{'='}, 2)
  814. if len(fields) != 2 {
  815. continue
  816. }
  817. key, val := bytes.TrimSpace(fields[0]), bytes.TrimSpace(fields[1])
  818. labels[string(key)] = string(bytes.Trim(val, `"`))
  819. }
  820. con, _ := NewContext(labels["file"])
  821. con["level"] = fmt.Sprintf("s0:c%d,c%d", maxCategory-2, maxCategory-1)
  822. privContainerMountLabel = con.get()
  823. reserveLabel(privContainerMountLabel)
  824. }
  825. func label(key string) string {
  826. loadLabelsOnce.Do(func() {
  827. loadLabels()
  828. })
  829. return labels[key]
  830. }
  831. // kvmContainerLabels returns the default processLabel and mountLabel to be used
  832. // for kvm containers by the calling process.
  833. func kvmContainerLabels() (string, string) {
  834. processLabel := label("kvm_process")
  835. if processLabel == "" {
  836. processLabel = label("process")
  837. }
  838. return addMcs(processLabel, label("file"))
  839. }
  840. // initContainerLabels returns the default processLabel and file labels to be
  841. // used for containers running an init system like systemd by the calling process.
  842. func initContainerLabels() (string, string) {
  843. processLabel := label("init_process")
  844. if processLabel == "" {
  845. processLabel = label("process")
  846. }
  847. return addMcs(processLabel, label("file"))
  848. }
  849. // containerLabels returns an allocated processLabel and fileLabel to be used for
  850. // container labeling by the calling process.
  851. func containerLabels() (processLabel string, fileLabel string) {
  852. if !getEnabled() {
  853. return "", ""
  854. }
  855. processLabel = label("process")
  856. fileLabel = label("file")
  857. readOnlyFileLabel = label("ro_file")
  858. if processLabel == "" || fileLabel == "" {
  859. return "", fileLabel
  860. }
  861. if readOnlyFileLabel == "" {
  862. readOnlyFileLabel = fileLabel
  863. }
  864. return addMcs(processLabel, fileLabel)
  865. }
  866. func addMcs(processLabel, fileLabel string) (string, string) {
  867. scon, _ := NewContext(processLabel)
  868. if scon["level"] != "" {
  869. mcs := uniqMcs(CategoryRange)
  870. scon["level"] = mcs
  871. processLabel = scon.Get()
  872. scon, _ = NewContext(fileLabel)
  873. scon["level"] = mcs
  874. fileLabel = scon.Get()
  875. }
  876. return processLabel, fileLabel
  877. }
  878. // securityCheckContext validates that the SELinux label is understood by the kernel
  879. func securityCheckContext(val string) error {
  880. //nolint:gosec // ignore G306: permissions to be 0600 or less.
  881. return os.WriteFile(filepath.Join(getSelinuxMountPoint(), "context"), []byte(val), 0o644)
  882. }
  883. // copyLevel returns a label with the MLS/MCS level from src label replaced on
  884. // the dest label.
  885. func copyLevel(src, dest string) (string, error) {
  886. if src == "" {
  887. return "", nil
  888. }
  889. if err := SecurityCheckContext(src); err != nil {
  890. return "", err
  891. }
  892. if err := SecurityCheckContext(dest); err != nil {
  893. return "", err
  894. }
  895. scon, err := NewContext(src)
  896. if err != nil {
  897. return "", err
  898. }
  899. tcon, err := NewContext(dest)
  900. if err != nil {
  901. return "", err
  902. }
  903. mcsDelete(tcon["level"])
  904. _ = mcsAdd(scon["level"])
  905. tcon["level"] = scon["level"]
  906. return tcon.Get(), nil
  907. }
  908. // chcon changes the fpath file object to the SELinux label.
  909. // If fpath is a directory and recurse is true, then chcon walks the
  910. // directory tree setting the label.
  911. func chcon(fpath string, label string, recurse bool) error {
  912. if fpath == "" {
  913. return ErrEmptyPath
  914. }
  915. if label == "" {
  916. return nil
  917. }
  918. excludePaths := map[string]bool{
  919. "/": true,
  920. "/bin": true,
  921. "/boot": true,
  922. "/dev": true,
  923. "/etc": true,
  924. "/etc/passwd": true,
  925. "/etc/pki": true,
  926. "/etc/shadow": true,
  927. "/home": true,
  928. "/lib": true,
  929. "/lib64": true,
  930. "/media": true,
  931. "/opt": true,
  932. "/proc": true,
  933. "/root": true,
  934. "/run": true,
  935. "/sbin": true,
  936. "/srv": true,
  937. "/sys": true,
  938. "/tmp": true,
  939. "/usr": true,
  940. "/var": true,
  941. "/var/lib": true,
  942. "/var/log": true,
  943. }
  944. if home := os.Getenv("HOME"); home != "" {
  945. excludePaths[home] = true
  946. }
  947. if sudoUser := os.Getenv("SUDO_USER"); sudoUser != "" {
  948. if usr, err := user.Lookup(sudoUser); err == nil {
  949. excludePaths[usr.HomeDir] = true
  950. }
  951. }
  952. if fpath != "/" {
  953. fpath = strings.TrimSuffix(fpath, "/")
  954. }
  955. if excludePaths[fpath] {
  956. return fmt.Errorf("SELinux relabeling of %s is not allowed", fpath)
  957. }
  958. if !recurse {
  959. err := lSetFileLabel(fpath, label)
  960. if err != nil {
  961. // Check if file doesn't exist, must have been removed
  962. if errors.Is(err, os.ErrNotExist) {
  963. return nil
  964. }
  965. // Check if current label is correct on disk
  966. flabel, nerr := lFileLabel(fpath)
  967. if nerr == nil && flabel == label {
  968. return nil
  969. }
  970. // Check if file doesn't exist, must have been removed
  971. if errors.Is(nerr, os.ErrNotExist) {
  972. return nil
  973. }
  974. return err
  975. }
  976. return nil
  977. }
  978. return rchcon(fpath, label)
  979. }
  980. func rchcon(fpath, label string) error { //revive:disable:cognitive-complexity
  981. fastMode := false
  982. // If the current label matches the new label, assume
  983. // other labels are correct.
  984. if cLabel, err := lFileLabel(fpath); err == nil && cLabel == label {
  985. fastMode = true
  986. }
  987. return pwalkdir.Walk(fpath, func(p string, _ fs.DirEntry, _ error) error {
  988. if fastMode {
  989. if cLabel, err := lFileLabel(fpath); err == nil && cLabel == label {
  990. return nil
  991. }
  992. }
  993. err := lSetFileLabel(p, label)
  994. // Walk a file tree can race with removal, so ignore ENOENT.
  995. if errors.Is(err, os.ErrNotExist) {
  996. return nil
  997. }
  998. return err
  999. })
  1000. }
  1001. // dupSecOpt takes an SELinux process label and returns security options that
  1002. // can be used to set the SELinux Type and Level for future container processes.
  1003. func dupSecOpt(src string) ([]string, error) {
  1004. if src == "" {
  1005. return nil, nil
  1006. }
  1007. con, err := NewContext(src)
  1008. if err != nil {
  1009. return nil, err
  1010. }
  1011. if con["user"] == "" ||
  1012. con["role"] == "" ||
  1013. con["type"] == "" {
  1014. return nil, nil
  1015. }
  1016. dup := []string{
  1017. "user:" + con["user"],
  1018. "role:" + con["role"],
  1019. "type:" + con["type"],
  1020. }
  1021. if con["level"] != "" {
  1022. dup = append(dup, "level:"+con["level"])
  1023. }
  1024. return dup, nil
  1025. }
  1026. // findUserInContext scans the reader for a valid SELinux context
  1027. // match that is verified with the verifier. Invalid contexts are
  1028. // skipped. It returns a matched context or an empty string if no
  1029. // match is found. If a scanner error occurs, it is returned.
  1030. func findUserInContext(context Context, r io.Reader, verifier func(string) error) (string, error) {
  1031. fromRole := context["role"]
  1032. fromType := context["type"]
  1033. scanner := bufio.NewScanner(r)
  1034. for scanner.Scan() {
  1035. fromConns := strings.Fields(scanner.Text())
  1036. if len(fromConns) == 0 {
  1037. // Skip blank lines
  1038. continue
  1039. }
  1040. line := fromConns[0]
  1041. if line[0] == ';' || line[0] == '#' {
  1042. // Skip comments
  1043. continue
  1044. }
  1045. // user context files contexts are formatted as
  1046. // role_r:type_t:s0 where the user is missing.
  1047. lineArr := strings.SplitN(line, ":", 4)
  1048. // skip context with typo, or role and type do not match
  1049. if len(lineArr) != 3 ||
  1050. lineArr[0] != fromRole ||
  1051. lineArr[1] != fromType {
  1052. continue
  1053. }
  1054. for _, cc := range fromConns[1:] {
  1055. toConns := strings.SplitN(cc, ":", 4)
  1056. if len(toConns) != 3 {
  1057. continue
  1058. }
  1059. context["role"] = toConns[0]
  1060. context["type"] = toConns[1]
  1061. outConn := context.get()
  1062. if err := verifier(outConn); err != nil {
  1063. continue
  1064. }
  1065. return outConn, nil
  1066. }
  1067. }
  1068. if err := scanner.Err(); err != nil {
  1069. return "", fmt.Errorf("failed to scan for context: %w", err)
  1070. }
  1071. return "", nil
  1072. }
  1073. func getDefaultContextFromReaders(c *defaultSECtx) (string, error) {
  1074. if c.verifier == nil {
  1075. return "", ErrVerifierNil
  1076. }
  1077. context, err := newContext(c.scon)
  1078. if err != nil {
  1079. return "", fmt.Errorf("failed to create label for %s: %w", c.scon, err)
  1080. }
  1081. // set so the verifier validates the matched context with the provided user and level.
  1082. context["user"] = c.user
  1083. context["level"] = c.level
  1084. conn, err := findUserInContext(context, c.userRdr, c.verifier)
  1085. if err != nil {
  1086. return "", err
  1087. }
  1088. if conn != "" {
  1089. return conn, nil
  1090. }
  1091. conn, err = findUserInContext(context, c.defaultRdr, c.verifier)
  1092. if err != nil {
  1093. return "", err
  1094. }
  1095. if conn != "" {
  1096. return conn, nil
  1097. }
  1098. return "", fmt.Errorf("context %q not found: %w", c.scon, ErrContextMissing)
  1099. }
  1100. func getDefaultContextWithLevel(user, level, scon string) (string, error) {
  1101. userPath := filepath.Join(policyRoot(), selinuxUsersDir, user)
  1102. fu, err := os.Open(userPath)
  1103. if err != nil {
  1104. return "", err
  1105. }
  1106. defer fu.Close()
  1107. defaultPath := filepath.Join(policyRoot(), defaultContexts)
  1108. fd, err := os.Open(defaultPath)
  1109. if err != nil {
  1110. return "", err
  1111. }
  1112. defer fd.Close()
  1113. c := defaultSECtx{
  1114. user: user,
  1115. level: level,
  1116. scon: scon,
  1117. userRdr: fu,
  1118. defaultRdr: fd,
  1119. verifier: securityCheckContext,
  1120. }
  1121. return getDefaultContextFromReaders(&c)
  1122. }