Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(451)

Side by Side Diff: runtime/bin/tls_socket.cc

Issue 11419138: Rename TlsSocket to SecureSocket, and all other Tls... items to Secure.... (Closed) Base URL: https://dart.googlecode.com/svn/branches/bleeding_edge/dart
Patch Set: Rename C++ class from Filter to SSLFilter. Created 8 years, 1 month ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
« no previous file with comments | « runtime/bin/tls_socket.h ('k') | runtime/bin/tls_socket_patch.dart » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
(Empty)
1 // Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file
2 // for details. All rights reserved. Use of this source code is governed by a
3 // BSD-style license that can be found in the LICENSE file.
4
5 #include "bin/tls_socket.h"
6
7 #include <errno.h>
8 #include <fcntl.h>
9 #include <sys/stat.h>
10 #include <stdio.h>
11 #include <string.h>
12
13 #include <nss.h>
14 #include <pk11pub.h>
15 #include <prerror.h>
16 #include <prinit.h>
17 #include <prnetdb.h>
18 #include <ssl.h>
19 #include <sslproto.h>
20
21 #include "bin/builtin.h"
22 #include "bin/dartutils.h"
23 #include "bin/net/nss_memio.h"
24 #include "bin/thread.h"
25 #include "bin/utils.h"
26 #include "platform/utils.h"
27
28 #include "include/dart_api.h"
29
30 bool TlsFilter::library_initialized_ = false;
31 dart::Mutex TlsFilter::mutex_; // To protect library initialization.
32 // The password is needed when creating secure server sockets. It can
33 // be null if only secure client sockets are used.
34 const char* TlsFilter::password_ = NULL;
35
36 static const int kTlsFilterNativeFieldIndex = 0;
37
38 static TlsFilter* GetTlsFilter(Dart_NativeArguments args) {
39 TlsFilter* filter;
40 Dart_Handle dart_this = ThrowIfError(Dart_GetNativeArgument(args, 0));
41 ASSERT(Dart_IsInstance(dart_this));
42 ThrowIfError(Dart_GetNativeInstanceField(
43 dart_this,
44 kTlsFilterNativeFieldIndex,
45 reinterpret_cast<intptr_t*>(&filter)));
46 return filter;
47 }
48
49
50 static void SetTlsFilter(Dart_NativeArguments args, TlsFilter* filter) {
51 Dart_Handle dart_this = ThrowIfError(Dart_GetNativeArgument(args, 0));
52 ASSERT(Dart_IsInstance(dart_this));
53 ThrowIfError(Dart_SetNativeInstanceField(
54 dart_this,
55 kTlsFilterNativeFieldIndex,
56 reinterpret_cast<intptr_t>(filter)));
57 }
58
59
60 void FUNCTION_NAME(TlsSocket_Init)(Dart_NativeArguments args) {
61 Dart_EnterScope();
62 Dart_Handle dart_this = ThrowIfError(Dart_GetNativeArgument(args, 0));
63 TlsFilter* filter = new TlsFilter;
64 SetTlsFilter(args, filter);
65 filter->Init(dart_this);
66 Dart_ExitScope();
67 }
68
69
70 void FUNCTION_NAME(TlsSocket_Connect)(Dart_NativeArguments args) {
71 Dart_EnterScope();
72 Dart_Handle host_name_object = ThrowIfError(Dart_GetNativeArgument(args, 1));
73 Dart_Handle port_object = ThrowIfError(Dart_GetNativeArgument(args, 2));
74 Dart_Handle is_server_object = ThrowIfError(Dart_GetNativeArgument(args, 3));
75 Dart_Handle certificate_name_object =
76 ThrowIfError(Dart_GetNativeArgument(args, 4));
77
78 const char* host_name = NULL;
79 // TODO(whesse): Is truncating a Dart string containing \0 what we want?
80 ThrowIfError(Dart_StringToCString(host_name_object, &host_name));
81
82 int64_t port;
83 if (!DartUtils::GetInt64Value(port_object, &port) ||
84 port < 0 || port > 65535) {
85 Dart_ThrowException(DartUtils::NewDartArgumentError(
86 "Illegal port parameter in _TlsFilter.connect"));
87 }
88
89 if (!Dart_IsBoolean(is_server_object)) {
90 Dart_ThrowException(DartUtils::NewDartArgumentError(
91 "Illegal is_server parameter in _TlsFilter.connect"));
92 }
93 bool is_server = DartUtils::GetBooleanValue(is_server_object);
94
95 const char* certificate_name = NULL;
96 // If this is a server connection, get the certificate to connect with.
97 // TODO(whesse): Use this parameter for a client certificate as well.
98 if (is_server) {
99 if (!Dart_IsString(certificate_name_object)) {
100 Dart_ThrowException(DartUtils::NewDartArgumentError(
101 "Non-String certificate parameter in _TlsFilter.connect"));
102 }
103 ThrowIfError(Dart_StringToCString(certificate_name_object,
104 &certificate_name));
105 }
106
107 GetTlsFilter(args)->Connect(host_name,
108 static_cast<int>(port),
109 is_server,
110 certificate_name);
111 Dart_ExitScope();
112 }
113
114
115 void FUNCTION_NAME(TlsSocket_Destroy)(Dart_NativeArguments args) {
116 Dart_EnterScope();
117 TlsFilter* filter = GetTlsFilter(args);
118 SetTlsFilter(args, NULL);
119 filter->Destroy();
120 delete filter;
121 Dart_ExitScope();
122 }
123
124
125 void FUNCTION_NAME(TlsSocket_Handshake)(Dart_NativeArguments args) {
126 Dart_EnterScope();
127 GetTlsFilter(args)->Handshake();
128 Dart_ExitScope();
129 }
130
131
132 void FUNCTION_NAME(TlsSocket_RegisterHandshakeCompleteCallback)(
133 Dart_NativeArguments args) {
134 Dart_EnterScope();
135 Dart_Handle handshake_complete =
136 ThrowIfError(Dart_GetNativeArgument(args, 1));
137 if (!Dart_IsClosure(handshake_complete)) {
138 Dart_ThrowException(DartUtils::NewDartArgumentError(
139 "Illegal argument to RegisterHandshakeCompleteCallback"));
140 }
141 GetTlsFilter(args)->RegisterHandshakeCompleteCallback(handshake_complete);
142 Dart_ExitScope();
143 }
144
145
146 void FUNCTION_NAME(TlsSocket_ProcessBuffer)(Dart_NativeArguments args) {
147 Dart_EnterScope();
148 Dart_Handle buffer_id_object = ThrowIfError(Dart_GetNativeArgument(args, 1));
149 int64_t buffer_id = DartUtils::GetIntegerValue(buffer_id_object);
150 if (buffer_id < 0 || buffer_id >= TlsFilter::kNumBuffers) {
151 Dart_ThrowException(DartUtils::NewDartArgumentError(
152 "Illegal argument to ProcessBuffer"));
153 }
154
155 intptr_t bytes_read =
156 GetTlsFilter(args)->ProcessBuffer(static_cast<int>(buffer_id));
157 Dart_SetReturnValue(args, Dart_NewInteger(bytes_read));
158 Dart_ExitScope();
159 }
160
161
162 void FUNCTION_NAME(TlsSocket_SetCertificateDatabase)
163 (Dart_NativeArguments args) {
164 Dart_EnterScope();
165 Dart_Handle certificate_database_object =
166 ThrowIfError(Dart_GetNativeArgument(args, 0));
167 // Check that the type is string, and get the UTF-8 C string value from it.
168 const char* certificate_database = NULL;
169 if (Dart_IsString(certificate_database_object)) {
170 ThrowIfError(Dart_StringToCString(certificate_database_object,
171 &certificate_database));
172 } else {
173 Dart_ThrowException(DartUtils::NewDartArgumentError(
174 "Non-String certificate directory argument to SetCertificateDatabase"));
175 }
176
177 Dart_Handle password_object = ThrowIfError(Dart_GetNativeArgument(args, 1));
178 // Check that the type is string or null,
179 // and get the UTF-8 C string value from it.
180 const char* password = NULL;
181 if (Dart_IsString(password_object)) {
182 ThrowIfError(Dart_StringToCString(password_object, &password));
183 } else if (Dart_IsNull(password_object)) {
184 // Pass the empty string as the password.
185 password = "";
186 } else {
187 Dart_ThrowException(DartUtils::NewDartArgumentError(
188 "Password argument to SetCertificateDatabase is not a String or null"));
189 }
190
191 TlsFilter::InitializeLibrary(certificate_database, password);
192 Dart_ExitScope();
193 }
194
195
196 void TlsFilter::Init(Dart_Handle dart_this) {
197 string_start_ = ThrowIfError(
198 Dart_NewPersistentHandle(DartUtils::NewString("start")));
199 string_length_ = ThrowIfError(
200 Dart_NewPersistentHandle(DartUtils::NewString("length")));
201
202 InitializeBuffers(dart_this);
203 filter_ = memio_CreateIOLayer(kMemioBufferSize);
204 }
205
206
207 void TlsFilter::InitializeBuffers(Dart_Handle dart_this) {
208 // Create TlsFilter buffers as ExternalUint8Array objects.
209 Dart_Handle dart_buffers_object = ThrowIfError(
210 Dart_GetField(dart_this, DartUtils::NewString("buffers")));
211 Dart_Handle dart_buffer_object =
212 Dart_ListGetAt(dart_buffers_object, kReadPlaintext);
213 Dart_Handle tls_external_buffer_class =
214 Dart_InstanceGetClass(dart_buffer_object);
215 Dart_Handle dart_buffer_size = ThrowIfError(
216 Dart_GetField(tls_external_buffer_class, DartUtils::NewString("SIZE")));
217 buffer_size_ = DartUtils::GetIntegerValue(dart_buffer_size);
218 if (buffer_size_ <= 0 || buffer_size_ > 1024 * 1024) {
219 Dart_ThrowException(
220 DartUtils::NewString("Invalid buffer size in _TlsExternalBuffer"));
221 }
222
223 Dart_Handle data_identifier = DartUtils::NewString("data");
224 for (int i = 0; i < kNumBuffers; ++i) {
225 dart_buffer_objects_[i] = ThrowIfError(
226 Dart_NewPersistentHandle(Dart_ListGetAt(dart_buffers_object, i)));
227 buffers_[i] = new uint8_t[buffer_size_];
228 Dart_Handle data = ThrowIfError(
229 Dart_NewExternalByteArray(buffers_[i], buffer_size_, NULL, NULL));
230 ThrowIfError(Dart_SetField(dart_buffer_objects_[i],
231 data_identifier,
232 data));
233 }
234 }
235
236
237 void TlsFilter::RegisterHandshakeCompleteCallback(Dart_Handle complete) {
238 ASSERT(NULL == handshake_complete_);
239 handshake_complete_ = ThrowIfError(Dart_NewPersistentHandle(complete));
240 }
241
242
243 void TlsFilter::InitializeLibrary(const char* certificate_database,
244 const char* password) {
245 MutexLocker locker(&mutex_);
246 if (!library_initialized_) {
247 library_initialized_ = true;
248 password_ = strdup(password); // This one copy persists until Dart exits.
249 PR_Init(PR_USER_THREAD, PR_PRIORITY_NORMAL, 0);
250 // TODO(whesse): Verify there are no UTF-8 issues here.
251 SECStatus status = NSS_Init(certificate_database);
252 if (status != SECSuccess) {
253 ThrowPRException("Unsuccessful NSS_Init call.");
254 }
255
256 status = NSS_SetDomesticPolicy();
257 if (status != SECSuccess) {
258 ThrowPRException("Unsuccessful NSS_SetDomesticPolicy call.");
259 }
260 // Enable TLS, as well as SSL3 and SSL2.
261 status = SSL_OptionSetDefault(SSL_ENABLE_TLS, PR_TRUE);
262 if (status != SECSuccess) {
263 ThrowPRException("Unsuccessful SSL_OptionSetDefault enable TLS call.");
264 }
265 } else {
266 ThrowException("Called TlsFilter::InitializeLibrary more than once");
267 }
268 }
269
270 char* PasswordCallback(PK11SlotInfo* slot, PRBool retry, void* arg) {
271 if (!retry) {
272 return PL_strdup(static_cast<char*>(arg)); // Freed by NSS internals.
273 }
274 return NULL;
275 }
276
277 void TlsFilter::Connect(const char* host_name,
278 int port,
279 bool is_server,
280 const char* certificate_name) {
281 is_server_ = is_server;
282 if (in_handshake_) {
283 ThrowException("Connect called while already in handshake state.");
284 }
285
286 filter_ = SSL_ImportFD(NULL, filter_);
287 if (filter_ == NULL) {
288 ThrowPRException("Unsuccessful SSL_ImportFD call");
289 }
290
291 SECStatus status;
292 if (is_server) {
293 PK11_SetPasswordFunc(PasswordCallback);
294 CERTCertDBHandle* certificate_database = CERT_GetDefaultCertDB();
295 if (certificate_database == NULL) {
296 ThrowPRException("Certificate database cannot be loaded");
297 }
298 CERTCertificate* certificate = CERT_FindCertByNameString(
299 certificate_database,
300 const_cast<char*>(certificate_name));
301 if (certificate == NULL) {
302 ThrowPRException("Cannot find server certificate by name");
303 }
304 SECKEYPrivateKey* key = PK11_FindKeyByAnyCert(
305 certificate,
306 static_cast<void*>(const_cast<char*>(password_)));
307 if (key == NULL) {
308 if (PR_GetError() == -8177) {
309 ThrowPRException("Certificate database password incorrect");
310 } else {
311 ThrowPRException("Unsuccessful PK11_FindKeyByAnyCert call."
312 " Cannot find private key for certificate");
313 }
314 }
315 // kt_rsa (key type RSA) is an enum constant from the NSS libraries.
316 // TODO(whesse): Allow different key types.
317 status = SSL_ConfigSecureServer(filter_, certificate, key, kt_rsa);
318 if (status != SECSuccess) {
319 ThrowPRException("Unsuccessful SSL_ConfigSecureServer call");
320 }
321 } else { // Client.
322 if (SSL_SetURL(filter_, host_name) == -1) {
323 ThrowPRException("Unsuccessful SetURL call");
324 }
325 }
326
327 PRBool as_server = is_server ? PR_TRUE : PR_FALSE; // Convert bool to PRBool.
328 status = SSL_ResetHandshake(filter_, as_server);
329 if (status != SECSuccess) {
330 ThrowPRException("Unsuccessful SSL_ResetHandshake call");
331 }
332
333 // SetPeerAddress
334 PRNetAddr host_address;
335 char host_entry_buffer[PR_NETDB_BUF_SIZE];
336 PRHostEnt host_entry;
337 PRStatus rv = PR_GetHostByName(host_name, host_entry_buffer,
338 PR_NETDB_BUF_SIZE, &host_entry);
339 if (rv != PR_SUCCESS) {
340 ThrowPRException("Unsuccessful PR_GetHostByName call");
341 }
342
343 int index = PR_EnumerateHostEnt(0, &host_entry, port, &host_address);
344 if (index == -1 || index == 0) {
345 ThrowPRException("Unsuccessful PR_EnumerateHostEnt call");
346 }
347 memio_SetPeerName(filter_, &host_address);
348 }
349
350
351 void TlsFilter::Handshake() {
352 SECStatus status = SSL_ForceHandshake(filter_);
353 if (status == SECSuccess) {
354 if (in_handshake_) {
355 ThrowIfError(Dart_InvokeClosure(handshake_complete_, 0, NULL));
356 in_handshake_ = false;
357 }
358 } else {
359 PRErrorCode error = PR_GetError();
360 if (error == PR_WOULD_BLOCK_ERROR) {
361 if (!in_handshake_) {
362 in_handshake_ = true;
363 }
364 } else {
365 if (is_server_) {
366 ThrowPRException("Unexpected handshake error in server");
367 } else {
368 ThrowPRException("Unexpected handshake error in client");
369 }
370 }
371 }
372 }
373
374
375 void TlsFilter::Destroy() {
376 for (int i = 0; i < kNumBuffers; ++i) {
377 Dart_DeletePersistentHandle(dart_buffer_objects_[i]);
378 delete[] buffers_[i];
379 }
380 Dart_DeletePersistentHandle(string_start_);
381 Dart_DeletePersistentHandle(string_length_);
382 Dart_DeletePersistentHandle(handshake_complete_);
383 // TODO(whesse): Free NSS objects here.
384 }
385
386
387 intptr_t TlsFilter::ProcessBuffer(int buffer_index) {
388 Dart_Handle buffer_object = dart_buffer_objects_[buffer_index];
389 Dart_Handle start_object = ThrowIfError(
390 Dart_GetField(buffer_object, string_start_));
391 Dart_Handle length_object = ThrowIfError(
392 Dart_GetField(buffer_object, string_length_));
393 int64_t unsafe_start = DartUtils::GetIntegerValue(start_object);
394 int64_t unsafe_length = DartUtils::GetIntegerValue(length_object);
395 ASSERT(unsafe_start >= 0);
396 ASSERT(unsafe_start < buffer_size_);
397 ASSERT(unsafe_length >= 0);
398 ASSERT(unsafe_length <= buffer_size_);
399 intptr_t start = static_cast<intptr_t>(unsafe_start);
400 intptr_t length = static_cast<intptr_t>(unsafe_length);
401 uint8_t* buffer = buffers_[buffer_index];
402
403 int bytes_processed = 0;
404 switch (buffer_index) {
405 case kReadPlaintext: {
406 int bytes_free = buffer_size_ - start - length;
407 bytes_processed = PR_Read(filter_,
408 buffer + start + length,
409 bytes_free);
410 if (bytes_processed < 0) {
411 ASSERT(bytes_processed == -1);
412 // TODO(whesse): Handle unexpected errors here.
413 PRErrorCode pr_error = PR_GetError();
414 if (PR_WOULD_BLOCK_ERROR != pr_error) {
415 ThrowPRException("Error reading plaintext from TlsFilter");
416 }
417 bytes_processed = 0;
418 }
419 break;
420 }
421
422 case kWriteEncrypted: {
423 const uint8_t* buf1;
424 const uint8_t* buf2;
425 unsigned int len1;
426 unsigned int len2;
427 int bytes_free = buffer_size_ - start - length;
428 memio_Private* secret = memio_GetSecret(filter_);
429 memio_GetWriteParams(secret, &buf1, &len1, &buf2, &len2);
430 int bytes_to_send =
431 dart::Utils::Minimum(len1, static_cast<unsigned>(bytes_free));
432 if (bytes_to_send > 0) {
433 memmove(buffer + start + length, buf1, bytes_to_send);
434 bytes_processed = bytes_to_send;
435 }
436 bytes_to_send = dart::Utils::Minimum(len2,
437 static_cast<unsigned>(bytes_free - bytes_processed));
438 if (bytes_to_send > 0) {
439 memmove(buffer + start + length + bytes_processed, buf2,
440 bytes_to_send);
441 bytes_processed += bytes_to_send;
442 }
443 if (bytes_processed > 0) {
444 memio_PutWriteResult(secret, bytes_processed);
445 }
446 break;
447 }
448
449 case kReadEncrypted: {
450 if (length > 0) {
451 bytes_processed = length;
452 memio_Private* secret = memio_GetSecret(filter_);
453 uint8_t* filter_buf;
454 int free_bytes = memio_GetReadParams(secret, &filter_buf);
455 if (free_bytes < bytes_processed) bytes_processed = free_bytes;
456 memmove(filter_buf,
457 buffer + start,
458 bytes_processed);
459 memio_PutReadResult(secret, bytes_processed);
460 }
461 break;
462 }
463
464 case kWritePlaintext: {
465 if (length > 0) {
466 bytes_processed = PR_Write(filter_,
467 buffer + start,
468 length);
469 }
470
471 if (bytes_processed < 0) {
472 ASSERT(bytes_processed == -1);
473 // TODO(whesse): Handle unexpected errors here.
474 PRErrorCode pr_error = PR_GetError();
475 if (PR_WOULD_BLOCK_ERROR != pr_error) {
476 ThrowPRException("Error reading plaintext from TlsFilter");
477 }
478 bytes_processed = 0;
479 }
480 break;
481 }
482 }
483 return bytes_processed;
484 }
OLDNEW
« no previous file with comments | « runtime/bin/tls_socket.h ('k') | runtime/bin/tls_socket_patch.dart » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698