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     * @see org.apache.commons.net.SocketClient
085     * @see RExecClient
086     * @see RLoginClient
087     ***/
088    
089    public class RCommandClient extends RExecClient
090    {
091        /***
092         * The default rshell port.  Set to 514 in BSD Unix.
093         ***/
094        public static final int DEFAULT_PORT = 514;
095    
096        /***
097         * The smallest port number an rcmd client may use.  By BSD convention
098         * this number is 512.
099         ***/
100        public static final int MIN_CLIENT_PORT = 512;
101    
102        /***
103         * The largest port number an rcmd client may use.  By BSD convention
104         * this number is 1023.
105         ***/
106        public static final int MAX_CLIENT_PORT = 1023;
107    
108        // Overrides method in RExecClient in order to implement proper
109        // port number limitations.
110        @Override
111        InputStream _createErrorStream() throws IOException
112        {
113            int localPort;
114            ServerSocket server;
115            Socket socket;
116    
117            localPort = MAX_CLIENT_PORT;
118            server = null; // Keep compiler from barfing
119    
120            for (localPort = MAX_CLIENT_PORT; localPort >= MIN_CLIENT_PORT; --localPort)
121            {
122                try
123                {
124                    server = _serverSocketFactory_.createServerSocket(localPort, 1,
125                             getLocalAddress());
126                    break; // got a socket
127                }
128                catch (SocketException e)
129                {
130                    continue;
131                }
132            }
133    
134            if (server == null) {
135                throw new BindException("All ports in use.");
136            }
137    
138            _output_.write(Integer.toString(server.getLocalPort()).getBytes());
139            _output_.write('\0');
140            _output_.flush();
141    
142            socket = server.accept();
143            server.close();
144    
145            if (isRemoteVerificationEnabled() && !verifyRemote(socket))
146            {
147                socket.close();
148                throw new IOException(
149                    "Security violation: unexpected connection attempt by " +
150                    socket.getInetAddress().getHostAddress());
151            }
152    
153            return (new SocketInputStream(socket, socket.getInputStream()));
154        }
155    
156        /***
157         * The default RCommandClient constructor.  Initializes the
158         * default port to <code> DEFAULT_PORT </code>.
159         ***/
160        public RCommandClient()
161        {
162            setDefaultPort(DEFAULT_PORT);
163        }
164    
165    
166        /***
167         * Opens a Socket connected to a remote host at the specified port and
168         * originating from the specified local address using a port in a range
169         * acceptable to the BSD rshell daemon.
170         * Before returning, {@link org.apache.commons.net.SocketClient#_connectAction_  _connectAction_() }
171         * is called to perform connection initialization actions.
172         * <p>
173         * @param host  The remote host.
174         * @param port  The port to connect to on the remote host.
175         * @param localAddr  The local address to use.
176         * @exception SocketException If the socket timeout could not be set.
177         * @exception BindException If all acceptable rshell ports are in use.
178         * @exception IOException If the socket could not be opened.  In most
179         *  cases you will only want to catch IOException since SocketException is
180         *  derived from it.
181         ***/
182        public void connect(InetAddress host, int port, InetAddress localAddr)
183        throws SocketException, BindException, IOException
184        {
185            int localPort;
186    
187            localPort = MAX_CLIENT_PORT;
188    
189            for (localPort = MAX_CLIENT_PORT; localPort >= MIN_CLIENT_PORT; --localPort)
190            {
191                try
192                {
193                    _socket_ =
194                        _socketFactory_.createSocket(host, port, localAddr, localPort);
195                }
196                catch (BindException be) {
197                    continue;
198                }
199                catch (SocketException e)
200                {
201                    continue;
202                }
203                break;
204            }
205    
206            if (localPort < MIN_CLIENT_PORT)
207                throw new BindException("All ports in use or insufficient permssion.");
208    
209            _connectAction_();
210        }
211    
212    
213    
214        /***
215         * Opens a Socket connected to a remote host at the specified port and
216         * originating from the current host at a port in a range acceptable
217         * to the BSD rshell daemon.
218         * Before returning, {@link org.apache.commons.net.SocketClient#_connectAction_  _connectAction_() }
219         * is called to perform connection initialization actions.
220         * <p>
221         * @param host  The remote host.
222         * @param port  The port to connect to on the remote host.
223         * @exception SocketException If the socket timeout could not be set.
224         * @exception BindException If all acceptable rshell ports are in use.
225         * @exception IOException If the socket could not be opened.  In most
226         *  cases you will only want to catch IOException since SocketException is
227         *  derived from it.
228         ***/
229        @Override
230        public void connect(InetAddress host, int port)
231        throws SocketException, IOException
232        {
233            connect(host, port, InetAddress.getLocalHost());
234        }
235    
236    
237        /***
238         * Opens a Socket connected to a remote host at the specified port and
239         * originating from the current host at a port in a range acceptable
240         * to the BSD rshell daemon.
241         * Before returning, {@link org.apache.commons.net.SocketClient#_connectAction_  _connectAction_() }
242         * is called to perform connection initialization actions.
243         * <p>
244         * @param hostname  The name of the remote host.
245         * @param port  The port to connect to on the remote host.
246         * @exception SocketException If the socket timeout could not be set.
247         * @exception BindException If all acceptable rshell ports are in use.
248         * @exception IOException If the socket could not be opened.  In most
249         *  cases you will only want to catch IOException since SocketException is
250         *  derived from it.
251         * @exception UnknownHostException If the hostname cannot be resolved.
252         ***/
253        @Override
254        public void connect(String hostname, int port)
255        throws SocketException, IOException, UnknownHostException
256        {
257            connect(InetAddress.getByName(hostname), port, InetAddress.getLocalHost());
258        }
259    
260    
261        /***
262         * Opens a Socket connected to a remote host at the specified port and
263         * originating from the specified local address using a port in a range
264         * acceptable to the BSD rshell daemon.
265         * Before returning, {@link org.apache.commons.net.SocketClient#_connectAction_  _connectAction_() }
266         * is called to perform connection initialization actions.
267         * <p>
268         * @param hostname  The remote host.
269         * @param port  The port to connect to on the remote host.
270         * @param localAddr  The local address to use.
271         * @exception SocketException If the socket timeout could not be set.
272         * @exception BindException If all acceptable rshell ports are in use.
273         * @exception IOException If the socket could not be opened.  In most
274         *  cases you will only want to catch IOException since SocketException is
275         *  derived from it.
276         ***/
277        public void connect(String hostname, int port, InetAddress localAddr)
278        throws SocketException, IOException
279        {
280            connect(InetAddress.getByName(hostname), port, localAddr);
281        }
282    
283    
284        /***
285         * Opens a Socket connected to a remote host at the specified port and
286         * originating from the specified local address and port. The
287         * local port must lie between <code> MIN_CLIENT_PORT </code> and
288         * <code> MAX_CLIENT_PORT </code> or an IllegalArgumentException will
289         * be thrown.
290         * Before returning, {@link org.apache.commons.net.SocketClient#_connectAction_  _connectAction_() }
291         * is called to perform connection initialization actions.
292         * <p>
293         * @param host  The remote host.
294         * @param port  The port to connect to on the remote host.
295         * @param localAddr  The local address to use.
296         * @param localPort  The local port to use.
297         * @exception SocketException If the socket timeout could not be set.
298         * @exception IOException If the socket could not be opened.  In most
299         *  cases you will only want to catch IOException since SocketException is
300         *  derived from it.
301         * @exception IllegalArgumentException If an invalid local port number
302         *            is specified.
303         ***/
304        @Override
305        public void connect(InetAddress host, int port,
306                            InetAddress localAddr, int localPort)
307        throws SocketException, IOException, IllegalArgumentException
308        {
309            if (localPort < MIN_CLIENT_PORT || localPort > MAX_CLIENT_PORT)
310                throw new IllegalArgumentException("Invalid port number " + localPort);
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         * <p>
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         * @exception SocketException If the socket timeout could not be set.
329         * @exception 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         * @exception UnknownHostException If the hostname cannot be resolved.
333         * @exception 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            super.connect(hostname, port, localAddr, localPort);
344        }
345    
346    
347        /***
348         * Remotely executes a command through the rshd daemon on the server
349         * to which the RCommandClient is connected.  After calling this method,
350         * you may interact with the remote process through its standard input,
351         * output, and error streams.  You will typically be able to detect
352         * the termination of the remote process after reaching end of file
353         * on its standard output (accessible through
354         * {@link #getInputStream  getInputStream() }.  Disconnecting
355         * from the server or closing the process streams before reaching
356         * end of file will not necessarily terminate the remote process.
357         * <p>
358         * If a separate error stream is requested, the remote server will
359         * connect to a local socket opened by RCommandClient, providing an
360         * independent stream through which standard error will be transmitted.
361         * The local socket must originate from a secure port (512 - 1023),
362         * and rcommand() ensures that this will be so.
363         * RCommandClient will also do a simple security check when it accepts a
364         * connection for this error stream.  If the connection does not originate
365         * from the remote server, an IOException will be thrown.  This serves as
366         * a simple protection against possible hijacking of the error stream by
367         * an attacker monitoring the rexec() negotiation.  You may disable this
368         * behavior with
369         * {@link org.apache.commons.net.bsd.RExecClient#setRemoteVerificationEnabled setRemoteVerificationEnabled()}
370         * .
371         * <p>
372         * @param localUsername  The user account on the local machine that is
373         *        requesting the command execution.
374         * @param remoteUsername  The account name on the server through which to
375         *        execute the command.
376         * @param command   The command, including any arguments, to execute.
377         * @param separateErrorStream True if you would like the standard error
378         *        to be transmitted through a different stream than standard output.
379         *        False if not.
380         * @exception IOException If the rcommand() attempt fails.  The exception
381         *            will contain a message indicating the nature of the failure.
382         ***/
383        public void rcommand(String localUsername, String remoteUsername,
384                             String command, boolean separateErrorStream)
385        throws IOException
386        {
387            rexec(localUsername, remoteUsername, command, separateErrorStream);
388        }
389    
390    
391        /***
392         * Same as
393         * <code> rcommand(localUsername, remoteUsername, command, false); </code>
394         ***/
395        public void rcommand(String localUsername, String remoteUsername,
396                             String command)
397        throws IOException
398        {
399            rcommand(localUsername, remoteUsername, command, false);
400        }
401    
402    }
403