~hww3/caudium

ref: 47931f4d3b9dead91ca25da525f6bd24cd9e6563 caudium/server/protocols/ssl3.pike -rw-r--r-- 13.7 KiB
47931f4dWilliam Welliver basic sni support. still probably want a setting to enable sni on the port 1 year, 25 days ago
                                                                                
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
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
/*
 * Caudium - An extensible World Wide Web server
 * Copyright � 2000-2005 The Caudium Group
 * Copyright � 1994-2001 Roxen Internet Software
 * 
 * This program 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.
 * 
 * This program 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 this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 *
 */

/* $Id$
 *
 * SSL3 (https) protocol
 */

inherit "protocols/http" : http;
inherit "caudiumlib";

mapping to_send;

#include <stdio.h>
#include <caudium.h>
#include <module.h>

// #define SSL3_DEBUG

#if constant(gethrtime)
# define HRTIME() gethrtime()
# define HRSEC(X) ((int)((X)*1000000))
# define SECHR(X) ((X)/(float)1000000)
#else
# define HRTIME() (predef::time())
# define HRSEC(X) (X)
# define SECHR(X) ((float)(X))
#endif

#ifdef PROFILE
#define REQUEST_DEBUG
int req_time = HRTIME();
#endif

//#define REQUEST_DEBUG

#ifdef REQUEST_DEBUG
#define REQUEST_WERR(X)	roxen_perror((X)+"\n")
#else
#define REQUEST_WERR(X)
#endif

#ifdef FD_DEBUG
#define MARK_FD(X) catch{REQUEST_WERR(X); mark_fd(my_fd->query_fd(), (X)+" "+remoteaddr);}
#else
#define MARK_FD(X) REQUEST_WERR(X)
#endif

class roxen_ssl_context {
  import SSL.Constants;

  inherit SSL.Context;
  int port; /* port number */
  protected object caudium_server;
  
  protected void create(object _caudium) {
     caudium_server = _caudium;
     ::create(); 
  }
  
  array(CertificatePair) find_cert_domain(string(8bit) domain) {
    array res;
    object conf = caudium->get_configuration_for_sni(domain);
    if(conf) {
      res = conf->get_sni_configuration()->find_cert_domain(domain);; 
    } 
    else { 
      res =  ::find_cert_domain(domain);
    }
    return res;
  }
}

private object new_context(object c)
{
//#ifdef SSL3_DEBUG
  roxen_perror(sprintf("SSL3:new_context(X)\n"));
//#endif /* SSL3_DEBUG */
  mapping contexts = caudium->query_var("ssl3_contexts");
  object ctx = roxen_ssl_context(caudium);
  
  if (!contexts)
  {
    contexts = ([ c : ctx ]);
    caudium->set_var("ssl3_contexts", contexts);
  }
  else
    contexts[c] = ctx;
  return ctx;
}

private object get_context(object c)
{
#ifdef SSL3_DEBUG
  roxen_perror(sprintf("SSL3:get_context()\n"));
#endif /* SSL3_DEBUG */
  mapping contexts = caudium->query_var("ssl3_contexts");

  return contexts && contexts[c];
}

array|void real_port(array port, object cfg)
{
#ifdef SSL3_DEBUG
  werror("SSL3: real_port()\n");
  werror(sprintf("port = %O\n", port));
#endif

  object ctx = new_context(cfg);

  ctx->certificates=({});
  ctx->port = port[0];

  // enable use of the session cache
  ctx->use_cache = 1;

  mapping options = cfg->parse_ssl_args(port[3]);

#ifdef SSL3_DEBUG
  werror(sprintf("options = %O\n", options));
#endif
  cfg->load_ssl_configuration(options, ctx);

}

#define CHUNK 16384

string to_send_buffer;
int done;

protected void write_more();

void got_data_to_send(mixed fooid, string data)
{
#ifdef SSL3_DEBUG
  roxen_perror(sprintf("SSL3:got_data_to_send(X, \"%s\")\n", data));
#endif /* SSL3_DEBUG */
  if (!to_send_buffer) {
    to_send_buffer = data;
    my_fd->set_nonblocking(0, write_more, end);
    return;
  }
  to_send_buffer += data;
}

void no_data_to_send(mixed fooid)
{
#ifdef SSL3_DEBUG
  roxen_perror(sprintf("SSL3:no_data_to_send(X)\n"));
#endif /* SSL3_DEBUG */
  if (to_send->file) {
    to_send->file->set_blocking();
    to_send->file->close();
  }
  to_send->file = 0;
  if (!to_send_buffer) {
    // We need to wake up the sender,
    // so that it can close the connection.
    my_fd->set_nonblocking(0, write_more, end);
  }
}

string|int get_data()
{
#ifdef SSL3_DEBUG
  roxen_perror(sprintf("SSL3:get_data()\n"));
#endif /* SSL3_DEBUG */
  string s;
  if ((s = to_send->head))
  {
    to_send->head = 0;
    return s;
  }

  if ((s = to_send->data))
  {
    to_send->data = 0;
    return s;
  }

  s = to_send_buffer;
  to_send_buffer = 0;

  if (to_send->file) {
    /* There's a file, but no data yet
     * disable ourselves until there is.
     */
#ifdef SSL3_DEBUG
  roxen_perror("SSL3:get_data(): file, but no data yet.\n");
#endif /* SSL3_DEBUG */
    my_fd->set_nonblocking(0, 0, end);
    return s || -1;
  }

  return s;
}

protected void die()
{
  my_fd->set_blocking();
  my_fd->close();
  if (done++) destroy();
}

string cache;
protected void write_more()
{
#ifdef SSL3_DEBUG
  roxen_perror(sprintf("SSL3:write_more()\n"));
#endif /* SSL3_DEBUG */
  string|int s;
  if (!(s = (cache || get_data())) || s == "") {
//    perror("SSL3:: Done.\n");
    die();
    return;
  }

  if(s == -1) // we have an fd, but no data yet.
    return;

  if (sizeof(s)) {
    int pos = my_fd->write(s);

    // perror("Wrote "+pos+" bytes ("+s+")\n");
  
    if(pos <= 0) // Ouch.
    {
#ifdef DEBUG
      perror("SSL3:: Broken pipe.\n");
#endif
      die();
      return;
    }  
    if(pos < strlen(s))
      cache = s[pos..];
    else
      cache = 0;
  } else {
    cache = 0;
  }
}

string get_data_file()
{
#ifdef SSL3_DEBUG
  roxen_perror(sprintf("SSL3:get_data_file()\n"));
#endif /* SSL3_DEBUG */
  string s;
  if ((s = to_send->head))
  {
    to_send->head = 0;
    return s;
  }

  if ((s = to_send->data))
  {
    to_send->data = 0;
    return s;
  }

  if(to_send->file) {
    // Read some more data
    s = to_send->file->read(CHUNK,1);
  }

  if (!s || !sizeof(s)) {
    if (to_send->file) {
      to_send->file->close();
      to_send->file = 0;
    }
  }

  return s;
}

protected void write_more_file()
{
#ifdef SSL3_DEBUG
  roxen_perror(sprintf("SSL3:write_more_file()\n"));
#endif /* SSL3_DEBUG */
  string s;

  if(!(s = (cache || get_data_file()))) {
//    perror("SSL3:: Done.\n");
    die();
    return;
  }    

  if (s && sizeof(s)) {
    int pos = my_fd->write(s);

    // perror("Wrote "+pos+" bytes ("+s+")\n");
  
    if(pos <= 0) // Ouch.
    {
#ifdef DEBUG
      perror("SSL3:: Broken pipe.\n");
#endif
      die();
      return;
    }  
    if(pos < strlen(s))
      cache = s[pos..];
    else
      cache = 0;
  } else {
    // we got to this point; no data left
    cache = 0;
    die();    
  }
}

void do_send_result_async(string head_string)
{
  file->head = head_string;
  to_send = copy_value(file);

  if (objectp(to_send->file)) {
    array st = to_send->file->stat && to_send->file->stat();
    if (st && (st[1] >= 0)) {
      // Ordinary file -- can't use non-blocking I/O
      my_fd->set_nonblocking(0, write_more_file, do_log);
    } else {
      my_fd->set_nonblocking(0, write_more, do_log);
      to_send->file->set_nonblocking(got_data_to_send, 0, no_data_to_send);
    }
  } else
    my_fd->set_nonblocking(0, write_more, do_log);
  if (done++) destroy();
}

void do_log()
{
  MARK_FD("HTTP logging"); // fd can be closed here

  if(conf)
  {
    if(file->len > 0) conf->sent+=file->len;
    file->len += misc->_log_cheat_addition;
    conf->log(file, this_object());
  }

  end(0,1);
  return;
}

protected int parse_got()
{
  string server_name = my_fd->get_server_name();
  if(server_name) {
    object c = caudium->get_configuration_for_sni(server_name);
    if(c) { werror("got sni config: %O\n", c); 
      conf = c;
    }
  }

  int r = ::parse_got();
  if(r == -1)
  {
    array certs;
    if(my_fd && my_fd->get_peer_certificates)
      certs = my_fd->get_peer_certificates();
    if(certs)
      foreach(certs;int cn;string der)
      {
        werror("cert %d subject: %s\n", cn, Standards.PKCS.Certificate.get_dn_string(
          Standards.PKCS.Certificate.get_certificate_subject(der)));
      }
  }

  // let's slide our client certificate info in...
//  if()
//  {
//  }

  return r;
}


// TODO: when we have an http->ssl3 redirect, we end up with spurious errors in the log file
// from sslfile (indexing the null value query_backend, etc). 
class fallback_redirect_request {
  string in = "";
  string out;
  string default_prefix;
  int port;
  object f;

  void die()
  {
#ifdef SSL3_DEBUG
    roxen_perror(sprintf("SSL3:fallback_redirect_request::die()\n"));
#endif /* SSL3_DEBUG */
#if 0
    /* Close the file, DAMMIT */
    object dummy = Stdio.File();
    if (dummy->open("/dev/null", "rw"))
      dummy->dup2(f);
#endif    
    f->close();
    destruct(f);
    destruct(this_object());
  }
  
  void write_callback(object id)
  {
#ifdef SSL3_DEBUG
    roxen_perror(sprintf("SSL3:fallback_redirect_request::write_callback()\n"));
#endif /* SSL3_DEBUG */
    int written = id->write(out);
    if (written <= 0)
      die();
    out = out[written..];
    if (!strlen(out))
      die();
  }

  void read_callback(object id, string s)
  {
#ifdef SSL3_DEBUG

    roxen_perror(sprintf("SSL3:fallback_redirect_request::read_callback(X, \"%s\")\n", s));
#endif /* SSL3_DEBUG */
    in += s;
    string name;
    string prefix;

    if (search(in, "\r\n\r\n") >= 0)
    {
//      werror(sprintf("request = '%s'\n", in));
      array(string) lines = in / "\r\n";
      array(string) req = replace(lines[0], "\t", " ") / " ";
      if (sizeof(req) < 2)
      {
	out = "HTTP/1.0 400 Bad Request\r\n\r\n";
      }
      else
      {
	if (sizeof(req) == 2)
	{
	  name = req[1];
	}
	else
	{
	  name = req[1..sizeof(req)-2] * " ";
	  foreach(Array.map(lines[1..], `/, ":"), array header)
	  {
	    if ( (sizeof(header) >= 2) &&
		 (lower_case(header[0]) == "host") )
	      prefix = "https://" + (header[1]/":")[0] - " ";
	  }
	}
	if (prefix) {
	  if (prefix[-1] == '/')
	    prefix = prefix[..strlen(prefix)-2];
	  prefix = prefix + ":" + port;
	} else {
	  /* default_prefix (aka MyWorldLocation) already contains the
	   * portnumber.
	   */
	  if (!(prefix = default_prefix)) {
	    /* This case is most unlikely to occur,
	     * but better safe than sorry...
	     */
	    prefix = "https://localhost:" + port;
	  } else if (prefix[..4] == "http:") {
	    /* Broken MyWorldLocation -- fix. */
	    prefix = "https:" + prefix[5..];
	  }
	}
	out = sprintf("HTTP/1.0 301 Redirect to secure server\r\n"
		      "Location: %s%s\r\n\r\n", prefix, name);
      }
      f->set_read_callback(0);
      f->set_write_callback(write_callback);
    }
  }
  
  void create(object socket, string s, string l, int p)
  {
#ifdef SSL3_DEBUG
    roxen_perror(sprintf("SSL3:fallback_redirect_request(X, \"%s\", \"%s\", %d)\n", s, l||"CONFIG PORT", p));
#endif /* SSL3_DEBUG */
    f = socket;
    default_prefix = l;
    port = p;
    f->set_nonblocking(read_callback, 0, die);
    f->set_id(f);
    read_callback(f, s);
    write_callback(f);
  }
}

void http_fallback(object alert, object|int n, string data)
{
  object ctx;
  ctx = get_context(my_fd->config);
#ifdef SSL3_DEBUG
  roxen_perror(sprintf("SSL3:http_fallback(X, %O, \"%s\")\n", n, data));
#endif /* SSL3_DEBUG */
//  trace(1);
#if 0
  werror(sprintf("ssl3->http_fallback: alert(%d, %d)\n"
		 "seq_num = %s\n"
		 "data = '%s'", alert->level, alert->description,
		 (string) n, data));
#endif
  if ((!my_fd->current_write_state || !my_fd->current_write_state->seq_num)
    || search(lower_case(data), "http")!=-1)
  {

    /* Redirect to a https-url */
//    my_fd->set_close_callback(0);
//    my_fd->leave_me_alone = 1;
    fallback_redirect_request(my_fd->raw_file, data,
			      my_fd->config && 
			      my_fd->config->query("MyWorldLocation"),
			      ctx->port);
      my_fd = 0;
//    destruct(my_fd);
    destruct(this_object());
//    my_fd = 0; /* Forget ssl-object */
  }
}

void ssl_accept_callback(object id)
{
#ifdef SSL3_DEBUG
  roxen_perror(sprintf("SSL3:ssl_accept_callback(X)\n"));
#endif /* SSL3_DEBUG */
  id->set_alert_callback(0); /* Forget about http_fallback */
  id->raw_file = 0;          /* Not needed any more */
}

class roxen_sslfile {
  inherit SSL.File : ssl;

  object raw_file;
  object config;

  int destructme; // 0: alive, 1: parent wants destruct, 2: self wants destruct.
  int query_fd() { return -1; }
  void die(int status)
  {
#ifdef SSL3_DEBUG
    roxen_perror(sprintf("SSL3:roxen_sslfile::die(%d)\n", status));
#endif /* SSL3_DEBUG */
    close();
    if ((destructme |= 2) == 3) destruct();
  }

  void create(object f, object ctx, object id)
  {
#ifdef SSL3_DEBUG
    roxen_perror(sprintf("SSL3:roxen_sslfile(X, X, X)\n"));
#endif /* SSL3_DEBUG */
    raw_file = f;
    config = id;
    ssl::create(f, ctx);
  }

#ifdef SSL3_DEBUG
  void destroy()
  {
    roxen_perror(sprintf("SSL3:roxen_sslfile::destroy()\n"));
  }
#endif /* SSL3_DEBUG */
}

private object my_fd_for_destruct; // Used to keep my_fd around for destroy().

void destroy()
{
#ifdef SSL3_DEBUG
  roxen_perror(sprintf("SSL3:destroy()\n"));
#endif /* SSL3_DEBUG */
  catch {
    // When the request disappear there's noone else interested in
    // my_fd, so it should destruct itself asap.
    if ((my_fd_for_destruct->destructme |= 1) == 3)
      destruct (my_fd_for_destruct);
  };
}

void create(void|object f, void|object c)
{
#ifdef SSL3_DEBUG
  roxen_perror(sprintf("SSL3:create(X, X)\n"));
#endif /* SSL3_DEBUG */

  if(f)
  {
    object ctx;

    ctx = get_context(c);
    if (!ctx)
    {
      roxen_perror("ssl3.pike: No SSL context!\n");
      throw( ({ "ssl3.pike: No SSL context!\n", backtrace() }) );
    }
    remoteaddr = Caudium.get_address(f->query_address()||"");
    my_fd_for_destruct = my_fd = roxen_sslfile(f, ctx, c);

    my_fd->set_accept_callback(ssl_accept_callback);
    conf = c;
    my_fd->set_nonblocking(got_data,0,end);
    if(my_fd->set_alert_callback)

    my_fd->accept();
    my_fd->set_alert_callback(http_fallback);

  } else {
    // Main object. 
  }
  
  server_protocol="HTTPS";
}