* io.c (rb_open_file): encoding in mode string was ignored if perm is
[ruby-svn.git] / sample / openssl / echo_svr.rb
blob719de6be843627b38724085394939b9f6ce4962c
1 #!/usr/bin/env ruby
3 require 'socket'
4 require 'openssl'
5 require 'optparse'
7 options = ARGV.getopts("p:c:k:C:")
9 port      = options["p"] || "2000"
10 cert_file = options["c"]
11 key_file  = options["k"]
12 ca_path   = options["C"]
14 if cert_file && key_file
15   cert = OpenSSL::X509::Certificate.new(File::read(cert_file))
16   key  = OpenSSL::PKey::RSA.new(File::read(key_file))
17 else
18   key = OpenSSL::PKey::RSA.new(512){ print "." }
19   puts
20   cert = OpenSSL::X509::Certificate.new
21   cert.version = 2
22   cert.serial = 0
23   name = OpenSSL::X509::Name.new([["C","JP"],["O","TEST"],["CN","localhost"]])
24   cert.subject = name
25   cert.issuer = name
26   cert.not_before = Time.now
27   cert.not_after = Time.now + 3600
28   cert.public_key = key.public_key
29   ef = OpenSSL::X509::ExtensionFactory.new(nil,cert)
30   cert.extensions = [
31     ef.create_extension("basicConstraints","CA:FALSE"),
32     ef.create_extension("subjectKeyIdentifier","hash"),
33     ef.create_extension("extendedKeyUsage","serverAuth"),
34     ef.create_extension("keyUsage",
35                         "keyEncipherment,dataEncipherment,digitalSignature")
36   ]
37   ef.issuer_certificate = cert
38   cert.add_extension ef.create_extension("authorityKeyIdentifier",
39                                          "keyid:always,issuer:always")
40   cert.sign(key, OpenSSL::Digest::SHA1.new)
41 end
43 ctx = OpenSSL::SSL::SSLContext.new()
44 ctx.key = key
45 ctx.cert = cert
46 if ca_path
47   ctx.verify_mode =
48     OpenSSL::SSL::VERIFY_PEER|OpenSSL::SSL::VERIFY_FAIL_IF_NO_PEER_CERT
49   ctx.ca_path = ca_path
50 else
51   $stderr.puts "!!! WARNING: PEER CERTIFICATE WON'T BE VERIFIED !!!"
52 end
54 tcps = TCPServer.new(port)
55 ssls = OpenSSL::SSL::SSLServer.new(tcps, ctx)
56 loop do
57   ns = ssls.accept
58   puts "connected from #{ns.peeraddr}"
59   while line = ns.gets
60     puts line.inspect
61     ns.write line
62   end
63   puts "connection closed"
64   ns.close
65 end