638 stories
·
38 followers

Polyinstantiating /tmp and /var/tmp directories

2 Shares

On Linux systems, the /tmp/ and /var/tmp/ locations are world-writable. They are used to provide a common location for temporary files and are protected through the sticky bit, so that users cannot remove files they don't own from the directory, even though the directory itself is world-writable. Several daemons/applications use the /tmp or /var/tmp directories to temporarily store data, log information, or to share information between their sub-components. However, due to the shared nature of these directories, several attacks are possible, including:

Polyinstantiation of temporary directories is a proactive security measure which reduces chances of attacks that are made possible by /tmp and /var/tmp directories being world-writable.

Setting Up Polyinstantiated Directories

Configuring polyinstantiated directories is a three-step process (this example assumes that a Red Hat Enterprise Linux 7 system is used):

First, create the parent directories which will hold the polyinstantiation child directories. Since in this case we want to setup polyinstantiated /tmp and /var/tmp, we create /tmp-inst and /var/tmp/tmp-inst as the parent directories.

$ sudo mkdir --mode 000 /tmp-inst
$ sudo mkdir --mode 000 /var/tmp/tmp-inst

Creating these directories with mode 000 ensures that no users can access them directly. Only polyinstantiated instances mounted on /tmp (or /var/tmp) can be used.

Second, configure /etc/security/namespace.conf. This file already contains an example configuration which we can use. In our case we will just uncomment the lines corresponding to /tmp and /var/tmp.

 /tmp     /tmp-inst/            level      root,adm 
 /var/tmp /var/tmp/tmp-inst/    level      root,adm

This configuration specifies that /tmp must be polyinstantiated from a subdirectory of /tmp-inst. The third field specifies the method used for polyinstatiation which in our case is based on process MLS level. The last field is a comma-separated list of uids or usernames for whom the polyinstantiation is not performed1. More information about the configuration parameters can be found in /usr/share/doc/pam-1.1.8/txts/README.pam_namespace.

Also ensure that pam_namespace is enabled in the PAM login configuration file. This should already be enabled by default on Red Hat Enterprise Linux systems.

 session    required    pam_namespace.so

Third, setup the correct selinux context. This is a two-step process. In the first step we need to enable the global SELinux boolean for polyinstantiation using the following command:

$ sudo setsebool polyinstantiation_enabled=1

You can verify it worked by using:

$ sudo getsebool polyinstantiation_enabled
polyinstantiation_enabled --> on

In the second step, we need to set the process SELinux context of the polyinstantiated parent directories using the following commands:

$ sudo chcon --reference=/tmp /tmp-inst
$ sudo chcon --reference=/var/tmp/ /var/tmp/tmp-inst

The above commands use the selinux context of the /tmp and /var/tmp directories, respectively, as references and copies them to our polyinstantiated parent directories.

Once the above is done, you can logoff and login, and each non-root user gets their own polyinstantiation of /tmp and /var/tmp directories.

PrivateTmp feature of systemd

Daemons running on systems which use systemd can now use the PrivateTmp feature. This enables a private /tmp directory for each daemon that is not shared by the processes outside of the namespace, however this makes sharing between processes outside the namespace using /tmp impossible. The main difference between polyinstantiated /tmp and PrivateTmp is that the former creates a per-user /tmp directory, while the latter creates a per-deamon or process /tmp.

Conclusion

In conclusion, while polyinstantiation will not prevent every type of attack (caused by flaws in the applications running on the system, or mis-configurations like weak root password, wrong directory/file permissions etc), it is a useful addition to your security toolkit that is straightforward to configure. Polyinstantiation can also be used for other directories such as /home. Some time ago, polyinstantiated /tmp by default was proposed for Fedora, but several issues caused the proposal to be denied.


  1. Default values include the root and the adm user. Since root is a superuser anyway, it does not make any sense to polyinstantiate the /tmp directory for the root user. 

Category

Secure
Read the whole story
llucax
19 days ago
reply
Berlin
afita
19 days ago
reply
Cluj-Napoca, România
Share this story
Delete

Ryabitsev:Travel (Linux) laptop setup

1 Share
On his blog, Linux Foundation Director of IT Infrastructure Security Konstantin Ryabitsev has some advice for laptop security when traveling overseas. Some attendees of LinuxCon China in Beijing June 19-20 have asked for his thoughts, so he put together the post, which is good advice, if perhaps overly paranoid for some, no matter what country you might be visiting. "China is not signatory to the "Personal Use Exemption" when it comes to encrypted devices, so bringing a laptop with encrypted hard drive with you is not technically legal. If the border officer does not like you for some reason and has grounds to suspect you are not being truthful about your stated reasons for entering China, you may be asked to decrypt your devices for a search. Failure to do so may result in unpleasantness, and you may be detained or fined merely on the grounds of having an encrypted device when entering the country. (As opposed to, for example, entering a country that is signatory to the personal use exemption, where just having an encrypted device is not grounds for any action. That said, it is never in your interest to make the border officer not like you for some reason. Until you are admitted to the country as a legal alien, the Geneva Convention and the Universal Declaration of Human Rights are pretty much the only legal frameworks protecting you as a person against foreign government action.) It is important to point out that you are extremely unlikely to be penalized for bringing in an encrypted laptop with you to China, as any kind of widespread zealous application of such practice would quickly shut down any business travel to China -- and this is definitely not in the government's interest."
Read the whole story
afita
97 days ago
reply
Cluj-Napoca, România
Share this story
Delete

Food Nutrition Per Dollar – 44 Micro Nutrients Sorted By Highest Nutrition Rank

1 Share

Any Biology Experts think they can understand the biological implications of this data? Email me

Quick Tips To Save Money On Food

Despite Marketing Companies ability to control your perception- Fresh Food is lower cost than Canned, Frozen, Prepared/boxed, Fast Food.

After a half of a decade studying this problem, the math has changed my life.

Consume More-
  • Milk
  • Eggs
  • Romaine Lettuce
  • Kale
  • Potatoes
  • Carrots
  • Beans
  • Peanuts
  • Spinach
  • (Flour?)
  • Butternut Squash
  • Jalapeno Peppers
  • Lentils
  • Canned Tomatoes
Consume Less-

  • Out of Season/Location Fresh Foods
  • Energy Drinks
  • Alcoholic Drinks(sorry not a ton of nutrition in beer + wine)
  • Brand Name Apples
General Results

Best Values- The Math

There are two types of data presented. Nutrition Per Dollar and Nutrition Ratio Total(Sum).

A straight addition of nutrients would yield an unimportant number due to a wildly high amount of Vitamin A in carrots.

The solution was to remove the dimensions of each to find a Nutrient Ratio:

(Ingredient’s Nutrient mg/dollar) / Max Nutrient mg/dollar

This creates a scale from 0 to 1, where 1 is the best value for that Nutrient/$. By removing the dimensions, we can now add these up. If we decided we wanted to weight one nutrient over others, we could use multiplication.

The numbers below are an addition of 37 micronutrients I considered beneficial.

On Data Collection- I nearly always picked the lowest cost option, and obtained nutrition data from here.

Lowest Cost Nutrition

Understanding and implementing top 50 ranked foods is valuable.

Nutrition Ratio Total = Sum of 37 (Nutrient/$ / Highest Nutrient/$). The original Nutrient/$ can be found below.

The Nutrition Ratio Total is good for understanding scale of value. IE: Oranges(1.57) are 3x more Nutritious Per Dollar than Lemons(0.51).

If you havent eaten a specific vegetable before, I’d toss the veggie into something you already enjoy. We started adding Spinach or Kale to our friend rice. After 10 minutes of cooking, it still tastes like my favorite fried rice in the world, but it has Kale.

Frozen food doesnt show up until #19, where Frozen Carrots are 2x more expensive than Fresh Carrots. The lesson here is to reduce/eliminate canned and frozen food. Fresh/Raw foods are typically cheaper.

One more cost saving tip- Replace a $1.69 Red Pepper with Carrots. Just as sweet.

Flour + Cereal- Apparently low fiber and enriched with vitamins help you score pretty well. Monster took a note from them. We sometimes use flour to thicken our soups/stews, but that’s about it.

Here is the Excel Data:

Download the raw data here

Complete Nutrition Per Dollar- 44 More Charts

Hungry? Get Infinity Data Per Dollar, Download the raw data here.

Bio/Med/Health people- I’d like to learn more about this data and implications of it. Please contact me.

How To Eat For 1,000$/year

A half decade of studying this topic and having to cook for my ‘used to be picky’ wife, here is my ultimate guide to eating the most nutritious, healthy, low cost food ever. We aim to eat around 700 Calories Per Dollar and my ‘used to be picky’ wife now prefers our menu over restaurants.

Foods to remember

Protein– Beans, Lentils, Chicken, Eggs, Milk, and potentially discounted meats(turkey,pork/ground beef).
Veggies– Leafy greens, Carrots, and in-season veggies
Carbs– Pick Bread, Rice, Noodles- Don’t buy premade boxed rice/noodles.
Spices– Reward yourself. By eating at home you can borderline go wild on spices, sauces, etc… I’ll stay within ~1$ on things like, cream of chicken, a variety of spices, dressing, BBQ sauces, etc…

Make The Food Taste Good

80% of the taste is Easy

Salt, Lemon/Lime/Vinegar, Sugar, Butter/Oil/Fats, and umami taste good.

Add each slowly and taste like you would testing saltiness.

The challenging 20%

Play around with texture, how you cook each type of food. Mess around with timing when you add spices/sauces.

My preferred texture, usually uses this method to cooking anything- Cook chicken on medium-high ~4 minutes, flip, 4 minutes, (optional deglaze), throw in veggies, cook everything for ~8 minutes. Serve on top of the carb. Change around timing when you add spices and sauces, the order will slightly change the finished product.

Everything tastes good. There are almost 0 foul flavors. Just make sure you Salt, Add an Acid, Add sweetness, Fats, and Umami (the 5 things up top).

Grocery Shop

I go to the lowest cost store in my area with a printed out grocery list of what we are eating for the week(we cycle through 28 recipes).

Writing the list was a solid 1 hour job to type everything out and plan it. We even sorted by isle. However after 5 years of using it, grocery shopping takes less than 15 minutes including checkout.

Pick fresh veggies, chicken, eggs, milk. Our list is more specific but we often will grab low cost, in-season foods. When in doubt- You are still saving money not eating out, and all food will taste good.

Buy fresh instead of canned, frozen. Avoid processed rice/noodles.

Need Ideas?

  1. Go on Google
  2. type in a protein a veggie and a carb, IE:

    Chicken Rice Peas

There will be a recipe for it. And since all food tastes good, it probably will too.

AVOID

Avoid Fast Food, Restaurants, Boxed Food, Canned Food, Frozen Food, Processed Food. (sorry, I just really want to save you money.)

Even Clif Bars on sale for 1$ off were less than 20g Protein Per Dollar.

Marketing is Crooked

You were told, McDonalds was the cheapest, most nutritious food. How did that 440 Calorie Per Dollar propaganda spread? Today its 2-3x more expensive than anything we eat.

How much did McDonald’s pay The Telegraph to write the article “McDouble is ‘cheapest and most nutritious food in human history'” ?

You were told Prepared Foods are cheaper than fresh food.

Nice move Marketing Companies. You got away with it for, ~20 years?

After years of studying cost effective eating- Healthy, fresh foods are almost always cheaper than anything a company prepares and re-sells.

We understand the convenience factor of having food prepared for us. That has value.

However, Marketing Companies pushed the idea their foods are low cost. I thought I was saving money by eating canned veggies.

We finally have data that can shut those rumors down.

Next Efficiency

This project took months, planning the project, getting reliable data formatted well, and 2 weekends at the grocery store buying literally every veggie and fruit, excel fun, and trying to wrap my head around explaining 40+ data sets.

Next up- I am bumping up to weekly articles. Fluids Per Dollar, Caffeine Per Second, Should You Shop For Gas, Dog Food Per Dollar, an update to Paper Products Per Dollar, Best College Degrees, Caffeine Per Second, Caffeine Per Second, and more. 😛

I’ve really enjoyed studying time and will focus on a major Protein Per Second article. Protein is weird since it often needs to be prepared. There are obvious things like Whey protein that would top the list, but I think it would be fascinating to compare cooking eggs and McDonalds.

And… Don’t worry, I’ve already started thinking about the linear algebra to calculate The Most Efficient Meal and Efficient Daily Diet.

I need to know people want Efficiency, Show your support by sharing this article. Be the person to save your friends $10,000s. I need to know if I should keep going. Please Share.

The post Food Nutrition Per Dollar – 44 Micro Nutrients Sorted By Highest Nutrition Rank appeared first on Efficiency Is Everything.

Read the whole story
afita
106 days ago
reply
Cluj-Napoca, România
Share this story
Delete

Do It for the Cash

1 Share

Let’s say you don’t care about the environment at all. All you care about is money. Why? Well, perhaps you’re testing the theory that money can’t buy you happiness—and you demand first-hand proof. Maybe you have a psychological disorder—greed may be just that. Or possibly you look forward to living in the most unequal society that has ever existed on the planet so you’ll have more material for the dystopian masterpiece you’re writing—and you figure you may as well be at the top while you’re at it, although you won’t make your money writing and the few people who will still be able to afford to buy your book won’t read it. Also, sorry about the libraries closing 

If for no other reason, reduce your waste to save cold hard cash. Don’t do it for the oceans. Don’t do it to conserve resources so others may have a share of them. Don’t do it for the next generation. Be completely selfish about it. Your motives are your own business. Do whatever it takes to get on board. I have argued—rather effectively I believe—that reducing your waste can improve your sex life.

1. Buy less stuff

The waste-reducing reason: This is pretty self-explanatory. If you want to reduce your waste, buy less stuff. You’ll have fewer things to deal with when they break/wear out/you no longer find them useful.

Since I write a food blog, let’s look at kitchen gadgets for example. They can tempt us foodie types. But gadgets take up precious cupboard or counter space. And eventually the flimsy ones break. I know I push pressure cookers on here regularly (they will change your life) but if you think you will never use one, don’t buy one. That goes for other wants. You might have a solution for that want-soon-turned-need right under your nose. For at least a year, I had wanted a lame for scoring my sourdough bread but the only type I could find had a large plastic handle. When the blade dulls, you toss the whole thing. So I made my own with a recyclable razor blade. Not that I can make everything. But if I think I need a new gadget, rather than rushing out to buy it, I can usually find a solution. This is what Google is for.

cherry pitter and bread lame
Homemade cherry pitter and bread lame

When you do buy stuff—and this includes some ingredients—buy multi-purpose stuff to avoid waste. You can substitute many ingredients for other ingredients you may already have on hand. For example, to make baking powder, combine 1 teaspoon baking soda with 2 teaspoons cream of tartar. Since we almost always have cream of tartar on hand (we need it for recipes such as meringues and macaroons), and baking soda is a must (for cooking, cleaning, sometimes washing hair), we also have baking-powder-in-the-making on hand too.

The I-just-want-to-save-cash reason: Again, this is pretty self-explanatory. That whole “Save big when you shop at [name of store] this weekend!” is pretty standard marketing fare. Ummm, you save money when you don’t spend it.

2. When you do buy, look for second-hand first

The waste-reducing reason: Many manufacturers envelop their goods in so much packaging. And if you take into account all of the resources that go into producing new goods—the harvest, production and transportation of raw materials; the raw materials themselves; the energy and water consumed during production; the fossil fuels burned for shipping—that new pair of jeans has a large footprint whether you bring your own bag to the store or not (but of course do bring one…).

amount of water to make jeans
Thirsty jeans

Soon after we went plastic-free, I needed new sheets. One fitted sheet had worn out. Other fitted sheets disappeared somehow. I avoided buying new sheets for a long time because they always come packaged in one of those giant clear plastic zippered cases. What do you do with those? Then I found a bunch of sheets at the thrift shop that looked just fine. When I told my ex about my score of new-to-me sheets, he said, “Ewww gross, you bought used sheets?!” to which I responded “Have you ever stayed in a hotel?”

The I-just-want-to-save-cash reason: I have found so much great stuff at thrift stores, such as the Fiesta Ware below—$27 for the equivalent of four place settings. One place setting costs about $50 retail. The All Clad kettle farther down cost $10 ($100 retail) and the pressure cooker $15 ($45 retail).

Fiesta Ware score at the thrift shop
$25 for both of these and look, I’m pushing the pressure cooker again…

3. Bring lunch to work

The waste-reducing reason: Do you cook most of the meals at home only to have people pooh-pooh your leftovers the following night? Save them for lunch. I almost always take leftovers to work for lunch and whatever fruit or vegetables need to be eaten soon. This reduces food waste. Tossed food not only squanders the food but also all the resources that went into growing that food—the land, the water, the energy, the labor. When the food rots in landfill, it releases methane gas, a greenhouse gas more potent that carbon dioxide.

I pack my lunches in LunchBots or glass jars and containers. I take any compost home in these containers and add that to my pile. I bring a cloth napkin also. All of this goes into a reusable cloth bag. We have real utensils at the office so I don’t need to bring those.

The I-just-want-to-save-cash reason: We have limited food options at the office where I work. A sandwich at one of the only restaurants near us costs about $8. It tastes delicious but if I order one each of the two to three days a week I work onsite, I would spend about between $70 to $100 a month on sandwiches. My leftovers cost a fraction of that—let’s say a quarter of what I would spend in a restaurant. Plus my healthier food may save money on healthcare down the line…

4. Buy from bulk bins

The waste-reducing reason: If you want to reduce your waste and you have access to bulk bins, shopping with your own reusable cloth bags and jars will reduce a huge amount of plastic packaging—and paper packaging, but mostly plastic packaging because it’s everywhere. 

The I-just-want-to-save-cash reason: Make sure you get your glass jars weighed and marked (i.e., tared) before you fill them so you pay for the weight of the food in the jar only and not for the weight of the jar. For the most part, I pay less for food I buy from the bulk bins than I would if I bought everything prepackaged. Most spices cost much less. Olive oil can be a bit of a wash at some stores. Since you can buy only what you need when you buy in bulk, you reduce food waste, which also saves money.

bulk shopping
Bulk bins at Goodness Me! in Guelph, Ontario

5. Shop with reusables

The waste-reducing reason: My zero-waste shopping kit includes cloth shopping bags, homemade cloth produce bags, metal containers and glass jars. For my most recent big haul, I used 25 jars, three cloth produce bags and four cloth shopping bags. That diverted at least 32 plastic packages and bags from landfill, but likely more, since I bought large quantities in a few of my big jars. Had those bigger portions been packaged, they would have required at least a couple of packages per large jar for an equivalent amount of food.

The I-just-want-to-save-cash reason: I get a discount when I bring my own bags and jars (this depends on the store and at some stores, depends on the cashier). For this haul, I received a discount of 5 cents per bag or jar, for a total discount of $1.60.

Bulk haul from Rainbow Co-op in San Francisco

6. Cook

The waste-reducing reason: Processed food comes in shiny—and mostly plastic—packaging. If you cook your food and shop as above, you’ll greatly reduce both your packaging waste and your food waste.

Some ingredients actually require less effort to make than to trek to the store and buy. Plus you reduce your packaging. A cup of my homemade vanilla extract replaces several plastic bottles’ worth of store-bought.

The I-just-want-to-save-cash reason: I can cook a vat of chana masala—enough for at least two meals for three of us—made with organic ingredients of the best quality, for about $12. At my favorite Indian restaurant, one serving of chana masala costs $13.95. (I’m usually very modest but I think mine tastes just as good.)

That homemade vanilla extract costs much less money than store-bought. I can make about six bottles of vanilla extract for less than $20. The equivalent amount of inexpensive vanilla extract costs $30. And it’s so easy to start—split vanilla beans and drop them into a cup of vodka, rum or bourbon and set that aside to steep for a couple of months. 

homemade vanilla extract
Homemade vanilla extract in the making

7. Preserve food

The waste-reducing reason: I make lots of different fermented foods—sourdough bread, kombucha, ginger beer, dill pickles, sauerkraut, hot peppers, preserved lemons. By making these myself I eliminate all the packaging waste of store-bought items. I am convinced that most people simplifying their lives will stumble onto fermentation at some point.

I also freeze food. Every September or so, I madly process tomatoes. On Saturdays or Sundays, a few weekends in a row near the end of tomato season, I spend part of the day roasting, packing and freezing 20-pound hauls of tomatoes. Yes, it’s a lot of work but throughout winter I have really delicious tomatoes. The taste of canned cannot compare.

The I-just-want-to-save-cash reason: A loaf of authentic sourdough at my farmer’s market costs $8. Mine, let’s say $2 including the energy. A bottle of ho-hum ginger beer costs a couple of dollars. Mine costs pennies—50 cents a bottle tops—and it tastes fantastic. A small jar of preserved lemons will set you back about $8—if you can find any. I have a lemon tree so my preserved lemons cost basically nothing to make. The only comparable tomatoes I have found cost $8 for a 16-ounce jar. Mine cost about a dollar for the same amount.

Yes, if I spent these hours working at my day job, I would earn more money than I save. But I enjoy making all of this. I enjoy even more eating all of this.

Frozen tomatoes in jars

8. Bring your own cup

The waste-reducing reason: At my favorite cafe, I pay for a small tea even though I bring a large, 16-ounce thermos. I start to shake if I have two cups of black tea in the thing. Other stores, if anything, offer a small discount. Until cafes charge for a throwaway cup, rather than give a discount, I don’t believe we will make much of a dent in the billions-of-coffee-cups-to-landfill-each-year problem. People don’t care about a 10 cent discount but charge them 10 cents for a cup and they suddenly will. Passionately! For now, as with most everything in the lifecycle of stuff, it’s up to us, the consumer, to make changes.

The I-just-want-to-save-cash reason: I’m sitting at Philz as I type this. A small tea costs $3.50. A large costs $4.50.

Klean Kanteen thermos
Bring your own

9. Drink more water

She does go on about bottled water…

The waste-reducing reason: Bottled water has to go. According to The Story of Stuff website, Americans alone “buy more than half a million bottles of water per week. That enough to circle the globe more than 5 times.” This is madness.

The I-just-want-to-save-cash reason: A case of bottled water costs between $5 and $10 depending on the size, brand and store. The equivalent from your tap costs basically $0.

10. Cut the soda, energy drinks, juice and other bottled beverages

The waste-reducing reason: Even if they do come in glass—which burns more fossil fuel for transport than plastic due to the weight—bottled beverages almost always have a big plastic lid that generally can’t go in the recycling bin. And if these bottles are made of plastic? Well, consider this: Coke, which decades ago abandoned its refillable bottle program, produced more than 100 billion plastic bottles in 2016. Billion. With a “b.” As in barons, bleak, blackguards, abominable (close enough).

I don’t buy bottled beverages. I make kombucha, ginger beer, beet kvass… I even make my own booze. In fact, I rarely used to drink until I figured out how to make booze. It’s so easy. So maybe this is a bad example…

The I-just-want-to-save-cash reason: A 16-ounce bottle of my homemade organic kombucha, using the best organic looseleaf tea I can find, costs 50 cents a bottle maximum. Store-bought costs between $4 to $5.

homemade kombucha
Cherry kombucha (left bottle and small jar) and hibiscus (right bottles)

11. Eat lower on the food chain

The waste-reducing reason: Where I live, meat and cheese have the most packaging. I can buy meat at one butcher in my own container but if you take into account the resources that went into producing a pound of beef versus a pound of lentils, the latter has a much smaller footprint.

We eat lots of beans and legumes, lots of vegetables and very little fish or meat (my younger daughter likes it so I make it for her sometimes). Someone on Instagram recently asked me how to make a diet based on vegetables more tasty. We use lots of spices—cumin, crushed red chilies, turmeric, ginger, garlic, coriander, cinnamon, cardamom, oregano, basil, nutmeg—and I make all sorts of fermented food. The spices and ferments add SO much flavor.

The I-just-want-to-save-cash reason: A pound of organic pastured ground beef costs about $10 a pound at the Whole Foods near me. A pound of chickpeas costs a fifth of that. Like brown bagging it at work rather than dining out, eating food lower on the food chain—more vegetables and whole grains and less meat—may save healthcare dollars later

12. Ditch the coupons

The waste-reducing reason: “Wait, what?” I hear you say. “I care about reducing waste but I also agreed to read this long post for your money-saving tips.” Hear me out. Real food rarely goes on sale. Usually only the processed, food-like products go on sale—the stuff in plastic packaging. Glance through a Sunday flyer or a coupon booklet and you’ll notice coupons mostly for processed food, commercial cleaners and other consumer products. How often do you see a big sale on bunches of fresh carrots? Stick with real food and you cut the packaging.

The I-just-want-to-save-cash reason: Avoid the products associated with most coupons and you’ll buy less processed food and fewer consumer products—that stuff isn’t cheap.

zero waste shopping
A recent farmer’s market haul

See my recent post “21 Consumer Products You Can (Likely) Live Without” for more stuff to cut that will save you money. You don’t fool me though. I know you don’t do this for the cash only 😉

Read the whole story
afita
117 days ago
reply
Cluj-Napoca, România
Share this story
Delete

Running system services in containers

2 Shares

At FOSDEM, in the awesome Guile track, I briefly demoed a new experimental GuixSD feature as part my talk on system services: the ability to run system services in containers or “sandboxes”. This post discusses the rationale, status, and implementation of this feature.

The problem

Our computers run many programs that talk to the Internet, and the Internet is an unsafe place as we all know—with states and assorted organizations collecting “zero-day exploits” to exploit them as they see fit. One of the big tasks of operating system distributions has been to keep track of known software vulnerabilities and patch their packages as soon as possible.

When we look closer, many vulnerabilities out there can be exploited because of a combination of two major weaknesses of GNU/Linux and similar Unix-like operating systems: lack of memory-safety in the C language family, and ambient authority in the operating system itself. The former leads to a huge class of bugs that become security issues: buffer overflows, use-after-free, and so on. The latter makes them more exploitable because processes have access to many resources beyond those they really need.

Security-sensitive software is now increasingly written in memory-safe languages, as is the case for Guix and GuixSD. Projects that have been using C are even considering a complete rewrite, as is the case for Tor. Of course the switch away from memory-unsafe languages won’t happen overnight, but it’s good to see a consensus emerging.

The operating system side of things is less bright. Although the principle of least authority (POLA) has been well-known in operating system circles for a long time, it remains foreign to Unix and GNU/Linux. Processes run with the full authority of their user. On top of that, until recent changes to the Linux kernel, resources were global and there was essentially a single view of the file system, of the process hierarchy, and so on. So when a remote-code-execution vulnerability affects a system service—like in the BitlBee instant messaging gateway (CVE-2016-10188) running on my laptop—an attacker could potentially do a lot on your machine.

Fortunately, many daemons have built-in mechanisms to work around this operating system defect. For instance, BitlBee, and Tor can be told to switch to a separate unprivileged user, avahi-daemon and ntpd can do that and also change root. These techniques do reduce the privileges of those processes, but they are still imperfect and ad hoc.

Increasing process isolation with containers

The optimal solution to this problem would be to honor POLA in the first place. As an example, the venerable GNU/Hurd is a capability-based operating system. Thus, GNU/Hurd has supported fine-grained virtualization from the start: a newly-created process can be given a capability to its own proc server (which implements the POSIX notion of processes), to a specific TCP/IP server, etc. In addition, its POSIX personality offers interesting extensions, such as the fact that processes run with the authority of zero or more UIDs. For instance, the Hurd’s login program starts off with zero UIDs and gains a UID when someone has been authenticated.

Back to GNU/Linux, “namespaces” have been introduced as a way to retrofit per-process views of the system resources, and thus improve isolation among processes. Each process can run in a separate namespace and thus have a different view of the file system, process tree, and so on (a process running in separate namespaces is often referred to as a “container”, although that term is sometimes used to denote much larger tooling and practices built around namespaces.) Why not use that to better isolate system services?

Apparently this idea has been floating around. systemd has been considering to extend its “unit files” to include directives instructing systemd to run daemons in separate namespaces. GuixSD uses the Shepherd instead of systemd, but running system services in separate namespaces is something we had been considering for a while.

In fact, adding the ability to run system services in containers was a low-hanging fruit: we already had call-with-container to run code in containers, so all we needed to do was to provide a containerized service starter that uses call-with-container.

The Shepherd itself remains unaware of namespaces, it simply ends up calling make-forkexec-constructor/container instead of make-forkexec-constructor and that’s it. The changes to the service definitions of BitlBee and Tor are minimal. The end result, for Tor, looks like this:

(let ((torrc (tor-configuration->torrc config)))
  (with-imported-modules (source-module-closure
                          '((gnu build shepherd)
                            (gnu system file-systems)))
    (list (shepherd-service
           (provision '(tor))
           (requirement '(user-processes loopback syslogd))

           (modules '((gnu build shepherd)
                      (gnu system file-systems)))

           (start #~(make-forkexec-constructor/container
                     (list #$(file-append tor "/bin/tor") "-f" #$torrc)

                     #:mappings (list (file-system-mapping
                                       (source "/var/lib/tor")
                                       (target source)
                                       (writable? #t))
                                      (file-system-mapping
                                       (source "/dev/log") ;for syslog
                                       (target source)))))
           (stop #~(make-kill-destructor))
           (documentation "Run the Tor anonymous network overlay.")))))

The with-imported-modules form above instructs Guix to import our (gnu build shepherd) library, which provides make-forkexec-constructor/container, into PID 1. The start method of the service specifies the command to start the daemon, as well as file systems to map in its mount name space (“bind mounts”). Here all we need is write access to /var/lib/tor and to /dev/log (for logging via syslogd). In addition to these two mappings, make-forkexec-constructor/container automatically adds /gnu/store and a bunch of files in /etc as we will see below.

Containerized services in action

So what do these containerized services look like when they’re running? When we run herd status bitblee, disappointingly, we don’t see anything special:

charlie@guixsd ~$ sudo herd status bitlbee
Status of bitlbee:
  It is started.
  Running value is 487.
  It is enabled.
  Provides (bitlbee).
  Requires (user-processes networking).
  Conflicts with ().
  Will be respawned.
charlie@guixsd ~$ ps -f 487
UID        PID  PPID  C STIME TTY      STAT   TIME CMD
bitlbee    487     1  0 Apr11 ?        Ss     0:00 /gnu/store/pm05bfywrj2k699qbxpjjqfyfk3grz2i-bitlbee-3.5.1/sbin/bitlbee -n -F -u bitlbee -c /gnu/store/y4jfxya56i1hl9z0a2h4hdar2wm

Again this is because the Shepherd has no idea what a namespace is, so it just displays the daemon’s PID in the global namespace, 487. The process is running as user bitlbee, as requested by the -u bitlbee command-line option.

We can invoke nsenter and take a look at what the BitlBee process “sees” in its namespace:

charlie@guixsd ~$ sudo nsenter -t 487 -m -p -i -u $(readlink -f $(type -P bash))
root@guixsd /# echo /*
/dev /etc /gnu /proc /tmp /var
root@guixsd /# echo /proc/[0-9]*
/proc/1 /proc/5
root@guixsd /# read line < /proc/1/cmdline
root@guixsd /# echo $line
/gnu/store/pm05bfywrj2k699qbxpjjqfyfk3grz2i-bitlbee-3.5.1/sbin/bitlbee-n-F-ubitlbee-c/gnu/store/y4jfxya56i1hl9z0a2h4hdar2wmivgbl-bitlbee.conf
root@guixsd /# echo /etc/*
/etc/hosts /etc/nsswitch.conf /etc/passwd /etc/resolv.conf /etc/services
root@guixsd /# echo /var/*
/var/lib /var/run
root@guixsd /# echo /var/lib/*
/var/lib/bitlbee
root@guixsd /# echo /var/run/*
/var/run/bitlbee.pid /var/run/nscd

There’s no /home and generally very little in BitlBee’s mount namespace. Notably, the namespace lacks /run/setuid-programs, which is where setuid programs live in GuixSD. Its /etc directory contains the minimal set of files needed for proper operation rather than the complete /etc of the host. /var contains nothing but BitlBee’s own state files, as well as the socket to libc’s name service cache daemon (nscd), which runs in the host system and performs name lookups on behalf of applications.

As can be seen in /proc, there’s only a couple of processes in there and “PID 1” in that namespace is the bitlbee daemon. Finally, the /tmp directory is a private tmpfs:

root@guixsd /# : > /tmp/hello-bitlbee
root@guixsd /# echo /tmp/*
/tmp/hello-bitlbee
root@guixsd /# exit
charlie@guixsd ~$ ls /tmp/*bitlbee
ls: cannot access '/tmp/*bitlbee': No such file or directory

Our bitlbee process runs in a separate mount, PID, and IPC namespace, but it runs in the global user namespace. The reason for this is that we want the -u bitlbee option (which instructs bitlbee to setuid to an unprivileged user at startup) to work as expected. It also shares the network namespace because obviously it needs to access the network.

A nice side-effect of these fully-specified execution environments for services is that it makes them more likely to behave in a reproducible fashion across machines—just like fully-specified build environments help achieve reproducible builds.

Conclusion

GuixSD master and its upcoming release include this feature and a couple of containerized services, and it works like a charm! Yet, there are still open questions as to the way forward.

First, we only looked at “simple” services so far, with simple static file system mappings. Good candidates for increased isolation are HTTP servers such as NGINX. However, for these, it’s more difficult to determine the set of file system mappings that must be made. GuixSD has the advantage that it knows how NGINX is configured and could potentially derive file system mappings from that information. Getting it right may be trickier than it seems, though, so this is something we’ll have to investigate.

Another open question is how the service isolation work should be split between the distro, the init system, and the upstream service author. Authors of daemons already do part of the work via setuid and sometimes chroot. Going beyond that would often hamper portability (the namespace interface is specific to the kernel Linux) or even functionality if the daemon ends up lacking access to resources it needs.

The init system alone also lacks information to decide what goes into the namespaces of the service. For instance, neither the upstream author nor the init system “knows” whether the distro is running nscd and thus they cannot tell whether the nscd socket should be bind-mounted in the service’s namespace. A similar issue is that of D-Bus policy files discussed in this LWN article. Moving D-Bus functionality into the init system itself to solve this problem, as the article suggests, seems questionable, notably because it would add more code to this critical process. Instead, on GuixSD, a service author can make the right policy files available in the sandbox; in fact, GuixSD already knows which policy files are needed thanks to its service framework so we might even be able to automate it.

At this point it seems that tight integration between the distro and the init system is the best way to precisely define system service sandboxes. GuixSD’s declarative approach to system services along with tight Shepherd integration help a lot here, but it remains to be seen how difficult it is to create sandboxes for complex system services such as NGINX.

About GNU Guix

GNU Guix is a transactional package manager for the GNU system. The Guix System Distribution or GuixSD is an advanced distribution of the GNU system that relies on GNU Guix and respects the user's freedom.

In addition to standard package management features, Guix supports transactional upgrades and roll-backs, unprivileged package management, per-user profiles, and garbage collection. Guix uses low-level mechanisms from the Nix package manager, except that packages are defined as native Guile modules, using extensions to the Scheme language. GuixSD offers a declarative approach to operating system configuration management, and is highly customizable and hackable.

GuixSD can be used on an i686 or x86_64 machine. It is also possible to use Guix on top of an already installed GNU/Linux system, including on mips64el, armv7, and aarch64.

Read the whole story
afita
160 days ago
reply
Cluj-Napoca, România
Share this story
Delete

Unity is dead. Long live Ubuntu!

1 Share
Rollercoaster ... of Linux. Again. In this article, I discuss the recent announcement by Canonical to stop the development for phone and convergence, why this happened and what it implies, the technological and strategic directions and challenges, Gnome 3 alternative, fragmentation, uncertain future, and more. Take a look.
Read the whole story
afita
166 days ago
reply
Cluj-Napoca, România
Share this story
Delete
Next Page of Stories