    001/*
    002 * Licensed to the Apache Software Foundation (ASF) under one or more
    003 * contributor license agreements.  See the NOTICE file distributed with
    004 * this work for additional information regarding copyright ownership.
    005 * The ASF licenses this file to You under the Apache License, Version 2.0
    006 * (the "License"); you may not use this file except in compliance with
    007 * the License.  You may obtain a copy of the License at
    008 *
    009 *      http://www.apache.org/licenses/LICENSE-2.0
    010 *
    011 * Unless required by applicable law or agreed to in writing, software
    012 * distributed under the License is distributed on an "AS IS" BASIS,
    013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    014 * See the License for the specific language governing permissions and
    015 * limitations under the License.
    016 */
    017
    018package org.apache.commons.net.bsd;
    019
    020import java.io.IOException;
    021import java.io.InputStream;
    022import java.net.BindException;
    023import java.net.InetAddress;
    024import java.net.ServerSocket;
    025import java.net.Socket;
    026import java.net.SocketException;
    027import java.net.UnknownHostException;
    028
    029import org.apache.commons.net.io.SocketInputStream;
    030
    031/***
    032 * RCommandClient is very similar to
    033 * {@link org.apache.commons.net.bsd.RExecClient},
    034 * from which it is derived, and implements the rcmd() facility that
    035 * first appeared in 4.2BSD Unix.  rcmd() is the facility used by the rsh
    036 * (rshell) and other commands to execute a command on another machine
    037 * from a trusted host without issuing a password.  The trust relationship
    038 * between two machines is established by the contents of a machine's
    039 * /etc/hosts.equiv file and a user's .rhosts file.  These files specify
    040 * from which hosts and accounts on those hosts rcmd() requests will be
    041 * accepted.  The only additional measure for establishing trust is that
    042 * all client connections must originate from a port between 512 and 1023.
    043 * Consequently, there is an upper limit to the number of rcmd connections
    044 * that can be running simultaneously.   The required ports are reserved
    045 * ports on Unix systems, and can only be bound by a
    046 * process running with root permissions (to accomplish this rsh, rlogin,
    047 * and related commands usualy have the suid bit set).  Therefore, on a
    048 * Unix system, you will only be able to successfully use the RCommandClient
    049 * class if the process runs as root.  However, there is no such restriction
    050 * on Windows95 and some other systems.  The security risks are obvious.
    051 * However, when carefully used, rcmd() can be very useful when used behind
    052 * a firewall.
    053 * <p>
    054 * As with virtually all of the client classes in org.apache.commons.net, this
    055 * class derives from SocketClient.  But it overrides most of its connection
    056 * methods so that the local Socket will originate from an acceptable
    057 * rshell port.  The way to use RCommandClient is to first connect
    058 * to the server, call the {@link #rcommand  rcommand() } method,
    059 * and then
    060 * fetch the connection's input, output, and optionally error streams.
    061 * Interaction with the remote command is controlled entirely through the
    062 * I/O streams.  Once you have finished processing the streams, you should
    063 * invoke {@link org.apache.commons.net.bsd.RExecClient#disconnect disconnect() }
    064 *  to clean up properly.
    065 * <p>
    066 * By default the standard output and standard error streams of the
    067 * remote process are transmitted over the same connection, readable
    068 * from the input stream returned by
    069 * {@link org.apache.commons.net.bsd.RExecClient#getInputStream getInputStream() }
    070 * .  However, it is
    071 * possible to tell the rshd daemon to return the standard error
    072 * stream over a separate connection, readable from the input stream
    073 * returned by {@link org.apache.commons.net.bsd.RExecClient#getErrorStream getErrorStream() }
    074 * .  You
    075 * can specify that a separate connection should be created for standard
    076 * error by setting the boolean <code> separateErrorStream </code>
    077 * parameter of {@link #rcommand  rcommand() } to <code> true </code>.
    078 * The standard input of the remote process can be written to through
    079 * the output stream returned by
    080 * {@link org.apache.commons.net.bsd.RExecClient#getOutputStream getOutputStream() }
    081 * .
    082 * @see org.apache.commons.net.SocketClient
    083 * @see RExecClient
    084 * @see RLoginClient
    085 ***/
    086
    087public class RCommandClient extends RExecClient
    088{
    089    /***
    090     * The default rshell port.  Set to 514 in BSD Unix.
    091     ***/
    092    public static final int DEFAULT_PORT = 514;
    093
    094    /***
    095     * The smallest port number an rcmd client may use.  By BSD convention
    096     * this number is 512.
    097     ***/
    098    public static final int MIN_CLIENT_PORT = 512;
    099
    100    /***
    101     * The largest port number an rcmd client may use.  By BSD convention
    102     * this number is 1023.
    103     ***/
    104    public static final int MAX_CLIENT_PORT = 1023;
    105
    106    // Overrides method in RExecClient in order to implement proper
    107    // port number limitations.
    108    @Override
    109    InputStream _createErrorStream() throws IOException
    110    {
    111        int localPort;
    112        ServerSocket server;
    113        Socket socket;
    114
    115        localPort = MAX_CLIENT_PORT;
    116        server = null; // Keep compiler from barfing
    117
    118        for (localPort = MAX_CLIENT_PORT; localPort >= MIN_CLIENT_PORT; --localPort)
    119        {
    120            try
    121            {
    122                server = _serverSocketFactory_.createServerSocket(localPort, 1,
    123                         getLocalAddress());
    124                break; // got a socket
    125            }
    126            catch (SocketException e)
    127            {
    128                continue;
    129            }
    130        }
    131
    132        if (server == null) {
    133            throw new BindException("All ports in use.");
    134        }
    135
    136        _output_.write(Integer.toString(server.getLocalPort()).getBytes("UTF-8")); // $NON-NLS
    137        _output_.write(NULL_CHAR);
    138        _output_.flush();
    139
    140        socket = server.accept();
    141        server.close();
    142
    143        if (isRemoteVerificationEnabled() && !verifyRemote(socket))
    144        {
    145            socket.close();
    146            throw new IOException(
    147                "Security violation: unexpected connection attempt by " +
    148                socket.getInetAddress().getHostAddress());
    149        }
    150
    151        return (new SocketInputStream(socket, socket.getInputStream()));
    152    }
    153
    154    /***
    155     * The default RCommandClient constructor.  Initializes the
    156     * default port to <code> DEFAULT_PORT </code>.
    157     ***/
    158    public RCommandClient()
    159    {
    160        setDefaultPort(DEFAULT_PORT);
    161    }
    162
    163
    164    /***
    165     * Opens a Socket connected to a remote host at the specified port and
    166     * originating from the specified local address using a port in a range
    167     * acceptable to the BSD rshell daemon.
    168     * Before returning, {@link org.apache.commons.net.SocketClient#_connectAction_  _connectAction_() }
    169     * is called to perform connection initialization actions.
    170     *
    171     * @param host  The remote host.
    172     * @param port  The port to connect to on the remote host.
    173     * @param localAddr  The local address to use.
    174     * @throws SocketException If the socket timeout could not be set.
    175     * @throws BindException If all acceptable rshell ports are in use.
    176     * @throws IOException If the socket could not be opened.  In most
    177     *  cases you will only want to catch IOException since SocketException is
    178     *  derived from it.
    179     ***/
    180    public void connect(InetAddress host, int port, InetAddress localAddr)
    181    throws SocketException, BindException, IOException
    182    {
    183        int localPort;
    184
    185        localPort = MAX_CLIENT_PORT;
    186
    187        for (localPort = MAX_CLIENT_PORT; localPort >= MIN_CLIENT_PORT; --localPort)
    188        {
    189            try
    190            {
    191                _socket_ =
    192                    _socketFactory_.createSocket(host, port, localAddr, localPort);
    193            }
    194            catch (BindException be) {
    195                continue;
    196            }
    197            catch (SocketException e)
    198            {
    199                continue;
    200            }
    201            break;
    202        }
    203
    204        if (localPort < MIN_CLIENT_PORT) {
    205            throw new BindException("All ports in use or insufficient permssion.");
    206        }
    207
    208        _connectAction_();
    209    }
    210
    211
    212
    213    /***
    214     * Opens a Socket connected to a remote host at the specified port and
    215     * originating from the current host at a port in a range acceptable
    216     * to the BSD rshell daemon.
    217     * Before returning, {@link org.apache.commons.net.SocketClient#_connectAction_  _connectAction_() }
    218     * is called to perform connection initialization actions.
    219     *
    220     * @param host  The remote host.
    221     * @param port  The port to connect to on the remote host.
    222     * @throws SocketException If the socket timeout could not be set.
    223     * @throws BindException If all acceptable rshell ports are in use.
    224     * @throws IOException If the socket could not be opened.  In most
    225     *  cases you will only want to catch IOException since SocketException is
    226     *  derived from it.
    227     ***/
    228    @Override
    229    public void connect(InetAddress host, int port)
    230    throws SocketException, IOException
    231    {
    232        connect(host, port, InetAddress.getLocalHost());
    233    }
    234
    235
    236    /***
    237     * Opens a Socket connected to a remote host at the specified port and
    238     * originating from the current host at a port in a range acceptable
    239     * to the BSD rshell daemon.
    240     * Before returning, {@link org.apache.commons.net.SocketClient#_connectAction_  _connectAction_() }
    241     * is called to perform connection initialization actions.
    242     *
    243     * @param hostname  The name of the remote host.
    244     * @param port  The port to connect to on the remote host.
    245     * @throws SocketException If the socket timeout could not be set.
    246     * @throws BindException If all acceptable rshell ports are in use.
    247     * @throws IOException If the socket could not be opened.  In most
    248     *  cases you will only want to catch IOException since SocketException is
    249     *  derived from it.
    250     * @throws UnknownHostException If the hostname cannot be resolved.
    251     ***/
    252    @Override
    253    public void connect(String hostname, int port)
    254    throws SocketException, IOException, UnknownHostException
    255    {
    256        connect(InetAddress.getByName(hostname), port, InetAddress.getLocalHost());
    257    }
    258
    259
    260    /***
    261     * Opens a Socket connected to a remote host at the specified port and
    262     * originating from the specified local address using a port in a range
    263     * acceptable to the BSD rshell daemon.
    264     * Before returning, {@link org.apache.commons.net.SocketClient#_connectAction_  _connectAction_() }
    265     * is called to perform connection initialization actions.
    266     *
    267     * @param hostname  The remote host.
    268     * @param port  The port to connect to on the remote host.
    269     * @param localAddr  The local address to use.
    270     * @throws SocketException If the socket timeout could not be set.
    271     * @throws BindException If all acceptable rshell ports are in use.
    272     * @throws IOException If the socket could not be opened.  In most
    273     *  cases you will only want to catch IOException since SocketException is
    274     *  derived from it.
    275     ***/
    276    public void connect(String hostname, int port, InetAddress localAddr)
    277    throws SocketException, IOException
    278    {
    279        connect(InetAddress.getByName(hostname), port, localAddr);
    280    }
    281
    282
    283    /***
    284     * Opens a Socket connected to a remote host at the specified port and
    285     * originating from the specified local address and port. The
    286     * local port must lie between <code> MIN_CLIENT_PORT </code> and
    287     * <code> MAX_CLIENT_PORT </code> or an IllegalArgumentException will
    288     * be thrown.
    289     * Before returning, {@link org.apache.commons.net.SocketClient#_connectAction_  _connectAction_() }
    290     * is called to perform connection initialization actions.
    291     *
    292     * @param host  The remote host.
    293     * @param port  The port to connect to on the remote host.
    294     * @param localAddr  The local address to use.
    295     * @param localPort  The local port to use.
    296     * @throws SocketException If the socket timeout could not be set.
    297     * @throws IOException If the socket could not be opened.  In most
    298     *  cases you will only want to catch IOException since SocketException is
    299     *  derived from it.
    300     * @throws IllegalArgumentException If an invalid local port number
    301     *            is specified.
    302     ***/
    303    @Override
    304    public void connect(InetAddress host, int port,
    305                        InetAddress localAddr, int localPort)
    306    throws SocketException, IOException, IllegalArgumentException
    307    {
    308        if (localPort < MIN_CLIENT_PORT || localPort > MAX_CLIENT_PORT) {
    309            throw new IllegalArgumentException("Invalid port number " + localPort);
    310        }
    311        super.connect(host, port, localAddr, localPort);
    312    }
    313
    314
    315    /***
    316     * Opens a Socket connected to a remote host at the specified port and
    317     * originating from the specified local address and port. The
    318     * local port must lie between <code> MIN_CLIENT_PORT </code> and
    319     * <code> MAX_CLIENT_PORT </code> or an IllegalArgumentException will
    320     * be thrown.
    321     * Before returning, {@link org.apache.commons.net.SocketClient#_connectAction_  _connectAction_() }
    322     * is called to perform connection initialization actions.
    323     *
    324     * @param hostname  The name of the remote host.
    325     * @param port  The port to connect to on the remote host.
    326     * @param localAddr  The local address to use.
    327     * @param localPort  The local port to use.
    328     * @throws SocketException If the socket timeout could not be set.
    329     * @throws IOException If the socket could not be opened.  In most
    330     *  cases you will only want to catch IOException since SocketException is
    331     *  derived from it.
    332     * @throws UnknownHostException If the hostname cannot be resolved.
    333     * @throws IllegalArgumentException If an invalid local port number
    334     *            is specified.
    335     ***/
    336    @Override
    337    public void connect(String hostname, int port,
    338                        InetAddress localAddr, int localPort)
    339    throws SocketException, IOException, IllegalArgumentException, UnknownHostException
    340    {
    341        if (localPort < MIN_CLIENT_PORT || localPort > MAX_CLIENT_PORT) {
    342            throw new IllegalArgumentException("Invalid port number " + localPort);
    343        }
    344        super.connect(hostname, port, localAddr, localPort);
    345    }
    346
    347
    348    /***
    349     * Remotely executes a command through the rshd daemon on the server
    350     * to which the RCommandClient is connected.  After calling this method,
    351     * you may interact with the remote process through its standard input,
    352     * output, and error streams.  You will typically be able to detect
    353     * the termination of the remote process after reaching end of file
    354     * on its standard output (accessible through
    355     * {@link #getInputStream  getInputStream() }.  Disconnecting
    356     * from the server or closing the process streams before reaching
    357     * end of file will not necessarily terminate the remote process.
    358     * <p>
    359     * If a separate error stream is requested, the remote server will
    360     * connect to a local socket opened by RCommandClient, providing an
    361     * independent stream through which standard error will be transmitted.
    362     * The local socket must originate from a secure port (512 - 1023),
    363     * and rcommand() ensures that this will be so.
    364     * RCommandClient will also do a simple security check when it accepts a
    365     * connection for this error stream.  If the connection does not originate
    366     * from the remote server, an IOException will be thrown.  This serves as
    367     * a simple protection against possible hijacking of the error stream by
    368     * an attacker monitoring the rexec() negotiation.  You may disable this
    369     * behavior with
    370     * {@link org.apache.commons.net.bsd.RExecClient#setRemoteVerificationEnabled setRemoteVerificationEnabled()}
    371     * .
    372     * <p>
    373     * @param localUsername  The user account on the local machine that is
    374     *        requesting the command execution.
    375     * @param remoteUsername  The account name on the server through which to
    376     *        execute the command.
    377     * @param command   The command, including any arguments, to execute.
    378     * @param separateErrorStream True if you would like the standard error
    379     *        to be transmitted through a different stream than standard output.
    380     *        False if not.
    381     * @throws IOException If the rcommand() attempt fails.  The exception
    382     *            will contain a message indicating the nature of the failure.
    383     ***/
    384    public void rcommand(String localUsername, String remoteUsername,
    385                         String command, boolean separateErrorStream)
    386    throws IOException
    387    {
    388        rexec(localUsername, remoteUsername, command, separateErrorStream);
    389    }
    390
    391
    392    /***
    393     * Same as
    394     * <code> rcommand(localUsername, remoteUsername, command, false); </code>
    395     * @param localUsername the local user
    396     * @param remoteUsername the remote user
    397     * @param command the command
    398     * @throws IOException on error
    399     ***/
    400    public void rcommand(String localUsername, String remoteUsername,
    401                         String command)
    402    throws IOException
    403    {
    404        rcommand(localUsername, remoteUsername, command, false);
    405    }
    406
    407}
    408