ssh

Module

ssh

Module Summary

Main API of the ssh application

Description

Interface module for the ssh application.

See ssh(6) for details of supported version, algorithms and unicode support.

Options

The exact behaviour of some functions can be adjusted with the use of options which are documented together with the functions. Generally could each option be used at most one time in each function call. If given two or more times, the effect is not predictable unless explicitly documented.

The options are of different kinds:

Limits

which alters limits in the system, for example number of simultaneous login attempts.

Timeouts

which give some defined behaviour if too long time elapses before a given event or action, for example time to wait for an answer.

Callbacks

which gives the caller of the function the possibility to execute own code on some events, for example calling an own logging function or to perform an own login function

Behaviour

which changes the systems behaviour.

Data types

Type definitions that are used more than once in this module, or abstractions to indicate the intended use of the data type, or both:

boolean() =

true | false

string() =

[byte()]

ssh_daemon_ref() =

opaque() - as returned by ssh:daemon/[1,2,3]

ssh_connection_ref() =

opaque() - as returned by ssh:connect/3

ip_address() =

inet::ip_address

subsystem_spec() =

{subsystem_name(), {channel_callback(), channel_init_args()}}

subsystem_name() =

string()

channel_callback() =

atom() - Name of the Erlang module implementing the subsystem using the ssh_channel behavior, see ssh_channel(3)

key_cb() =

atom() | {atom(), list()}

atom() - Name of the erlang module implementing the behaviours ssh_client_key_api or ssh_client_key_api as the case maybe.

list() - List of options that can be passed to the callback module.

channel_init_args() =

list()

algs_list() =

list( alg_entry() )

alg_entry() =

{kex, simple_algs()} | {public_key, simple_algs()} | {cipher, double_algs()} | {mac, double_algs()} | {compression, double_algs()}

simple_algs() =

list( atom() )

double_algs() =

[{client2serverlist,simple_algs()},{server2client,simple_algs()}] | simple_algs()

modify_algs_list() =

list( {append,algs_list()} | {prepend,algs_list()} | {rm,algs_list()} )

Exports

close(ConnectionRef) -> ok

Types

Closes an SSH connection.

connect(Host, Port, Options) ->connect(Host, Port, Options, Timeout) ->connect(TcpSocket, Options) ->connect(TcpSocket, Options, Timeout) -> {ok, ssh_connection_ref()} | {error, Reason}

Types

22 is default, the assigned well-known port number for SSH. Negotiation time-out in milli-seconds. The default value is infinity. For connection time-out, use option {connect_timeout, timeout()}. The socket is supposed to be from gen_tcp:connect or gen_tcp:accept with option {active,false}

Connects to an SSH server. No channel is started. This is done by calling ssh_connection:session_channel/[2, 4].

Options:

{inet, inet | inet6}

IP version to use.

{user_dir, string()}

Sets the user directory, that is, the directory containing ssh configuration files for the user, such as known_hosts, id_rsa, id_dsa, and authorized_key. Defaults to the directory normally referred to as ~/.ssh.

{dsa_pass_phrase, string()}

If the user DSA key is protected by a passphrase, it can be supplied with this option.

{rsa_pass_phrase, string()}

If the user RSA key is protected by a passphrase, it can be supplied with this option.

{ecdsa_pass_phrase, string()}

If the user ECDSA key is protected by a passphrase, it can be supplied with this option.

{silently_accept_hosts, boolean()}
{silently_accept_hosts, CallbackFun}
{silently_accept_hosts, {HashAlgoSpec, CallbackFun} }

HashAlgoSpec = crypto:digest_type() | [ crypto:digest_type() ]
CallbackFun = fun(PeerName, FingerPrint) -> boolean()
PeerName = string()
FingerPrint = string() | [ string() ]

This option guides the connect function how to act when the connected server presents a Host Key that the client has not seen before. The default is to ask the user with a question on stdio of whether to accept or reject the new Host Key. See also the option user_dir for the path to the file known_hosts where previously accepted Host Keys are recorded.

The option can be given in three different forms as seen above:

  • The value is a boolean(). The value true will make the client accept any unknown Host Key without any user interaction. The value false keeps the default behaviour of asking the the user on stdio.
  • A CallbackFun will be called and the boolean return value true will make the client accept the Host Key. A return value of false will make the client to reject the Host Key and therefore also the connection will be closed. The arguments to the fun are:
    • PeerName - a string with the name or address of the remote host.
    • FingerPrint - the fingerprint of the Host Key as public_key:ssh_hostkey_fingerprint/1 calculates it.
  • A tuple {HashAlgoSpec, CallbackFun}. The HashAlgoSpec specifies which hash algorithm shall be used to calculate the fingerprint used in the call of the CallbackFun. The HashALgoSpec is either an atom or a list of atoms as the first argument in public_key:ssh_hostkey_fingerprint/2. If it is a list of hash algorithm names, the FingerPrint argument in the CallbackFun will be a list of fingerprints in the same order as the corresponding name in the HashAlgoSpec list.
{save_accepted_host, boolean()}

If true, the client saves an accepted host key to avoid the accept question the next time the same host is connected. If the option key_cb is not present, the key is saved in the file "known_hosts".

If false, the key is not saved and the key will still be unknown at the next access of the same host.

{user_interaction, boolean()}

If false, disables the client to connect to the server if any user interaction is needed, such as accepting the server to be added to the known_hosts file, or supplying a password. Defaults to true. Even if user interaction is allowed it can be suppressed by other options, such as silently_accept_hosts and password. However, those options are not always desirable to use from a security point of view.

{disconnectfun, fun(Reason:term()) -> _}

Provides a fun to implement your own logging when a server disconnects the client.

{unexpectedfun, fun(Message:term(), Peer) -> report | skip }

Provides a fun to implement your own logging or other action when an unexpected message arrives. If the fun returns report the usual info report is issued but if skip is returned no report is generated.

Peer is in the format of {Host,Port}.

{pref_public_key_algs, list()}

List of user (client) public key algorithms to try to use.

The default value is the public_key entry in ssh:default_algorithms/0.

If there is no public key of a specified type available, the corresponding entry is ignored. Note that the available set is dependent on the underlying cryptolib and current user's public keys.

{preferred_algorithms, algs_list()}

List of algorithms to use in the algorithm negotiation. The default algs_list() can be obtained from default_algorithms/0.

If an alg_entry() is missing in the algs_list(), the default value is used for that entry.

Here is an example of this option:

{preferred_algorithms, 
 [{public_key,['ssh-rsa','ssh-dss']},
  {cipher,[{client2server,['aes128-ctr']},
           {server2client,['aes128-cbc','3des-cbc']}]},
  {mac,['hmac-sha2-256','hmac-sha1']},
  {compression,[none,zlib]}
  ]
}

The example specifies different algorithms in the two directions (client2server and server2client), for cipher but specifies the same algorithms for mac and compression in both directions. The kex (key exchange) is implicit but public_key is set explicitly.

For background and more examples see the User's Guide.

Warning

Changing the values can make a connection less secure. Do not change unless you know exactly what you are doing. If you do not understand the values then you are not supposed to change them.

{modify_algorithms, modify_algs_list()}

Modifies the list of algorithms to use in the algorithm negotiation. The modifications are applied after the option preferred_algorithms (if existing) is applied.

The algoritm for modifications works like this:

  • Input is the modify_algs_list() and a set of algorithms A obtained from the preferred_algorithms option if existing, or else from the ssh:default_algorithms/0.

  • The head of the modify_algs_list() modifies A giving the result A'.

    The possible modifications are:

    • Append or prepend supported but not enabled algorithm(s) to the list of algorithms. If the wanted algorithms already are in A they will first be removed and then appended or prepended,

    • Remove (rm) one or more algorithms from A.

  • Repeat the modification step with the tail of modify_algs_list() and the resulting A'.

If an unsupported algorithm is in the modify_algs_list(), it will be silently ignored

If there are more than one modify_algorithms options, the result is undefined.

Here is an example of this option:

{modify_algorithms, 
 [{prepend, [{kex, ['diffie-hellman-group1-sha1']}],
  {rm,      [{compression, [none]}]}
 ]
}

The example specifies that:

  • the old key exchange algorithm 'diffie-hellman-group1-sha1' should be the main alternative. It will be the main alternative since it is prepened to the list

  • The compression algorithm none (= no compression) is removed so compression is enforced

For background and more examples see the User's Guide.

{dh_gex_limits,{Min=integer(),I=integer(),Max=integer()}}

Sets the three diffie-hellman-group-exchange parameters that guides the connected server in choosing a group. See RFC 4419 for the function of thoose. The default value is {1024, 6144, 8192}.

{connect_timeout, timeout()}

Sets a time-out on the transport layer connection. For gen_tcp the time is in milli-seconds and the default value is infinity.

{auth_methods, string()}

Comma-separated string that determines which authentication methods that the client shall support and in which order they are tried. Defaults to "publickey,keyboard-interactive,password"

{user, string()}

Provides a username. If this option is not given, ssh reads from the environment (LOGNAME or USER on UNIX, USERNAME on Windows).

{password, string()}

Provides a password for password authentication. If this option is not given, the user is asked for a password, if the password authentication method is attempted.

{recv_ext_info, boolean()}

Tell the server that the client accepts extension negotiation. See Draft-ietf-curdle-ssh-ext-info (work in progress) for details.

Currently implemented extension is server-sig-algs which is the list of the server's preferred user's public key algorithms.

Default value is true.

{key_cb, key_cb()}

Module implementing the behaviour ssh_client_key_api. Can be used to customize the handling of public keys. If callback options are provided along with the module name, they are made available to the callback module via the options passed to it under the key 'key_cb_private'.

{quiet_mode, atom() = boolean()}

If true, the client does not print anything on authorization.

{id_string, random | string()}

The string that the client presents to a connected server initially. The default value is "Erlang/VSN" where VSN is the ssh application version number.

The value random will cause a random string to be created at each connection attempt. This is to make it a bit more difficult for a malicious peer to find the ssh software brand and version.

{fd, file_descriptor()}

Allows an existing file descriptor to be used (by passing it on to the transport protocol).

{rekey_limit, integer()}

Provides, in bytes, when rekeying is to be initiated. Defaults to once per each GB and once per hour.

{idle_time, integer()}

Sets a time-out on a connection when no channels are active. Defaults to infinity.

{ssh_msg_debug_fun, fun(ConnectionRef::ssh_connection_ref(), AlwaysDisplay::boolean(), Msg::binary(), LanguageTag::binary()) -> _}

Provide a fun to implement your own logging of the SSH message SSH_MSG_DEBUG. The last three parameters are from the message, see RFC4253, section 11.3. The ConnectionRef is the reference to the connection on which the message arrived. The return value from the fun is not checked.

The default behaviour is ignore the message. To get a printout for each message with AlwaysDisplay = true, use for example {ssh_msg_debug_fun, fun(_,true,M,_)-> io:format("DEBUG: ~p~n", [M]) end}

connection_info(ConnectionRef, [Option]) ->[{Option, Value}]

Types

Retrieves information about a connection.

daemon(Port) ->daemon(Port, Options) ->daemon(HostAddress, Port, Options) ->daemon(TcpSocket) ->daemon(TcpSocket, Options) -> {ok, ssh_daemon_ref()} | {error, atom()}

Types

The socket is supposed to be from gen_tcp:connect or gen_tcp:accept with option {active,false}

Starts a server listening for SSH connections on the given port. If the Port is 0, a random free port is selected. See daemon_info/1 about how to find the selected port number.

Please note that by historical reasons both the HostAddress argument and the inet socket option ip set the listening address. This is a source of possible inconsistent settings.

The rules for handling the two address passing options are:

  • if HostAddress is an IP-address, that IP-address is the listening address. An 'ip'-option will be discarded if present.
  • if HostAddress is loopback, the listening address is loopback and an loopback address will be choosen by the underlying layers. An 'ip'-option will be discarded if present.
  • if HostAddress is any and no 'ip'-option is present, the listening address is any and the socket will listen to all addresses
  • if HostAddress is any and an 'ip'-option is present, the listening address is set to the value of the 'ip'-option

Options:

{inet, inet | inet6}

IP version to use when the host address is specified as any.

{subsystems, [subsystem_spec()]}

Provides specifications for handling of subsystems. The "sftp" subsystem specification is retrieved by calling ssh_sftpd:subsystem_spec/1. If the subsystems option is not present, the value of [ssh_sftpd:subsystem_spec([])] is used. The option can be set to the empty list if you do not want the daemon to run any subsystems.

{shell, {Module, Function, Args} | fun(string() = User) - > pid() | fun(string() = User, ip_address() = PeerAddr) -> pid()}

Defines the read-eval-print loop used when a shell is requested by the client. The default is to use the Erlang shell: {shell, start, []}

{ssh_cli, {channel_callback(), channel_init_args()} | no_cli}

Provides your own CLI implementation, that is, a channel callback module that implements a shell and command execution. The shell read-eval-print loop can be customized, using the option shell. This means less work than implementing an own CLI channel. If set to no_cli, the CLI channels are disabled and only subsystem channels are allowed.

{user_dir, string()}

Sets the user directory. That is, the directory containing ssh configuration files for the user, such as known_hosts, id_rsa, id_dsa, and authorized_key. Defaults to the directory normally referred to as ~/.ssh.

{system_dir, string()}

Sets the system directory, containing the host key files that identify the host keys for ssh. Defaults to /etc/ssh. For security reasons, this directory is normally accessible only to the root user.

{auth_methods, string()}

Comma-separated string that determines which authentication methods that the server is to support and in what order they are tried. Defaults to "publickey,keyboard-interactive,password"

Note that the client is free to use any order and to exclude methods.

{auth_method_kb_interactive_data, PromptTexts}
where:
PromptTexts = kb_int_tuple() | fun(Peer::{IP::tuple(),Port::integer()}, User::string(), Service::string()) -> kb_int_tuple()
kb_int_tuple() = {Name::string(), Instruction::string(), Prompt::string(), Echo::boolean()}

Sets the text strings that the daemon sends to the client for presentation to the user when using keyboar-interactive authentication. If the fun/3 is used, it is called when the actual authentication occurs and may therefore return dynamic data like time, remote ip etc.

The parameter Echo guides the client about need to hide the password.

The default value is: {auth_method_kb_interactive_data, {"SSH server", "Enter password for \""++User++"\"", "password: ", false}>

{user_passwords, [{string() = User, string() = Password}]}

Provides passwords for password authentication. The passwords are used when someone tries to connect to the server and public key user-authentication fails. The option provides a list of valid usernames and the corresponding passwords.

{password, string()}

Provides a global password that authenticates any user. From a security perspective this option makes the server very vulnerable.

{preferred_algorithms, algs_list()}

List of algorithms to use in the algorithm negotiation. The default algs_list() can be obtained from default_algorithms/0.

If an alg_entry() is missing in the algs_list(), the default value is used for that entry.

Here is an example of this option:

{preferred_algorithms, 
 [{public_key,['ssh-rsa','ssh-dss']},
  {cipher,[{client2server,['aes128-ctr']},
           {server2client,['aes128-cbc','3des-cbc']}]},
  {mac,['hmac-sha2-256','hmac-sha1']},
  {compression,[none,zlib]}
  ]
}

The example specifies different algorithms in the two directions (client2server and server2client), for cipher but specifies the same algorithms for mac and compression in both directions. The kex (key exchange) is implicit but public_key is set explicitly.

For background and more examples see the User's Guide.

Warning

Changing the values can make a connection less secure. Do not change unless you know exactly what you are doing. If you do not understand the values then you are not supposed to change them.

{modify_algorithms, modify_algs_list()}

Modifies the list of algorithms to use in the algorithm negotiation. The modifications are applied after the option preferred_algorithms is applied (if existing)

The possible modifications are to:

  • Append or prepend supported but not enabled algorithm(s) to the list of algorithms.

    If the wanted algorithms already are in the list of algorithms, they will first be removed and then appended or prepended.

  • Remove (rm) one or more algorithms from the list of algorithms.

If an unsupported algorithm is in the list, it will be silently ignored

Here is an example of this option:

{modify_algorithms, 
 [{prepend, [{kex, ['diffie-hellman-group1-sha1']}],
  {rm,      [{compression, [none]}]}
 ]
}

The example specifies that:

  • the old key exchange algorithm 'diffie-hellman-group1-sha1' should be the main alternative. It will be the main alternative since it is prepened to the list

  • The compression algorithm none (= no compression) is removed so compression is enforced

For background and more examples see the User's Guide.

{dh_gex_groups, [{Size=integer(),G=integer(),P=integer()}] | {file,filename()} {ssh_moduli_file,filename()} }

Defines the groups the server may choose among when diffie-hellman-group-exchange is negotiated. See RFC 4419 for details. The three variants of this option are:

{Size=integer(),G=integer(),P=integer()}
The groups are given explicitly in this list. There may be several elements with the same Size. In such a case, the server will choose one randomly in the negotiated Size.
{file,filename()}
The file must have one or more three-tuples {Size=integer(),G=integer(),P=integer()} terminated by a dot. The file is read when the daemon starts.
{ssh_moduli_file,filename()}
The file must be in ssh-keygen moduli file format. The file is read when the daemon starts.

The default list is fetched from the public_key application.

{dh_gex_limits,{Min=integer(),Max=integer()}}

Limits what a client can ask for in diffie-hellman-group-exchange. The limits will be {MaxUsed = min(MaxClient,Max), MinUsed = max(MinClient,Min)} where MaxClient and MinClient are the values proposed by a connecting client.

The default value is {0,infinity}.

If MaxUsed < MinUsed in a key exchange, it will fail with a disconnect.

See RFC 4419 for the function of the Max and Min values.

{pwdfun, fun(User::string(), Password::string(), PeerAddress::{ip_adress(),port_number()}, State::any()) -> boolean() | disconnect | {boolean(),any()} }

Provides a function for password validation. This could used for calling an external system or if passwords should be stored as a hash. The fun returns:

  • true if the user and password is valid and
  • false otherwise.

This fun can also be used to make delays in authentication tries for example by calling timer:sleep/1. To facilitate counting of failed tries the State variable could be used. This state is per connection only. The first time the pwdfun is called for a connection, the State variable has the value undefined. The pwdfun can return - in addition to the values above - a new state as:

  • {true, NewState:any()} if the user and password is valid or
  • {false, NewState:any()} if the user or password is invalid

A third usage is to block login attempts from a missbehaving peer. The State described above can be used for this. In addition to the responses above, the following return value is introduced:

  • disconnect if the connection should be closed immediately after sending a SSH_MSG_DISCONNECT message.
{pwdfun, fun(User::string(), Password::string()) -> boolean()}

Provides a function for password validation. This function is called with user and password as strings, and returns true if the password is valid and false otherwise.

This option ({pwdfun,fun/2}) is the same as a subset of the previous ({pwdfun,fun/4}). It is kept for compatibility.

{negotiation_timeout, integer()}

Maximum time in milliseconds for the authentication negotiation. Defaults to 120000 (2 minutes). If the client fails to log in within this time, the connection is closed.

{max_sessions, pos_integer()}

The maximum number of simultaneous sessions that are accepted at any time for this daemon. This includes sessions that are being authorized. Thus, if set to N, and N clients have connected but not started the login process, connection attempt N+1 is aborted. If N connections are authenticated and still logged in, no more logins are accepted until one of the existing ones log out.

The counter is per listening port. Thus, if two daemons are started, one with {max_sessions,N} and the other with {max_sessions,M}, in total N+M connections are accepted for the whole ssh application.

Notice that if parallel_login is false, only one client at a time can be in the authentication phase.

By default, this option is not set. This means that the number is not limited.

{max_channels, pos_integer()}

The maximum number of channels with active remote subsystem that are accepted for each connection to this daemon

By default, this option is not set. This means that the number is not limited.

{parallel_login, boolean()}

If set to false (the default value), only one login is handled at a time. If set to true, an unlimited number of login attempts are allowed simultaneously.

If the max_sessions option is set to N and parallel_login is set to true, the maximum number of simultaneous login attempts at any time is limited to N-K, where K is the number of authenticated connections present at this daemon.

Warning

Do not enable parallel_logins without protecting the server by other means, for example, by the max_sessions option or a firewall configuration. If set to true, there is no protection against DOS attacks.

{minimal_remote_max_packet_size, non_negative_integer()}

The least maximum packet size that the daemon will accept in channel open requests from the client. The default value is 0.

{id_string, random | string()}

The string the daemon will present to a connecting peer initially. The default value is "Erlang/VSN" where VSN is the ssh application version number.

The value random will cause a random string to be created at each connection attempt. This is to make it a bit more difficult for a malicious peer to find the ssh software brand and version.

{send_ext_info, boolean()}

Send a list of extensions to the client if the client has asked for it. See Draft-ietf-curdle-ssh-ext-info (work in progress) for details.

Currently implemented extension is sending server-sig-algs which is the list of the server's preferred user's public key algorithms.

Default value is true.

{key_cb, key_cb()}

Module implementing the behaviour ssh_server_key_api. Can be used to customize the handling of public keys. If callback options are provided along with the module name, they are made available to the callback module via the options passed to it under the key 'key_cb_private'.

{profile, atom()}

Used together with ip-address and port to uniquely identify a ssh daemon. This can be useful in a virtualized environment, where there can be more that one server that has the same ip-address and port. If this property is not explicitly set, it is assumed that the the ip-address and port uniquely identifies the SSH daemon.

{fd, file_descriptor()}

Allows an existing file-descriptor to be used (passed on to the transport protocol).

{failfun, fun(User::string(), PeerAddress::ip_address(), Reason::term()) -> _}

Provides a fun to implement your own logging when a user fails to authenticate.

{connectfun, fun(User::string(), PeerAddress::ip_address(), Method::string()) ->_}

Provides a fun to implement your own logging when a user authenticates to the server.

{disconnectfun, fun(Reason:term()) -> _}

Provides a fun to implement your own logging when a user disconnects from the server.

{unexpectedfun, fun(Message:term(), Peer) -> report | skip }

Provides a fun to implement your own logging or other action when an unexpected message arrives. If the fun returns report the usual info report is issued but if skip is returned no report is generated.

Peer is in the format of {Host,Port}.

{idle_time, integer()}

Sets a time-out on a connection when no channels are active. Defaults to infinity.

{ssh_msg_debug_fun, fun(ConnectionRef::ssh_connection_ref(), AlwaysDisplay::boolean(), Msg::binary(), LanguageTag::binary()) -> _}

Provide a fun to implement your own logging of the SSH message SSH_MSG_DEBUG. The last three parameters are from the message, see RFC4253, section 11.3. The ConnectionRef is the reference to the connection on which the message arrived. The return value from the fun is not checked.

The default behaviour is ignore the message. To get a printout for each message with AlwaysDisplay = true, use for example {ssh_msg_debug_fun, fun(_,true,M,_)-> io:format("DEBUG: ~p~n", [M]) end}

daemon_info(Daemon) -> {ok, [DaemonInfo]} | {error,Error}

Types

Returns a key-value list with information about the daemon. For now, only the listening port is returned. This is intended for the case the daemon is started with the port set to 0.

default_algorithms() -> algs_list()

Returns a key-value list, where the keys are the different types of algorithms and the values are the algorithms themselves. An example:

20> ssh:default_algorithms().
[{kex,['diffie-hellman-group1-sha1']},
 {public_key,['ssh-rsa','ssh-dss']},
 {cipher,[{client2server,['aes128-ctr','aes128-cbc','3des-cbc']},
          {server2client,['aes128-ctr','aes128-cbc','3des-cbc']}]},
 {mac,[{client2server,['hmac-sha2-256','hmac-sha1']},
       {server2client,['hmac-sha2-256','hmac-sha1']}]},
 {compression,[{client2server,[none,zlib]},
               {server2client,[none,zlib]}]}]
21> 

shell(Host) ->shell(Host, Option) ->shell(Host, Port, Option) ->shell(TcpSocket) -> _

Types

The socket is supposed to be from gen_tcp:connect or gen_tcp:accept with option {active,false}

Starts an interactive shell over an SSH server on the given Host. The function waits for user input, and does not return until the remote shell is ended (that is, exit from the shell).

start() ->start(Type) -> ok | {error, Reason}

Types

Utility function that starts the applications crypto, public_key, and ssh. Default type is temporary. For more information, see the application(3) manual page in Kernel.

stop() -> ok | {error, Reason}

Types

Stops the ssh application. For more information, see the application(3) manual page in Kernel.

stop_daemon(DaemonRef) ->stop_daemon(Address, Port) -> ok

Types

Stops the listener and all connections started by the listener.

stop_listener(DaemonRef) ->stop_listener(Address, Port) -> ok

Types

Stops the listener, but leaves existing connections started by the listener operational.

© 2010–2017 Ericsson AB
Licensed under the Apache License, Version 2.0.