selinux.go 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  1. package selinux
  2. import (
  3. "bufio"
  4. "crypto/rand"
  5. "encoding/binary"
  6. "fmt"
  7. "github.com/dotcloud/docker/pkg/mount"
  8. "github.com/dotcloud/docker/pkg/system"
  9. "io"
  10. "os"
  11. "regexp"
  12. "strconv"
  13. "strings"
  14. "syscall"
  15. )
  16. const (
  17. Enforcing = 1
  18. Permissive = 0
  19. Disabled = -1
  20. selinuxDir = "/etc/selinux/"
  21. selinuxConfig = selinuxDir + "config"
  22. selinuxTypeTag = "SELINUXTYPE"
  23. selinuxTag = "SELINUX"
  24. selinuxPath = "/sys/fs/selinux"
  25. xattrNameSelinux = "security.selinux"
  26. stRdOnly = 0x01
  27. )
  28. var (
  29. assignRegex = regexp.MustCompile(`^([^=]+)=(.*)$`)
  30. spaceRegex = regexp.MustCompile(`^([^=]+) (.*)$`)
  31. mcsList = make(map[string]bool)
  32. selinuxfs = "unknown"
  33. selinuxEnabled = false
  34. selinuxEnabledChecked = false
  35. )
  36. type SELinuxContext map[string]string
  37. func GetSelinuxMountPoint() string {
  38. if selinuxfs != "unknown" {
  39. return selinuxfs
  40. }
  41. selinuxfs = ""
  42. mounts, err := mount.GetMounts()
  43. if err != nil {
  44. return selinuxfs
  45. }
  46. for _, mount := range mounts {
  47. if mount.Fstype == "selinuxfs" {
  48. selinuxfs = mount.Mountpoint
  49. break
  50. }
  51. }
  52. if selinuxfs != "" {
  53. var buf syscall.Statfs_t
  54. syscall.Statfs(selinuxfs, &buf)
  55. if (buf.Flags & stRdOnly) == 1 {
  56. selinuxfs = ""
  57. }
  58. }
  59. return selinuxfs
  60. }
  61. func SelinuxEnabled() bool {
  62. if selinuxEnabledChecked {
  63. return selinuxEnabled
  64. }
  65. selinuxEnabledChecked = true
  66. if fs := GetSelinuxMountPoint(); fs != "" {
  67. if con, _ := Getcon(); con != "kernel" {
  68. selinuxEnabled = true
  69. }
  70. }
  71. return selinuxEnabled
  72. }
  73. func ReadConfig(target string) (value string) {
  74. var (
  75. val, key string
  76. bufin *bufio.Reader
  77. )
  78. in, err := os.Open(selinuxConfig)
  79. if err != nil {
  80. return ""
  81. }
  82. defer in.Close()
  83. bufin = bufio.NewReader(in)
  84. for done := false; !done; {
  85. var line string
  86. if line, err = bufin.ReadString('\n'); err != nil {
  87. if err != io.EOF {
  88. return ""
  89. }
  90. done = true
  91. }
  92. line = strings.TrimSpace(line)
  93. if len(line) == 0 {
  94. // Skip blank lines
  95. continue
  96. }
  97. if line[0] == ';' || line[0] == '#' {
  98. // Skip comments
  99. continue
  100. }
  101. if groups := assignRegex.FindStringSubmatch(line); groups != nil {
  102. key, val = strings.TrimSpace(groups[1]), strings.TrimSpace(groups[2])
  103. if key == target {
  104. return strings.Trim(val, "\"")
  105. }
  106. }
  107. }
  108. return ""
  109. }
  110. func GetSELinuxPolicyRoot() string {
  111. return selinuxDir + ReadConfig(selinuxTypeTag)
  112. }
  113. func readCon(name string) (string, error) {
  114. var val string
  115. in, err := os.Open(name)
  116. if err != nil {
  117. return "", err
  118. }
  119. defer in.Close()
  120. _, err = fmt.Fscanf(in, "%s", &val)
  121. return val, err
  122. }
  123. func Setfilecon(path string, scon string) error {
  124. return system.Lsetxattr(path, xattrNameSelinux, []byte(scon), 0)
  125. }
  126. func Getfilecon(path string) (string, error) {
  127. var scon []byte
  128. cnt, err := syscall.Getxattr(path, xattrNameSelinux, scon)
  129. scon = make([]byte, cnt)
  130. cnt, err = syscall.Getxattr(path, xattrNameSelinux, scon)
  131. return string(scon), err
  132. }
  133. func Setfscreatecon(scon string) error {
  134. return writeCon("/proc/self/attr/fscreate", scon)
  135. }
  136. func Getfscreatecon() (string, error) {
  137. return readCon("/proc/self/attr/fscreate")
  138. }
  139. func Getcon() (string, error) {
  140. return readCon("/proc/self/attr/current")
  141. }
  142. func Getpidcon(pid int) (string, error) {
  143. return readCon(fmt.Sprintf("/proc/%d/attr/current", pid))
  144. }
  145. func Getexeccon() (string, error) {
  146. return readCon("/proc/self/attr/exec")
  147. }
  148. func writeCon(name string, val string) error {
  149. if !SelinuxEnabled() {
  150. return nil
  151. }
  152. out, err := os.OpenFile(name, os.O_WRONLY, 0)
  153. if err != nil {
  154. return err
  155. }
  156. defer out.Close()
  157. if val != "" {
  158. _, err = out.Write([]byte(val))
  159. } else {
  160. _, err = out.Write(nil)
  161. }
  162. return err
  163. }
  164. func Setexeccon(scon string) error {
  165. return writeCon(fmt.Sprintf("/proc/self/task/%d/attr/exec", syscall.Gettid()), scon)
  166. }
  167. func (c SELinuxContext) Get() string {
  168. return fmt.Sprintf("%s:%s:%s:%s", c["user"], c["role"], c["type"], c["level"])
  169. }
  170. func NewContext(scon string) SELinuxContext {
  171. c := make(SELinuxContext)
  172. if len(scon) != 0 {
  173. con := strings.SplitN(scon, ":", 4)
  174. c["user"] = con[0]
  175. c["role"] = con[1]
  176. c["type"] = con[2]
  177. c["level"] = con[3]
  178. }
  179. return c
  180. }
  181. func SelinuxGetEnforce() int {
  182. var enforce int
  183. enforceS, err := readCon(fmt.Sprintf("%s/enforce", selinuxPath))
  184. if err != nil {
  185. return -1
  186. }
  187. enforce, err = strconv.Atoi(string(enforceS))
  188. if err != nil {
  189. return -1
  190. }
  191. return enforce
  192. }
  193. func SelinuxGetEnforceMode() int {
  194. switch ReadConfig(selinuxTag) {
  195. case "enforcing":
  196. return Enforcing
  197. case "permissive":
  198. return Permissive
  199. }
  200. return Disabled
  201. }
  202. func mcsAdd(mcs string) {
  203. mcsList[mcs] = true
  204. }
  205. func mcsDelete(mcs string) {
  206. mcsList[mcs] = false
  207. }
  208. func mcsExists(mcs string) bool {
  209. return mcsList[mcs]
  210. }
  211. func IntToMcs(id int, catRange uint32) string {
  212. var (
  213. SETSIZE = int(catRange)
  214. TIER = SETSIZE
  215. ORD = id
  216. )
  217. if id < 1 || id > 523776 {
  218. return ""
  219. }
  220. for ORD > TIER {
  221. ORD = ORD - TIER
  222. TIER -= 1
  223. }
  224. TIER = SETSIZE - TIER
  225. ORD = ORD + TIER
  226. return fmt.Sprintf("s0:c%d,c%d", TIER, ORD)
  227. }
  228. func uniqMcs(catRange uint32) string {
  229. var (
  230. n uint32
  231. c1, c2 uint32
  232. mcs string
  233. )
  234. for {
  235. binary.Read(rand.Reader, binary.LittleEndian, &n)
  236. c1 = n % catRange
  237. binary.Read(rand.Reader, binary.LittleEndian, &n)
  238. c2 = n % catRange
  239. if c1 == c2 {
  240. continue
  241. } else {
  242. if c1 > c2 {
  243. t := c1
  244. c1 = c2
  245. c2 = t
  246. }
  247. }
  248. mcs = fmt.Sprintf("s0:c%d,c%d", c1, c2)
  249. if mcsExists(mcs) {
  250. continue
  251. }
  252. mcsAdd(mcs)
  253. break
  254. }
  255. return mcs
  256. }
  257. func FreeContext(con string) {
  258. if con != "" {
  259. scon := NewContext(con)
  260. mcsDelete(scon["level"])
  261. }
  262. }
  263. func GetLxcContexts() (processLabel string, fileLabel string) {
  264. var (
  265. val, key string
  266. bufin *bufio.Reader
  267. )
  268. if !SelinuxEnabled() {
  269. return "", ""
  270. }
  271. lxcPath := fmt.Sprintf("%s/content/lxc_contexts", GetSELinuxPolicyRoot())
  272. in, err := os.Open(lxcPath)
  273. if err != nil {
  274. return "", ""
  275. }
  276. defer in.Close()
  277. bufin = bufio.NewReader(in)
  278. for done := false; !done; {
  279. var line string
  280. if line, err = bufin.ReadString('\n'); err != nil {
  281. if err == io.EOF {
  282. done = true
  283. } else {
  284. goto exit
  285. }
  286. }
  287. line = strings.TrimSpace(line)
  288. if len(line) == 0 {
  289. // Skip blank lines
  290. continue
  291. }
  292. if line[0] == ';' || line[0] == '#' {
  293. // Skip comments
  294. continue
  295. }
  296. if groups := assignRegex.FindStringSubmatch(line); groups != nil {
  297. key, val = strings.TrimSpace(groups[1]), strings.TrimSpace(groups[2])
  298. if key == "process" {
  299. processLabel = strings.Trim(val, "\"")
  300. }
  301. if key == "file" {
  302. fileLabel = strings.Trim(val, "\"")
  303. }
  304. }
  305. }
  306. if processLabel == "" || fileLabel == "" {
  307. return "", ""
  308. }
  309. exit:
  310. mcs := IntToMcs(os.Getpid(), 1024)
  311. scon := NewContext(processLabel)
  312. scon["level"] = mcs
  313. processLabel = scon.Get()
  314. scon = NewContext(fileLabel)
  315. scon["level"] = mcs
  316. fileLabel = scon.Get()
  317. return processLabel, fileLabel
  318. }
  319. func SecurityCheckContext(val string) error {
  320. return writeCon(fmt.Sprintf("%s.context", selinuxPath), val)
  321. }
  322. func CopyLevel(src, dest string) (string, error) {
  323. if !SelinuxEnabled() {
  324. return "", nil
  325. }
  326. if src == "" {
  327. return "", nil
  328. }
  329. if err := SecurityCheckContext(src); err != nil {
  330. return "", err
  331. }
  332. if err := SecurityCheckContext(dest); err != nil {
  333. return "", err
  334. }
  335. scon := NewContext(src)
  336. tcon := NewContext(dest)
  337. tcon["level"] = scon["level"]
  338. return tcon.Get(), nil
  339. }