Class: Rack::TCTP

Inherits:
Object
  • Object
show all
Defined in:
lib/rack/tctp.rb,
ext/engine/engine.c

Overview

This middleware enables Rack to make use of the Trusted Cloud Transfer Protocol (TCTP) for HTTP end-to-end body confidentiality and integrity.

Defined Under Namespace

Classes: ClientHALEC, Engine, HALEC, SSLError, ServerHALEC

Constant Summary collapse

DEFAULT_TCTP_DISCOVERY_INFORMATION =
'/.*:/halecs'
TCTP_DISCOVERY_MEDIA_TYPE =
'text/prs.tctp-discovery'
TCTP_MEDIA_TYPE =
'binary/prs.tctp'

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(app, logger = nil) ⇒ TCTP

Initializes TCTP middleware



28
29
30
31
32
33
34
35
36
37
38
# File 'lib/rack/tctp.rb', line 28

def initialize(app, logger = nil)
  unless logger
    @logger = ::Logger.new(STDOUT)
    @logger.level = ::Logger::FATAL
  else
    @logger = logger
  end

  @app = app
  @sessions = {}
end

Instance Attribute Details

#sessionsObject (readonly)

The TCTP sessions



25
26
27
# File 'lib/rack/tctp.rb', line 25

def sessions
  @sessions
end

Class Method Details

.new_slugObject

Generate a new random slug (2^64 possibilities)



20
21
22
# File 'lib/rack/tctp.rb', line 20

def self.new_slug
  slug_base.convert(rand(2**64), 10)
end

.slug_baseObject

The slug URI can contain any HTTP compatible characters



15
16
17
# File 'lib/rack/tctp.rb', line 15

def self.slug_base
  Radix::Base.new(Radix::BASE::B62 + ['-', '_'])
end

Instance Method Details

#call(env) ⇒ Object

Middleware call. Supports all TCTP use cases:

  • TCTP discovery

  • HALEC creation

  • HALEC handshake

  • Decrypting TCTP secured entity-bodies

  • Encrypting entity-bodies using TCTP



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
# File 'lib/rack/tctp.rb', line 46

def call(env)
  status, headers, body = nil, nil, nil

  begin
    req = Rack::Request.new(env)

    case
      when is_tctp_discovery?(req)
        # TCTP discovery
        # TODO Parameterize discovery information
        [200, {"Content-Type" => TCTP_DISCOVERY_MEDIA_TYPE, "Content-Length" => DEFAULT_TCTP_DISCOVERY_INFORMATION.length.to_s}, [DEFAULT_TCTP_DISCOVERY_INFORMATION]]
      when is_halec_creation?(req)
        # HALEC creation
        halec = ServerHALEC.new(url: halec_uri(req.env, "/halecs/#{TCTP::new_slug}"))

        session = sessions[req.cookies['tctp_session_cookie']] || TCTPSession.new

        # Send client_hello to server HALEC and read handshake_response
        client_hello = req.body.read
        halec.engine.inject client_hello
        halec.engine.read
        handshake_response = [halec.engine.extract]

        # Set location header and content-length
        header = {
            'Location' => halec.url.to_s,
            'Content-Length' => handshake_response[0].length.to_s,
            'Content-Type' => TCTP_MEDIA_TYPE
        }

        # Set the TCTP session cookie header
        Rack::Utils.set_cookie_header!(header, "tctp_session_cookie", {:value => session.session_id, :path => '/', :expires => Time.now+24*60*60})

        # Persist session and HALEC
        session.push_halec(halec)
        sessions[session.session_id] = session

        [201, header, handshake_response]
      when is_halec_handshake?(req)
        # Get persisted server HALEC
        halec = @sessions[req.cookies['tctp_session_cookie']].halecs[halec_uri(req.env, req.path_info)]

        # Write handshake message to server HALEC
        halec.engine.inject req.body.read

        # Receive handshake response
        halec.engine.read
        handshake_response = halec.engine.extract

        # Send back server HALEC response
        [200, {
            'Content-Length' => handshake_response.length.to_s,
            'Content-Type' => TCTP_MEDIA_TYPE
        }, [handshake_response]]
      else
        # Decrypt TCTP secured bodies
        if is_tctp_encrypted_body?(req) then
          decrypted_body = StringIO.new

          halec_url = req.body.gets.chomp

          # Gets the HALEC
          halec = @sessions[req.cookies['tctp_session_cookie']].halecs[URI(halec_url)]

          read_body = req.body.read

          begin
            decrypted_body.write halec.decrypt_data(read_body)
          rescue Exception => e
            error(e.message + e.backtrace.join("<br/>\n"))
          end

          decrypted_body.rewind

          env['rack.input'] = decrypted_body
        end

        status, headers, body = @app.call(env)

        if is_tctp_response_requested?(req) && status >= 200 && ![204, 205, 304].include?(status)
          # Gets the first free server HALEC for encryption
          # TODO Send error if cookie is missing
          session = @sessions[req.cookies['tctp_session_cookie']]

          unless session
            return no_usable_halec_error
          end

          halec = session.pop_halec

          unless halec
            return no_usable_halec_error
          end

          # The length of the content body
          content_body_length = 0

          # The first line
          first_line = halec.url.to_s + "\r\n"
          content_body_length += first_line.length

          # Encrypt the body. The first line of the response specifies the used HALEC
          encrypted_body = []
          encrypted_body << first_line

          # Encrypt each body fragment
          body.each do |fragment|
            encrypted_fragment = halec.encrypt_data fragment
            encrypted_body << encrypted_fragment
            content_body_length += encrypted_fragment.length
          end

          encrypted_body.define_singleton_method :close do
            session.push_halec halec

            super() if self.class.superclass.respond_to? :close
          end

          # Finding this bug took waaaay too long ...
          body.close if body.respond_to?(:close)

          # Sets the content length and encoding
          headers['Content-Length'] = content_body_length.to_s
          headers['Content-Encoding'] = 'encrypted'

          [status, headers, encrypted_body]
        else
          [status, headers, body]
        end
    end
  rescue Exception => e
    # TODO Handle SSL Error
    @logger.fatal e

    error "Error in TCTP middleware. #{e} #{e.backtrace.inspect}"
  end
end