1#compdef ssh slogin=ssh scp ssh-add ssh-agent ssh-keygen sftp ssh-copy-id
2
3# Completions currently based on OpenSSH 6.0 (released on 2012-04-22).
4#
5# TODO: update ssh-keygen (not based on 5.9)
6# TODO: sshd, ssh-keyscan, ssh-keysign
7
8_ssh () {
9  local curcontext="$curcontext" state line expl common tmp cmds suf ret=1
10  typeset -A opt_args
11
12  common=(
13    '(-2)-1[forces ssh to try protocol version 1 only]'
14    '(-1)-2[forces ssh to try protocol version 2 only]'
15    '(-6)-4[forces ssh to use IPv4 addresses only]'
16    '(-4)-6[forces ssh to use IPv6 addresses only]'
17    '-C[compress data]'
18    # for protocol version 2, this can be a comma-separated list
19    '-c+[select encryption cipher]:encryption cipher:(idea des 3des blowfish arcfour tss none)'
20    '-F+[specify alternate config file]:config file:_files'
21    '*-i+[select identity file]:SSH identity file:_files'
22    '*-o+[specify extra options]:option string:->option'
23  )
24  common_transfer=(
25    '-l[limit used bandwidth]:bandwidth in KiB/s:'
26    '-P+[specify port on remote host]:port number on remote host'
27    '-p[preserve modification times, access times and modes]'
28    '-q[disable progress meter and warnings]'
29    '-r[recursively copy directories (follows symbolic links)]'
30    '-S+[specify ssh program]:path to ssh:_command_names -e' \
31    '-v[verbose mode]'
32  )
33
34  case "$service" in
35  ssh)
36    _arguments -C -s \
37      '(-a)-A[enables forwarding of the authentication agent connection]' \
38      '(-A)-a[disable forwarding of authentication agent connection]' \
39      '(-P)-b+[specify interface to transmit on]:bind address:_bind_addresses' \
40      '-D+[specify a dynamic port forwarding]:dynamic port forwarding:->dynforward' \
41      '-e+[set escape character]:escape character (or `none'\''):' \
42      '(-n)-f[go to background]' \
43      '-g[allow remote hosts to connect to local forwarded ports]' \
44      '-I+[specify smartcard device]:device:_files' \
45      '-K[enable GSSAPI-based authentication and forwarding]' \
46      '-k[disable forwarding of GSSAPI credentials]' \
47      '*-L[specify local port forwarding]:local port forwarding:->forward' \
48      '-l+[specify login name]:login name:_ssh_users' \
49      '-M[master mode for connection sharing]' \
50      '(-1)-m+[specify mac algorithms]:mac spec:->macs' \
51      '(-1)-N[do not execute a remote command (protocol version 2 only)]' \
52      '-n[redirect stdin from /dev/null]' \
53      '-O:multiplex control command:((check\:"check master process is running" exit\:"request the master to exit" forward\:"request forward without command execution" stop\:"request the master to stop accepting further multiplexing requests" cancel\:"cancel existing forwardings with -L and/or -R"))' \
54      '-P[use non privileged port]' \
55      '-p+[specify port on remote host]:port number on remote host' \
56      '(-v)*-q[quiet operation]' \
57      '*-R[specify remote port forwarding]:remote port forwarding:->forward' \
58      '-S+[specify location of control socket for connection sharing]:path to control socket:_files' \
59      '(-1)-s[invoke subsystem]' \
60      '(-1 -t)-T[disable pseudo-tty allocation (protocol version 2 only)]' \
61      '(-T)-t[force pseudo-tty allocation]' \
62      '-V[show version number]' \
63      '(-q)*-v[verbose mode]' \
64      '-W[forward standard input and output to host]:stdinout forward:->hostport' \
65      '-w[request tunnel device forwarding]:local_tun[\:remote_tun] (integer or "any"):' \
66      '(-x -Y)-X[enable (untrusted) X11 forwarding]' \
67      '(-X -Y)-x[disable X11 forwarding]' \
68      '(-x -X)-Y[enable trusted X11 forwarding]' \
69      '-y[send log info via syslog instead of stderr]' \
70      ':remote host name:->userhost' \
71      '*::args:->command' "$common[@]" && ret=0
72    ;;
73  scp)
74    _arguments -C -s \
75      '-3[copy through local host, not directly between the remote hosts]' \
76      '-B[batch mode (don'\''t ask for passphrases)]' \
77      '*:file:->file' "$common[@]" "$common_transfer[@]" && ret=0
78    ;;
79  ssh-add)
80    _arguments -s \
81      '-c[identity is subject to confirmation via SSH_ASKPASS]' \
82      '-D[delete all identities]' \
83      '-d[remove identity]' \
84      '-e[remove keys provided by the PKCS#11 shared library]:library:' \
85      '-k[load plain private keys only and skip certificates]' \
86      '-L[lists public key parameters of all identities in the agent]'\
87      '-l[list all identities]' \
88      '-s[add keys provided by the PKCS#11 shared library]:library:' \
89      '-t[set maximum lifetime for identity]:maximum lifetime (in seconds or time format):' \
90      '-X[unlock the agent]' \
91      '-x[lock the agent with a password]' \
92      '*:SSH identity file:_files'
93    return
94    ;;
95  ssh-agent)
96    _arguments -s \
97      '(-k)-a[UNIX-domain socket to bind agent to]:UNIX-domain socket:_files' \
98      '(-k -s)-c[force csh-style shell]' \
99      '(-k)-d[debug mode]' \
100      '-k[kill current agent]' \
101      '(-k -c)-s[force sh-style shell]' \
102      '-t[set default maximum lifetime for identities]:maximum lifetime (in seconds or time format):' \
103      '*::command: _normal'
104    return
105    ;;
106  ssh-keygen)
107    cmds=( -p -i -e -y -c -l -B -D -U )
108    _arguments \
109      '-q[silence ssh-keygen]' \
110      "($cmds -P)-b[specify number of bits in key]:bits in key" \
111      "($cmds -P)-t[specify the type of the key to create]:key type:(rsa1 rsa dsa ecdsa)" \
112      "(${cmds#-p })-N[provide new passphrase]:new passphrase" \
113      "($cmds -b -t)-C[provide new comment]:new comment" \
114      '(-D)-f[key file]:key file:_files' \
115      '('${(j. .)cmds:#-[pc]}' -t -b)-P[provide old passphrase]:old passphrase' \
116      "($cmds -q -b -t -C)-p[change passphrase of private key file]" \
117      "($cmds -q -b -t -N -C -P)-i[import key to OpenSSH format]" \
118      "($cmds -q -b -t -N -C -P)-e[export key to SECSH file format]" \
119      "($cmds -q -b -t -N -C -P)-y[get public key from private key]" \
120      "($cmds -q -b -t -N)-c[change comment in private and public key files]" \
121      "($cmds -q -b -t -N -C -P)-l[show fingerprint of key file]" \
122      "($cmds -q -b -t -N -C -P)-B[show the bubblebabble digest of key]" \
123      "($cmds -q -b -t -N -C -P -f)-D[download key stored in smartcard reader]:reader" \
124      "($cmds -q -b -t -N -C -P)-U[upload key to smartcard reader]:reader"
125    return
126    ;;
127  sftp)
128    _arguments -C -s \
129      '-B+[specify buffer size]:buffer size in bytes (default\: 32768):' \
130      '-b+[specify batch file to read]:batch file:_files' \
131      '-D[connect directly to a local sftp server]:sftp server path:' \
132      '-R[specify number of outstanding requests]:number of requests (default\: 64):' \
133      '-s[SSH2 subsystem or path to sftp server on the remote host]' \
134      '1:file:->rfile' '*:file:->file' "$common[@]" "$common_transfer[@]" && ret=0
135    ;;
136  (ssh-copy-id)
137    _arguments \
138      '-i:SSH identity file:_files' \
139      ':remote host name:->userhost' \
140    ;;
141  esac
142
143  while [[ -n "$state" ]]; do
144    lstate="$state"
145    state=''
146
147    case "$lstate" in
148    option)
149      if compset -P '*='; then
150        case "$IPREFIX" in
151        *(#i)(afstokenpassing|batchmode|challengeresponseauthentication|checkhostip|clearallforwardings|compression|enablesshkeysign|exitonforwardfailure|fallbacktorsh|forward(agent|x11)|forwardx11trusted|gatewayports|gssapiauthentication|gssapidelegatecredentials|gssapitrustdns|hashknownhosts|hostbasedauthentication|identitiesonly|kbdinteractiveauthentication|(tcp|)keepalive|nohostauthenticationforlocalhost|passwordauthentication|permitlocalcommand|pubkeyauthentication|rhosts(|rsa)authentication|rsaauthentication|usersh|kerberos(authentication|tgtpassing)|useprivilegedport|visualhostkey)=*)
152          _wanted values expl 'truth value' compadd yes no && ret=0
153          ;;
154        *(#i)addressfamily=*)
155          _wanted values expl 'address family' compadd any inet inet6 && ret=0
156          ;;
157        *(#i)bindaddress=*)
158          _wanted bind-addresses expl 'bind address' _bind_addresses && ret=0
159          ;;
160        *(#i)ciphers=*)
161          _values -s , 'encryption cipher' \
162              '3des-cbc' \
163              'aes128-cbc' \
164              'aes192-cbc' \
165              'aes256-cbc' \
166              'aes128-ctr' \
167              'aes192-ctr' \
168              'aes256-ctr' \
169              'arcfour128' \
170              'arcfour256' \
171              'arcfour' \
172              'blowfish-cbc' \
173              'cast128-cbc' \
174              \
175              'rijndael128-cbc' \
176              'rijndael192-cbc' \
177              'rijndael256-cbc' \
178              'rijndael-cbc@lysator.liu.se' \
179              && ret=0
180          ;;
181        *(#i)cipher=*)
182          _wanted values expl 'encryption cipher (protocol version 1)' \
183              compadd blowfish 3des des idea arcfour tss none && ret=0
184          ;;
185        *(#i)compressionlevel=*)
186          _values 'compression level' {1..9} && ret=0
187          ;;
188        *(#i)connectionattempts=*)
189          _message -e 'connection attempts' && ret=0
190          ;;
191        *(#i)connecttimeout=*)
192          _message -e 'connection timeout' && ret=0
193          ;;
194        *(#i)controlmaster=*)
195          _wanted values expl 'truthish value' compadd yes no auto autoask && ret=0
196          ;;
197        *(#i)controlpath=*)
198          _description files expl 'path to control socket'
199          _files "$expl[@]" && ret=0
200          ;;
201        *(#i)controlpersist=*)
202          _message -e 'timeout'
203          ret=0
204          _wanted values expl 'truth value' compadd yes no && ret=0
205          ;;
206        *(#i)escapechar=*)
207          _message -e 'escape character (or `none'\'')'
208          ret=0
209          ;;
210        *(#i)forwardx11timeout=*)
211          _message -e 'timeout'
212          ret=0
213          ;;
214        *(#i)globalknownhostsfile=*)
215          _description files expl 'global file with known hosts'
216          _files "$expl[@]" && ret=0
217          ;;
218        *(#i)hostname=*)
219          _wanted hosts expl 'real host name to log into' _ssh_hosts && ret=0
220          ;;
221        *(#i)hostkeyalgorithms=*)
222          _values -s , 'host key algorithms' \
223              'ecdsa-sha2-nistp256-cert-v01@openssh.com' \
224              'ecdsa-sha2-nistp384-cert-v01@openssh.com' \
225              'ecdsa-sha2-nistp521-cert-v01@openssh.com' \
226              'ssh-rsa-cert-v01@openssh.com' \
227              'ssh-dss-cert-v01@openssh.com' \
228              'ssh-rsa-cert-v00@openssh.com' \
229              'ssh-dss-cert-v00@openssh.com' \
230              'ecdsa-sha2-nistp256' \
231              'ecdsa-sha2-nistp384' \
232              'ecdsa-sha2-nistp521' \
233              'ssh-rsa' \
234              'ssh-dss' && ret=0
235          ;;
236        *(#i)identityfile=*)
237          _description files expl 'SSH identity file'
238          _files "$expl[@]" && ret=0
239          ;;
240        *(#i)ipqos=*)
241          local descr
242          if [[ $PREFIX = *\ *\ * ]]; then return 1; fi
243          if compset -P '* '; then
244            descr='QoS for non-interactive sessions'
245          else
246            descr='QoS [for interactive sessions if second value given, separated by white space]'
247          fi
248          _values $descr 'af11' 'af12' 'af13' 'af14' 'af22' \
249              'af23' 'af31' 'af32' 'af33' 'af41' 'af42' 'af43' \
250              'cs0' 'cs1' 'cs2' 'cs3' 'cs4' 'cs5' 'cs6' 'cs7' 'ef' \
251              'lowdelay' 'throughput' 'reliability' && ret=0
252          ;;
253        *(#i)(local|remote)forward=*)
254          state=forward
255          ;;
256        *(#i)dynamicforward=*)
257          state=dynforward
258          ;;
259        *(#i)kbdinteractivedevices=*)
260          _values -s , 'keyboard-interactive authentication methods' \
261              'bsdauth' 'pam' 'skey' && ret=0
262          ;;
263        *(#i)kexalgorithms=*)
264          _values -s , 'KEX algorithms' \
265              ecdh-sha2-nistp256 ecdh-sha2-nistp384 ecdh-sha2-nistp521 \
266              diffie-hellman-group-exchange-sha256 \
267              diffie-hellman-group-exchange-sha1 \
268              diffie-hellman-group14-sha1 diffie-hellman-group1-sha1 && ret=0
269          ;;
270        *(#i)localcommand=*)
271          _description commands expl 'run command locally after connecting'
272          _command_names && ret=0
273          ;;
274        *(#i)loglevel=*)
275          _values 'log level' QUIET FATAL ERROR INFO VERBOSE\
276              DEBUG DEBUG1 DEBUG2 DEBUG3 && ret=0
277          ;;
278        *(#i)macs=*)
279          state=macs
280          ;;
281        *(#i)numberofpasswordprompts=*)
282          _message -e 'number of password prompts'
283          ret=0
284          ;;
285        *(#i)pkcs11provider=*)
286          _description files expl 'PKCS#11 shared library'
287          _files -g '*.so' "$expl[@]" && ret=0
288          ;;
289        *(#i)port=*)
290          _message -e 'port number on remote host'
291          ret=0
292          ;;
293        *(#i)preferredauthentications=*)
294          _values -s , 'authentication method' gssapi-with-mic \
295              hostbased publickey keyboard-interactive password && ret=0
296          ;;
297        *(#i)protocol=*)
298          _values -s , 'protocol version' \
299              '1' \
300              '2' && ret=0
301          ;;
302        *(#i)proxycommand=*)
303          compset -q
304          shift 1 words
305          (( CURRENT-- ))
306          _normal && ret=0
307          ;;
308        *(#i)rekeylimit=*)
309          _message -e 'maximum number of bytes transmitted before renegotiating session key'
310          ret=0
311          ;;
312        *(#i)requesttty=*)
313          _values 'request a pseudo-tty' \
314              'no[never request a TTY]' \
315              'yes[always request a TTY when stdin is a TTY]' \
316              'force[always request a TTY]' \
317              'auto[request a TTY when opening a login session]' && ret=0
318          ;;
319        *(#i)sendenv=*)
320          _wanted envs expl 'environment variable' _parameters -g 'scalar*export*' && ret=0
321          ;;
322        *(#i)serveralivecountmax=*)
323          _message -e 'number of alive messages without replies before disconnecting'
324          ret=0
325          ;;
326        *(#i)serveraliveinterval=*)
327          _message -e 'timeout in seconds since last data was received to send alive message'
328          ret=0
329          ;;
330        *(#i)(stricthostkeychecking|verifyhostkeydns)=*)
331          _wanted values expl 'checking type' compadd yes no ask && ret=0
332          ;;
333        *(#i)tunnel=*)
334          _values 'request device forwarding' \
335              'yes' \
336              'point-to-point' \
337              'ethernet' \
338              'no' && ret=0
339          ;;
340        *(#i)tunneldevice=*)
341          _message -e 'local_tun[:remote_tun] (integer or "any")'
342          ret=0
343          ;;
344        *(#i)userknownhostsfile=*)
345          _description files expl 'user file with known hosts'
346          _files "$expl[@]" && ret=0
347          ;;
348        *(#i)user=*)
349          _wanted users expl 'user to log in as' _ssh_users && ret=0
350          ;;
351        *(#i)xauthlocation=*)
352          _description files expl 'xauth program'
353          _files "$expl[@]" -g '*(-*)' && ret=0
354          ;;
355        esac
356      else
357        # old options are after the empty "\"-line
358        _wanted values expl 'configure file option' \
359            compadd -M 'm:{a-z}={A-Z}' -S '=' - \
360                AddressFamily \
361                BatchMode \
362                BindAddress \
363                ChallengeResponseAuthentication \
364                CheckHostIP \
365                Cipher \
366                Ciphers \
367                ClearAllForwardings \
368                Compression \
369                CompressionLevel \
370                ConnectionAttempts \
371                ConnectTimeout \
372                ControlMaster \
373                ControlPath \
374                ControlPersist \
375                DynamicForward \
376                EnableSSHKeysign \
377                EscapeChar \
378                ExitOnForwardFailure \
379                ForwardAgent \
380                ForwardX11 \
381                ForwardX11Timeout \
382                ForwardX11Trusted \
383                GatewayPorts \
384                GlobalKnownHostsFile \
385                GSSAPIAuthentication \
386                GSSAPIDelegateCredentials \
387                GSSAPITrustDns \
388                HashKnownHosts \
389                Host \
390                HostbasedAuthentication \
391                HostKeyAlgorithms \
392                HostKeyAlias \
393                HostName \
394                IdentitiesOnly \
395                IdentityFile \
396                IPQoS \
397                KbdInteractiveAuthentication \
398                KbdInteractiveDevices \
399                KexAlgorithms \
400                LocalCommand \
401                LocalForward \
402                LogLevel \
403                MACs \
404                NoHostAuthenticationForLocalhost \
405                NumberOfPasswordPrompts \
406                PasswordAuthentication \
407                PermitLocalCommand \
408                PKCS11Provider \
409                Port \
410                PreferredAuthentications \
411                Protocol \
412                ProxyCommand \
413                PubkeyAuthentication \
414                RekeyLimit \
415                RemoteForward \
416                RequestTTY \
417                RhostsRSAAuthentication \
418                RSAAuthentication \
419                SendEnv \
420                ServerAliveCountMax \
421                ServerAliveInterval \
422                StrictHostKeyChecking \
423                TCPKeepAlive \
424                Tunnel \
425                TunnelDevice \
426                UsePrivilegedPort \
427                User \
428                UserKnownHostsFile \
429                VerifyHostKeyDNS \
430                VisualHostKey \
431                XAuthLocation \
432                \
433                AFSTokenPassing \
434                FallBackToRsh \
435                KeepAlive \
436                KerberosAuthentication \
437                KerberosTgtPassing \
438                PreferredAuthentications \
439                ProtocolKeepAlives \
440                RhostsAuthentication \
441                SetupTimeOut \
442                SmartcardDevice \
443                UseRsh \
444                && ret=0
445      fi
446      ;;
447    forward)
448      local port=false host=false listen=false bind=false
449      if compset -P 1 '*:'; then
450        if [[ $IPREFIX != (*=|)<-65535>: ]]; then
451          if compset -P 1 '*:'; then
452            if compset -P '*:'; then
453              port=true
454            else
455              host=true
456            fi
457          else
458            listen=true
459            ret=0
460          fi
461        else
462          if compset -P '*:'; then
463            port=true
464          else
465            host=true
466          fi
467        fi
468      else
469        listen=true
470        bind=true
471      fi
472      $port && { _message -e port-numbers 'port number'; ret=0 }
473      $listen && { _message -e port-numbers 'listen-port number'; ret=0 }
474      $host && { _wanted hosts expl host _ssh_hosts -S: && ret=0 }
475      $bind && { _wanted bind-addresses expl bind-address _bind_addresses -S: && ret=0 }
476      return ret
477      ;;
478    dynforward)
479      _message -e port-numbers 'listen-port number'
480      if ! compset -P '*:'; then
481        _wanted bind-addresses expl bind-address _bind_addresses -qS:
482      fi
483      return 0
484      ;;
485    hostport)
486      if compset -P '*:'; then
487        _message -e port-numbers 'port number'
488        ret=0
489      else
490        _wanted hosts expl host _ssh_hosts -S: && ret=0
491      fi
492      return ret
493      ;;
494    macs)
495      _values -s , 'MAC algorithms' hmac-md5 hmac-sha1 umac-64@openssh.com \
496          hmac-ripemd160 hmac-sha1-96 hmac-md5-96 hmac-sha2-256 \
497          hmac-sha2-256-96 hmac-sha2-512 hmac-sha2-512-96 && ret=0
498      ;;
499    command)
500      shift 1 words
501      (( CURRENT-- ))
502      _normal
503      return
504      ;;
505    userhost)
506      if compset -P '*@'; then
507        _wanted hosts expl 'remote host name' _ssh_hosts && ret=0
508      elif compset -S '@*'; then
509        _wanted users expl 'login name' _ssh_users -S '' && ret=0
510      else
511        if (( $+opt_args[-l] )); then
512          tmp=()
513        else
514          tmp=( 'users:login name:_ssh_users -qS@' )
515        fi
516        _alternative \
517            'hosts:remote host name:_ssh_hosts' \
518            "$tmp[@]" && ret=0
519      fi
520      ;;
521    file)
522      if compset -P '[^./][^/]#:'; then
523        _remote_files -- ssh ${(kv)~opt_args[(I)-[FP1246]]/-P/-p} && ret=0
524      elif compset -P '*@'; then
525        suf=( -S '' )
526        compset -S ':*' || suf=( -r: -S: )
527        _wanted hosts expl 'remote host name' _ssh_hosts $suf && ret=0
528      else
529        _alternative \
530            'files:: _files' \
531            'hosts:remote host name:_ssh_hosts -r: -S:' \
532            'users:user:_ssh_users -qS@' && ret=0
533      fi
534      ;;
535    rfile)
536      if compset -P '*:'; then
537        _remote_files -- ssh && ret=0
538      elif compset -P '*@'; then
539        _wanted hosts expl host _ssh_hosts -r: -S: && ret=0
540      else
541        _alternative \
542            'hosts:remote host name:_ssh_hosts -r: -S:' \
543            'users:user:_ssh_users -qS@' && ret=0
544      fi
545      ;;
546    esac
547  done
548
549  return ret
550}
551
552_ssh_users () {
553  _combination -s '[:@]' my-accounts users-hosts users "$@"
554}
555
556_ssh_hosts () {
557  local -a config_hosts
558  local config
559  integer ind
560
561  # If users-hosts matches, we shouldn't complete anything else.
562  if [[ "$IPREFIX" == *@ ]]; then
563    _combination -s '[:@]' my-accounts users-hosts "users=${IPREFIX/@}" hosts "$@" && return
564  else
565    _combination -s '[:@]' my-accounts users-hosts \
566      ${opt_args[-l]:+"users=${opt_args[-l]:q}"} hosts "$@" && return
567  fi
568  if (( ind = ${words[(I)-F]} )); then
569    config=${~words[ind+1]}
570  else
571    config="$HOME/.ssh/config"
572  fi
573  if [[ -r $config ]]; then
574    local IFS=$'\t ' key hosts host
575    while read key hosts; do
576      if [[ "$key" == (#i)host ]]; then
577         for host in ${(z)hosts}; do
578            case $host in
579            (*[*?]*) ;;
580            (*) config_hosts+=("$host") ;;
581            esac
582         done
583      fi
584    done < "$config"
585    if (( ${#config_hosts} )); then
586      _wanted hosts expl 'remote host name' \
587        compadd -M 'm:{a-zA-Z}={A-Za-z} r:|.=* r:|=*' "$@" $config_hosts
588    fi
589  fi
590}
591
592_ssh "$@"
593