File: tlsServer.cxx

package info (click to toggle)
stun 0.96.dfsg-6
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd, wheezy
  • size: 380 kB
  • ctags: 293
  • sloc: cpp: 3,674; sh: 149; makefile: 84
file content (502 lines) | stat: -rw-r--r-- 13,366 bytes parent folder | download | duplicates (5)
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

/* 
   This program takes no arguments. It opens the STUN tcp port and rus a tls server
   on it. 
*/

#include <sys/types.h>
#include <string.h>
#include <openssl/e_os2.h>
#include <openssl/evp.h>
#include <openssl/crypto.h>
#include <openssl/err.h>
#include <openssl/pem.h>
#include <openssl/pkcs7.h>
#include <openssl/x509.h>
#include <openssl/x509v3.h>
#include <openssl/ssl.h>
#ifdef WIN32
#include <errno.h>
#include <winsock2.h>
#include <io.h>
#endif
 
#ifndef WIN32
#include <sys/types.h>
#include <sys/time.h>
#include <sys/socket.h>
#include <sys/select.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#endif

#ifdef WIN32
# include <windows.h>
# include <winbase.h>
# include <errno.h>
# include <winsock2.h>
# include <io.h>
typedef unsigned int u_int32_t;
#endif

#include <cassert>
#include <fcntl.h>

#include <iostream>
#include <cstdlib>
#include <stdio.h>

#ifdef __MACH__
typedef int socklen_t;
#endif

#include "stun.h"

using namespace std;



#define MAX_CONNECTIONS 64


#ifdef WIN32
typedef int socklen_t;
//#define errno WSAGetLastError()
typedef SOCKET Socket;
#else
typedef int Socket;
static const Socket INVALID_SOCKET = -1;
static const int SOCKET_ERROR = -1;
#endif



// TODO - !cj! - need to deal with closing connections 


void 
makeSocketNonBlocking(Socket fd)
{
#if WIN32
   unsigned long noBlock = 1;
   int errNoBlock = ioctlsocket( fd, FIONBIO , &noBlock );
   if ( errNoBlock != 0 )
   {
      assert(0);
   }
#else
   int flags  = fcntl( fd, F_GETFL, 0);
   int errNoBlock = fcntl(fd, F_SETFL, flags | O_NONBLOCK );
   if ( errNoBlock != 0 ) // !cj! I may have messed up this line 
   {
      assert(0);
   }
#endif
}


int 
main()
{
#ifdef WIN32 
   WORD wVersionRequested = MAKEWORD( 2, 2 );
   WSADATA wsaData;
   int err;

   err = WSAStartup( wVersionRequested, &wsaData );
   if ( err != 0 ) 
   {
      // could not find a usable WinSock DLL
      //cerr << "Could not load winsock" << endl;
      assert(0); // is this is failing, try a different version that 2.2, 1.0 or later will likely work 
      exit(1);
   }
#endif

   // contexts for each connection 
   SSL* ssl[MAX_CONNECTIONS];

   // buffers for each connection
   BIO* bio[MAX_CONNECTIONS];

   // file descriptors for each connection
   Socket fd[MAX_CONNECTIONS];

   // ip address of other side of connection 
   int  peerip[MAX_CONNECTIONS];

   // root cert list 
   X509_STORE* certAuthorities;
   // my public cert
   X509* publicCert;
   // my private key 
   EVP_PKEY* privateKey;
   // SSL Context 
   SSL_CTX* ctx;
   
   Socket mFd;
   
   char* password = "password";
   

   for ( int i=0; i<MAX_CONNECTIONS; i++ )
   {
      fd[i]=-1;
      bio[i]=0;
      ssl[i]=0;
   }
   

   // load public cert 
   FILE* fp = fopen("id.pem","rb");
   if ( !fp )
   {
      cerr << "Could not read public cert" <<endl; exit(1);
   }
   publicCert = PEM_read_X509(fp,NULL,NULL,NULL);
   if (!publicCert)
   {
      cerr << "Error reading contents of public cert"<<endl; exit(1);
   }
   cerr << "Loaded public cert"<<endl;


   // load private key 
   fp = fopen("id_key.pem","rb");
   if ( !fp )
   {
      cerr << "Could not read private key"<<endl; exit(1);
   }
   privateKey = PEM_read_PrivateKey(fp,NULL,NULL,password);
   if (!privateKey)
   {
      cerr << "Error reading contents of private key file "<<endl;exit(1);
   }
   cerr << "Loaded private key "<<endl;
   
   // load root certs 
   certAuthorities = X509_STORE_new();
   assert( certAuthorities );
   if ( X509_STORE_load_locations(certAuthorities,"root.pem",NULL) != 1 )
   {  
      cerr << "Error reading contents of root cert file "<<endl;
   }
   cerr << "Loaded public CAs"<<endl;

   
   // set up main security context    
   SSL_library_init();
   
   SSL_load_error_strings();
   
   OpenSSL_add_all_ciphers();
   OpenSSL_add_all_digests();
   
   ERR_load_crypto_strings();
   
   ctx=SSL_CTX_new( TLSv1_method() );
   assert( ctx );
   
   int ok;
   ok = SSL_CTX_use_certificate(ctx, publicCert);
   assert( ok == 1);
   
   ok = SSL_CTX_use_PrivateKey(ctx,privateKey);
   assert( ok == 1);
   
   assert( certAuthorities );
   SSL_CTX_set_cert_store(ctx, certAuthorities);
   
   
   // open a socket to listen for requests on 
   mFd = socket(PF_INET, SOCK_STREAM, 0);

   sockaddr_in addr;
   addr.sin_family = AF_INET;
   addr.sin_addr.s_addr = htonl(INADDR_ANY); 
   addr.sin_port = htons(STUN_PORT);
   
   if ( bind( mFd, (struct sockaddr*) &addr, sizeof(addr)) == SOCKET_ERROR )
   {
      int err = errno;
      if ( err == EADDRINUSE )
      {
         cerr << "Port already in use"<<endl;
      }
      else
      {
         cerr << "Could not bind to port"<<endl;
      }
      
      exit(0);
   }

   makeSocketNonBlocking(mFd);

   int e = listen(mFd,64 );
   if (e != 0 )
   {
      assert(0);
   }


   cerr << "Ready for requests" << endl;
   
   while ( true ) 
   {
      // set up the read fd set for select 
      fd_set read;
      FD_ZERO(&read);
      int size=0;

      FD_SET(mFd, &read);
      size = mFd+1;

      for ( int i=0; i<MAX_CONNECTIONS; i++ )
      {
         if ( fd[i] > 0 )
         {
            FD_SET(fd[i], &read); 
            size = ( int(fd[i]+1) > size) ? int(fd[i]+1) : size;
         }
         
      }


      // do a select 
      unsigned long ms = 500;
      struct timeval tv;
      tv.tv_sec = (ms/1000);
      tv.tv_usec = (ms%1000)*1000;
      int e = select(size, &read, NULL, NULL, &tv);
      
      cerr << "." ;
      
      // process any new connections 
      if ( FD_ISSET(mFd, &read))
      {
         cerr << "Got a new connection" << endl;
         
         // find an unused connection 
         int i=0;
         for ( ; i<MAX_CONNECTIONS; i++ )
         {
            if ( fd[i] == -1 ) 
            {
               break;
            }
         }
         
         if ( i >= MAX_CONNECTIONS )
         {
            cerr << "Ran out of connections to use "<<endl;
            break;
         }
         
         struct sockaddr_in peer;
         int peerLen=sizeof(peer);
         fd[i] = accept( mFd, (struct sockaddr*)&peer,(socklen_t*)&peerLen);
         if ( fd[i] == -1 )
         {
            int err = errno;
            cerr << "Error on accept: " << strerror(err)<<endl;
            break;
         }
         
         int* ptr =  (int*)( &peer.sin_addr );
         peerip[i] = *ptr;
         
         ssl[i] = NULL;
         
         ssl[i] = SSL_new(ctx);
         assert(ssl[i]);
         
         bio[i] = BIO_new_socket(fd[i],0/*close flag*/);
         assert( bio[i] );
         
         SSL_set_bio( ssl[i], bio[i], bio[i] );
         
         int ok=0;
         ok = SSL_accept(ssl[i]);
         
         if ( ok != 1 )
         {
            int err = SSL_get_error(ssl[i],ok);
            char buf[256];
            ERR_error_string_n(err,buf,sizeof(buf));
            
            cerr << "ssl connection failed "<<endl;
            
            bio[i] = NULL;
         }
         
         makeSocketNonBlocking(fd[i]);
      }
      

      // process reads and writes 
      for (int i=0; i<MAX_CONNECTIONS; i++) 
      {
         if ( ssl[i] )
            if (  FD_ISSET( fd[i], &read) ||  SSL_pending(ssl[i])  )
            {
               cerr << "got a message on connection " << i << endl;
            
               char buf[STUN_MAX_MESSAGE_SIZE];
                   
               int ret = SSL_read(ssl[i],buf,sizeof(buf));
               if (ret < 0 )
               {
                  int err = SSL_get_error(ssl[i],ret);
                  switch (err)
                  {
                     case SSL_ERROR_WANT_READ:
                     case SSL_ERROR_WANT_WRITE:
                     case SSL_ERROR_NONE:
                     {
                        cerr << "Got TLS read got condition of " << err  <<endl;
                     }
                     break;
                     default:
                     {
                        char buf[256];
                        ERR_error_string_n(err,buf,sizeof(buf));
                        cerr << "Got TLS read error " << err  << " " << buf  <<endl;
                     }
                     break;
                  }
                  // !cj! - big mem leak here - need to close and cleanup 
                  closesocket( fd[i] );
                  fd[i] = -1;
                  ssl[i]=0;
               }
            
               cerr << "Received message with " << ret << " bytes"<<endl;
            
               StunAddress4 from;
               StunAddress4 myAddr;
               StunAddress4 altAddr;
               StunMessage resp;
               StunAddress4 destination;
               StunAtrString hmacPassword;
               bool changePort;
               bool changeIp;
            
               from.addr = peerip[i];
            
               bool ok = stunServerProcessMsg( buf,ret, 
                                               from, 
                                               myAddr,
                                               altAddr, 
                                               &resp,
                                               &destination,
                                               &hmacPassword,
                                               &changePort,
                                               &changeIp,
                                               true /*verbose*/ );

               if (!ok )
               { 
                  cerr << "Message did not parse - closeing conneciton " << i  <<endl;
                  closesocket( fd[i] );
                  fd[i] = -1;
                  ssl[i]=0;
               }
            
               if (ok)
               {
                  int len = stunEncodeMessage( resp, buf, sizeof(buf), hmacPassword );
           
                  ret = SSL_write(ssl[i],(const char*)buf,len);

                  if (ret < 0 )
                  {
                     int err = SSL_get_error(ssl[i],ret);
                     switch (err)
                     {
                        case SSL_ERROR_WANT_READ:
                        case SSL_ERROR_WANT_WRITE:
                        case SSL_ERROR_NONE:
                        {
                           cerr << "Got TLS write got codition of " << err  <<endl;
                        }
                        break;
                        default:
                        {
                           cerr << "Got TLS write error " << err  <<endl;
                        }
                        break;
                     }
                     // !cj! big mem leak - need to cleanup 
                     closesocket( fd[i] );
                     fd[i] = -1;
                     ssl[i]=0;
                  }
               }
            }
      }
   }
   
   return 0;
}


/* ====================================================================
 * The Vovida Software License, Version 1.0 
 * 
 * Copyright (c) 2000 Vovida Networks, Inc.  All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 * 
 * 3. The names "VOCAL", "Vovida Open Communication Application Library",
 *    and "Vovida Open Communication Application Library (VOCAL)" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact vocal@vovida.org.
 *
 * 4. Products derived from this software may not be called "VOCAL", nor
 *    may "VOCAL" appear in their name, without prior written
 *    permission of Vovida Networks, Inc.
 * 
 * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND
 * NON-INFRINGEMENT ARE DISCLAIMED.  IN NO EVENT SHALL VOVIDA
 * NETWORKS, INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT DAMAGES
 * IN EXCESS OF $1,000, NOR FOR ANY INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
 * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
 * DAMAGE.
 * 
 * ====================================================================
 * 
 * This software consists of voluntary contributions made by Vovida
 * Networks, Inc. and many individuals on behalf of Vovida Networks,
 * Inc.  For more information on Vovida Networks, Inc., please see
 * <http://www.vovida.org/>.
 *
 */

// Local Variables:
// mode:c++
// c-file-style:"ellemtel"
// c-file-offsets:((case-label . +))
// indent-tabs-mode:nil
// End: