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    
018    package org.apache.commons.net.bsd;
019    
020    import java.io.IOException;
021    import java.io.InputStream;
022    import java.net.BindException;
023    import java.net.InetAddress;
024    import java.net.ServerSocket;
025    import java.net.Socket;
026    import java.net.SocketException;
027    import java.net.UnknownHostException;
028    
029    import 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     * <p>
083     * <p>
084     * @author Daniel F. Savarese
085     * @see org.apache.commons.net.SocketClient
086     * @see RExecClient
087     * @see RLoginClient
088     ***/
089    
090    public class RCommandClient extends RExecClient
091    {
092        /***
093         * The default rshell port.  Set to 514 in BSD Unix.
094         ***/
095        public static final int DEFAULT_PORT = 514;
096    
097        /***
098         * The smallest port number an rcmd client may use.  By BSD convention
099         * this number is 512.
100         ***/
101        public static final int MIN_CLIENT_PORT = 512;
102    
103        /***
104         * The largest port number an rcmd client may use.  By BSD convention
105         * this number is 1023.
106         ***/
107        public static final int MAX_CLIENT_PORT = 1023;
108    
109        // Overrides method in RExecClient in order to implement proper
110        // port number limitations.
111        @Override
112        InputStream _createErrorStream() throws IOException
113        {
114            int localPort;
115            ServerSocket server;
116            Socket socket;
117    
118            localPort = MAX_CLIENT_PORT;
119            server = null; // Keep compiler from barfing
120    
121            for (localPort = MAX_CLIENT_PORT; localPort >= MIN_CLIENT_PORT; --localPort)
122            {
123                try
124                {
125                    server = _serverSocketFactory_.createServerSocket(localPort, 1,
126                             getLocalAddress());
127                    break; // got a socket
128                }
129                catch (SocketException e)
130                {
131                    continue;
132                }
133            }
134    
135            if (server == null) {
136                throw new BindException("All ports in use.");
137            }
138    
139            _output_.write(Integer.toString(server.getLocalPort()).getBytes());
140            _output_.write('\0');
141            _output_.flush();
142    
143            socket = server.accept();
144            server.close();
145    
146            if (isRemoteVerificationEnabled() && !verifyRemote(socket))
147            {
148                socket.close();
149                throw new IOException(
150                    "Security violation: unexpected connection attempt by " +
151                    socket.getInetAddress().getHostAddress());
152            }
153    
154            return (new SocketInputStream(socket, socket.getInputStream()));
155        }
156    
157        /***
158         * The default RCommandClient constructor.  Initializes the
159         * default port to <code> DEFAULT_PORT </code>.
160         ***/
161        public RCommandClient()
162        {
163            setDefaultPort(DEFAULT_PORT);
164        }
165    
166    
167        /***
168         * Opens a Socket connected to a remote host at the specified port and
169         * originating from the specified local address using a port in a range
170         * acceptable to the BSD rshell daemon.
171         * Before returning, {@link org.apache.commons.net.SocketClient#_connectAction_  _connectAction_() }
172         * is called to perform connection initialization actions.
173         * <p>
174         * @param host  The remote host.
175         * @param port  The port to connect to on the remote host.
176         * @param localAddr  The local address to use.
177         * @exception SocketException If the socket timeout could not be set.
178         * @exception BindException If all acceptable rshell ports are in use.
179         * @exception IOException If the socket could not be opened.  In most
180         *  cases you will only want to catch IOException since SocketException is
181         *  derived from it.
182         ***/
183        public void connect(InetAddress host, int port, InetAddress localAddr)
184        throws SocketException, BindException, IOException
185        {
186            int localPort;
187    
188            localPort = MAX_CLIENT_PORT;
189    
190            for (localPort = MAX_CLIENT_PORT; localPort >= MIN_CLIENT_PORT; --localPort)
191            {
192                try
193                {
194                    _socket_ =
195                        _socketFactory_.createSocket(host, port, localAddr, localPort);
196                }
197                catch (BindException be) {
198                    continue;
199                }
200                catch (SocketException e)
201                {
202                    continue;
203                }
204                break;
205            }
206    
207            if (localPort < MIN_CLIENT_PORT)
208                throw new BindException("All ports in use or insufficient permssion.");
209    
210            _connectAction_();
211        }
212    
213    
214    
215        /***
216         * Opens a Socket connected to a remote host at the specified port and
217         * originating from the current host at a port in a range acceptable
218         * to the BSD rshell daemon.
219         * Before returning, {@link org.apache.commons.net.SocketClient#_connectAction_  _connectAction_() }
220         * is called to perform connection initialization actions.
221         * <p>
222         * @param host  The remote host.
223         * @param port  The port to connect to on the remote host.
224         * @exception SocketException If the socket timeout could not be set.
225         * @exception BindException If all acceptable rshell ports are in use.
226         * @exception IOException If the socket could not be opened.  In most
227         *  cases you will only want to catch IOException since SocketException is
228         *  derived from it.
229         ***/
230        @Override
231        public void connect(InetAddress host, int port)
232        throws SocketException, IOException
233        {
234            connect(host, port, InetAddress.getLocalHost());
235        }
236    
237    
238        /***
239         * Opens a Socket connected to a remote host at the specified port and
240         * originating from the current host at a port in a range acceptable
241         * to the BSD rshell daemon.
242         * Before returning, {@link org.apache.commons.net.SocketClient#_connectAction_  _connectAction_() }
243         * is called to perform connection initialization actions.
244         * <p>
245         * @param hostname  The name of the remote host.
246         * @param port  The port to connect to on the remote host.
247         * @exception SocketException If the socket timeout could not be set.
248         * @exception BindException If all acceptable rshell ports are in use.
249         * @exception IOException If the socket could not be opened.  In most
250         *  cases you will only want to catch IOException since SocketException is
251         *  derived from it.
252         * @exception UnknownHostException If the hostname cannot be resolved.
253         ***/
254        @Override
255        public void connect(String hostname, int port)
256        throws SocketException, IOException, UnknownHostException
257        {
258            connect(InetAddress.getByName(hostname), port, InetAddress.getLocalHost());
259        }
260    
261    
262        /***
263         * Opens a Socket connected to a remote host at the specified port and
264         * originating from the specified local address using a port in a range
265         * acceptable to the BSD rshell daemon.
266         * Before returning, {@link org.apache.commons.net.SocketClient#_connectAction_  _connectAction_() }
267         * is called to perform connection initialization actions.
268         * <p>
269         * @param hostname  The remote host.
270         * @param port  The port to connect to on the remote host.
271         * @param localAddr  The local address to use.
272         * @exception SocketException If the socket timeout could not be set.
273         * @exception BindException If all acceptable rshell ports are in use.
274         * @exception IOException If the socket could not be opened.  In most
275         *  cases you will only want to catch IOException since SocketException is
276         *  derived from it.
277         ***/
278        public void connect(String hostname, int port, InetAddress localAddr)
279        throws SocketException, IOException
280        {
281            connect(InetAddress.getByName(hostname), port, localAddr);
282        }
283    
284    
285        /***
286         * Opens a Socket connected to a remote host at the specified port and
287         * originating from the specified local address and port. The
288         * local port must lie between <code> MIN_CLIENT_PORT </code> and
289         * <code> MAX_CLIENT_PORT </code> or an IllegalArgumentException will
290         * be thrown.
291         * Before returning, {@link org.apache.commons.net.SocketClient#_connectAction_  _connectAction_() }
292         * is called to perform connection initialization actions.
293         * <p>
294         * @param host  The remote host.
295         * @param port  The port to connect to on the remote host.
296         * @param localAddr  The local address to use.
297         * @param localPort  The local port to use.
298         * @exception SocketException If the socket timeout could not be set.
299         * @exception IOException If the socket could not be opened.  In most
300         *  cases you will only want to catch IOException since SocketException is
301         *  derived from it.
302         * @exception IllegalArgumentException If an invalid local port number
303         *            is specified.
304         ***/
305        @Override
306        public void connect(InetAddress host, int port,
307                            InetAddress localAddr, int localPort)
308        throws SocketException, IOException, IllegalArgumentException
309        {
310            if (localPort < MIN_CLIENT_PORT || localPort > MAX_CLIENT_PORT)
311                throw new IllegalArgumentException("Invalid port number " + localPort);
312            super.connect(host, port, localAddr, localPort);
313        }
314    
315    
316        /***
317         * Opens a Socket connected to a remote host at the specified port and
318         * originating from the specified local address and port. The
319         * local port must lie between <code> MIN_CLIENT_PORT </code> and
320         * <code> MAX_CLIENT_PORT </code> or an IllegalArgumentException will
321         * be thrown.
322         * Before returning, {@link org.apache.commons.net.SocketClient#_connectAction_  _connectAction_() }
323         * is called to perform connection initialization actions.
324         * <p>
325         * @param hostname  The name of the remote host.
326         * @param port  The port to connect to on the remote host.
327         * @param localAddr  The local address to use.
328         * @param localPort  The local port to use.
329         * @exception SocketException If the socket timeout could not be set.
330         * @exception IOException If the socket could not be opened.  In most
331         *  cases you will only want to catch IOException since SocketException is
332         *  derived from it.
333         * @exception UnknownHostException If the hostname cannot be resolved.
334         * @exception IllegalArgumentException If an invalid local port number
335         *            is specified.
336         ***/
337        @Override
338        public void connect(String hostname, int port,
339                            InetAddress localAddr, int localPort)
340        throws SocketException, IOException, IllegalArgumentException, UnknownHostException
341        {
342            if (localPort < MIN_CLIENT_PORT || localPort > MAX_CLIENT_PORT)
343                throw new IllegalArgumentException("Invalid port number " + localPort);
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         * @exception 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         ***/
396        public void rcommand(String localUsername, String remoteUsername,
397                             String command)
398        throws IOException
399        {
400            rcommand(localUsername, remoteUsername, command, false);
401        }
402    
403    }
404