|
2 | 2 |
|
3 | 3 | # Module and documentation by Eric S. Raymond, 21 Dec 1998 |
4 | 4 |
|
5 | | -import os, shlex, stat |
| 5 | +import os, stat |
6 | 6 |
|
7 | 7 | __all__ = ["netrc", "NetrcParseError"] |
8 | 8 |
|
9 | 9 |
|
| 10 | +def _can_security_check(): |
| 11 | + # On WASI, getuid() is indicated as a stub but it may also be missing. |
| 12 | + return os.name == 'posix' and hasattr(os, 'getuid') |
| 13 | + |
| 14 | + |
| 15 | +def _getpwuid(uid): |
| 16 | + try: |
| 17 | + import pwd |
| 18 | + return pwd.getpwuid(uid)[0] |
| 19 | + except (ImportError, LookupError): |
| 20 | + return f'uid {uid}' |
| 21 | + |
| 22 | + |
10 | 23 | class NetrcParseError(Exception): |
11 | 24 | """Exception raised on syntax errors in the .netrc file.""" |
12 | 25 | def __init__(self, msg, filename=None, lineno=None): |
@@ -142,18 +155,12 @@ def _parse(self, file, fp, default_netrc): |
142 | 155 | self._security_check(fp, default_netrc, self.hosts[entryname][0]) |
143 | 156 |
|
144 | 157 | def _security_check(self, fp, default_netrc, login): |
145 | | - if os.name == 'posix' and default_netrc and login != "anonymous": |
| 158 | + if _can_security_check() and default_netrc and login != "anonymous": |
146 | 159 | prop = os.fstat(fp.fileno()) |
147 | | - if prop.st_uid != os.getuid(): |
148 | | - import pwd |
149 | | - try: |
150 | | - fowner = pwd.getpwuid(prop.st_uid)[0] |
151 | | - except KeyError: |
152 | | - fowner = 'uid %s' % prop.st_uid |
153 | | - try: |
154 | | - user = pwd.getpwuid(os.getuid())[0] |
155 | | - except KeyError: |
156 | | - user = 'uid %s' % os.getuid() |
| 160 | + current_user_id = os.getuid() |
| 161 | + if prop.st_uid != current_user_id: |
| 162 | + fowner = _getpwuid(prop.st_uid) |
| 163 | + user = _getpwuid(current_user_id) |
157 | 164 | raise NetrcParseError( |
158 | 165 | (f"~/.netrc file owner ({fowner}, {user}) does not match" |
159 | 166 | " current user")) |
|
0 commit comments