Skip to content

readlink on Windows cannot read app exec links #82015

Closed

Description

@zooba
BPO 37834
Nosy @pfmoore, @tjguk, @ned-deily, @ambv, @zware, @eryksun, @zooba, @miss-islington
PRs
  • bpo-37834: Normalise handling of reparse points on Windows #15231
  • [3.8] bpo-37834: Normalise handling of reparse points on Windows (GH-15231) #15370
  • bpo-37834: Fix test on Windows 7 #15377
  • [3.8] bpo-37834: Fix test on Windows 7 (GH-15377) #15378
  • bpo-37834: Prevent shutil.rmtree exception #15602
  • [3.8] bpo-37834: Prevent shutil.rmtree exception (GH-15602) #15603
  • Note: these values reflect the state of the issue at the time it was migrated and might not reflect the current state.

    Show more details

    GitHub fields:

    assignee = 'https://github.com/zooba'
    closed_at = <Date 2019-08-30.09:05:01.404>
    created_at = <Date 2019-08-12.18:49:21.984>
    labels = ['3.8', '3.9', 'OS-windows']
    title = 'readlink on Windows cannot read app exec links'
    updated_at = <Date 2019-08-30.09:05:01.403>
    user = 'https://github.com/zooba'

    bugs.python.org fields:

    activity = <Date 2019-08-30.09:05:01.403>
    actor = 'lukasz.langa'
    assignee = 'steve.dower'
    closed = True
    closed_date = <Date 2019-08-30.09:05:01.404>
    closer = 'lukasz.langa'
    components = ['Windows']
    creation = <Date 2019-08-12.18:49:21.984>
    creator = 'steve.dower'
    dependencies = []
    files = []
    hgrepos = []
    issue_num = 37834
    keywords = ['patch']
    message_count = 56.0
    messages = ['349486', '349499', '349501', '349502', '349504', '349541', '349591', '349597', '349601', '349611', '349617', '349618', '349622', '349626', '349747', '349749', '349758', '349770', '349779', '349786', '349808', '349812', '349813', '349818', '349827', '349829', '349831', '349834', '349835', '349839', '349841', '349875', '349876', '349888', '349889', '349890', '349969', '349970', '349972', '349975', '349981', '350013', '350106', '350121', '350125', '350141', '350144', '350146', '350148', '350814', '350815', '350818', '350824', '350825', '350831', '350834']
    nosy_count = 8.0
    nosy_names = ['paul.moore', 'tim.golden', 'ned.deily', 'lukasz.langa', 'zach.ware', 'eryksun', 'steve.dower', 'miss-islington']
    pr_nums = ['15231', '15370', '15377', '15378', '15602', '15603']
    priority = 'normal'
    resolution = 'fixed'
    stage = 'resolved'
    status = 'closed'
    superseder = None
    type = None
    url = 'https://bugs.python.org/issue37834'
    versions = ['Python 3.8', 'Python 3.9']

    Activity

    1. zooba commented on Aug 12, 2019

      @zooba
      MemberAuthor

      The IO_REPARSE_TAG_APPEXECLINK was introduced for aliases to installed UWP apps that require activation before they can be executed.

      Currently these are in an unusual place as far as Python support goes - stat() fails where lstat() succeeds, but the lstat() result doesn't have the right flags to make is_link() return True.

      It's not clear whether we *should* treat these as regular symlinks, given there are a number of practical differences, but since we can enable it I'm going to post a PR anyway.

    2. zooba commented on Aug 12, 2019

      @zooba
      MemberAuthor

      Added an update with a new stat field (st_reparse_tag) so that we can tell them apart, which also means I can add a test for readlink.

    3. self-assigned this
      on Aug 12, 2019
    4. eryksun commented on Aug 12, 2019

      @eryksun
      Contributor

      Symlinks are specially interpreted by the file API, I/O manager, and network redirector. So I think they should remain a separate category. readlink() and is_link() should be reserved for POSIX symlinks, i.e. only IO_REPARSE_TAG_SYMLINK.

      These app-exec reparse points are not name surrogates (i.e. 0x2000_0000 set in the tag), and they lack an associated filter driver that handles them in normal file operations. I/O syscalls that try to reparse the path fail with STATUS_IO_REPARSE_TAG_NOT_HANDLED.

      It's also messy to conflate different things in general for the sake of a particular case. For example, if code sees the app-exec link as a symlink because ntpath.is_link() is true, it may try to copy it via os.readlink() and os.symlink(). This creates a different type of reparse point, if the user even has the symlink privilege, which may not behave the same as the original app-exec link in a CreateProcessW call. (I don't know what the end goal is for the Windows team in terms of allowing app executables under "%ProgramFiles%\WindowsApps" to be executed directly.)

      How about adding a separate function such as nt.read_reparse_point() that's able to read reparse points that are documented (most types are opaque) and can be interpreted as a string, or a tuple of strings? The internal implementation could be shared with os.readlink.

      The current behavior of follow_symlinks in stat() is problematic. It should be limited to symlinks. So another idea that I think could prove generally useful is to extend stat() and lstat() with a follow_reparse_points=True parameter. If false, it would imply follow_symlinks is false. Explicitly passing follow_symlinks=True with follow_reparse_points=False would be an error. With follow_symlinks=False and follow_reparse_points=True, it would only open a symlink and follow all other types of reparse points. The stat result would gain an st_reparse_tag field (already added by your PR), which would be non-zero whenever a reparse point is opened.

    5. eryksun commented on Aug 12, 2019

      @eryksun
      Contributor

      How about adding a separate function such as nt.read_reparse_point()

      If we support reading junctions, this should be using the substitute name (with \??\ replaced by \\?\) instead of the print name. For both symlinks and junctions, [MS-FSCC] 2.1.2 states that the print name SHOULD be informative, not that it MUST be, where SHOULD and MUST are defined by RFC2119. The print name can be non-informative for some reason (e.g. maybe to use the whole 16 KiB buffer for the target path.) For symlinks that's not normally observed, since CreateSymbolicLinkW is conservative. For junctions, applications and frameworks use a low-level IOCTL to set them, and they're not necessarily bothering to set a print name. For example, PowerShell omits it:

      PS C:\Mount> new-item Spam -type junction -value C:\Temp\Spam | out-null
      PS C:\Mount> fsutil.exe reparsepoint query spam
      Reparse Tag Value : 0xa0000003
      Tag value: Microsoft
      Tag value: Name Surrogate
      Tag value: Mount Point
      Substitue Name offset: 0
      Substitue Name length: 32
      Print Name offset:     34
      Print Name Length:     0
      Substitute Name:       \??\C:\Temp\Spam
      

      This mount point works fine despite the lack of a print name.

    6. zooba commented on Aug 12, 2019

      @zooba
      MemberAuthor

      Thanks Eryk for your valuable response :)

      readlink() and is_link() should be reserved for POSIX symlinks, i.e. only IO_REPARSE_TAG_SYMLINK.

      I'm okay with that reasoning. Honestly, the only real problem I've seen is in applications that use a reimplementation of spawn() rather than the UCRT's version (which handles the reparse point jsut fine).

      they lack an associated filter driver that handles them in normal file operations

      Also true, and likely to be a cause of more problems. But not ours to fix :)

      How about adding a separate function such as nt.read_reparse_point() that's able to read reparse points [...]? The internal implementation could be shared with os.readlink.

      Maybe it can just return bytes and let the caller do the parsing?

      The current behavior of follow_symlinks in stat() is problematic. It should be limited to symlinks.

      This sounds like a good option to me, too. So that would suggest that Modules/posixmodule.c in win32_xstat_impl would verify both FILE_ATTRIBUTE_REPARSE_POINT and IO_REPARSE_TAG_SYMLINK? And if the tag is different it'll return information about the reparse point rather than the target?

      The stat result would gain an st_reparse_tag field (already added by your PR), which would be non-zero whenever a reparse point is opened.

      I agree this can stay. We don't need the rest of the logic here - callers who care to follow non-symlink reparse points can use the new nt.read_reparse_point() function to do it.

    7. eryksun commented on Aug 13, 2019

      @eryksun
      Contributor

      Honestly, the only real problem I've seen is in applications that use
      a reimplementation of spawn() rather than the UCRT's version (which
      handles the reparse point jsut fine).

      I looked into this spawn problem. It's due to Cygwin's spawnve, which calls NtOpenFile to open the file, and then memory-maps it and reads the image header [1]. For an app-exec link, this fails with STATUS_IO_REPARSE_TAG_NOT_HANDLED, which is translated to Windows ERROR_CANT_ACCESS_FILE (1920). In turn, Cygwin translates this error to its to default errno value, EACCES. (The Windows CRT uses EINVAL as the default.)

      [1] https://github.com/cygwin/cygwin/blob/aa55d22cb55d67d7f77ee9d58f9016c42c3ee495/winsup/cygwin/spawn.cc#L1035

      Maybe it can just return bytes and let the caller do the parsing?

      It could parse out as much as possible and return a struct sequence:

      ReparseTag (int)
      ReparseGuid (string, or None for Microsoft tags)
      SymlinkFlags (int, SYMLINK_FLAG_RELATIVE) 
      PrintName (string or None)
      SubstituteName (string or None)
      DataBuffer (bytes)
      

      Only the ReparseTag and DataBuffer fields would always be present. ReparseGuid would be present for non-Microsoft tags (i.e. bit 31 is unset). The result could maybe have one or more fields for the app-exec-link type.

      This sounds like a good option to me, too. So that would suggest that
      Modules/posixmodule.c in win32_xstat_impl would verify both
      FILE_ATTRIBUTE_REPARSE_POINT and IO_REPARSE_TAG_SYMLINK? And if the
      tag is different it'll return information about the reparse point
      rather than the target?

      Maybe have two non-overlapping options, follow_symlinks and follow_nonlinks. The latter might be more sensible as a single option for lstat(), since it never follows symlinks. Then if either follow_symlinks or follow_nonlinks is false, stat has to open the reparse point and get the tag to determine whether it should reopen with reparsing enabled.

      The straight-forward way to get the tag is GetFileInformationByHandleEx: FileAttributeTagInfo. This should succeed if the file system supports reparse points. But still check for FILE_ATTRIBUTE_REPARSE_POINT in the attributes before trusting the tag value. If the call fails, assume it's not a reparse point and proceed to GetFileInformationByHandleW.

      Another tag to look for is IO_REPARSE_TAG_AF_UNIX (0x8000_0023). It's relatively new, so I haven't used it yet. I suppose it should be mapped S_IFSOCK in the stat result.

    8. zooba commented on Aug 13, 2019

      @zooba
      MemberAuthor

      I looked into this spawn problem. It's due to Cygwin's spawnve, which calls NtOpenFile to open the file, and then memory-maps it and reads the image header [1].

      Great, that's roughly what I suspected. Unfortunately, I've been told that looking into Cygwin's (GPL'd) code myself is going to cost me two weeks of dev work ("cooling off" period), so someone else will have to help them fix it.

      It could parse out as much as possible and return a struct sequence

      TBH, I feel like that's more work than is worth us doing for something that will be relatively rarely used, will live in the stdlib, and is obviously something that will become outdated as Microsoft adds new reparse points.

      If we return the parsed data as opaque bytes then someone can write a simple PyPI package to extract the contents. (Presumably the reparse tag will have come from stat() already.)

      Maybe have two non-overlapping options, follow_symlinks and follow_nonlinks

      I read this suggestion the first time and I think it would send the message that we are more capable than we really are :)

      In theory, we can't follow any reparse point that isn't documented as being followable and provides the target name is a stable, documented manner. The appexec links don't do this (I just looked at the returned buffer), so we really should just not follow them. They exist solely so that CreateProcess internally returns a unique error code that can be handled without impacting regular process start, which means we *don't* want to follow them.

      Again, if someone writes the PyPI package to parse all known reparse points, they can do that.

      Now, directory junctions are far more interesting. My gut feel is that we should treat them the same as symlinks (with respect to stat vs. lstat) for consistency, but I'll gladly defer to you (Eryk) for the edge cases that may introduce.

      ---

      My plan for PR 15231 is:

      • make os.stat only follow symlinks and junctions
      • make os.readlink only read symlinks and junctions
      • add st_reparse_tag field to os.stat
    9. zooba commented on Aug 13, 2019

      @zooba
      MemberAuthor

      If we support reading junctions, this should be using the substitute name (with \??\ replaced by \\?\) instead of the print name.

      GetFinalPathName() does this conversion for us, any reason not to use that? (GetFullPathName() doesn't seem to recognize the \??\ prefix and will prepend the current drive)

    10. zooba commented on Aug 13, 2019

      @zooba
      MemberAuthor

      Latest PR update uses GetFinalPathName to resolve SubstituteName, returning it unmodified on failure (e.g. symlink where the target file no longer exists).

      Replacing "\??\" with "\\?\" in place is trivial though, as we start with a mutable buffer. I'm just not clear that it's as simple as that, though.

    11. eryksun commented on Aug 13, 2019

      @eryksun
      Contributor

      I feel like that's more work than is worth us doing for something that
      will be relatively rarely used, will live in the stdlib, and is
      obviously something that will become outdated as Microsoft adds new
      reparse points.

      Junctions (NT 5) and symlinks (NT 6) are stable. So if os.read_reparse_point only returns the unparsed bytes, maybe add os.read_junction as well. I know other projects overload this on POSIX readlink. They're both name-surrogate reparse points, but they have different constraints and behavior.

      The I/O manager tries to make a junction behave something like a hard link to a directory, with the addition of being able to link across local volumes. This is in turn relates to how it evaluates relative symbolic links. For example, if "C:/Junction" and "C:/Symlink" both target r"\\?\C:\Temp1\Temp2", and there's a relative symlink "C:/Temp1/Temp2/foo_link" that targets r"..\foo", then "C:/Junction/foo_link" references "C:/foo" but "C:/Symlink/foo_link" references "C:/Temp1/foo".

      Another difference is with remote filesystems. SMB special cases symlinks to have the server send the reparse request over the wire to be evaluated on the client side. (Refer to [MS-SMB2] 2.2.2.1 Symbolic Link Error Response, and the subsequent section about client-side handling of this error.) So an absolute symlink on the server that targets r"\\?\C:\Windows" actually references the client's "C:/Windows" directory, whereas the same junction target would reference the server's "C:/Windows" directory. The symlink evaluation will succeed only if the client's R2L (remote to local) policy allows it. Symlinks can also target remote devices, depending on the L2R and R2R policy settings. Junctions are restricted to local devices.

      In theory, we can't follow any reparse point that isn't documented as
      being followable and provides the target name is a stable, documented
      manner.

      To follow a reparse point, we're just calling CreateFileW the normal way, without FILE_FLAG_OPEN_REPARSE_POINT. The Windows API also does this (usually via NtOpenFile, but this has a similar FILE_OPEN_REPARSE_POINT option) for tags it doesn't handle. That's why MoveFileExW (os.rename and os.replace) fails on one of these app-exec links. In some cases, it adds a third open attempt if the reparse point isn't handled. This is important for DeleteFileW (os.remove) and RemoveDirectoryW (os.rmdir) because we should be able to delete a bad reparse point.

      The appexec links don't do this (I just looked at the returned
      buffer), so we really should just not follow them. They exist solely
      so that CreateProcess internally returns a unique error code that can
      be handled without impacting regular process start, which means we
      *don't* want to follow them.

      I know, so a regular stat() will fail. I think for an honest result, stat() should fail for a reparse point that can't be handled. Scripts can use stat(path, follow_nonlinks=False) or stat(path, follow_reparse_points=False), or however this eventually gets parameterized to force opening all reparse points.

      Now, directory junctions are far more interesting. My gut feel is that
      we should treat them the same as symlinks (with respect to stat vs.
      lstat) for consistency

      Junctions are their own thing. They're mount points that behave like Unix volume mounts (in Windows, target the root directory of a volume device named by its "Volume{...}" name) or Unix bind mounts (in Windows, target arbitrary directories on any local volume; in Linux it's a mount created with --bind or FUSE bindfs). Bind-like junctions are also similar to DOS subst drives (e.g. "W:" -> "C:/Windows") and UNC shares. These are all mount points of one sort or another.

      OTOH, the base device names such as "//?/C:" and "//?/Volume{...}", without a specified root directory, are aliases (object symlinks) for an NT device such as r"\Device\HarddiskVolume2". These paths open the volume itself, not the mounted filesystem, so they're not like Unix mount points. They're like Unix '/dev/sda1' device paths, except in Unix, devices don't have their own namespaces, so it would be nonsense to open "/dev/sda1/".

      RemoveDirectoryW for a volume mount is special cased to call DeleteVolumeMountPointW, which notifies the mount-point manager. It won't do this for a junction that targets the same volume root directory via the DOS drive-letter name -- or any other device alias for that matter (e.g. Windows 10 creates "\\?\BootPartition" as an alternative named for the system "C:" drive). So bind-like mounts are different from volume mounts, but both are different from symlinks.

    12. eryksun commented on Aug 13, 2019

      @eryksun
      Contributor

      Replacing "\??\" with "\\?\" in place is trivial though, as we start
      with a mutable buffer. I'm just not clear that it's as simple as that,
      though.

      If the path starts with "\\??\\" we can just change the first question mark to a backslash. For a symlink, fail at this step if Flags includes SYMLINK_FLAG_RELATIVE, which would be inconsistent data.

      "\\??\\" is the NT prefix for the caller's local (logon session) device directory. This implicitly shadows the global device directory, "\\Global??". We don't use NT's real "\\Device" directory in Windows, but it's available as "//?/GlobalRoot/Device" or "//?/Global/GlobalRoot/Device".

      "\\??\\" shouldn't be used directly in Windows programming, since GetFullPathNameW (often implicitly called) doesn't recognize it, but some API functions will pass it along, even though they should really fail the call. It will work until it doesn't, and by then we could have a right mess.

      If a path starts with exactly "\\\\?\\" (backslash only), Windows simply copies it verbatim, except for changing the prefix to "\\??\\". Other Windows device prefixes where the domain is "." or "?" can use any mix of forward slash and backslash because they get normalized first (e.g. "//?\\" -> "\\\\?\\"). Only an initial "\\\\?\\" bypasses the normalization step.

    13. 34 remaining items

    14. zooba commented on Aug 22, 2019

      @zooba
      MemberAuthor

      Adding a small fix for the Win7 buildbots in PR 15377

    15. zooba commented on Aug 22, 2019

      @zooba
      MemberAuthor

      New changeset 374be59 by Steve Dower in branch 'master':
      bpo-37834: Fix test on Windows 7 (GH-15377)
      374be59

    16. miss-islington commented on Aug 22, 2019

      @miss-islington
      Contributor

      New changeset 967d625 by Miss Islington (bot) in branch '3.8':
      bpo-37834: Fix test on Windows 7 (GH-15377)
      967d625

    17. zooba commented on Aug 22, 2019

      @zooba
      MemberAuthor

      That should be all the buildbot issues fixes, so I'm marking this resolved and will wait for the inevitable 3.8.0b4 feedback!

    18. ambv commented on Aug 29, 2019

      @ambv
      Contributor

      There's a bug on macOS that is blocking the release regarding stat.FILE_ATTRIBUTE_REPARSE_POINT being used to check whether os.stat_result objects have the st_file_attributes attribute.

    19. reopened this on Aug 29, 2019
    20. ambv commented on Aug 29, 2019

      @ambv
      Contributor

      Unit tests didn't catch it since it fails on older macOS releases.

    21. ned-deily commented on Aug 29, 2019

      @ned-deily
      Member

      One problem seems to be that the code added for this issue assumes that the documentation is correct in implying that the stat.FILE_ATTRIBUTE_* constants (like stat.FILE_ATTRIBUTE_REPARSE_POINT) are only present on Windows. But besides being conditionally created in _stat.c, they are also undconditionally defined in stat.py on all platforms. That makes some of the tests in shutil.py, like:
      if hasattr(stat, 'FILE_ATTRIBUTE_REPARSE_POINT'):
      to determine which versions of _rmtree_islink and _rmtree_isdir to define problematic.

    22. ned-deily commented on Aug 29, 2019

      @ned-deily
      Member

      ... and the other important difference is that older versions of macOS do not support fd functions so _use_fd_functions is false and the alternate path is taken in shutil.rmtree, the path that calls _rm_tree_islink which fails.

      >>> shutil.rmtree('a')
      Traceback (most recent call last):
        File "<stdin>", line 1, in <module>
        File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/shutil.py", line 718, in rmtree
          if _rmtree_islink(path):
        File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/shutil.py", line 564, in _rmtree_islink
          (st.st_file_attributes & stat.FILE_ATTRIBUTE_REPARSE_POINT
      AttributeError: 'os.stat_result' object has no attribute 'st_file_attributes'
    23. zooba commented on Aug 29, 2019

      @zooba
      MemberAuthor

      Huh, didn't realise those were always defined in stat.py.

      Changing the test to "hasattr(... "st_file_attributes")" should be fine. I can get to it in a couple of hours if nobody else gets there first.

    24. ambv commented on Aug 29, 2019

      @ambv
      Contributor

      New changeset 7fcc208 by Łukasz Langa (Ned Deily) in branch 'master':
      bpo-37834: Prevent shutil.rmtree exception (GH-15602)
      7fcc208

    25. ambv commented on Aug 29, 2019

      @ambv
      Contributor

      New changeset 25a044e by Łukasz Langa in branch '3.8':
      [3.8] bpo-37834: Prevent shutil.rmtree exception (GH-15602) (bpo-15603)
      25a044e

    26. transferred this issue fromon Apr 10, 2022
    Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

    Metadata

    Metadata

    Assignees

    Labels

    3.8 (EOL)3.9 (EOL)OS-windows

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions