View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *      http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  
18  package org.apache.commons.net.bsd;
19  
20  import java.io.IOException;
21  import java.io.InputStream;
22  import java.net.BindException;
23  import java.net.InetAddress;
24  import java.net.ServerSocket;
25  import java.net.Socket;
26  import java.net.SocketException;
27  import java.net.UnknownHostException;
28  
29  import org.apache.commons.net.io.SocketInputStream;
30  
31  /***
32   * RCommandClient is very similar to
33   * {@link org.apache.commons.net.bsd.RExecClient},
34   * from which it is derived, and implements the rcmd() facility that
35   * first appeared in 4.2BSD Unix.  rcmd() is the facility used by the rsh
36   * (rshell) and other commands to execute a command on another machine
37   * from a trusted host without issuing a password.  The trust relationship
38   * between two machines is established by the contents of a machine's
39   * /etc/hosts.equiv file and a user's .rhosts file.  These files specify
40   * from which hosts and accounts on those hosts rcmd() requests will be
41   * accepted.  The only additional measure for establishing trust is that
42   * all client connections must originate from a port between 512 and 1023.
43   * Consequently, there is an upper limit to the number of rcmd connections
44   * that can be running simultaneously.   The required ports are reserved
45   * ports on Unix systems, and can only be bound by a
46   * process running with root permissions (to accomplish this rsh, rlogin,
47   * and related commands usualy have the suid bit set).  Therefore, on a
48   * Unix system, you will only be able to successfully use the RCommandClient
49   * class if the process runs as root.  However, there is no such restriction
50   * on Windows95 and some other systems.  The security risks are obvious.
51   * However, when carefully used, rcmd() can be very useful when used behind
52   * a firewall.
53   * <p>
54   * As with virtually all of the client classes in org.apache.commons.net, this
55   * class derives from SocketClient.  But it overrides most of its connection
56   * methods so that the local Socket will originate from an acceptable
57   * rshell port.  The way to use RCommandClient is to first connect
58   * to the server, call the {@link #rcommand  rcommand() } method,
59   * and then
60   * fetch the connection's input, output, and optionally error streams.
61   * Interaction with the remote command is controlled entirely through the
62   * I/O streams.  Once you have finished processing the streams, you should
63   * invoke {@link org.apache.commons.net.bsd.RExecClient#disconnect disconnect() }
64   *  to clean up properly.
65   * <p>
66   * By default the standard output and standard error streams of the
67   * remote process are transmitted over the same connection, readable
68   * from the input stream returned by
69   * {@link org.apache.commons.net.bsd.RExecClient#getInputStream getInputStream() }
70   * .  However, it is
71   * possible to tell the rshd daemon to return the standard error
72   * stream over a separate connection, readable from the input stream
73   * returned by {@link org.apache.commons.net.bsd.RExecClient#getErrorStream getErrorStream() }
74   * .  You
75   * can specify that a separate connection should be created for standard
76   * error by setting the boolean <code> separateErrorStream </code>
77   * parameter of {@link #rcommand  rcommand() } to <code> true </code>.
78   * The standard input of the remote process can be written to through
79   * the output stream returned by
80   * {@link org.apache.commons.net.bsd.RExecClient#getOutputStream getOutputStream() }
81   * .
82   * @see org.apache.commons.net.SocketClient
83   * @see RExecClient
84   * @see RLoginClient
85   ***/
86  
87  public class RCommandClient extends RExecClient
88  {
89      /***
90       * The default rshell port.  Set to 514 in BSD Unix.
91       ***/
92      public static final int DEFAULT_PORT = 514;
93  
94      /***
95       * The smallest port number an rcmd client may use.  By BSD convention
96       * this number is 512.
97       ***/
98      public static final int MIN_CLIENT_PORT = 512;
99  
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      * @exception SocketException If the socket timeout could not be set.
175      * @exception BindException If all acceptable rshell ports are in use.
176      * @exception 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      * @exception SocketException If the socket timeout could not be set.
223      * @exception BindException If all acceptable rshell ports are in use.
224      * @exception 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      * @exception SocketException If the socket timeout could not be set.
246      * @exception BindException If all acceptable rshell ports are in use.
247      * @exception 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      * @exception 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      * @exception SocketException If the socket timeout could not be set.
271      * @exception BindException If all acceptable rshell ports are in use.
272      * @exception 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      * @exception SocketException If the socket timeout could not be set.
297      * @exception 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      * @exception 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      * @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         }
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      * @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