Merge #14984: On POSIX, enforce permissions when reading default .netrc.
diff --git a/Lib/netrc.py b/Lib/netrc.py
index 0fd37e3..713e322 100644
--- a/Lib/netrc.py
+++ b/Lib/netrc.py
@@ -2,7 +2,7 @@
 
 # Module and documentation by Eric S. Raymond, 21 Dec 1998
 
-import os, shlex
+import os, stat, shlex, pwd
 
 __all__ = ["netrc", "NetrcParseError"]
 
@@ -21,6 +21,7 @@
 
 class netrc:
     def __init__(self, file=None):
+        default_netrc = file is None
         if file is None:
             try:
                 file = os.path.join(os.environ['HOME'], ".netrc")
@@ -29,9 +30,9 @@
         self.hosts = {}
         self.macros = {}
         with open(file) as fp:
-            self._parse(file, fp)
+            self._parse(file, fp, default_netrc)
 
-    def _parse(self, file, fp):
+    def _parse(self, file, fp, default_netrc):
         lexer = shlex.shlex(fp)
         lexer.wordchars += r"""!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~"""
         lexer.commenters = lexer.commenters.replace('#', '')
@@ -88,6 +89,26 @@
                 elif tt == 'account':
                     account = lexer.get_token()
                 elif tt == 'password':
+                    if os.name == 'posix' and default_netrc:
+                        prop = os.fstat(fp.fileno())
+                        if prop.st_uid != os.getuid():
+                            try:
+                                fowner = pwd.getpwuid(prop.st_uid)[0]
+                            except KeyError:
+                                fowner = 'uid %s' % prop.st_uid
+                            try:
+                                user = pwd.getpwuid(os.getuid())[0]
+                            except KeyError:
+                                user = 'uid %s ' % os.getuid()
+                            raise NetrcParseError(
+                                ("~/.netrc file owner (%s) does not match"
+                                 " current user (%s)") % (fowner, user),
+                                file, lexer.lineno)
+                        if (prop.st_mode & (stat.S_IRWXG | stat.S_IRWXO)):
+                            raise NetrcParseError(
+                               "~/.netrc access too permissive: access"
+                               " permissions must restrict access to only"
+                               " the owner", file, lexer.lineno)
                     password = lexer.get_token()
                 else:
                     raise NetrcParseError("bad follower token %r" % tt,
diff --git a/Lib/test/test_netrc.py b/Lib/test/test_netrc.py
index 2795456..4156c53 100644
--- a/Lib/test/test_netrc.py
+++ b/Lib/test/test_netrc.py
@@ -5,9 +5,6 @@
 
 class NetrcTestCase(unittest.TestCase):
 
-    def tearDown(self):
-        os.unlink(temp_filename)
-
     def make_nrc(self, test_data):
         test_data = textwrap.dedent(test_data)
         mode = 'w'
@@ -15,6 +12,7 @@
             mode += 't'
         with open(temp_filename, mode) as fp:
             fp.write(test_data)
+        self.addCleanup(os.unlink, temp_filename)
         return netrc.netrc(temp_filename)
 
     def test_default(self):
@@ -103,6 +101,28 @@
             """, '#pass')
 
 
+    @unittest.skipUnless(os.name == 'posix', 'POSIX only test')
+    def test_security(self):
+        # This test is incomplete since we are normally not run as root and
+        # therefore can't test the file ownership being wrong.
+        d = test_support.TESTFN
+        os.mkdir(d)
+        self.addCleanup(test_support.rmtree, d)
+        fn = os.path.join(d, '.netrc')
+        with open(fn, 'wt') as f:
+            f.write("""\
+                machine foo.domain.com login bar password pass
+                default login foo password pass
+                """)
+        with test_support.EnvironmentVarGuard() as environ:
+            environ.set('HOME', d)
+            os.chmod(fn, 0600)
+            nrc = netrc.netrc()
+            self.assertEqual(nrc.hosts['foo.domain.com'],
+                             ('bar', None, 'pass'))
+            os.chmod(fn, 0o622)
+            self.assertRaises(netrc.NetrcParseError, netrc.netrc)
+
 def test_main():
     test_support.run_unittest(NetrcTestCase)