src/ssl.lua

1
------------------------------------------------------------------------------
2
-- LuaSec 0.4
3
-- Copyright (C) 2006-2009 Bruno Silvestre
4
--
5
------------------------------------------------------------------------------
6
 
7
module("ssl", package.seeall)
8
 
9
require("ssl.core")
10
require("ssl.context")
11
require("ssl.x509")
12
 
13
 
14
_VERSION   = "0.4"
15
_COPYRIGHT = "LuaSec 0.4 - Copyright (C) 2006-2009 Bruno Silvestre\n" .. 
16
             "LuaSocket 2.0.2 - Copyright (C) 2004-2007 Diego Nehab"
17
 
18
-- Export functions
19
rawconnection = core.rawconnection
20
rawcontext    = context.rawcontext
21
loaddhparams  = context.loaddhparams
22
 
23
cert_from_pem = x509.cert_from_pem
24
 
25
--
26
--
27
--
28
local function optexec(func, param, ctx)
29
  if param then
30
    if type(param) == "table" then
31
      return func(ctx, unpack(param))
32
    else
33
      return func(ctx, param)
34
    end
35
  end
36
  return true
37
end
38
 
39
--
40
--
41
--
42
function newcontext(cfg)
43
   local succ, msg, ctx
44
   -- Create the context
45
   ctx, msg = context.create(cfg.protocol)
46
   if not ctx then return nil, msg end
47
   -- Mode
48
   succ, msg = context.setmode(ctx, cfg.mode)
49
   if not succ then return nil, msg end
50
   -- Load the key
51
   if cfg.key then
52
      succ, msg = context.loadkey(ctx, cfg.key, cfg.password)
53
      if not succ then return nil, msg end
54
   end
55
   -- Load the certificate
56
   if cfg.certificate then
57
      succ, msg = context.loadcert(ctx, cfg.certificate)
58
      if not succ then return nil, msg end
59
   end
60
   -- Load the CA certificates
61
   if cfg.cafile or cfg.capath then
62
      succ, msg = context.locations(ctx, cfg.cafile, cfg.capath)
63
      if not succ then return nil, msg end
64
   end
65
   -- Set the verification options
66
   succ, msg = optexec(context.setverify, cfg.verify, ctx)
67
   if not succ then return nil, msg end
68
   -- Set SSL options
69
   succ, msg = optexec(context.setoptions, cfg.options, ctx)
70
   if not succ then return nil, msg end
71
   -- Set SSL ciphers
72
   succ, msg = optexec(context.setcipher, cfg.ciphers, ctx)
73
   if not succ then return nil, msg end
74
   -- Set the depth for certificate verification
75
   if cfg.depth then
76
      succ, msg = context.setdepth(ctx, cfg.depth)
77
      if not succ then return nil, msg end
78
   end
79
   return ctx
80
end
81
 
82
--
83
--
84
--
85
function wrap(sock, cfg)
86
   local ctx, msg
87
   if type(cfg) == "table" then
88
      ctx, msg = newcontext(cfg)
89
      if not ctx then return nil, msg end
90
   else
91
      ctx = cfg
92
   end
93
   local s, msg = core.create(ctx)
94
   if s then
95
      core.setfd(s, sock:getfd())
96
      sock:setfd(core.invalidfd)
97
      return s
98
   end
99
   return nil, msg 
100
end