summaryrefslogtreecommitdiff
path: root/gnu/javax/net/ssl/provider/Handshake.java
blob: ef9e72381c1d05346bc79f5abb855bc9eb0644d0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
/* Handshake.java -- SSL handshake message.
   Copyright (C) 2006  Free Software Foundation, Inc.

This file is a part of GNU Classpath.

GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or (at
your option) any later version.

GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
General Public License for more details.

You should have received a copy of the GNU General Public License
along with GNU Classpath; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
USA

Linking this library statically or dynamically with other modules is
making a combined work based on this library.  Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.

As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module.  An independent module is a module which is not derived from
or based on this library.  If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so.  If you do not wish to do so, delete this
exception statement from your version.  */


package gnu.javax.net.ssl.provider;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.EOFException;
import java.io.InputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.StringReader;
import java.io.StringWriter;

import java.security.PublicKey;

import java.util.ArrayList;
import java.util.Collections;

import javax.net.ssl.SSLProtocolException;

final class Handshake implements Constructed
{

  // Fields.
  // -------------------------------------------------------------------------

  private static final buffer BUF = new buffer();

  private final Type type;
  private final Body body;

  // Constructors.
  // -------------------------------------------------------------------------

  Handshake(Type type, Body body)
  {
    this.type = type;
    this.body = body;
  }

  // Class methods.
  // -------------------------------------------------------------------------

  static Handshake read(byte[] buffer) throws IOException
  {
    return read(new ByteArrayInputStream(buffer));
  }

  static Handshake read(byte[] buffer, CipherSuite suite, PublicKey key)
    throws IOException
  {
    return read(new ByteArrayInputStream(buffer), suite, key);
  }

  static Handshake read(InputStream in) throws IOException
  {
    return read(in, null, null);
  }

  static Handshake read(InputStream in, CipherSuite suite, PublicKey key)
    throws IOException
  {
    return read(in, suite, key, null);
  }

  static Handshake read(InputStream in, CertificateType certType)
    throws IOException
  {
    return read(in, null, null, certType);
  }

  static Handshake read(InputStream in, CipherSuite suite, PublicKey key,
                        CertificateType certType)
    throws IOException
  {
    Type type = Type.read(in);
    byte[] lenbuf = new byte[3];
    in.read(lenbuf);
    int len = (lenbuf[0] & 0xFF) << 16 | (lenbuf[1] & 0xFF) << 8
            | (lenbuf[2] & 0xFF);
    Body body = null;
    if (type == Type.HELLO_REQUEST)
      {
        body = null;
      }
    else if (type == Type.CLIENT_HELLO)
      {
        // Most likely a V2 hello. If the first byte is 0x30, and if this
        // is not a V2 client hello, then it is a V3 client hello with
        // at least 1.5 million cipher specs, which is unlikely.
        if (lenbuf[0] == 3 && (lenbuf[1] >= 0 && lenbuf[1] <= 2))
          {
            ProtocolVersion vers = null;
            switch (lenbuf[1])
              {
              case 0:
                vers = ProtocolVersion.SSL_3;
                break;
              case 1:
                vers = ProtocolVersion.TLS_1;
                break;
              case 2:
                vers = ProtocolVersion.TLS_1_1;
                break;
              }
            int specLen = (lenbuf[2] & 0xFF) << 8 | (in.read() & 0xFF);
            int idLen   = (in.read() & 0xFF) << 8 | (in.read() & 0xFF);
            int chalLen = (in.read() & 0xFF) << 8 | (in.read() & 0xFF);

            ArrayList suites = new ArrayList(specLen / 3);
            for (int i = 0; i < specLen; i += 3)
              {
                if (in.read() == 0)
                  {
                    suites.add(CipherSuite.read(in).resolve(vers));
                  }
                else
                  {
                    in.read();
                    in.read();
                  }
              }
            byte[] id = new byte[idLen];
            in.read(id);
            byte[] challenge = new byte[chalLen];
            in.read(challenge);
            if (challenge.length > 32)
              challenge = Util.trim(challenge, 32);
            else if (challenge.length < 32)
              {
                byte[] b = new byte[32];
                System.arraycopy(challenge, 0, b, b.length - challenge.length,
                                 challenge.length);
                challenge = b;
              }
            int time = (challenge[0] & 0xFF) << 24 | (challenge[1] & 0xFF) << 16
                     | (challenge[2] & 0xFF) <<  8 | (challenge[3] & 0xFF);
            Random rand = new Random(time, Util.trim(challenge, 4, 28));
            return new Handshake(Handshake.Type.CLIENT_HELLO,
              new ClientHello(vers, rand, id, suites,
                              Collections.singletonList(CompressionMethod.NULL)));
          }
        // Since hello messages may contain extensions, we read the whole
        // thing here.
        byte[] buf = new byte[len];
        int count = 0;
        while (count < len)
          {
            int l = in.read(buf, count, len - count);
            if (l == -1)
              {
                throw new EOFException("unexpected end of input stream");
              }
            count += l;
          }
        body = ClientHello.read(new ByteArrayInputStream(buf));
      }
    else if (type == Type.SERVER_HELLO)
      {
        byte[] buf = new byte[len];
        int count = 0;
        while (count < len)
          {
            int l = in.read(buf, count, len - count);
            if (l == -1)
              {
                throw new EOFException("unexpected end of input stream");
              }
            count += l;
          }
        body = ServerHello.read(new ByteArrayInputStream(buf));
      }
    else if (type == Type.CERTIFICATE)
      {
        body = Certificate.read(in, certType);
      }
    else if (type == Type.SERVER_KEY_EXCHANGE)
      {
        body = ServerKeyExchange.read(in, suite, key);
      }
    else if (type == Type.CERTIFICATE_REQUEST)
      {
        body = CertificateRequest.read(in);
      }
    else if (type == Type.CERTIFICATE_VERIFY)
      {
        body = (CertificateVerify) CertificateVerify.read(in, suite, key);
      }
    else if (type == Type.CLIENT_KEY_EXCHANGE)
      {
        body = ClientKeyExchange.read(in, suite, key);
      }
    else if (type == Type.SERVER_HELLO_DONE)
      {
        body = null;
      }
    else if (type == Type.FINISHED)
      {
        body = Finished.read(in, suite);
      }
    else
      {
        throw new SSLProtocolException("unknown HandshakeType: " +
                                       type.getValue());
      }

    return new Handshake(type, body);
  }

  // Instance methods.
  // -------------------------------------------------------------------------

  public void write(OutputStream out)
  {
    throw new UnsupportedOperationException();
  }

  public int write(OutputStream out, ProtocolVersion version)
    throws IOException
  {
    out.write(type.getValue());
    if (body == null)
      {
        out.write(0);
        out.write(0);
        out.write(0);
        return 4;
      }
    else
      {
        ByteArrayOutputStream bout = BUF.getBuffer();
        bout.reset();
        if (body instanceof ServerKeyExchange)
          {
            ((ServerKeyExchange) body).write(bout, version);
          }
        else if (body instanceof ClientKeyExchange)
          {
            ((ClientKeyExchange) body).write(bout, version);
          }
        else if (body instanceof CertificateVerify)
          {
            ((CertificateVerify) body).write(bout, version);
          }
        else
          {
            body.write(bout);
          }
        out.write(bout.size() >>> 16 & 0xFF);
        out.write(bout.size() >>>  8 & 0xFF);
        out.write(bout.size() & 0xFF);
        bout.writeTo(out);
        return 4 + bout.size();
      }
  }

  Type getType()
  {
    return type;
  }

  Body getBody()
  {
    return body;
  }

  public String toString()
  {
    StringWriter str = new StringWriter();
    PrintWriter out = new PrintWriter(str);
    String nl = System.getProperty("line.separator");
    StringBuffer buf = new StringBuffer();
    out.println("struct {");
    out.println("  type = " + type + ";");
    if (body != null)
      {
        BufferedReader r = new BufferedReader(new StringReader(body.toString()));
        String s;
        try
          {
            while ((s = r.readLine()) != null)
              {
                out.print("  ");
                out.println(s);
              }
          }
        catch (IOException ignored)
          {
          }
      }
    out.println("} Handshake;");
    return str.toString();
  }

  // Inner class.
  // -------------------------------------------------------------------------

  static interface Body extends Constructed
  {
  }

  static class Type implements Enumerated
  {

    // Constants and fields.
    // -----------------------------------------------------------------------

    public static final Type
      HELLO_REQUEST       = new Type( 0), CLIENT_HELLO        = new Type( 1),
      SERVER_HELLO        = new Type( 2), CERTIFICATE         = new Type(11),
      SERVER_KEY_EXCHANGE = new Type(12), CERTIFICATE_REQUEST = new Type(13),
      SERVER_HELLO_DONE   = new Type(14), CERTIFICATE_VERIFY  = new Type(15),
      CLIENT_KEY_EXCHANGE = new Type(16), FINISHED            = new Type(20),
      CERTIFICATE_URL     = new Type(21), CERTIFICATE_STATUS  = new Type(22);

    private final int value;

    // Constructor.
    // -----------------------------------------------------------------------

    private Type(int value)
    {
      this.value = value;
    }

    // Class methods.
    // -----------------------------------------------------------------------

    public static Type read(InputStream in) throws IOException
    {
      int i = in.read();
      if (i == -1)
        {
          throw new EOFException("unexpected end of input stream");
        }
      switch (i & 0xFF)
        {
        case  0: return HELLO_REQUEST;
        case  1: return CLIENT_HELLO;
        case  2: return SERVER_HELLO;
        case 11: return CERTIFICATE;
        case 12: return SERVER_KEY_EXCHANGE;
        case 13: return CERTIFICATE_REQUEST;
        case 14: return SERVER_HELLO_DONE;
        case 15: return CERTIFICATE_VERIFY;
        case 16: return CLIENT_KEY_EXCHANGE;
        case 20: return FINISHED;
        case 21: return CERTIFICATE_URL;
        case 22: return CERTIFICATE_STATUS;
        default: return new Type(i);
        }
    }

    // Instance methods.
    // -----------------------------------------------------------------------

    public byte[] getEncoded()
    {
      return new byte[] { (byte) value };
    }

    public int getValue()
    {
      return value;
    }

    public String toString()
    {
      switch (value)
        {
        case  0: return "hello_request";
        case  1: return "client_hello";
        case  2: return "server_hello";
        case 11: return "certificate";
        case 12: return "server_key_exchange";
        case 13: return "certificate_request";
        case 14: return "server_hello_done";
        case 15: return "certificate_verify";
        case 16: return "client_key_exchange";
        case 20: return "finished";
        case 21: return "certificate_url";
        case 22: return "certificate_status";
        default: return "unknown(" + value + ")";
        }
    }
  }

  private static class buffer extends ThreadLocal
  {
    static final int SIZE = 2048;

    protected Object initialValue()
    {
      return new ByteArrayOutputStream(SIZE);
    }

    ByteArrayOutputStream getBuffer()
    {
      return (ByteArrayOutputStream) get();
    }
  }
}