  Installing and using SSLtcl
  Peter Antman
  Mon Jan 19 01:53:02 MET 1998

  This is documentation for SSLtcl. SSLtcl is a free loadable module for
  tcl that extends the socket command with SSL (SECURE SOCKET LAYER)
  functions. That is, it makes it possible for tcl to communicate
  securely over the Internet.  SSLtcl is actually a thin wrapper around
  Eric Young's free SSL implementation SSLeay, that contain all crypto-
  graphic libraries necessary to do secure SSL outside the USA. SSLtcl
  can be build both statically and dynamically linked against SSLeay.
  Against dynamically linked binaries there is no export restriction.
  However, for statically linked binaries export restrictions in some
  countries, most notable USA, restricts exports.
  ______________________________________________________________________

  Table of Contents:

  1. SSLtcl

  2. Bugs

  3. Copyright

  4. Installation

  5. SSLtcl Manual Page

     5.1 NAME
     5.2 SYNOPSIS
     5.3 DESCRIPTION
     5.4 CLIENT SOCKET
     5.5 SERVER SOCKET
     5.6 SUPPORTED CIPHERS
     5.7 TIPS
     5.8 BUGS AND FEATURES
     5.9 AUTHOR
     5.10 SEE ALSO

  6. Demonstrations of how to use SSLtcl

  7. Certificate questions

  ______________________________________________________________________

  1.  SSLtcl

  SSLtcl is a free loadable module for tcl that extends the socket
  command with SSL (SECURE SOCKET LAYER) functions. That is, it makes it
  possible for tcl applications to communicate securely over the
  Internet. SSLtcl is actually a thin wrapper around Eric Young's free
  SSL implementation SSLeay, that contain all cryptographic libraries
  insecurely to do secure SSL outside the USA.

  SSL is a protocol invented by Netscape to do secure transactions over
  the web. It implements both protocols to know who you are talking to
  and protocols to hide your precious data.

  SSLeay is a free implementation of SSL done in Australia. It contains
  all the cryptographic feature that is not allowed to be exported
  outside USA by USA companies. It, for example, contain RC4 128 bit and
  triple-des (168 bit).

  To read more about SSL and SSLeay see the SSLeay FAQ,
  http://www.psy.uq.oz.au/~ftp/Crypto

  SSLtcl is a loadable module for tcl that makes it possible to use SSL
  inside tcl. It actually provides a extended socket command with which
  you can create a client and a server that can communicate with the SSL
  protocol, that is securely communicate over the Internet. It is - I
  think - the easiest way there is to day to incorporate SSL in to your
  programs.

  SSLtcl can be found at

  ftp://ftp.mc.hik.se/pub/users/mia95anp/ssl/SSLtcl-0.42.tar.gz

  http://www.abc.se/~m9339/prog/ssl/SSLtcl-0.42.tar.gz

  It has also been uploaded to

  sunsite.unc.edu/incoming/Linux

  www.neosoft.com/tcl

  A dynamically linked rpm-version will also bee done in the near future
  and be uploaded to

  ftp.redhat.com

  The official homepage for SSLtcl is

  http://www.abc.se/~m9339/prog/ssl/

  To install SSLtcl you should read the Installation instruction either
  in this manual or in the file INSTALL.

  Howto use it is described in the manual pages ssltcl(n). There is also
  a demo directory with some example scripts that uses SSLtcl.so. Read
  the section in this manual about the demo scripts or the README in the
  demo directory. For your convenience a have included a demo CA and a
  demo certificate where the passphrase for the keys is removed. They
  are located in the demo/demoCA directory and is used by the demo
  scripts.

  In this manual there is also a section which briefly describes how to
  handle and generate your own certificates. If this information is not
  enough reed the SSLeay FAQ.
  2.  Bugs

  0.42 is the first public release of SSLtcl. I have tried to test is as
  hard as possible, but it will probably contain bugs. Please send bug
  reports or other comments to:

  peter.antman@abc.se

  There is one feature that I am not to happy about. It is described in
  the manual page.

  I hope to have the time to extend SSLtcl with further commands in the
  future. Especially I would like to have a tcl procedure callback for
  the password and for client verification. I nice way of storing the
  certificates would also be nice.

  3.  Copyright

  SSLtcl is copyrighted by Peter Antman, and licenced under GNU/GPL.
  This means that it is free fore use and further development but that
  any changes has to be made public.

  SSLtcl does not contain code only written by me. In the spirit of free
  software development a have reused code, which means that SSLtcl
  contains code, codefragments or hard to decide inspired by other code
  This code is copyrighted under other conditions than GNU/GPL

  SSLtcl contains codes from:

  tcl8.0 core

       This software is copyrighted by the Regents of the Univer-
       sity of California, Sun Microsystems, Inc., and other par-
       ties.  The following terms apply to all files associated
       with the software unless explicitly disclaimed in individual
       files.

  tclSSL

       Copyright (c) 1995-1997  Tony Bringardner

  SSLeay

       Copyright (C) 1997 Eric Young (eay@cryptsoft.com) All rights
       reserved

  apache-ssl

       Copyright (c) 1995 Ben Laurie.  All rights reserved.

  All of this code are copyrighted under somewhat more liberal rules.
  That is. It is possible to make changes to the code and incorporate
  them in to a product without releasing the new source code. This is
  not possible under GNU/GPL - and that is its intention. To do this
  with SSLtcl you would have to remove all codes written by me, and that
  would eventually mean that SSLtcl would stop working.

  That is. You are free to use and modify SSLtcl as long as my and all
  other copyright holders are not removed and as long as the sourcecode
  is made freely available.

  In my interpretation this makes it possible to use the vanilla SSLtcl
  in a commercial product without being forced to release source code
  for that product, except for SSLtcl, which - if vanilla - already is
  freely available.

  4.  Installation

  To install SSLtcl you need the sources for tcl8.0 and either
  SSLeay-0.6.6 or SSLeay-0.8.1. As for now SSLeay-0.6.6 should be
  considered some what stabler than SSLeay-0.8..1, but on the other hand
  does 0.8.1 implement SSLv3, which 0.6.6 does not.

  Both tcl and SSLeay works on many kinds of machines. SSLtcl however is
  only tested on Linux and incorporates special UNIX code from tcl which
  makes it quite unlikely that it will build on anything else than UNIX.

  You can get tcl8.0 from ftp://ftp.smli.com/pub/tcl . Even if you have
  the binaries and libraries for tcl8.0 already installed you will also
  need the source code and the contents in tclConfig.sh has to contain
  information about where to find the source. (You may edit the Makefile
  to solve this but it is up to You).

  You can get SSLeay from ftp://ftp.psy.uq.oz.au/pub/Crypto/SSL or
  mirrors. On Linux You can build both static and shared libraries for
  SSLeay. To link SSLtcl dynamically against SSLeay You have to have
  shared libraries, see further down for instructions.

  Get the source for SSLtcl and go to the directory where You wants to
  have it and unpack the source. The easiest place to have it is under
  /usr/local/src, especially if tcl and SSLeay is built and installed
  under /usr/local.

  tar -xvzf SSLtcl-0.42.tar.gz

  If the above conditions are fulfilled You can build and install SSLtcl
  with the following commands:

       make

       make install

  This will build the shared library SSLtcl.so and install it in
  /usr/local/lib. It will also install the manual page ssltcl in
  /usr/local/man/mann

  You can now read the manual with the command

       man ssltcl

  If You have any problem with that You can always use groff to read it.

       groff -Tascii -man ssltcl.n| less

  It is possible to build SSLtcl under more constrained conditions
  through the use of options to configure.

  If you don't want to install under /usr/local you can use:

       --prefix=PATH

  If you don't have the sourcecode to tcl8.0 in the same directory as
  SSLtcl or you did not use the source-code to build tcl8.0 you can
  specify an alternative location. The point is that the configure
  script needs to know where the tclConfig.sh is.

       --with-tcl=PATH

  where PATH is the library where tclConfig.sh is.

  If SSL is in a strange location You can tell configure where with the
  option

       --with-ssl=PATH

  If You have the SSL libraries in another location than under ssl/lib
  You can use the following option to tell where they are. For example
  if you have installed the shared SSL libraries under /usr/local/lib.

       --with-ssl-lib-dir=PATH

  Here is an example of building SSLtcl in /usr/src but with tcl8.0 and
  SSLeay under /usr/local and shared libraries in /usr/local/lib

  To link SSLtcl dynamically against SSLeay you have to build shared
  SSLeay libraries. This is not done in the usual SSLeay build process,
  so you have to do it your self. First build it the usual way according
  to the INSTALL instructions in SSLeay. Then you may try the following
  command

       sh shlib/linux.sh

  If any error are reported check the following things.

  1. If you are building SSLeay-0.8.1 its seems to be a bug in
  crypto/crypto.c. Uncomment the next last #endif statement, like this:

       #endif
       /*#endif*/
       #ifdef CRYPTO_PKCS7_SUBSET /* I have an excplicit removal of 7 lines */

       #include ''pkcs7/pk7_lib.c''
       #include ''pkcs7/pkcs7err.c''
       #endif
       and try again

  2. If you are building SSleay-0.6.6 you have to, at least I had to,
  build one of the needed assembly code files your self.

       cd crypto/des/asm
       perl des-som3.pl elf >dx86-elf.s

  and try again

  You then have to manually install the shared files. Copy all files,
  including symlinks, that contain an .so. That is libcrypto.so and
  libssl.so and friends to the place you want them. Remember to att the
  directory to /etc/ld.so.conf if its not there all ready an run:

       ldconfig

  You the load the module into your tcl applications by the command:

       load /usr/local/lib/SSLtcl.so SSLtcl

  and then you can use the socket command with ssl features.Read the
  manual pages or look in the demo directory.

  5.  SSLtcl Manual Page

  5.1.  NAME

  SSLtcl - a loadable module that extends the tcl socket command with
  SSL

  5.2.  SYNOPSIS

  load $PATH/SLtcl.so SSLtcl

  socket [-myaddr addr] [-myport myport] [-async] [-ssl [-verify NUM]
  [-cert Certificate] [-key privateKey] [-CAfile CAfile] [-CAdir CAdir]
  ] host port

  socket  -server command [-ssl -cert Certificate [-key privateKey]
  [-verify NUM] [-Verify NUM] [-CAfile CAfile] [-CAdir CAdir] [-myaddr
  addr] port

  5.3.  DESCRIPTION

  SSLtcl creates a new tcl socket command with SSL capabilities. Se
  socket(n) for a description of the tcl socket command. Used with -ssl
  option it creates a SSL based connection. If -ssl is left out it
  function as the normal socket command and only options described in
  socket(n) is available. SSLtcls socket creates either a server SSL
  socket or a client SSL socket, exactly as the normal socket command.

  5.4.  CLIENT SOCKET

  If the -server option is not specified,  then  the  client side  of a
  connection is opened and the command returns a channel identifier that
  can be used for both  reading  and writing.   Port  and  host specify
  a port to connect to;  there must be a server accepting connections on
  this port. Port  is  an  integer  port  number  and  host is either a
  domain-style name such as www.sunlabs.com or  a  numerical IP  address
  such as 127.0.0.1.  Use localhost to refer to the host on which the
  command is invoked. The following options may also be present before
  host  to specify additional information about the connection:

     -myaddr addr
        Addr  gives  the  domain-style name or numerical IPaddress of
        the client-side network interface to use for  the  connection.
        This option may be useful if  the client machine has multiple
        network interfaces. If  the  option is  omitted  then  the
        client-side interface will be chosen by the system software.

      -myport port
        Port specifies an integer port number  to  use  for the
        client's  side of  the  connection.   If this option is omitted,
        the client's port number will bechosen at random by the system
        software.

       -async
        The  -async  option will cause the client socket to be connected
        asynchronously. This  means  that  the socket  will be created
        immediately but may not yet be connected to the server, when the
        call to socket  returns. When a gets or flush is done on the
        socket  before the connection attempt succeeds or fails, if  the
        socket is in blocking mode, the operation will  wait until the
        connection is completed or fails. If  the  socket  is  in
        nonblocking mode and a gets or flush is done on the socket
        before  the  connection attempt succeeds  or  fails, the
        operation returns  immediately and fblocked on the socket
        returns 1.

     -ssl
        The -ssl option turns SSL on an makes the following options
        available.

     -verify num
        Turns verification of server on. num is an integer that
        specifies how deep in the certificate chain verification is
        required to succeed.

     -key privateKey
        Specifies the private key that accompanies the own certificate.
        A certificate is only required for the client if it is going to
        be verified by the server. If left out will be set to the same
        value as given for -cert.

     -cert Certificate
        The client certificate, pem encoded, that it will send to the
        server if required.

     -CAfile CAfile
        A file containing certificates from Certificate Authorities that
        the client wants to trust. To verify a server a CAfile, or a
        CAdir, is required.

     -CAdir CAdir
        A hashed directory that contains certificates from Certificate
        Authorities that the client wants to trust. To verify a server a
        CAdir, or a CAfile, is required.

     -ciphers cipherlist
        cipherlist is a colon separated list of ciphers that the clients
        wants to support. The first one will be tried first, and so on.
        See Supported ciphers below.

  5.5.  SERVER SOCKET

  If the -server option is specified  then  the  new  socket will  be a
  server  for the port given by port.  Tcl will automatically accept
  connections to the given  port.   For each  connection Tcl will create
  a new channel that may be used to communicate with the  client.   Tcl
  then  invokes command  with  three additional arguments: the name of
  the new channel, the address, in network address notation,  of  the
  client's host, and the client's port number. The  following
  additional  option  may  also be specified before host:

     -myaddr addr
        Addr gives the domain-style name  or  numerical  IP address of
        the server-side network interface to use for the connection.
        This option may be useful  if  the server machine has multiple
        network interfaces.  If the option is omitted then the server
        socket  is bound  to the special address INADDR_ANY so that it
        can accept connections from any interface.

     -ssl
        The -ssl option turns SSL on an makes the following options
        available.

     -verify num
        Turns verification of client on. num is an integer that
        specifies how deep in the certificate chain verification is
        required to succeed. Will only report verification result, not
        stop the connection

     -Verify num
        Same as -verify, but will stop the connection if verify fails.

     -key privateKey
        Specifies the private key that accompanies the server
        certificate.  If left out will be set to the same value as given
        for -cert.

     -cert Certificate
        The server certificate, pem encoded; it is required.

     -CAfile CAfile
        A file contaning certificates from Certificate Authorities that
        the server wants to trust. To verify a client a CAfile, or a
        CAdir, is required.

     -CAdir CAdir
        A hashed directory that contains certificates from Certificate
        Authorities that the server wants to trust. To verify a client a
        CAdir, or a CAfile, is required.

     -ciphers cipherlist
        cipherlist is a colon separated list of ciphers that the server
        wants to support. The first one will be tried first, and so on.
        See Supported ciphers below.

     -maxacloops num
        Specififies the numer of times the server should try to accept a
        connection. num is an integer. The defaultvalue is 100000. The
        option exist because of a problem with non SSL aware clients and
        server socket in non -blocking mode. Without a timeout the
        server will block for ever. I will try to find a better solution
        in the furure. If releveant connections keeps returning with
        bgerror try to increase this value.

  Server channels cannot be used for input or output;  their sole use is
  to accept new client connections. The channels created for each
  incoming client connection are opened for input  and  output.  Closing
  the server channel shuts down  the server so that no new connections
  will  be  accepted; however, existing connections will be unaffected.
  Server  sockets  depend on the Tcl event mechanism to find out when
  new connections are opened.  If  the application doesn't  enter the
  event loop, for example by invoking the vwait command or calling the C
  procedure  Tcl_DoOneEvent,  then no connections will be accepted.

  5.6.  SUPPORTED CIPHERS

  The cipeherslist is specified as a colon separated list of ciphers.
  The following cipherabrewations, and  is supported:

       RC4-MD5
       EXP-RC4-MD5
       IDEA-CBC-MD5
       RC2-CBC-MD5
       EXP-RC2-CBC-MD5
       DES-CBC-MD5
       DES-CBC-SHA
       DES-CBC3-MD5
       DES-CBC3-SHA
       DES-CFB-M1
       NULL-MD5

  If You link SSLtcl against SSLeay-0.8.1 have a look in ssl.h for adi-
  tional ciphers.

  5.7.  TIPS

  In the SSLtcl distribution there are several scripts that can be used
  to understand how sockets and sockets with ssl could be used.
  tstSrc.tcl and tstCli.tcl is two small scripts with blocking IO using
  SSL that used connects and drop the connection. tstSrvReal.tcl and
  tstCliReal.tcl uses fileevent and nonblocking with SSL. This means You
  can establish several simultaneous connection with the server and send
  messages from the clients to the server. tstSrvRealNoSSL.tcl and
  tstCliRealNoSSL.tcl are the same as the previous scripts, except that
  SSL is left out.

  You may have to change the path to tclsh8.0 and to SSLtcl.so to get it
  to work. To generate own certificates to work with, see the SSLtcl
  documentation.

  5.8.  BUGS AND FEATURES

  SSLtcl is still under development and may contain bug or badly
  implemented solutions. Contact the author if something strange
  happens.

  5.9.  AUTHOR

  Peter Antman (peter.antman@abc.se)

  SSLtcl is based on tclSSL, an earlier work by Tony Bringardner. SSLtcl
  is heavily updated compared to tclSSL but owes its basic structure and
  ideas to tclSSL.

  SSLtcl is also based on the work by Eric Young, specially s_server and
  s_client, and Ben Lauries SSL patch to apache.

  Thank You all.

  5.10.  SEE ALSO

  socket(n), and the SSLeay documentation.

  6.  Demonstrations of how to use SSLtcl

  SSLtcl main program is a loadable module SSLtcl.so which can be loaded
  by tclsh or wish at any time. It then gives the programmer access to
  an extended version of tcl sockets. If you already know how to use the
  socket command then read the manual page and get on with it.

  If you feel unsure how to use sockets under tcl then have a look in
  demo.  There you find six example programs that utilize sockets with
  SSL. They show different ways of configuring the socket under tcl.

  The tcl socket command is among the most easiest ways to create
  applications that can communicate over tcp/ip. Its most fundamental
  aspect is that it either creates a client socket that directly tries
  to connect to a server. Or it creates a server socket that listens on
  the specified port and then creates additional sockets for each client
  that connect so that is can service more than one client at a time.

  To get tcl sockets to work in this nice way you have to have it in an
  event loop and you have to configure the channel the socket is wrapped
  in so that the program can take back command when it has started
  serving a client.

  The scripts in the demo directory contain different solutions to this
  problem.

  The scripts tstCli.tcl and tstSrv.tcl is two simple scripts that
  utilize sockets and SSL in an easy way; but with the negative
  sideffect that the server only will service one client at  time.

  Lets take a look at tstCli.tcl

           9   set shouldbe [exec cat tstCli.tcl]
           10  load ../SSLtcl.so SSLtcl
           11
           ...
           16  set s [socket -ssl -verify 1 -ciphers RC4-MD5 -cert demoCA/newcert.pem -key \

           17  demoCA/newkey.pem -CAfile demoCA/cacert.pem localhost 443]

           18
           19  puts $s ''GET /''
           20  puts ''Req complete''
           21  flush $s
           22  set got ''''
           23  while { [gets $s l ] >= 0 } {
           24          if { $got == '''' } {
           25                  set got $l
           26          } else {
           27                  set got ''$got\n$l''
           28          }
           29          # puts ''RECV($l)''
           30  }
           31  close $s
           32  puts ''Client done''
           33  if { $got == $shouldbe } {
           34          puts ''Client successful!!!''
           35  } else {
           36          puts ''Bummer!!!  Client did not rec what it should have!''

           37          exit -1;
           38  }
           39

  As you see it loads in SSLtcl.so in line 10. SSLtcl.so is not as is
  common under C based applications loaded from the best found location.
  Therefore you have to specify the full path. For example

  load /usr/local/lib/SSLtcl.so SSLtcl

  tstCli.tcl is a string fall through application. On line 16 it opens a
  socket and sets certain characteristics of it. Here we make it a
  client socket which uses SSL. All possible options is used in this
  example. The application will have its own certificate and will also
  have a file which contain certificate from Certificate Authorities it
  trusts. It also tells that it will only tolerate use of a special
  cipher.

  The socket command returns a channel identifier which we now can use
  to read from and write to.

  On line 19-21 the application writes to the socket and flushed the
  channel so that it really sends something. Because we are using SSL
  the communication with the server will take place over a cryptated
  tunnel.

  We then go in a loop and wait for something to read on the channel on
  lone 23-29. When we get something we immediately closes the cannel, as
  on line 31.

  This could be the basis of a webbrowser fetching webpages. That is,
  for a connectionless protocol.

  The server tstSrv.tcl is not that useful for real life problems,
  because it blocks while servicing clients. But is fairly easy to
  understand.

            9  set data [exec cat tstCli.tcl]
           10
           11  # This is the callback procedure that has to be part of the socket call

           12  proc getit { s ip port args } {
           13          global data
           14          puts $args
           15          puts ''Server socket ($s $ip $port)''
           16          set req [gets $s];
           17          puts ''RECV($req)''
           18          if { $req == ''GET /'' } {
           19                  puts $s $data
           20          } else {
           21                  puts ''UNKNOWN request''
           22                  puts $s ''UNKNOWN request''
           23          }
           24          close $s
           25  }
           26
           27  # load the module, with full path to it
           28  load ../SSLtcl.so SSLtcl
           29  set s [socket -server getit -ssl -Verify 1 -cert \
           30  demoCA/newcert.pem -key demoCA/newkey.pem \
           31  -CAfile demoCA/cacert.pem 443]
           32  puts $s
           33  set tst 0
           34  puts ''Server waiting connection on $s''
           35
           36  # Go into the eventloop
        37     vwait tst

  The main different between the client socket and a server socket is
  that the application have to enter an event loop. A server program is
  therefore not as straight a client program. Every server socket has to
  have a command to call back when a request arrives.

  At line 29 the channel is created. As we see we have to tell tcl that
  wee want a server socket with the switch -server. This option have a
  necessary argument, namely a callback command.

  This is created on line 12-25. When a client connects this client will
  be handed over to the callback command, in this case a procedure. The
  procedure is rather straightforward. It read from the channel with
  gets (line 16). Observe that this is not the same channel as that
  returned by the socket command, but is a new channel given as a
  argument to the procedure. It then writes back to the channel with
  puts $channelid something.

  At line 36 we went into an event loop. Nothing would have happen on
  the socket channel before we did go into that loop because tcl would
  not know how to handle the callback but would be busy doing other
  things.

  A connections is closed by closing the connection socket. The server
  socket is closed first when you close the channel you got back from
  the socket command.

  To do something more useful one would like at least the server to be
  able to respond to more than one client at a time. tstSrvReal is an
  example of such a client. It is basically build on two callback. One
  for the server socket to call, and one for every connections socket to
  call. To get a callback from every socket when it need attention wee
  have to configure it for that. This is done with the command filevent.
  At line 36 you can see how it is used in this example.

          9       # server writing back to client
      10  proc getit_fork {s l} {
      11          puts $s $l
      12          flush $s
      13  }
      14
      15  # the callback from filevent
      16  proc getit_hand {s} {
      17          puts filevent
      18            set l [gets $s]    ;# get the client packet
      19          puts ''got $l''
      20          if {[eof $s]} {    ;# client gone or finished
      21                  close $s        ;# release the servers client channel

      22          } elseif {$l == ''Q''} {
      23                  close $s
      24                  exit
      25          } elseif {$l == ''q''} {
      26                  close $s
      27                  return
      28          } else {
      29                  getit_fork $s $l
      30          }
      31  }
      32
      33  # The connection callback, called from ssl
      34  proc getit { s ip port args } {
      35          puts ''in getit''
      36          fileevent $s readable [list getit_hand $s]
      37
      38
      39          fconfigure $s -buffering line -blocking 0
      40          return
      41
      42  }
      43
      44  # load the module
      45  load ../SSLtcl.so SSLtcl
      46
      47  # create socket, with ssl
      48  set s [socket -server getit -ssl -Verify 1 -cert \
      49  demoCA/newcert.pem -key demoCA/newkey.pem \
      50  -CAfile /home/peter/ssl/demoCA/cacert.pem 443]
      51  puts ''Server waiting connection on $s''
      52
      53  # Go into the eventloop
    54    vwait events

  The main part of the program is rather short. On line 45 to 54 we load
  the module, creates the socket and goes into the event loop.

  But in the callback procedure we give to the -server option we behave
  differently. There we instead gives a new callback, configures the new
  channel and returns so that the main program can continue on.

  The filevent command is used to get tcl to call a procedure when there
  is something happening on the cannel. In our case we want is to call
  the procedure getit_hand when the channel is readable. And we send the
  new channel as an argument.

  We also configure the cannel. Especially useful is to configure it for
  non blocking mode. If we do not do that the server will not be able to
  service new client until the first connected has at least send
  something, which means that a client could easily freeze the whole
  server.

  In the new callback we read in what's in the socket and examine its
  connect. Useful is to check for End Of File, which is done on line 20
  so that we know if the client has disappeared.

  The stsCliReal.tcl is based on the same principles that tstSrvReal,
  that is, we implement an event loop and a callback even in the client.
  This is particularly good for connections that will be durable.

          9       load ../SSLtcl.so SSLtcl
      10
      11  #  I'm repeating this a few times to check for
      12  #  problems that may accumulate like file descriptor not being

      13  #  closed.
      14  proc read_sock {sock} {
      15    set l [gets $sock]
      16          if {[eof $sock]} {
      17                  close $sock
      18                  set eventLoop ''done''
      19          }
      20    puts stdout ''ServerReply:$l''
      21  }
      22
      23  # Read a line of text from stdin and send it to the echoserver socket,

      24  # on eof stdin closedown the echoserver client socket connection

      25  # this implements sending a message to the Server.
      26  proc read_stdin {wsock} {
      27          global  eventLoop
      28          set l [gets stdin]
      29          puts ''l: $l''
      30          if {[eof stdin]} {
      31                  close $wsock             ;# close the socket client connection

      32                  set eventLoop ''done''     ;# terminate the vwait (eventloop)

      33          } elseif {$l == ''Q''} {
      34                  puts $wsock $l
      35                  close $wsock
      36                  exit
      37          } elseif {$l == ''q''} {
      38                  puts $wsock $l
      39                  close $wsock
      40                  exit
      41          } else {
      42                  puts $wsock $l           ;# send the data to the server

      43    }
      44  }
      45
      46  # Create the socket and ssl enables it
      47  set s [socket -ssl -verify 1 -ciphers RC4-MD5 -cert demoCA/newcert.pem -key \

      48  demoCA/newkey.pem -CAfile demoCA/cacert.pem localhost 443]

      49
      50  puts $s
      51  fileevent $s readable [list read_sock $s]
      52  fconfigure $s -buffering line
      53  fileevent stdin readable [list read_stdin $s]
      54  vwait eventLoop
      55  puts ''Finished''

  In this we create the socket and then a callback for that socket with
  filevent on lines 47 and 51. We also creates a callback for
  standardin. This means that we can type something on the screen at it
  will be sent to the server. If something is on standardin we read it
  and sends it to the server.  If something is on the socket, we reads
  it and prints it to the terminal. On line 54 we go into an eventloop
  by waiting on an event on the variable eventLoop.

  The two scripts tstSrvRealNoSSL.tcl and tstCliRealNoSSL.tcl is exactly
  the same as the above scripts, except that they do not configure the
  socket for SSL (but it uses the socket command provided by SSLtcl.)

  7.  Certificate questions

  To do something really useful with SSL (and thereby SSLtcl) one have
  to be able to handle certificate. This can sometimes be a little hard
  to learn, so here are a few word about what to do to create
  certificates.

  Autentication in SSL is partly done through a chain of signed
  certificates, where there somewhere in the end is a signer that you
  have good reason to trust. For Netscape-servers and clients, and even
  for apache-ssl, there are certain organizations that acts as
  Certificate Authorities. To have a website that people really know are
  your you can create a certificate and get an authority that everybody
  trust to guaranty that this certificate it really yours.

  In the lingua franca of SSL (and SSLtcl) we can hereby speak of two
  different kind of certificate. One is a CA certificate. That is, it is
  a certificate that you uses to verify other certificates against. The
  other is your own certificate, that is signed by someone else, in
  SSLtcl called cert.  You will also have a private key that accompanies
  the certificate (where your public key is).

  I don't know if any CA will sign certificates for use in SSLtcl based
  applications. But you can set up your own CA and creates your own
  certificates.

  In the demo directory there is includes a demoCA directory. In it I
  have placed a demo CA certificate and a signed certificate. The
  private keys are removed prom there password so that they can be used
  by anybody.

  But when you start using SSLtcl you probably wants to create your own
  certificates. The easiest way to do that is to use the script CA.sh in
  the demo directory. This is a slightly modified version of the CA.sh
  that comes with SSLeay.

  Create a directory where you want to store your certificates and copy
  CA.sh there or start ut with its full path. The following command will
  set a demoCA up for you and create a CA certificate, that is a self
  signed certificate.

       CH.sh -newca

  You will be asked some questions, just answer them the best you can.
  If you are running a website you should however pay attention to the
  question about your common name. Several clients demand that this is
  not your personal name but the domainname of the server.

  You are now a CA authority. Time to sign some certificates. You begin
  by creating a certificate request:

       CA.sh -newreq

  and answers the questions again. Now you send it to your CA which is
  you and you sign it:

       CA.sh -sign

  By now you have a CAfile, a cert and a key. The key to use is the key
  that was generated when you did your request, not your CA. As you saw
  you had to fill in a password or passphrase each time you generated a
  certificate. This is to protect the private key. Anybody thats gets
  hold of your plain private key can pretend his you. So it should be
  protected. But sometimes it is quite boring to have to type the
  passfrase every time you do something with a key.  Luckily the
  passfrase can be removed with the following command:

       ssleay rsa -in key.pwprotected -out key.plain

  You will find ssleay in the bin directory under ssl.

  I couple of questions might remain.

  How to I do to get a (Netscape) client to accept my new CA?

  Here is a small cgi-bin script that handle just that. You call it
  without argument from a webpage and the client will have it send to
  it, and reject or save it.

  The only thing you have to do is to convert your CA from pem to der
  encoded this way:

       x509 -inform pem -outform der < newca.pem > newca.der

       #!/bin/sh
       # ca-cert.sh
       #
       # (c) Peter Antman, 1997.
       #
       # cgi-bin-script to send a server ca file to netscape.
       # The script is called witout any argument, and the der-encoded certificate

       # is specified in the variable ''certfile''

       certfile=/home/www/certs/newca.der

       if [ -e $certfile ]; then
               echo ''Content-Type: application/x-x509-ca-cert''; echo

               cat $certfile
       else

               cat << END
       Content-Type: text/html

       <HTML>
       <HEAD><TITLE>Certificate not found!

       <BODY>
       <B>Sorry, I can't find the certificate I had planned to send back.  Please tr

       y again some other time.

       END
       fi

       exit 0

  How do I sign a client certificate for Netscape?

  This is also a good question for a server maintainer. Client
  authentication through certificates and SSL can be a good way of
  server data only to people you really know who they are.

  For Netscape there is a special FORM tag in html that can be used to
  get Netscape to generate a certificate request and send it (and also
  get it back with a special mime format). Here is a perl cgi-bin script
  that does just that. It is selfexplaining. Just one thing should be
  said. It actually does three separate things that actual could be done
  separately. It gets the request, it signs the request, and it sends it
  back.

  #!/usr/bin/perl -T
  # client
  #
  #(c) Peter Antman, 1997.
  #
  # This script handles at client-sertificate request from a form
  # containinggen the keygen name pair.
  #

  $ENV{PATH} = '/bin:/usr/bin:/usr/local/ssl/bin';

  $tempfil = ''/tmp/client-req'';
  $utfil = ''/tmp/client-cert.der'';

  $online = ''/tmp/online-cert'';

  # the ca program
  $passwd = oph84ov; # Password for your private key

  # Command for the ca-program to make a client certificate
  $ca = ''/usr/local/ssl/bin/ca -config /usr/local/ssl/lib/min.cnf -key oph84ov -spkac /tmp/client-req -out /tmp/client-cert.der'';

  #$arg =  ''-config /usr/local/ssl/lib/min.cnf -key oph84ov -spkac /tmp/client-req -out /tmp/client-cert.der'';

  #@args = (''-config /usr/local/ssl/lib/min.cnf'', ''-key oph84ov'', ''spkac /tmp/client-req'', ''-out /tmp/client-cert.der'');

  #Tar in postdata
  if ($ENV{''REQUEST_METHOD''} eq ''POST'') {
                  # Get the input
      read(STDIN, $buffer, $ENV{'CONTENT_LENGTH'});
                  # Split the name-value pairs
      @pairs = split(/&/, $buffer);
                  # Load the FORM variables
           foreach $pair (@pairs) {
               ($name, $value) = split(/=/, $pair);
               $value =~ tr/+/ /;
               $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack(''C'', hex($1))/eg;

               $FORM{$name} = $value;
           }

  # Print the request to a temporary file. Should we untaint the form-variables

  # with a REGEXP?

      open (h, ''>$tempfil'');

      print h ''C = $FORM{land}\n'';
      print h ''SP = $FORM{stad}\n'';
      print h ''O = $FORM{org}\n'';
      print h ''CN = $FORM{namn}\n'';
      print h ''Email = $FORM{epost}\n'';

  # This is kinky, the newlines have to be escaped with an ''\''

      $FORM{key} =~ s/\n/\\\n/g;

      print h ''SPKAC = $FORM{key}'';

      close h;

  # make the client certificate; untained with PATH set. In reality all the

  # elements in the form, including SPKAC ougt to be considered tainted. But

  # if there is not a bug in ca they are not harmfull, because they are not

  # passed trough the shell

      system $ca;

  # make an x509 online version to use for individual client certification with

  # apache-sll

      if (-e ''$online''){
           open (f, ''>>$online'');
       }
      else{
            open (f, ''>$online'');
        }

      print f ''/C=$FORM{land}/SP=$FORM{stad}/O=$FORM{org}/CN=$FORM{namn}/Email=$FORM{epost}:xxj31ZMTZzkVA\n'';

      close f;

  # Send the client certificate to the browser

      print ''Content-type: application/x-x509-user-cert\n\n'';

      open (h, ''$utfil'');
      while (<h>){
          print
          }

  }

  If you plan to get serious in your certification business you should
  have a look in ssleay.cof. This is the default format file for
  certificate generation and it contains sections that you will have to
  change directly in this file.  You should create your own format file
  and learn how to feed it to SSLeay when you handle certificates.

