summaryrefslogtreecommitdiffstats
path: root/completions/ssh
blob: 386fd25bd2cf894bf1e7e9bbe103238f5843bd3e (plain)
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
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
# ssh(1) completion                                        -*- shell-script -*-

_comp_cmd_ssh__compgen_queries()
{
    local -a queries
    _comp_compgen -v queries -i ssh query "$1" help ||
        queries=(cipher cipher-auth mac kex key key-cert key-plain key-sig
            protocol-version compression sig ciphers macs kexalgorithms
            pubkeyacceptedkeytypes hostkeyalgorithms hostbasedkeytypes
            hostbasedacceptedkeytypes)
    _comp_compgen -c "${cur,,}" -U queries -- -W '"${queries[@]}" help'
}

# @since 2.12
_comp_xfunc_ssh_compgen_query()
{
    _comp_cmd_ssh__compgen_query ssh "$1"
}

# @deprecated 2.12 use _comp_xfunc_ssh_compgen_query
_ssh_query()
{
    local -a queries=()
    _comp_compgen -v queries -i ssh query "${1:-ssh}" "$2" &&
        printf "%s\n" "${queries[@]}"
}

_comp_cmd_ssh__compgen_query()
{
    _comp_compgen_split -- "$("$1" -Q "$2" 2>/dev/null)"
}

_comp_cmd_ssh__compgen_ciphers()
{
    local -a queries
    _comp_compgen -v queries -i ssh query "$1" cipher ||
        queries=(3des-cbc aes128-cbc aes192-cbc aes256-cbc aes128-ctr
            aes192-ctr aes256-ctr arcfour128 arcfour256 arcfour blowfish-cbc
            cast128-cbc)
    _comp_compgen -U queries -- -W '"${queries[@]}"'
}

_comp_cmd_ssh__compgen_macs()
{
    local -a queries
    _comp_compgen -v queries -i ssh query "$1" mac ||
        queries=(hmac-md5 hmac-sha1 umac-64@openssh.com hmac-ripemd160
            hmac-sha1-96 hmac-md5-96)
    _comp_compgen -U queries -- -W '"${queries[@]}"'
}

# @since 2.12
_comp_xfunc_ssh_compgen_options()
{
    # curl --silent https://raw.githubusercontent.com/openssh/openssh-portable/master/ssh_config.5 | _comp_awk '$1==".It" && $2=="Cm" && $3!="Host" && $3!="Match" {print "        "$3}' | sort
    local _opts=(
        AddKeysToAgent AddressFamily BatchMode BindAddress BindInterface
        CanonicalDomains CanonicalizeFallbackLocal CanonicalizeHostname
        CanonicalizeMaxDots CanonicalizePermittedCNAMEs CASignatureAlgorithms
        CertificateFile ChallengeResponseAuthentication CheckHostIP Ciphers
        ClearAllForwardings Compression ConnectionAttempts ConnectTimeout
        ControlMaster ControlPath ControlPersist DynamicForward
        EnableSSHKeysign EscapeChar ExitOnForwardFailure FingerprintHash
        ForwardAgent ForwardX11 ForwardX11Timeout ForwardX11Trusted
        GatewayPorts GlobalKnownHostsFile GSSAPIAuthentication
        GSSAPIDelegateCredentials HashKnownHosts HostbasedAuthentication
        HostbasedKeyTypes HostKeyAlgorithms HostKeyAlias Hostname
        IdentitiesOnly IdentityAgent IdentityFile IgnoreUnknown Include IPQoS
        KbdInteractiveAuthentication KbdInteractiveDevices KexAlgorithms
        LocalCommand LocalForward LogLevel MACs
        NoHostAuthenticationForLocalhost NumberOfPasswordPrompts
        PasswordAuthentication PermitLocalCommand PKCS11Provider Port
        PreferredAuthentications ProxyCommand ProxyJump ProxyUseFdpass
        PubkeyAcceptedAlgorithms PubkeyAuthentication RekeyLimit RemoteCommand
        RemoteForward RequestTTY RequiredRSASize RevokedHostKeys
        SecurityKeyProvider SendEnv ServerAliveCountMax ServerAliveInterval
        SetEnv StreamLocalBindMask StreamLocalBindUnlink StrictHostKeyChecking
        SyslogFacility TCPKeepAlive Tunnel TunnelDevice UpdateHostKeys User
        UserKnownHostsFile VerifyHostKeyDNS VisualHostKey XAuthLocation
    )
    # Selected old ones
    _opts+=(
        GSSAPIKeyExchange GSSAPIRenewalForcesRekey GSSAPIServerIdentity
        GSSAPITrustDns PubkeyAcceptedKeyTypes SmartcardDevice UsePrivilegedPort
    )
    local -a protocols
    _comp_compgen -v protocols -i ssh query ssh protocol-version
    if [[ ${protocols[*]-} == *1* ]]; then
        _opts+=(Cipher CompressionLevel Protocol RhostsRSAAuthentication
            RSAAuthentication)
    fi
    _comp_unlocal protocols

    compopt -o nospace
    _comp_compgen_split -l -- "$(
        shopt -s nocasematch
        local option
        for option in "${_opts[@]}"; do
            [[ $option == "$cur"* ]] && printf '%s=\n' "$option"
        done
    )"
}

_comp_deprecate_func 2.12 _ssh_options _comp_xfunc_ssh_compgen_options

# Complete a ssh suboption (like ForwardAgent=y<tab>)
# @param $1 the ssh executable to invoke
# @param $2 the string to complete including the equal sign
# Not all suboptions are completed.
# Doesn't handle comma-separated lists.
_comp_cmd_ssh__compgen_suboption()
{
    # Split into subopt and subval
    local _prev=${2%%=*} cur=${2#*=}

    case ${_prev,,} in
        batchmode | canonicaldomains | canonicalizefallbacklocal | \
            challengeresponseauthentication | checkhostip | \
            clearallforwardings | controlpersist | compression | \
            enablesshkeysign | exitonforwardfailure | forwardagent | \
            forwardx11 | forwardx11trusted | gatewayports | \
            gssapiauthentication | gssapikeyexchange | \
            gssapidelegatecredentials | gssapirenewalforcesrekey | \
            gssapitrustdns | hashknownhosts | hostbasedauthentication | \
            identitiesonly | kbdinteractiveauthentication | \
            kbdinteractivedevices | nohostauthenticationforlocalhost | \
            passwordauthentication | permitlocalcommand | proxyusefdpass | \
            pubkeyauthentication | rhostsrsaauthentication | \
            rsaauthentication | streamlocalbindunlink | \
            tcpkeepalive | useprivilegedport | visualhostkey)
            _comp_compgen -- -W 'yes no'
            ;;
        addkeystoagent)
            _comp_compgen -- -W 'yes ask confirm no'
            ;;
        addressfamily)
            _comp_compgen -- -W 'any inet inet6'
            ;;
        bindaddress)
            _comp_compgen_ip_addresses
            ;;
        canonicalizehostname)
            _comp_compgen -- -W 'yes no always'
            ;;
        identityfile)
            _comp_xfunc_ssh_compgen_identityfile
            ;;
        *file | identityagent | include | controlpath | revokedhostkeys | \
            xauthlocation)
            _comp_compgen_filedir
            ;;
        casignaturealgorithms)
            _comp_cmd_ssh__compgen_query "$1" sig
            ;;
        cipher)
            _comp_compgen -- -W 'blowfish des 3des'
            ;;
        ciphers)
            _comp_cmd_ssh__compgen_ciphers "$1"
            ;;
        controlmaster)
            _comp_compgen -- -W 'yes ask auto autoask no'
            ;;
        compressionlevel)
            _comp_compgen -- -W '{1..9}'
            ;;
        fingerprinthash)
            _comp_compgen -- -W 'md5 sha256'
            ;;
        ipqos)
            _comp_compgen -- -W 'af1{1..4} af2{2..3} af3{1..3} af4{1..3}
                cs{0..7} ef lowdelay throughput reliability'
            ;;
        hostbasedkeytypes | hostkeyalgorithms)
            _comp_cmd_ssh__compgen_query "$1" key
            ;;
        kexalgorithms)
            _comp_cmd_ssh__compgen_query "$1" kex
            ;;
        loglevel)
            _comp_compgen -- -W 'QUIET FATAL ERROR INFO VERBOSE DEBUG{,1,2,3}'
            ;;
        macs)
            _comp_cmd_ssh__compgen_macs "$1"
            ;;
        pkcs11provider)
            _comp_compgen_filedir so
            ;;
        preferredauthentications)
            _comp_compgen -- -W 'gssapi-with-mic host-based publickey
                keyboard-interactive password'
            ;;
        protocol)
            local -a protocols
            _comp_compgen -v protocols -i ssh query "$1" protocol-version
            [[ ${protocols-} ]] || protocols=(1 2)
            if ((${#protocols[@]} > 1)); then
                _comp_compgen -- -W '"${protocols[@]}"'
            fi
            ;;
        proxyjump)
            _comp_compgen_known_hosts -a ${configfile:+-F "$configfile"} -- "$cur"
            ;;
        proxycommand | remotecommand | localcommand)
            _comp_compgen_commands
            ;;
        pubkeyacceptedalgorithms | pubkeyacceptedkeytypes)
            _comp_cmd_ssh__compgen_query "$1" key
            ;;
        requesttty)
            _comp_compgen -- -W 'no yes force auto'
            ;;
        requiredrsasize)
            _comp_compgen -- -W '1024 2048 3072 4096 7680 15360'
            ;;
        stricthostkeychecking)
            _comp_compgen -- -W 'accept-new ask no off'
            ;;
        syslogfacility)
            _comp_compgen -- -W 'DAEMON USER AUTH LOCAL{0..7}'
            ;;
        tunnel)
            _comp_compgen -- -W 'yes no point-to-point ethernet'
            ;;
        updatehostkeys | verifyhostkeydns)
            _comp_compgen -- -W 'yes no ask'
            ;;
    esac
    return 0
}

# Try to complete -o SubOptions=
#
# Returns 0 if the completion was handled or non-zero otherwise.
# @since 2.12
_comp_xfunc_ssh_compgen_suboption_check()
{
    _comp_cmd_ssh__compgen_suboption_check ssh
}

# @param $1 the ssh executable to invoke
_comp_cmd_ssh__compgen_suboption_check()
{
    # Get prev and cur words without splitting on =
    local cur prev
    _comp_get_words -n := cur prev
    if [[ $cur == *=* && $prev == -*o ]]; then
        _comp_unlocal prev
        _comp_cmd_ssh__compgen_suboption "$1" "$cur"
        return $?
    fi
    return 1
}

# @deprecated 2.12 use `_comp_xfunc_ssh_compgen_suboption_check` instead
_ssh_suboption_check()
{
    _comp_cmd_ssh__compgen_suboption_check "${1:-ssh}"
}

# Search COMP_WORDS for '-F configfile' or '-Fconfigfile' argument
# @var[out] configfile   Found configfile, if any
_comp_cmd_ssh__configfile()
{
    configfile=""
    set -- "${words[@]}"
    while (($# > 0)); do
        if [[ $1 == -F* ]]; then
            local REPLY
            if ((${#1} > 2)); then
                _comp_dequote "${1:2}" && configfile=$REPLY
            else
                shift
                [[ ${1-} ]] && _comp_dequote "$1" && configfile=$REPLY
            fi
            break
        fi
        shift
    done
}

# With $1 set, look for public key files, else private
# @since 2.12
# shellcheck disable=SC2120
_comp_xfunc_ssh_compgen_identityfile()
{
    local cur=$cur tmp
    [[ ! $cur && -d ~/.ssh ]] && cur=~/.ssh/id
    _comp_compgen -v tmp -c "$cur" filedir &&
        _comp_compgen -U tmp -- -W '"${tmp[@]}"' -X "${1:+!}*.pub"
}

_comp_deprecate_func 2.12 _ssh_identityfile _comp_xfunc_ssh_compgen_identityfile

_comp_cmd_ssh()
{
    local cur prev words cword comp_args
    _comp_initialize -n : -- "$@" || return

    local configfile
    _comp_cmd_ssh__configfile

    _comp_cmd_ssh__compgen_suboption_check "$1" && return

    local ipvx

    # Keep cases sorted the same they're in ssh's usage message
    # (but do group ones with same arg completion)
    case $prev in
        -*B)
            _comp_compgen_available_interfaces -a
            return
            ;;
        -*b)
            _comp_compgen_ip_addresses
            return
            ;;
        -*c)
            _comp_cmd_ssh__compgen_ciphers "$1"
            return
            ;;
        -*[DeLpRW])
            return
            ;;
        -*[EFS])
            _comp_compgen_filedir
            return
            ;;
        -*I)
            _comp_compgen_filedir so
            return
            ;;
        -*i)
            _comp_xfunc_ssh_compgen_identityfile
            return
            ;;
        -*J)
            _comp_compgen_known_hosts -a ${configfile:+-F "$configfile"} -- "$cur"
            return
            ;;
        -*l)
            _comp_compgen -- -u
            return
            ;;
        -*m)
            _comp_cmd_ssh__compgen_macs "$1"
            return
            ;;
        -*O)
            _comp_compgen -- -W 'check forward cancel exit stop'
            return
            ;;
        -*o)
            _comp_xfunc_ssh_compgen_options "$1"
            return
            ;;
        -*Q)
            _comp_cmd_ssh__compgen_queries "$1"
            return
            ;;
        -*w)
            _comp_compgen_available_interfaces
            return
            ;;
        -*4*)
            ipvx=-4
            ;;
        -*6*)
            ipvx=-6
            ;;
    esac

    if [[ $cur == -F* ]]; then
        _comp_compgen -c "${cur#-F}" filedir
        # Prefix completions with '-F'
        COMPREPLY=("${COMPREPLY[@]/#/-F}")
    elif [[ $cur == -* ]]; then
        _comp_compgen_usage
    else
        local REPLY
        # Keep glob sort in sync with cases above
        _comp_count_args -n "=" -a "-*[BbcDeLpRWEFSIiJlmOoQw]"
        if ((REPLY > 1)); then
            compopt -o filenames
            _comp_compgen_commands
        else
            _comp_compgen_known_hosts ${ipvx-} -a ${configfile:+-F "$configfile"} \
                -- "$cur"
        fi
    fi
} &&
    shopt -u hostcomplete &&
    complete -F _comp_cmd_ssh ssh slogin autossh sidedoor

# sftp(1) completion
#
_comp_cmd_sftp()
{
    local cur prev words cword comp_args
    _comp_initialize -- "$@" || return

    local configfile
    _comp_cmd_ssh__configfile

    # Prefer `ssh` from same dir for resolving options, etc
    local pathcmd
    pathcmd=$(type -P "$1") && local PATH=${pathcmd%/*}:$PATH

    _comp_xfunc_ssh_compgen_suboption_check && return

    local ipvx=

    case $prev in
        -*[BDlPRs])
            return
            ;;
        -*[bF])
            _comp_compgen_filedir
            return
            ;;
        -*i)
            _comp_xfunc_ssh_compgen_identityfile
            return
            ;;
        -*c)
            _comp_cmd_ssh__compgen_ciphers
            return
            ;;
        -*J)
            _comp_compgen_known_hosts -a ${configfile:+-F "$configfile"} -- "$cur"
            return
            ;;
        -*o)
            _comp_xfunc_ssh_compgen_options
            return
            ;;
        -*S)
            _comp_compgen_commands
            return
            ;;
        -*4*)
            ipvx=-4
            ;;
        -*6*)
            ipvx=-6
            ;;
    esac

    if [[ $cur == -F* ]]; then
        _comp_compgen -c "${cur#-F}" filedir
        # Prefix completions with '-F'
        COMPREPLY=("${COMPREPLY[@]/#/-F}")
    elif [[ $cur == -* ]]; then
        _comp_compgen_usage
    else
        _comp_compgen_known_hosts ${ipvx:+"$ipvx"} -a ${configfile:+-F "$configfile"} -- "$cur"
    fi
} &&
    shopt -u hostcomplete && complete -F _comp_cmd_sftp sftp

# things we want to backslash escape in scp paths
# shellcheck disable=SC2089
_comp_cmd_scp__path_esc='[][(){}<>"'"'"',:;^&!$=?`\\|[:space:]]'

# Complete remote files with ssh.  If the first arg is -d, complete on dirs
# only.  Returns paths escaped with three backslashes.
# @since 2.12
# shellcheck disable=SC2120
_comp_xfunc_scp_compgen_remote_files()
{
    # remove backslash escape from the first colon
    cur=${cur/\\:/:}

    local _userhost=${cur%%?(\\):*}
    local _path=${cur#*:}

    # unescape (3 backslashes to 1 for chars we escaped)
    # shellcheck disable=SC2090
    _path=$(command sed -e 's/\\\\\\\('"$_comp_cmd_scp__path_esc"'\)/\\\1/g' <<<"$_path")

    # default to home dir of specified user on remote host
    if [[ ! $_path ]]; then
        _path=$(ssh -o 'Batchmode yes' "$_userhost" pwd 2>/dev/null)
    fi

    local _files
    if [[ ${1-} == -d ]]; then
        # escape problematic characters; remove non-dirs
        # shellcheck disable=SC2090
        _files=$(ssh -o 'Batchmode yes' "$_userhost" \
            command ls -aF1dL "$_path*" 2>/dev/null |
            command sed -e 's/'"$_comp_cmd_scp__path_esc"'/\\\\\\&/g' -e '/[^\/]$/d')
    else
        # escape problematic characters; remove executables, aliases, pipes
        # and sockets; add space at end of file names
        # shellcheck disable=SC2090
        _files=$(ssh -o 'Batchmode yes' "$_userhost" \
            command ls -aF1dL "$_path*" 2>/dev/null |
            command sed -e 's/'"$_comp_cmd_scp__path_esc"'/\\\\\\&/g' -e 's/[*@|=]$//g' \
                -e 's/[^\/]$/& /g')
    fi
    _comp_compgen_split -l -- "$_files"
}

# @deprecated 2.12 use `_comp_compgen -ax ssh remote_files` instead
_scp_remote_files()
{
    _comp_compgen -ax scp remote_files
}

# This approach is used instead of _comp_compgen_filedir to get a space
# appended after local file/dir completions, and -o nospace retained for
# others.  If first arg is -d, complete on directory names only.  The next arg
# is an optional prefix to add to returned completions.
# @since 2.12
_comp_xfunc_scp_compgen_local_files()
{
    local _dirsonly=""
    if [[ ${1-} == -d ]]; then
        _dirsonly=set
        shift
    fi

    local files
    _comp_expand_glob files '"$cur"*' || return 0
    if [[ $_dirsonly ]]; then
        _comp_compgen -U files split -l -- "$(
            command ls -aF1dL "${files[@]}" 2>/dev/null |
                command sed -e "s/$_comp_cmd_scp__path_esc/\\\\&/g" \
                    -e '/[^\/]$/d' -e "s/^/${1-}/"
        )"
    else
        _comp_compgen -U files split -l -- "$(
            command ls -aF1dL "${files[@]}" 2>/dev/null |
                command sed -e "s/$_comp_cmd_scp__path_esc/\\\\&/g" \
                    -e 's/[*@|=]$//g' -e 's/[^\/]$/& /g' -e "s/^/${1-}/"
        )"
    fi
}

# @deprecated 2.12
_scp_local_files()
{
    _comp_compgen -ax scp local_files "$@"
}

# scp(1) completion
#
_comp_cmd_scp()
{
    local cur prev words cword comp_args
    _comp_initialize -n : -- "$@" || return

    local configfile
    _comp_cmd_ssh__configfile

    # Prefer `ssh` from same dir for resolving options, remote files, etc
    local pathcmd
    pathcmd=$(type -P "$1") && local PATH=${pathcmd%/*}:$PATH

    _comp_xfunc_ssh_compgen_suboption_check && {
        ((${#COMPREPLY[@]})) && COMPREPLY=("${COMPREPLY[@]/%/ }")
        return
    }

    local ipvx

    case $prev in
        -*c)
            _comp_cmd_ssh__compgen_ciphers
            COMPREPLY=("${COMPREPLY[@]/%/ }")
            return
            ;;
        -*F)
            _comp_compgen_filedir
            compopt +o nospace
            return
            ;;
        -*i)
            _comp_xfunc_ssh_compgen_identityfile
            compopt +o nospace
            return
            ;;
        -*J)
            _comp_compgen_known_hosts -a ${configfile:+-F "$configfile"} -- "$cur"
            return
            ;;
        -*[lP])
            return
            ;;
        -*o)
            _comp_xfunc_ssh_compgen_options
            return
            ;;
        -*S)
            compopt +o nospace
            _comp_compgen_commands
            return
            ;;
        -*4*)
            ipvx=-4
            ;;
        -*6*)
            ipvx=-6
            ;;
    esac

    _comp_expand || return

    case $cur in
        !(*:*)/* | [.~]*) ;; # looks like a path
        *:*)
            _comp_xfunc_scp_compgen_remote_files
            return
            ;;
    esac

    local prefix

    if [[ $cur == -F* ]]; then
        cur=${cur#-F}
        prefix=-F
    else
        case $cur in
            -*)
                _comp_compgen_usage
                COMPREPLY=("${COMPREPLY[@]/%/ }")
                return
                ;;
            *)
                if ! _comp_looks_like_path "$cur"; then
                    _comp_compgen_known_hosts ${ipvx-} -c -a \
                        ${configfile:+-F "$configfile"} -- "$cur"
                fi
                ;;
        esac
    fi

    _comp_compgen -ax scp local_files "${prefix-}"
} &&
    complete -F _comp_cmd_scp -o nospace scp

# ex: filetype=sh