View Javadoc
1   /*
2    *  Licensed to the Apache Software Foundation (ASF) under one
3    *  or more contributor license agreements.  See the NOTICE file
4    *  distributed with this work for additional information
5    *  regarding copyright ownership.  The ASF licenses this file
6    *  to you under the Apache License, Version 2.0 (the
7    *  "License"); you may not use this file except in compliance
8    *  with the License.  You may obtain a copy of the License at
9    *
10   *    http://www.apache.org/licenses/LICENSE-2.0
11   *
12   *  Unless required by applicable law or agreed to in writing,
13   *  software distributed under the License is distributed on an
14   *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   *  KIND, either express or implied.  See the License for the
16   *  specific language governing permissions and limitations
17   *  under the License.
18   *
19   */
20  package org.apache.mina.proxy.handlers.socks;
21  
22  import java.util.Arrays;
23  
24  import org.apache.mina.core.buffer.IoBuffer;
25  import org.apache.mina.core.filterchain.IoFilter.NextFilter;
26  import org.apache.mina.proxy.session.ProxyIoSession;
27  import org.apache.mina.proxy.utils.ByteUtilities;
28  import org.slf4j.Logger;
29  import org.slf4j.LoggerFactory;
30  
31  /**
32   * Socks4LogicHandler.java - SOCKS4/SOCKS4a authentication mechanisms logic handler.
33   * 
34   * @author <a href="http://mina.apache.org">Apache MINA Project</a>
35   * @since MINA 2.0.0-M3
36   */
37  public class Socks4LogicHandler extends AbstractSocksLogicHandler {
38  
39      private static final Logger logger = LoggerFactory.getLogger(Socks4LogicHandler.class);
40  
41      /**
42       * @see AbstractSocksLogicHandler#AbstractSocksLogicHandler(ProxyIoSession)
43       * 
44       * @param proxyIoSession The original session
45       */
46      public Socks4LogicHandler(final ProxyIoSession proxyIoSession) {
47          super(proxyIoSession);
48      }
49  
50      /**
51       * Perform the handshake.
52       * 
53       * @param nextFilter the next filter
54       */
55      @Override
56      public void doHandshake(final NextFilter nextFilter) {
57          logger.debug(" doHandshake()");
58  
59          // Send request
60          writeRequest(nextFilter, request);
61      }
62  
63      /**
64       * Encode a SOCKS4/SOCKS4a request and writes it to the next filter
65       * so it can be sent to the proxy server.
66       * 
67       * @param nextFilter the next filter
68       * @param request the request to send.
69       */
70      protected void writeRequest(final NextFilter nextFilter, final SocksProxyRequest request) {
71          try {
72              boolean isV4ARequest = Arrays.equals(request.getIpAddress(), SocksProxyConstants.FAKE_IP);
73              byte[] userID = request.getUserName().getBytes("ASCII");
74              byte[] host = isV4ARequest ? request.getHost().getBytes("ASCII") : null;
75  
76              int len = 9 + userID.length;
77  
78              if (isV4ARequest) {
79                  len += host.length + 1;
80              }
81  
82              IoBuffer buf = IoBuffer.allocate(len);
83  
84              buf.put(request.getProtocolVersion());
85              buf.put(request.getCommandCode());
86              buf.put(request.getPort());
87              buf.put(request.getIpAddress());
88              buf.put(userID);
89              buf.put(SocksProxyConstants.TERMINATOR);
90  
91              if (isV4ARequest) {
92                  buf.put(host);
93                  buf.put(SocksProxyConstants.TERMINATOR);
94              }
95  
96              if (isV4ARequest) {
97                  logger.debug("  sending SOCKS4a request");
98              } else {
99                  logger.debug("  sending SOCKS4 request");
100             }
101 
102             buf.flip();
103             writeData(nextFilter, buf);
104         } catch (Exception ex) {
105             closeSession("Unable to send Socks request: ", ex);
106         }
107     }
108 
109     /**
110      * Handle incoming data during the handshake process. Should consume only the
111      * handshake data from the buffer, leaving any extra data in place.
112      * 
113      * @param nextFilter the next filter
114      * @param buf the server response data buffer
115      */
116     @Override
117     public void messageReceived(final NextFilter nextFilter, final IoBuffer buf) {
118         try {
119             if (buf.remaining() >= SocksProxyConstants.SOCKS_4_RESPONSE_SIZE) {
120                 handleResponse(buf);
121             }
122         } catch (Exception ex) {
123             closeSession("Proxy handshake failed: ", ex);
124         }
125     }
126 
127     /**
128      * Handle a SOCKS4/SOCKS4a response from the proxy server. Test
129      * the response buffer reply code and call {@link #setHandshakeComplete()}
130      * if access is granted.
131      * 
132      * @param buf the buffer holding the server response data.
133      * @throws Exception if server response is malformed or if request is rejected
134      * by the proxy server.
135      */
136     protected void handleResponse(final IoBuffer buf) throws Exception {
137         byte first = buf.get(0);
138 
139         if (first != 0) {
140             throw new Exception("Socks response seems to be malformed");
141         }
142 
143         byte status = buf.get(1);
144 
145         // Consumes all the response data from the buffer
146         buf.position(buf.position() + SocksProxyConstants.SOCKS_4_RESPONSE_SIZE);
147 
148         if (status == SocksProxyConstants.V4_REPLY_REQUEST_GRANTED) {
149             setHandshakeComplete();
150         } else {
151             throw new Exception("Proxy handshake failed - Code: 0x" + ByteUtilities.asHex(new byte[] { status }) + " ("
152                     + SocksProxyConstants.getReplyCodeAsString(status) + ")");
153         }
154     }
155 }