This file is indexed.

/usr/bin/adt-virt-ssh is in autopkgtest 3.6jessie1.

This file is owned by root:root, with mode 0o755.

The actual contents of the file can be viewed below.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
#!/usr/bin/python3
#
# adt-virt-ssh is part of autopkgtest
# autopkgtest is a tool for testing Debian binary packages
#
# autopkgtest is Copyright (C) 2006-2014 Canonical Ltd.
#
# Author: Jean-Baptiste Lallement <jean-baptiste.lallement@canonical.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#
# See the file CREDITS for a full list of credits information (often
# installed as /usr/share/doc/autopkgtest/CREDITS).

import sys
import os
import argparse
import tempfile
import shutil
import pipes
import time
import subprocess

try:
    our_base = os.environ['AUTOPKGTEST_BASE'] + '/lib'
except KeyError:
    our_base = '/usr/share/autopkgtest/python'
sys.path.insert(1, our_base)

import VirtSubproc
import adtlog

capabilities = []
args = None
workdir = None
sshcmd = None
sshconfig = {'identity': None,
             'login': None,
             'password': None,
             'port': None,
             'options': None,
             'hostname': None,
             'capabilities': None,
             'extraopts': None}
# Note: Running in jenkins might require -tt
sshopts = '-q -o BatchMode=yes -o UserKnownHostsFile=/dev/null '\
          '-o StrictHostKeyChecking=no -o CheckHostIP=no '\
          '-o ControlMaster=auto -o ControlPersist=60 '\
          '-o ControlPath=%s/ssh_control-%%r@%%h:%%p'


# Tests or builds sometimes leak background processes which might still be
# connected to ssh's stdout/err; we need to kill these after the main program
# (build or test script) finishes, otherwise we get eternal hangs as ssh waits
# until nothing is connected to its tty any more. So we run this in ssh,
# wrapping the actual command.
terminal_kill_wrapper = '''#!/bin/bash
set -u
PPPID=$(cut -f4 -d' ' /proc/$PPID/stat)
"$@"; RC=$?
set -e
myout=$(readlink /proc/$$/fd/1)
myerr=$(readlink /proc/$$/fd/2)
KILL=""
for fd in /proc/[0-9]*/fd/*; do
    t="`readlink $fd`" || continue
    if [ "$t" = "$myout" -o "$t" = "$myerr" ]; then
        pid=${fd#/proc/}; pid=${pid%%/*}
        [ $pid -ne $$ ] && [ $pid -ne $PPID ] && [ $pid -ne $PPPID ] || continue
        [ "$(< /proc/$pid/comm)" != sshd ] || continue
        #echo "XXXadt-ssh-wrapper($$ $PPID $PPPID $myout $myerr): killing $pid (`cat /proc/$pid/cmdline`)" >&2
        KILL="$KILL $pid"
    fi
done
[ -z "$KILL" ] || kill -9 $KILL || true
exit $RC
'''


cleanup_paths = []  # paths on the device which we created


def parse_args():
    global args

    parser = argparse.ArgumentParser(fromfile_prefix_chars='@')

    parser.add_argument('-d', '--debug', action='store_true',
                        help='Enable debugging output')
    parser.add_argument('-H', '--hostname',
                        help='hostname with optional user: [user@]hostname')
    parser.add_argument('-i', '--identity',
                        help='Selects a file from which the identity '
                        '(private key) for public key authentication is '
                        'read')
    parser.add_argument('-l', '--login',
                        help='Specifies the user to log in as on the '
                        'remote machine.')
    parser.add_argument('-P', '--password',
                        help='Specifies the sudo password on the remote host.'
                        ' It can be the password in clear text or a file '
                        'containing the password.')
    parser.add_argument('-p', '--port', type=str,
                        help='ssh port to use to connect to the host')
    parser.add_argument('-o', '--options',
                        help='Passed verbatim to ssh; see man ssh_config')
    parser.add_argument('-s', '--setup-script',
                        help='Setup script to prepare testbed and ssh connection')
    parser.add_argument('scriptargs', nargs=argparse.REMAINDER,
                        help='Additional arguments to pass to the setup '
                        'script for configuration')

    args = parser.parse_args()
    if args.debug:
        adtlog.verbosity = 2
    adtlog.debug(str(args))

    # shortcut for shipped scripts
    if args.setup_script and not os.path.exists(args.setup_script):
        shipped_script = os.path.join('/usr/share/autopkgtest/ssh-setup',
                                      args.setup_script)
        if os.path.exists(shipped_script):
            args.setup_script = shipped_script

    # turn --password file path into the actual password
    if args.password and os.path.exists(args.password):
        with open(args.password) as f:
            args.password = f.read().strip()


def execute_setup_script(command):
    '''Run the --setup-script, if given.

    Arguments passed after -- to the main program are passed verbatim to the
    setup script.  The output of the script must be of the form key=value and
    is parsed to populate sshconfig. Command line options always override the
    values from the setup script.

    :param command: Command to execute. The command must match a function in
                    the ssh script
    '''
    global sshconfig, args

    if args.setup_script:
        fpath = args.setup_script
        if not os.path.isfile(fpath):
            VirtSubproc.bomb('File not found: %s' % fpath)
        elif not os.access(fpath, os.X_OK):
            VirtSubproc.bomb('File is not executable: %s' % fpath)

        if args.scriptargs and args.scriptargs[0] == '--':
            del args.scriptargs[0]
        cmd = [args.setup_script, command] + args.scriptargs
        if args.login:
            cmd += ['-l', args.login]
        if sshconfig.get('extraopts'):
            cmd += sshconfig['extraopts'].split(' ')
        adtlog.debug('Executing host command: %s' % ' '.join(cmd))
        out = VirtSubproc.check_exec(cmd, outp=True, timeout=1800)
        if command in ['open', 'revert']:
            for k, v in dict([s.split('=', 1) for s in out.splitlines()
                              if s and '=' in s]).items():
                sshconfig[k] = v
            adtlog.debug('got sshconfig from script %s: %s' % (command, sshconfig))

    # Command line arguments take priority
    for param in sshconfig:
        a = getattr(args, param, None)
        if a is not None:
            sshconfig[param] = a


def host_setup(command):
    '''Prepare remote host for ssh connection and return its configuration

    When a --setup-script is passed, execute it and return its configuration.
    The configuration of the remote side can be overloaded by options on the
    command line.

    command should either be "open" or "revert".

    Sets the global sshcmd accordingly.
    '''
    global workdir, sshcmd

    try:
        if workdir is None:
            workdir = tempfile.mkdtemp(prefix='adt-virt-ssh.')
            os.chmod(workdir, 0o755)
        execute_setup_script(command)
        build_auxverb()
        wait_for_ssh(sshcmd)
    except:
        # Clean up on failure
        hook_cleanup()
        raise
    adtlog.debug('host set up for %s; ssh command: %s' % (command, sshcmd))


def build_auxverb():
    '''Generate sshcmd and auxverb from sshconfig'''

    global sshconfig, sshcmd, capabilities, workdir

    sshcmd = ['ssh'] + (sshopts % workdir).split()
    for param in sshconfig:
        if not sshconfig[param]:
            continue

        if param == 'identity':
            sshcmd += ['-i', sshconfig[param]]
        elif param == 'login':
            sshcmd += ['-l', sshconfig[param]]
            if sshconfig[param] != 'root':
                capabilities.append('suggested-normal-user=' + sshconfig[param])
        elif param == 'port':
            sshcmd += ['-p', sshconfig[param]]
        elif param == 'options':
            sshcmd += sshconfig[param].split()
        elif param == 'hostname':
            sshcmd += [sshconfig[param]]
        elif param == 'capabilities':
            capabilities += sshconfig[param].replace(',', ' ').split()
            # Remove duplicates
            capabilities = list(set(capabilities))
        elif param == 'password':
            if not args.password:
                args.password = sshconfig[param]  # forward to can_sudo
        elif param == 'extraopts':
            # Do nothing but don't print a warning. It will be passed back as
            # is to the ssh setup script
            pass
        else:
            adtlog.warning('Ignoring invalid parameter: %s' % param)

    if sshconfig['login'] != 'root':
        sudocmd = can_sudo(sshcmd)
    if sudocmd:
        if 'root-on-testbed' not in capabilities:
            capabilities.append('root-on-testbed')
    else:
        if 'root-on-testbed' in capabilities:
            capabilities.remove('root-on-testbed')

    # create local auxverb script
    auxverb = os.path.join(workdir, 'runcmd')
    with open(auxverb, 'w') as f:
        f.write('''#!/bin/bash
exec %s -- %s /tmp/adt-run-wrapper $(printf '%%q ' "$@")
''' % (" ".join(sshcmd), sudocmd or ''))
    os.chmod(auxverb, 0o755)
    VirtSubproc.auxverb = [auxverb]


def can_sudo(ssh_cmd):
    '''Determine if the user can sudo

    :param ssh_cmd: ssh command to connect to the host
    :returns: sudo command or None if user cannot sudo
    '''
    global cleanup_paths

    sudocmd = None

    # if we have a password, use that
    if args.password:
        cmd = 'F=`mktemp -t sudo_askpass.XXXX`;' \
              '/bin/echo -e "#!/bin/sh\necho \'%s\'" > $F;' \
              'chmod u+x $F; sync; echo $F' % args.password
        askpass = VirtSubproc.check_exec(
            ssh_cmd + ['/bin/sh', '-ec', pipes.quote(cmd)],
            outp=True, timeout=30).strip()
        adtlog.debug('created SUDO_ASKPASS from specified password')
        cleanup_paths.append(askpass)

        sudocmd = 'SUDO_ASKPASS=%s sudo -A' % askpass
        cmd = ssh_cmd + ['--'] + sudocmd.split() + ['/bin/true']
        rc = VirtSubproc.execute_timeout(None, 30, cmd)[0]
        if rc == 0:
            adtlog.debug('can_sudo: askpass works')
            return sudocmd
        else:
            adtlog.warning('specified sudo password fails, no root available')
            pass

    # otherwise, test if we can do it without password (NOPASSWD sudo option)
    sudocmd = "sudo -n"
    cmd = ssh_cmd + ['--'] + sudocmd.split() + ['/bin/true']
    rc = VirtSubproc.execute_timeout(None, 30, cmd)[0]
    if rc == 0:
        adtlog.debug('can_sudo: sudo without password works')
        return sudocmd
    else:
        adtlog.debug('can_sudo: sudo without password does not work')

    return None


def wait_for_ssh(ssh_cmd, timeout=300):
    cmd = ssh_cmd + ['/bin/true']
    start = time.time()
    elapsed = 0
    delay = 3

    while elapsed < timeout:
        try:
            rc = VirtSubproc.execute_timeout(None, 30, cmd)[0]
            if rc == 0:
                adtlog.debug('ssh connection established.')
                break
        except VirtSubproc.Timeout:
            pass
        adtlog.warning('ssh connection failed. Retrying in %d seconds...'
                       % delay)
        time.sleep(delay)
        elapsed = time.time() - start
    else:
        VirtSubproc.bomb('Timed out on waiting for ssh connection')

    # create remote wrapper
    rc = VirtSubproc.execute_timeout(
        terminal_kill_wrapper, 30, ssh_cmd +
        ['rm -f /tmp/adt-run-wrapper; set -C; cat > /tmp/adt-run-wrapper; chmod 755 /tmp/adt-run-wrapper'],
        stdin=subprocess.PIPE)[0]
    if rc != 0:
        VirtSubproc.bomb('Failed to create /tmp/adt-run-wrapper')


def hook_open():
    host_setup('open')


def hook_downtmp(path):
    return VirtSubproc.downtmp_mktemp(path)


def hook_forked_inchild():
    pass


def hook_revert():
    host_setup('revert')


def hook_reboot():
    global sshcmd

    execute_setup_script('reboot')
    wait_for_ssh(sshcmd)


def hook_cleanup():
    global capabilities, workdir, cleanup_paths

    VirtSubproc.downtmp_remove()
    if cleanup_paths:
        VirtSubproc.check_exec(['rm', '-rf'] + cleanup_paths, downp=True, timeout=10)

    execute_setup_script('cleanup')

    capabilities = [c for c in capabilities if not c.startswith('downtmp-host')]

    if workdir:
        shutil.rmtree(workdir)
        workdir = None


def hook_capabilities():
    return capabilities


parse_args()
VirtSubproc.main()