Compare commits

...
125 Commits
Author SHA1 Message Date
monojenkinsandAleksey Kliger 1d0d939dc3 [2019-10] [corlib] Capture the ExceptionDispatchInfo when rethrowing from TaskContinuation (#19210)
* [corlib] Capture the ExceptionDispatchInfo when rethrowing from TaskContinuation

In `task.GetAwaiter().OnCompleted(action)` if `action` throws, the
`TaskContinuation.RunOrScheduleAction method will catch the exception and then
call `RuntimeAugments.ReportUnhandledException`.  We must not simply throw the
exception again - in that case we will lose all the frames leading up to the
`catch` in `RunOrScheduleAction`.  Instead use ExceptionDispatchInfo to
caputure the original throw.

Addresses https://github.com/mono/mono/issues/19166

* [test] Add regression test

For annoying reasons we can't run this as a simple NUnit test because the
exception is unhandled on some arbitrary threadpool worker thread, and those
don't show up within an NUnit setup.

Additionally because the unhandled exception in the root domain would normally
terminate the application, we need to run this in a new appdomain.

Co-authored-by: Aleksey Kliger <[email protected]>
2020-03-12 21:56:08 -04:00
monojenkins d10cbf8993 [2019-10] [merp] Capture Environment.FailFast message in crash report (#19067)
[2019-10] [merp] Capture Environment.FailFast message in crash report

If the process calls `System.Environment.FailFast (message, exception)` we should capture the message in the crash report log.

Backport of #18920 (which is a handwritten backport of #18863)

/cc @lambdageek @monojenkins
2020-02-28 14:46:06 -05:00
Alexander Köplinger fb4d8f5eb1 Bump bockbuild for Pango nil check fix
Pango nil check fix: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1069059/

Brings in https://github.com/mono/bockbuild/pull/153

Backport of https://github.com/mono/mono/pull/18936
2020-02-24 19:46:18 +01:00
Ankit Jain eec411c38f [2019-10] Bump msbuild to track mono-2019-10 (#18989) 2020-02-24 19:42:15 +01:00
monojenkinsandEgor Bogatov 387bb6f8f2 Remove TestEnvVarSwitchForInnerHttpHandler test as it should be in XA/LinkerTests.cs instead (#18954)
Co-authored-by: Egor Bogatov <[email protected]>
2020-02-20 11:11:17 +01:00
Marius Ungureanu c0c5c78e2b Bump bockbuild to bring in Gtk# regression fix (#18912)
Backport of https://github.com/mono/mono/pull/18909
2020-02-18 19:45:36 +01:00
monojenkinsandEgor Bogatov a644983ae8 [2019-10] Make MonoWebRequestHandler linker friendly (#18835)
* Make MonoWebRequestHandler linker friendly

* Make MonoWebRequestHandler's ctor public (to be able to use in Activator.CreateInstance without binding flags)

* Update HttpClientHandler.SocketsHandler.Android.cs

* Update HttpClient.android.cs

Co-authored-by: Egor Bogatov <[email protected]>
2020-02-18 15:54:57 +03:00
monojenkinsandEgor Bogatov 85f47fae28 Move HttpClientHandlerTests.Android.cs to nunit (#18888)
Co-authored-by: Egor Bogatov <[email protected]>
2020-02-18 15:54:39 +03:00
Ankit Jain 26afa2d5bb [2019-10] Bump msbuild to track mono-2019-10 (#18861)
- Changes roslyn to `3.5.0-beta2-20074-05`
2020-02-17 12:39:31 +01:00
e5f0d5d928 [2019-10] [merp] Increase buffer size for state dump (#18838)
* [merp] Increase buffer size for state dump

Addresses https://github.com/mono/mono/issues/18796

* fix indentation

Co-authored-by: Alexis Christoforides <[email protected]>
Co-authored-by: Aleksey Kliger (λgeek) <[email protected]>
2020-02-15 17:12:05 -05:00
Alexander Köplinger e60eabc767 Move offsets-tool into mono/tools (#18783) (#18831)
Backporting this since we see errors during `pip install` on the Android Mono SDKs build on Linux and with this we're removing the call to pip (it wasn't needed).

Backport of #18783.
2020-02-13 16:01:06 +01:00
Ankit Jain 7a59bf3ea5 [2019-10] Bump msbuild to track mono-2019-10 (#18791)
* [2019-10] Bump msbuild to track mono-2019-10

* Bump roslyn to 3.5.0-beta3-20111-03 .

* Update nuget.exe to match xbuild

- the closest version available right now, to `5.5.0-rtm.6422` is
`5.5.0-preview2`, so using that for now.
2020-02-12 17:13:00 +01:00
monojenkins 47bb780c8d [2019-10] Allow users to switch to MonoWebRequestHandler on Android via UI (#18787)
* Bring back old HttpHandler for Android
Co-authored-by: Egor Bogatov <[email protected]>
2020-02-12 16:23:58 +03:00
Alexander Köplinger d6f592717e Bump bockbuild to get GTK NSPasteboardType change.
Backport from https://github.com/mono/mono/pull/18080
2020-02-10 16:23:03 +01:00
Matt Sylvia 1ee12f8625 Update deprecated query parameter to header (#18705)
Use of `access_token` is now deprecated, switching to HTTP header

```
Please use the Authorization HTTP header instead, as using the `access_token` query parameter is deprecated.
```

(cherry picked from commit 2f74ab393f)
2020-02-08 19:22:04 +01:00
monojenkinsandAlex Soto 8720142834 [iOS] Replace removed dsymutil -t switch with -num-threads (#18743)
Apple removed `-t` switch from dsymutil in favor of `-num-threads`

Co-authored-by: Alex Soto <[email protected]>
2020-02-07 11:13:42 +01:00
Alexander Köplinger 83c161f276 Skip WebAssembly build in sdks archive build on non-master branches
WebAssembly doesn't use our usual release branches yet.

(cherry picked from commit a40e1ae681)
2020-02-06 22:39:43 +01:00
monojenkinsandAlexis Christoforides 0e18125d71 [merp] Add an exception type for managed exceptions (#18722)
Addresses https://github.com/mono/mono/issues/18681

Co-authored-by: Alexis Christoforides <[email protected]>
2020-02-06 16:20:46 -05:00
vargaz 82fffe0749 [runtime] Disable lldb backtrace display on osx, it hangs on attaching in lldb. 2020-02-04 15:00:59 +01:00
Alexander Köplinger 1cca0cfebf Bump bockbuild for Pango patch
Fixes bug #1048838, correct SF font not loading in VSMac

Backport of https://github.com/mono/mono/pull/18566
2020-01-28 13:15:19 +01:00
monojenkinsandAlexander Köplinger b216675706 configure.ac: remove AC_SEARCH_LIBS for libintl (#18596)
This causes an additional dependency of mono on libintl which we didn't have before.
Reported by a user on gitter, it's problematic on macOS since it makes the mono binary depend on the libintl we ship in the Mono .pkg.

It was introduced in Mono 6.6 by https://github.com/mono/mono/commit/18e0ebfe89be0a175d2f904b9bb1ec6816daa318

Co-authored-by: Alexander Köplinger <[email protected]>
2020-01-27 17:03:02 +01:00
Ankit Jain c0a5db5f82 [2019-10] Bump msbuild to track mono-2019-10 (#18576) 2020-01-27 10:55:30 +01:00
monojenkinsandThays Grazia 9ce68dc791 [2019-10] [debugger] Native thread not executing managed code considered as terminated (#18503)
* If a thread was suspended and doesn't have any managed stack, it was considered as terminated, but it wasn't really terminated because it can execute managed code again, and stop in a breakpoint so if the execution arrives in debugger_agent_breakpoint_from_context we reset the flag terminated to FALSE.

* Adding terminated = FALSE in single_step_from_context.

Co-authored-by: Thays Grazia <[email protected]>
2020-01-24 12:45:58 -03:00
monojenkinsandBernhard Urban-Forster ea94456156 [interp] context can be uninitialized for get_resume_state callback (#18536)
`jit_tls->interp_context` gets initialized lazily, that is, upon the first interpreter execution on a specific thread (e.g. via interp_runtime_invoke). However, with mixed mode the execution can purely happen in AOT code upon the first interaction with the managed debugger.

Stack trace:

```
  thread #1, name = 'tid_407', queue = 'com.apple.main-thread'
    frame #0: 0x0000000190aedc94 libsystem_kernel.dylib`__psynch_cvwait + 8
    frame #1: 0x0000000190a0f094 libsystem_pthread.dylib`_pthread_cond_wait$VARIANT$armv81 + 672
    frame #2: 0x000000010431318c reloadcontext.iOS`mono_os_cond_wait(cond=0x0000000104b9ba78, mutex=0x0000000104b9ba30) at mono-os-mutex.h:219:8
    frame #3: 0x0000000104312a68 reloadcontext.iOS`mono_coop_cond_wait(cond=0x0000000104b9ba78, mutex=0x0000000104b9ba30) at mono-coop-mutex.h:91:2
    frame #4: 0x0000000104312858 reloadcontext.iOS`suspend_current at debugger-agent.c:3021:4
    frame #5: 0x000000010431be18 reloadcontext.iOS`process_event(event=EVENT_KIND_BREAKPOINT, arg=0x0000000145d09ae8, il_offset=0, ctx=0x0000000149015c20, events=0x0000000000000000, suspend_policy=2) at debugger-agent.c:4058:3
    frame #6: 0x0000000104310cf4 reloadcontext.iOS`process_breakpoint_events(_evts=0x000000028351a680, method=0x0000000145d09ae8, ctx=0x0000000149015c20, il_offset=0) at debugger-agent.c:4722:3
    frame #7: 0x000000010432f1c8 reloadcontext.iOS`mono_de_process_breakpoint(void_tls=0x0000000149014e00, from_signal=0) at debugger-engine.c:1141:2
    frame #8: 0x000000010430f238 reloadcontext.iOS`debugger_agent_breakpoint_from_context(ctx=0x000000016f656790) at debugger-agent.c:4938:2
    frame #9: 0x00000001011b73a4 reloadcontext.iOS`sdb_breakpoint_trampoline + 148
    frame #10: 0x00000001008511b4 reloadcontext.iOS`reloadcontext_iOS_Application_Main_string__(args=0x000000010703a030) at Main.cs:14
    frame #11: 0x00000001010f9730 reloadcontext.iOS`wrapper_runtime_invoke_object_runtime_invoke_dynamic_intptr_intptr_intptr_intptr + 272
    frame #12: 0x00000001042fd8b8 reloadcontext.iOS`mono_jit_runtime_invoke(method=0x0000000145d09ae8, obj=0x0000000000000000, params=0x000000016f656f20, exc=0x0000000000000000, error=0x000000016f656ff8) at mini-runtime.c:3162:3
    frame #13: 0x0000000104411950 reloadcontext.iOS`do_runtime_invoke(method=0x0000000145d09ae8, obj=0x0000000000000000, params=0x000000016f656f20, exc=0x0000000000000000, error=0x000000016f656ff8) at object.c:3052:11
    frame #14: 0x000000010440c4dc reloadcontext.iOS`mono_runtime_invoke_checked(method=0x0000000145d09ae8, obj=0x0000000000000000, params=0x000000016f656f20, error=0x000000016f656ff8) at object.c:3220:9
    frame #15: 0x0000000104415ae0 reloadcontext.iOS`do_exec_main_checked(method=0x0000000145d09ae8, args=0x000000010703a030, error=0x000000016f656ff8) at object.c:5184:3
    frame #16: 0x00000001044144ac reloadcontext.iOS`mono_runtime_exec_main_checked(method=0x0000000145d09ae8, args=0x000000010703a030, error=0x000000016f656ff8) at object.c:5281:9
    frame #17: 0x0000000104414500 reloadcontext.iOS`mono_runtime_run_main_checked(method=0x0000000145d09ae8, argc=1, argv=0x000000016f6570d0, error=0x000000016f656ff8) at object.c:4734:9
    frame #18: 0x00000001042d3b54 reloadcontext.iOS`mono_jit_exec_internal(domain=0x0000000145f00130, assembly=0x0000000281ba2900, argc=1, argv=0x000000016f6570d0) at driver.c:1320:13
    frame #19: 0x00000001042d39a4 reloadcontext.iOS`mono_jit_exec(domain=0x0000000145f00130, assembly=0x0000000281ba2900, argc=1, argv=0x000000016f6570d0) at driver.c:1265:7
    frame #20: 0x0000000104597994 reloadcontext.iOS`::xamarin_main(argc=5, argv=0x000000016f657a80, launch_mode=XamarinLaunchModeApp) at monotouch-main.m:483:8
    frame #21: 0x00000001008510dc reloadcontext.iOS`main(argc=5, argv=0x000000016f657a80) at main.m:104:11
    frame #22: 0x0000000190af8360 libdyld.dylib`start + 4
[...]
* thread #5, name = 'Debugger agent', stop reason = signal SIGABRT
  * frame #0: 0x0000000190aedec4 libsystem_kernel.dylib`__pthread_kill + 8
    frame #1: 0x0000000190a0d724 libsystem_pthread.dylib`pthread_kill$VARIANT$armv81 + 216
    frame #2: 0x000000019095d844 libsystem_c.dylib`abort + 100
    frame #3: 0x00000001045871b4 reloadcontext.iOS`log_callback(log_domain=0x0000000000000000, log_level="error", message="* Assertion at ../../../../../mono/mini/interp/interp.c:7176, condition `context' not met\n", fatal=4, user_data=0x0000000000000000) at runtime.m:1213:3
    frame #4: 0x0000000104544fc8 reloadcontext.iOS`eglib_log_adapter(log_domain=0x0000000000000000, log_level=G_LOG_LEVEL_ERROR, message="* Assertion at ../../../../../mono/mini/interp/interp.c:7176, condition `context' not met\n", user_data=0x0000000000000000) at mono-logger.c:405:2
    frame #5: 0x000000010456093c reloadcontext.iOS`monoeg_g_logstr(log_domain=0x0000000000000000, log_level=G_LOG_LEVEL_ERROR, msg="* Assertion at ../../../../../mono/mini/interp/interp.c:7176, condition `context' not met\n") at goutput.c:134:2
    frame #6: 0x0000000104560598 reloadcontext.iOS`monoeg_g_logv_nofree(log_domain=0x0000000000000000, log_level=G_LOG_LEVEL_ERROR, format="* Assertion at %s:%d, condition `%s' not met\n", args="e\x12z\x04\x01") at goutput.c:149:2
    frame #7: 0x000000010456061c reloadcontext.iOS`monoeg_assertion_message(format="* Assertion at %s:%d, condition `%s' not met\n") at goutput.c:184:22
    frame #8: 0x0000000104560674 reloadcontext.iOS`mono_assertion_message(file="../../../../../mono/mini/interp/interp.c", line=7176, condition="context") at goutput.c:203:2
    frame #9: 0x000000010459b570 reloadcontext.iOS`interp_get_resume_state(jit_tls=0x000000014900d000, has_resume_state=0x000000016fc7a9f4, interp_frame=0x000000016fc7a9e8, handler_ip=0x000000016fc7a9e0) at interp.c:7176:2
    frame #10: 0x0000000104319420 reloadcontext.iOS`compute_frame_info(thread=0x0000000104fe4130, tls=0x0000000149014e00, force_update=1) at debugger-agent.c:3422:3
    frame #11: 0x0000000104320d40 reloadcontext.iOS`thread_commands(command=1, p="", end="", buf=0x000000016fc7acf8) at debugger-agent.c:9048:3
    frame #12: 0x000000010431cca0 reloadcontext.iOS`debugger_thread(arg=0x0000000000000000) at debugger-agent.c:10132:10
    frame #13: 0x000000010447eb04 reloadcontext.iOS`start_wrapper_internal(start_info=0x0000000000000000, stack_ptr=0x000000016fc7b000) at threads.c:1232:3
    frame #14: 0x000000010447e788 reloadcontext.iOS`start_wrapper(data=0x000000028203ef40) at threads.c:1305:8
    frame #15: 0x0000000190a11d8c libsystem_pthread.dylib`_pthread_start + 15
[...]
```

Thanks to @drasticactions for helping me to reproduce.

Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1050615

Co-authored-by: Bernhard Urban-Forster <[email protected]>
2020-01-24 11:45:36 +01:00
monojenkinsandAlexander Köplinger 1182f8cbf5 Bump xsp to fix issues with removed Mono.Security APIs (#18486)
See https://github.com/mono/xsp/pull/88

Co-authored-by: Alexander Köplinger <[email protected]>
2020-01-16 21:51:39 +01:00
monojenkins 448e7ee959 [2019-10] [arm] account for signed bit when calculating offset to PLT entry (#18461)
[2019-10] [arm] account for signed bit when calculating offset to PLT entry

See `bl` documentation (make sure you look at the thumb2 one):
<img width="1003" alt="Screenshot 2020-01-14 at 22 43 33" src="https://user-images.githubusercontent.com/75403/72385601-2bb53b00-3720-11ea-9858-d73bc2d02a7e.png">


Fixes https://github.com/mono/mono/issues/18247

Backport of #18454.

/cc @lewurm
2020-01-16 10:37:03 +01:00
monojenkinsandAleksey Kliger f5eff7fa86 [2019-10] [loader] ReflectionOnlyLoad(byte[]) should not apply binding redirects (#18459)
* [loader] ReflectionOnlyLoad(byte[]) should not apply binding redirects

Match .NET Framework behavior.

Addresses https://github.com/mono/mono/issues/18388

* [tests] ReflectionOnlyLoad(byte[]) should not apply binding redirects

Regression test for https://github.com/mono/mono/issues/18388

Co-authored-by: Aleksey Kliger (λgeek) <[email protected]>
2020-01-15 10:48:22 +01:00
Ankit Jain a3c4b143a9 [2019-10] Bump msbuild to track mono-2019-10 (#18434) 2020-01-12 10:55:38 +01:00
Ankit Jain 41f9a07d3d [2019-10] Bump msbuild to track mono-2019-10 (#18414) 2020-01-10 12:41:50 +01:00
Martin Baulig 7a4a1ab42a [2019-10]: Bump CoreFX to latest mono-2019-10. (#18406) 2020-01-10 00:14:50 +01:00
Ankit Jain 4019940aaa [2019-10] Bump msbuild to track mono-2019-10 (#18393) 2020-01-09 22:17:42 +01:00
Ankit Jain ca47edd56d [2019-10] Bump msbuild to track mono-2019-10 (#18374) 2020-01-08 14:58:27 +01:00
monojenkins 6a246d0940 [2019-10] [jit] Avoid passing a vtable argument to DIM methods when making calls out of gsharedvt methods. (#18366)
* [jit] Avoid passing a vtable argument to DIM methods when making calls out of gsharedvt methods.

Fixes https://github.com/mono/mono/issues/18276.
2020-01-07 17:29:14 -05:00
imhameed 398bb16a40 [2019-10] Use byte-aligned LLVM loads and stores for unaligned mini IR loads and stores. (#18369)
Should fix https://github.com/mono/mono/issues/18221.

Backport of #18296.
2020-01-07 14:09:19 -08:00
Ankit Jain b38f2038ec [2019-10] Bump msbuild to track mono-2019-10 (#18259)
* Bump msbuild to track mono-2019-10

- update nuget.exe to 5.5.0-preview1 to match
2020-01-07 18:13:28 +01:00
monojenkins 2bb369f036 [2019-10] Add SignedCms to the TypeForwards in the System.Security.Cryptography.Pkcs facade (#18363)
* Add SignedCms to the typeforwards in the System.Security.Cryptography.Pkcs facade

* Added additional missing types from System.Security.Cryptography.Pkcs.

* It would be nice if the files I added had namespaces ;-)

* [csproj] Update project files

* Bump API snapshot submodule
2020-01-07 18:08:10 +01:00
Alexis Christoforides df42020fe6 [FileSystemWatcher] Fix wrong behaviour when move multiple files out of watched folder on mac (#41963) (#18224)
Backport of  https://github.com/dotnet/corefx/pull/41963


Fixes https://github.com/mono/mono/issues/16778

corefx PR: mono/corefx#385
2020-01-06 16:05:42 -05:00
monojenkins 2faea92a92 [2019-10] [metadata] Size 0 Blob heap is ok when resolving assembly refs (#18338)
* [metadata] Size 0 Blob heap is ok when resolving assembly refs

Sometimes ILasm can produce images with a Blob heap of size 0.  In cases where
we're loading assembly references from such an image, the hash (which is
optional) can be at index = 0 and the Blob heap size is also 0.

Also: add the hash value to the output of `monodis --assemblyref`

* [metadata] Add a separate assertion for the index == size == 0 case

And a comment explaining how it is likely to be triggered.  If the assembly is
reasonable the caller of mono_metadata_blob_heap should be updated to use
mono_metadata_blob_heap_null_ok instead

* [bcl] Allow Mono's ILASM to produce a size 0 Blob heap

ECMA 335 II.24.2.4 says that the user string and blob heaps should have an
entry at index 0 consisting of the single byte 0.  However .NET Framework (and
.NET Core) ilasm will entirely omit the Blob heap (that is, create a blob heap
entry of size 0) if it is not needed.  This PR changes Mono's ILASM to emit the
initial byte on demand only if one of the MetaDataStream.Add() methods is
called. Otherwise we will also emit a stream of size 0.

This is needed to compile some test cases.

* [tests] Add regression test for loading assemblies with size 0 Blob heap

Depends on ILASM that can emit a size 0 Blob heap
2020-01-06 16:03:08 -05:00
monojenkinsandMartin Baulig 99e3aed6ec Socket.BeginMConnect() should not attempt connections on unsupported address families. (#18321)
Fixes #16513.

Co-authored-by: Martin Baulig <[email protected]>
2020-01-01 17:32:16 -05:00
monojenkins 5f0704ce37 [eglib] Don't define _FORTIFY_SOURCE on Cygwin builds (#18312)
See https://github.com/msys2/MINGW-packages/issues/5803

Without -lssp (or -fstack-protector), -D_FORTIFY_SOURCE=2 leads to linker
errors.
2019-12-30 09:54:37 -05:00
monojenkins dc5902c243 [domain] Don't add NULL runtime to runtimes list (#18265)
Also when iterating over the runtimes, actually look at the current element,
not the first element.

Also mention the unsupported runtime version in the warning message when it is
passed to mono_init_internal.

Fixes https://github.com/mono/mono/issues/17916
2019-12-23 08:41:55 -05:00
Alexander Köplinger bfcac9bd30 Bump corefx to get test fix 2019-12-20 00:35:57 +01:00
Alexander Köplinger d56a0e72c2 [System] Add additional hardening against race in MonoTlsStream (#18250)
See https://github.com/mono/mono/issues/15805#issuecomment-567131297

(cherry picked from commit c8e19bec68)
2019-12-19 11:58:16 +01:00
Alexander Köplinger 9325d96ca3 [bcl] Split corlib and System.Core xunit test assemblies for monotouch profiles (#18228)
They cannot deal with large test assemblies so we need to split them.

We're doing this by introducing a new `#skip <PROFILE>` directive in the .sources format which defines where to split the assembly.
The logic is very simple: files up until the first `#skip` are common files which get included in each part, subsequent files are only in the respective part assembly.

Fixes https://github.com/mono/mono/issues/18213

(cherry picked from commit 3891fe97d2)
(cherry picked from commit a74416d950)
2019-12-18 22:33:30 +01:00
Ankit Jain 7e31b36d0d Bump msbuild to track mono-2019-10 (#18194)
.. to get changes from https://github.com/mono/msbuild/pull/184 .
2019-12-18 16:48:52 +01:00
monojenkins 8f396bbb40 [2019-10] [cominterop] Attach to runtime from IUnknown and IDispatch methods (#18186)
* [cominterop][test] Calling QueryInterface from an unattached thread asserts

If we pass a managed COM object to native code and the native code calls one of
the IUnknown methods, we assert because the thread is not attached but we want
to enter GC Unsafe mode.

* [cominterop] Attach to runtime from IUnkown and IDispatch methods

If the COM objects for a managed object is passed to a thread that hasn't
interacted with Mono before, we need to attach before doing GC thread state
transitions.

Addresses https://github.com/mono/mono/issues/18137

* [test] Call managed method through COM wrapper from unattached thread

This works, but I don't think we had a test previously.  Call a managed method
via a COM interface from a thread that is not attached to the runtime, to
ensure that it is attached.
2019-12-16 19:45:21 -05:00
Alexander Köplinger 25f7937972 [sdks] Use Xcode 11.3 stable version for iOS/Mac SDKs
As requested by the xamarin-macios team.

(cherry picked from commit 7e65a73d4d)
2019-12-13 18:14:49 +01:00
Ankit Jain 9bcfa60312 [2019-10] Bump msbuild to track mono-2019-10 (#18132)
* Bump msbuild to track mono-2019-10

* [2019-10] Bump msbuild to track mono-2019-10

* [2019-10] Bump msbuild to track mono-2019-10
2019-12-12 04:58:33 -05:00
monojenkins e6cd9a15cd [2019-10] [mini] Fix delegate trampoline virtual call via delgate Invoke (#18115)
[2019-10] [mini] Fix delegate trampoline virtual call via delgate Invoke

If we need to jit the Invoke method of a delegate, we get `tramp_info` with a
NULL method.

Background: normally when we create a delegate around a virtual method,
`handle_delegate_ctor` will just create a virtual invoke trampoline with
`mono_arch_get_delegate_virtual_invoke_impl` which doesn't get here.  But if
we're asked to compile the delegate's `Invoke` method, then `compile_special ()`
will create a `tramp_info` with a null method, and return a delegate trampoline.

That's the case here - we had
```
  var del = SomeDelegate(obj.VirtualMethod);
  var invoke_method = del.GetType().GetMethod ("Invoke");
  invoke_method.Invoke (del, args);
```
or
```
  var del = SomeDelegate(obj.VirtualMethod);
  var another_del = OtherDelegate (del.Invoke);
  another_del (args);
```

in both cases, we end up in mono_delegate_trampoline with `tramp_info->method == NULL`.

in the second case the IL is like this:
```
   newobj instance void Derived::'.ctor'
   ldvirtftn instance void class Base::VirtualMethod()
   newobj instance void class SomeDelegate::'.ctor'(object, native int)
```

So `delegate->target` is a derived instance but `delegate->method` is some base
class method.

Addresses https://github.com/mono/mono/issues/17718



Backport of #18073.

/cc @lambdageek
2019-12-11 00:35:54 +01:00
monojenkins 7c95e4bc48 [debugger] skip suspend for unattached threads (#18111)
When the debugger tries to suspend all the VM threads, it can happen with cooperative-suspend that it tries to suspend a thread that has previously been attached, but then did a "light" detach (that only unsets the domain). With the domain set to `NULL`, looking up a JitInfo for a given `ip` will result into a crash, but it isn't even necessarily needed for the purpose of suspending a thread.

More details: Consider the following:
```
(lldb) c
error: Process is running.  Use 'process interrupt' to pause execution.
Process 12832 stopped
* thread #9, name = 'tid_a31f', queue = 'NSOperationQueue 0x8069b670 (QOS: UTILITY)', stop reason = breakpoint 1.1
    frame #0: 0x00222870 WatchWCSessionAppWatchOSExtension`debugger_interrupt_critical(info=0x81365400, user_data=0xb04dc718) at debugger-agent.c:2716:6
   2713         MonoDomain *domain = (MonoDomain *) mono_thread_info_get_suspend_state (info)->unwind_data [MONO_UNWIND_DATA_DOMAIN];
   2714         if (!domain) {
   2715                 /* not attached */
-> 2716                 ji = NULL;
   2717         } else {
   2718                 ji = mono_jit_info_table_find_internal ( domain, MONO_CONTEXT_GET_IP (&mono_thread_info_get_suspend_state (info)->ctx), TRUE, TRUE);
   2719         }
Target 0: (WatchWCSessionAppWatchOSExtension) stopped.
(lldb) bt
* thread #9, name = 'tid_a31f', queue = 'NSOperationQueue 0x8069b670 (QOS: UTILITY)', stop reason = breakpoint 1.1
  * frame #0: 0x00222870 WatchWCSessionAppWatchOSExtension`debugger_interrupt_critical(info=0x81365400, user_data=0xb04dc718) at debugger-agent.c:2716:6
    frame #1: 0x004e177b WatchWCSessionAppWatchOSExtension`mono_thread_info_safe_suspend_and_run(id=0xb0767000, interrupt_kernel=0, callback=(WatchWCSessionAppWatchOSExtension`debugger_interrupt_critical at debugger-agent.c:2708), user_data=0xb04dc718) at mono-threads.c:1358:19
    frame #2: 0x00222799 WatchWCSessionAppWatchOSExtension`notify_thread(key=0x03994508, value=0x81378c00, user_data=0x00000000) at debugger-agent.c:2747:2
    frame #3: 0x00355bd8 WatchWCSessionAppWatchOSExtension`mono_g_hash_table_foreach(hash=0x8007b4e0, func=(WatchWCSessionAppWatchOSExtension`notify_thread at debugger-agent.c:2733), user_data=0x00000000) at mono-hash.c:310:4
    frame #4: 0x0021e955 WatchWCSessionAppWatchOSExtension`suspend_vm at debugger-agent.c:2844:3
    frame #5: 0x00225ff0 WatchWCSessionAppWatchOSExtension`process_event(event=EVENT_KIND_THREAD_START, arg=0x039945d0, il_offset=0, ctx=0x00000000, events=0x805b28e0, suspend_policy=2) at debugger-agent.c:4012:3
    frame #6: 0x00227c7c WatchWCSessionAppWatchOSExtension`process_profiler_event(event=EVENT_KIND_THREAD_START, arg=0x039945d0) at debugger-agent.c:4072:2
    frame #7: 0x0021b174 WatchWCSessionAppWatchOSExtension`thread_startup(prof=0x00000000, tid=2957889536) at debugger-agent.c:4149:2
    frame #8: 0x0037912d WatchWCSessionAppWatchOSExtension`mono_profiler_raise_thread_started(tid=2957889536) at profiler-events.h:103:1
    frame #9: 0x003d53da WatchWCSessionAppWatchOSExtension`fire_attach_profiler_events(tid=0xb04dd000) at threads.c:1120:2
    frame #10: 0x003d4d83 WatchWCSessionAppWatchOSExtension`mono_thread_attach(domain=0x801750a0) at threads.c:1547:2
    frame #11: 0x003df1a1 WatchWCSessionAppWatchOSExtension`mono_threads_attach_coop_internal(domain=0x801750a0, cookie=0xb04dcc0c, stackdata=0xb04dcba8) at threads.c:6008:3
    frame #12: 0x003df287 WatchWCSessionAppWatchOSExtension`mono_threads_attach_coop(domain=0x00000000, dummy=0xb04dcc0c) at threads.c:6045:9
    frame #13: 0x005034b8 WatchWCSessionAppWatchOSExtension`::xamarin_switch_gchandle(self=0x80762c20, to_weak=false) at runtime.m:1805:2
    frame #14: 0x005065c1 WatchWCSessionAppWatchOSExtension`::xamarin_retain_trampoline(self=0x80762c20, sel="retain") at trampolines.m:693:2
    frame #15: 0x657ea520 libobjc.A.dylib`objc_retain + 64
    frame #16: 0x4b4d9caa WatchConnectivity`__66-[WCSession onqueue_handleDictionaryMessageRequest:withPairingID:]_block_invoke + 279
    frame #17: 0x453c7df7 Foundation`__NSBLOCKOPERATION_IS_CALLING_OUT_TO_A_BLOCK__ + 12
    frame #18: 0x453c7cf4 Foundation`-[NSBlockOperation main] + 88
    frame #19: 0x453cacee Foundation`__NSOPERATION_IS_INVOKING_MAIN__ + 27
    frame #20: 0x453c6ebd Foundation`-[NSOperation start] + 835
    frame #21: 0x453cb606 Foundation`__NSOPERATIONQUEUE_IS_STARTING_AN_OPERATION__ + 27
    frame #22: 0x453cb12e Foundation`__NSOQSchedule_f + 194
    frame #23: 0x453cb26e Foundation`____addOperations_block_invoke_4 + 20
    frame #24: 0x65de007b libdispatch.dylib`_dispatch_call_block_and_release + 15
    frame #25: 0x65de126f libdispatch.dylib`_dispatch_client_callout + 14
    frame #26: 0x65de3788 libdispatch.dylib`_dispatch_continuation_pop + 421
    frame #27: 0x65de2ee3 libdispatch.dylib`_dispatch_async_redirect_invoke + 818
    frame #28: 0x65df087d libdispatch.dylib`_dispatch_root_queue_drain + 354
    frame #29: 0x65df0ff3 libdispatch.dylib`_dispatch_worker_thread2 + 109
    frame #30: 0x66024fa0 libsystem_pthread.dylib`_pthread_wqthread + 208
    frame #31: 0x66024e44 libsystem_pthread.dylib`start_wqthread + 36
```

Going further, `info` is about this thread:
```
(lldb) p/x *(int *)(((char *) info->node.key) + 0xa0)
(int) $2 = 0x01243f93
(lldb) thread list
Process 12832 stopped
  thread #1: tid = 0x1243ee1, 0x65f7e396 libsystem_kernel.dylib`mach_msg_trap + 10, name = 'tid_303', queue = 'com.apple.main-thread'
  thread #2: tid = 0x1243ee6, 0x65f816e2 libsystem_kernel.dylib`__recvfrom + 10
  thread #3: tid = 0x1243ee7, 0x65f81aea libsystem_kernel.dylib`__psynch_cvwait + 10, name = 'SGen worker'
  thread #4: tid = 0x1243ee9, 0x65f7e3d2 libsystem_kernel.dylib`semaphore_wait_trap + 10, name = 'Finalizer'
  thread #5: tid = 0x1243eea, 0x65f816e2 libsystem_kernel.dylib`__recvfrom + 10, name = 'Debugger agent'
  thread #6: tid = 0x1243f1d, 0x65f7e396 libsystem_kernel.dylib`mach_msg_trap + 10, name = 'com.apple.uikit.eventfetch-thread'
  thread #8: tid = 0x1243f93, 0x65f7e396 libsystem_kernel.dylib`mach_msg_trap + 10, name = 'tid_6d0f', queue = 'NSOperationQueue 0x8069b300 (QOS: UTILITY)'
* thread #9: tid = 0x12443a9, 0x00222870 WatchWCSessionAppWatchOSExtension`debugger_interrupt_critical(info=0x81365400, user_data=0xb04dc718) at debugger-agent.c:2716:6, name = 'tid_a31f', queue = 'NSOperationQueue 0x8069b670 (QOS: UTILITY)', stop reason = breakpoint 1.1
  thread #10: tid = 0x1244581, 0x65f7fd32 libsystem_kernel.dylib`__workq_kernreturn + 10
(lldb) thread select 8
* thread #8, name = 'tid_6d0f', queue = 'NSOperationQueue 0x8069b300 (QOS: UTILITY)'
    frame #0: 0x65f7e396 libsystem_kernel.dylib`mach_msg_trap + 10
libsystem_kernel.dylib`mach_msg_trap:
->  0x65f7e396 <+10>: retl
    0x65f7e397 <+11>: nop

libsystem_kernel.dylib`mach_msg_overwrite_trap:
    0x65f7e398 <+0>:  movl   $0xffffffe0, %eax         ; imm = 0xFFFFFFE0
    0x65f7e39d <+5>:  calll  0x65f85f44                ; _sysenter_trap
(lldb) bt
* thread #8, name = 'tid_6d0f', queue = 'NSOperationQueue 0x8069b300 (QOS: UTILITY)'
  * frame #0: 0x65f7e396 libsystem_kernel.dylib`mach_msg_trap + 10
    frame #1: 0x65f7e8ff libsystem_kernel.dylib`mach_msg + 47
    frame #2: 0x66079679 libxpc.dylib`_xpc_send_serializer + 104
    frame #3: 0x660794da libxpc.dylib`_xpc_pipe_simpleroutine + 80
    frame #4: 0x66079852 libxpc.dylib`xpc_pipe_simpleroutine + 43
    frame #5: 0x66043a8f libsystem_trace.dylib`___os_activity_stream_reflect_block_invoke_2 + 30
    frame #6: 0x65de126f libdispatch.dylib`_dispatch_client_callout + 14
    frame #7: 0x65de3d71 libdispatch.dylib`_dispatch_block_invoke_direct + 257
    frame #8: 0x65de3c62 libdispatch.dylib`dispatch_block_perform + 112
    frame #9: 0x6604349a libsystem_trace.dylib`_os_activity_stream_reflect + 725
    frame #10: 0x6604ef19 libsystem_trace.dylib`_os_log_impl_stream + 468
    frame #11: 0x6604e44d libsystem_trace.dylib`_os_log_impl_flatten_and_send + 6410
    frame #12: 0x6604cb3b libsystem_trace.dylib`_os_log + 137
    frame #13: 0x6604f4aa libsystem_trace.dylib`_os_log_impl + 31
    frame #14: 0x4b4eb4e9 WatchConnectivity`WCSerializePayloadDictionary + 393
    frame #15: 0x4b4d7c4d WatchConnectivity`-[WCSession onqueue_sendResponseDictionary:identifier:] + 195
    frame #16: 0x4b4da435 WatchConnectivity`__66-[WCSession onqueue_handleDictionaryMessageRequest:withPairingID:]_block_invoke.411 + 35
    frame #17: 0x453c7df7 Foundation`__NSBLOCKOPERATION_IS_CALLING_OUT_TO_A_BLOCK__ + 12
    frame #18: 0x453c7cf4 Foundation`-[NSBlockOperation main] + 88
    frame #19: 0x453cacee Foundation`__NSOPERATION_IS_INVOKING_MAIN__ + 27
    frame #20: 0x453c6ebd Foundation`-[NSOperation start] + 835
    frame #21: 0x453cb606 Foundation`__NSOPERATIONQUEUE_IS_STARTING_AN_OPERATION__ + 27
    frame #22: 0x453cb12e Foundation`__NSOQSchedule_f + 194
    frame #23: 0x453cb067 Foundation`____addOperations_block_invoke_2 + 20
    frame #24: 0x65dedf49 libdispatch.dylib`_dispatch_block_async_invoke2 + 77
    frame #25: 0x65de4461 libdispatch.dylib`_dispatch_block_async_invoke_and_release + 17
    frame #26: 0x65de126f libdispatch.dylib`_dispatch_client_callout + 14
    frame #27: 0x65de3788 libdispatch.dylib`_dispatch_continuation_pop + 421
    frame #28: 0x65de2ee3 libdispatch.dylib`_dispatch_async_redirect_invoke + 818
    frame #29: 0x65df087d libdispatch.dylib`_dispatch_root_queue_drain + 354
    frame #30: 0x65df0ff3 libdispatch.dylib`_dispatch_worker_thread2 + 109
    frame #31: 0x66024fa0 libsystem_pthread.dylib`_pthread_wqthread + 208
    frame #32: 0x66024e44 libsystem_pthread.dylib`start_wqthread + 36
```
which is a thread in a "light" detach state (aka. coop detach), where we only unset the domain:
https://github.com/mono/mono/blob/4cefdcb7ce2d939ee78fb45d1b4913eb3bc064fd/mono/metadata/threads.c#L6084-L6111

Fixes https://github.com/mono/mono/issues/17926
2019-12-10 13:43:42 -05:00
Ankit Jain 77147e7526 [2019-10] Bump msbuild+roslyn to track mono-2019-10 (#18093)
* [2019-10] Bump msbuild+roslyn to track mono-2019-10

- bumps roslyn to `3.5.0-beta1-19606-04`

* roslyn: Delete reference to the now removed Microsoft.Managed.EditorConfig.targets
2019-12-10 12:40:46 +01:00
Steve Pfister d7337e5beb Bump to mono/corefx@f3815a9 (#18104)
Picks up https://github.com/mono/corefx/pull/376

Backport of https://github.com/mono/mono/pull/18090
2019-12-10 12:37:11 +01:00
monojenkins 6ac11972db [2019-10] [threads] Add back mono_threads_attach_tools_thread as a public API (#18075)
* [utils] Add back mono_threads_attach_tools_thread

In https://github.com/mono/mono/commit/a5da7b21f4b6dbc5eaa09c2addee91b84dc1dbd5
we got rid of "tools" threads internally to the runtime.

However since the API was previously marked with MONO_API it was an internal
API that some embedders depended on.

This PR adds back an (external-only) limited form of tools thread.

The runtime is aware of the Tools thread in that FOREACH_THREAD_* macros will
iterate over them, and the thread has a coop thread state machine. (That is,
mono_thread_info_current() and GC Safe and GC Unsafe transitions all work.)

However the thread is:
1. Not stopped by the GC
2. Is not interrupted by profiler sampling.
3. Does not have a "current domain"
4. (As a consequence of the above) cannot call managed methods or touch managed
objects.

Such threads are useful for low-level interaction with the runtime such as
querying metadata, the JIT state and other coordination.

mono_threads_attach_tools_thread should be called no more than once.  It should
not be called on a thread that is already attached with mono_thread_atach, and
vice versa.

Addresses https://github.com/mono/mono/issues/18011

* [threads] Make mono_threads_attach_tools_thread into a public API
2019-12-06 17:56:10 -05:00
Steve Pfister b687667619 Bump corefx to pick up https://github.com/mono/corefx/pull/370 (#18068)
* Bump corefx to pick up https://github.com/mono/corefx/pull/370

Added HAVE_LCHFLAGS & HAVE_STAT_FLAGS to configure

Backport of https://github.com/mono/mono/pull/17758

* [csproj] Update project files
2019-12-06 12:22:19 +01:00
Alexander Köplinger da605d8081 Remove DNS lookups of the local hostname in tests (#18059)
This allows us to workaround issues we currently have in the macOS bot network where DNS lookup of the hostname fails.

(cherry picked from commit 269d509e42)
2019-12-05 23:21:28 +01:00
Ankit Jain a6e867fe96 Bump msbuild to track mono-2019-10 (#18045)
.. to get changes from https://github.com/mono/msbuild/pull/163 .

And bump roslyn to 3.4.0-beta4-19569-03 to match msbuild.
2019-12-05 00:42:12 +01:00
Alexander Köplinger 3387bd4a26 Bump bockbuild to get https://github.com/mono/bockbuild/pull/136 2019-12-05 00:36:16 +01:00
Thays Grazia 5dd74a60e8 Fix side effect. 2019-12-04 14:58:48 -06:00
Thays Grazia a36f07c803 Fix DIM in a generic interface. Fixes #17869 2019-12-04 14:58:48 -06:00
Ankit Jain 08e5a9751a Bump msbuild to track mono-2019-10 (#18014)
To get changes from mono/msbuild#159 .
2019-12-03 19:13:59 +01:00
monojenkins 56a583ea5c [2019-10] [profiler] disable inlining when coverage profiler is used and fix allocation sizes (#17991)
* [profiler] let compiler decide about the size of an entry

* [profiler] disable inlining when coverage profiler is used
2019-12-03 16:48:11 +01:00
monojenkins 914ffea421 [sgen] Don't trigger collections during allocation of thread objects (#17997)
Allocation of thread objects usese the mono_object_new_mature API. These objects are allocated before the thread is finished attaching to the runtime. This means that a collection can happen on an unattached thread as well as all its callbacks, which is a counter-intuitive behavior.

On android this is problematic because at the end of the SGen collection we need to call the java collection, which needs to have the thread attached. This could probably be fixed instead from the Xamarin.Android side, but this approach seems simpler and saner.

Fixes https://github.com/mono/mono/issues/17878
2019-12-03 10:10:15 +02:00
Bernhard Urban-Forster 18920a83f4 [interp] track valuetype stack for CEE_RET too (#17984)
[2019-10] [interp] track valuetype stack for CEE_RET too

Backport of #17968

Fixes https://github.com/mono/mono/issues/17924
2019-12-02 11:36:02 +01:00
monojenkins 6164496c68 [merp] Use timeline (and generate timeline breadcrumbs) for SendExceptionToTelemetry() (#17945)
Fixes https://github.com/mono/mono/issues/17790
2019-11-29 11:58:42 +01:00
Ankit Jain 6660ac4690 [2019-10] Bump msbuild to track mono-2019-10 (#17951)
* Bump msbuild to track mono-2019-10

* Bump nuget.exe to 5.4.0
2019-11-29 11:56:32 +01:00
monojenkins 4caf2b3dcc [2019-10] [threadpool] Decrement max_working when worker times out (#17944)
[2019-10] [threadpool] Decrement max_working when worker times out

The corresponding code in CoreCLR:
https://github.com/dotnet/runtime/blob/bf88f146412d1e2d41779422337184a802f186c9/src/coreclr/src/vm/win32threadpool.cpp#L2156-L2164

The issue is that counter._.max_working is only ever changed by:
1. the monitor_thread when it detects starvation (increment by 1).
2. the hill climbing algorithm (increment or decrement).

Creating a periodic load of creating many workers at once followed by a minute
or more of quiescence increases the variable worker.counters._.max_working in
monitor_thread(). Once that counter matches worker.limit_worker_max,
monitor_thread() keeps looping without unparking or creating a thread, even
though the actual number of threads/workers is small. If the existing threads
are all waiting on work that needs a new thread, then a deadlock occurs.

With this change, when a parked worker times out, it will lower max_working to
the number of active (working + parked + starting) threads minus itself (but no
less than limit_worker_min). As a result, monitor_thread will only increment
max_working as long as none of the already running workers are timing out.

Attempt to address https://github.com/mono/mono/issues/17833

---

Also allow monitor_thread to start workers if there aren't enough active, even if the max worker limit has been reached.

Work around a pathological condition where the work_item_count is non-zero, and
the max_working limit has been reached, but the number of active threads is
still below the max.  In that case, unpark some workers and start some new
threads.

May address http://work.azdo.io/827206

Backport of #17927.

/cc @lambdageek
2019-11-27 21:46:06 +01:00
monojenkins 49dce2286c [arm] if mtriple is provided, do not set -march (#17941)
[2019-10] [arm] if mtriple is provided, do not set -march

E.g. when passing `-march=arm -mtriple=armv7s-ios`, `-march` will win and thus ignore `armv7s`.

Fixes https://github.com/mono/mono/issues/17931

* Caused by 5e318afd2e
* Related with 4cd5068230
* Almost fixed by e431093f73

Hopefully we are done with it.




Backport of #17937.

/cc @lewurm
2019-11-27 19:15:13 +01:00
monojenkins 2fdb2f852f [2019-10] [runtime] Treat calling a non-virtual method through an open delegate the same as the normal case instead of the OPEN_VIRTUAL case. (#17904)
* [runtime] Treat calling a non-virtual method through an open delegate the same as the normal case instead of the OPEN_VIRTUAL case.

* [amd64] Fix the return value mapping in gsharedvt calls, the return address might be in different registers in the caller and callee.

* [runtime] Always initialize del->method_ptr even if interp_method is set, JITted code makes calls through it in mixed mode.

* Add a test for open delegates and gsharedvt.

* Increase nrgctx trampoline count, its needed by dynamic-method-churn.exe in full-aot-interp mode.
2019-11-26 21:54:13 +01:00
monojenkins 6d7c01ef83 Make debugger agent startup faster (#17909)
Mono SDB's debugger agent takes a `host:port` parameter to specify the host and
port on which to listen for debugger connection. `host` is passed, via
`mono_get_address_info`, to the `getaddrinfo(3)` standard library call which
does the job of translating the name to the IP address. However, there's no
special treatment for situations when `host` is already an IP address. In this
case `getaddrinfo` takes a lot of time to perform at least two DNS lookups (if
there's just a single DNS server configured) which will time out as the IP
address in `host` will not be resolved by any of the servers.

`getaddrinfo` takes a "hints" parameter where caller can specify some
information about the `host:port` pair to make the lookup faster/easier.
However, Mono doesn't specify the address family in the `hints` parameter, thus
forcing the slow path of DNS lookups on `getaddrinfo`.

This commit adds a new hint named `MONO_HINT_NUMERIC_HOST` (which maps to
`AI_NUMERICHOST` for `getaddrinfo`) which will allow, if set, `getaddrinfo` to
take a faster route in address discovery. Debugger agent will, in most cases,
get an IP address to instead of host name so we call `mono_get_address_info` up
to 3 times (IPv4, IPv6 and unspecified) in order to make the lookup faster.


Backport of #17898.
2019-11-26 00:47:42 +01:00
monojenkins ae85289ca6 2019-10] Add null check around sslStream when trying to dispose in MonoTlsStream
Fixes #15805 at least in terms of what may be making it crash.

Adds a null check around the sslStream before trying to dispose.

Backport of #17270.
2019-11-22 22:18:59 +01:00
Zoltan Varga e9b5aec5ec Bump cecil. (#17861) 2019-11-21 10:47:05 -05:00
monojenkins 7a71151252 enable gss on android (#17851) 2019-11-20 10:53:31 -05:00
monojenkins 775da627ea [debugger-agent] Fix CMD_VM_ALL_THREADS returning wrong value due to unitialized variable (#17848)
[2019-10] [debugger-agent] Fix CMD_VM_ALL_THREADS returning wrong value due to uninitialized variable

`remove_gc_finalizing` wasn't initialized so its value is undefined.

The `count_thread_check_gc_finalizer()` function only sets it in some cases so we could end up with the variable having an undefined (and probably not 0) value.

This resulted in the returned thread count from the debuggee being wrong because we'd decrement `count` even though we shouldn't.

Fixes regression from https://github.com/mono/mono/pull/15618

Thanks to @lewurm for helping me with this!

Backport of #17847.

/cc @akoeplinger
2019-11-20 13:56:05 +01:00
Jay Krell 56dbcbd9ae Fix samples to do what is intended, caught by C++ compilation error. (#17850) 2019-11-20 10:37:01 +01:00
monojenkinsandAleksey Kliger a0c52fed55 [2019-10] [embed] Assert when call mono_runtime_object_init (#17745)
* Adding unit-test of mono embedded

* Fix c++ build.

* Fix c++ build.

* Fix c++ build.

* Fix copy paster error.

* Changing to use the sample that is in samples/embeded as a unit test.

* Adding test-invoke from sample to unit-tests. Discovered an issue and fixed when calling mono_runtime_object_init.

* adding test file

* Fixing Formatting Changing makefile

* Adding -static flag to make sure that we are using the right version of mono.

* Adding -static flag to make sure that we are using the right version of mono.

* Adding -static flag to make sure that we are using the right version of mono.

* Fix coop suspend.

* Fix coop suspend.

* Removing static, this wasn't the problem.

* Update samples/embed/test.cs

Co-Authored-By: Aleksey Kliger (λgeek) <[email protected]>

* Update samples/embed/teste.c

Co-Authored-By: Aleksey Kliger (λgeek) <[email protected]>

* Update samples/embed/teste.c

Co-Authored-By: Aleksey Kliger (λgeek) <[email protected]>

* Update samples/embed/test-invoke.c

Co-Authored-By: Aleksey Kliger (λgeek) <[email protected]>

* Update samples/embed/test-invoke.c

Co-Authored-By: Aleksey Kliger (λgeek) <[email protected]>

* Using tabs
2019-11-19 14:33:34 +01:00
monojenkinsandAleksey Kliger 427ac4d876 [2019-10] [debugger] Assert when async debug a generic method (#17788)
* When we try to call a method to get the async_id to do an async debug and we are trying to do this in a generic method like this:

async Task<T> ExecuteAsync_Broken<T>()
 {
            await Task.Delay(2);
            return default;
  }

We need to inflate the generic type before call the method or we will get the error:  Could not execute the method because the containing type 'System.Runtime.CompilerServices.AsyncTaskMethodBuilder1[T_REF]’, is not fully instantiated.

Fixes #17549
Fixes #17569

* Do not use reserved word "class

* adding unit test

* Update mono/mini/debugger-agent.c

Co-Authored-By: Aleksey Kliger (λgeek) <[email protected]>

* Adding mono prefix.

* Moving mono_get_generic_context_from_stack_frame to debugger-engine because debugger-agent is not used on wasm, causing a compilation error.

* Moving mono_get_generic_context_from_stack_frame back to mini-exception and the declaration is in mini.h
2019-11-19 14:32:44 +01:00
monojenkins 5f3898fc40 [MacSDK] Bump xamarin-gtk-theme.py to latest revision from private bockbuild (#17791) 2019-11-14 09:27:15 +01:00
monojenkins dceea95adc [merp] Remove extraneous waitpid invocation (#17763)
This basically guarantees that the following waitpid invocation will fail. Fixes merp stating that its process has failed when it hasn't.
2019-11-11 09:20:40 +01:00
monojenkins 8acdda2d9b [2019-10] [profiler] Fix log profiling of native to managed wrappers (#17746)
* [profiler] Add test case for pinvokes and reverse pinvokes

* [profiler] Fix crash in native to managed wrappers

When we call back to managed from a pinvoke, we're in GC Safe mode and the
profiler instrumentation is inserted in the wrapper before it does the
transition to GC Unsafe.  So we need an extra transition before the profiler
calls its locking functions

Fixes https://github.com/mono/mono/issues/17687

* [coop] Mark internal GC Unsafe functions with MONO_PROFILER_API

Allow the profiler to transition to GC Unsafe mode

* [profiler] ptestrunner.pl fix profiler modules directory
2019-11-07 18:08:26 -05:00
monojenkins a6922d881d [runtime] Fix locking in mono_get_seq_points (). (#17741)
Fixes https://github.com/mono/mono/issues/17737.
2019-11-07 00:51:55 -05:00
monojenkins 1f45bc58eb [2019-10] [System.Net.Http]: Bring HttpClient from CoreFX on monotouch and xammac. (#17645)
Backport of #17628.

* Bump API snapshot submodule

* [csproj] Update project files
2019-11-05 22:11:48 +01:00
Alexander Köplinger e11954da4d [sdks] Use Xcode 11.2 stable version for iOS/Mac SDKs
As requested by the xamarin-macios team.
2019-11-04 15:27:20 +01:00
monojenkins e1f916ed1e [jit] Call mono_class_setup_fields () before accessing field->offset. Fixes https://github.com/mono/mono/issues/17665. (#17668) 2019-11-02 09:40:53 -04:00
monojenkins 844a1d5127 [llvm] Fix a case where we treated the dreg of a store_membase instruction as a dreg, its actually the base reg. (#17649) 2019-11-01 04:03:06 -04:00
monojenkins ced94157a7 [2019-10] Bump CoreFX to pickup corefx PR #367 to fix #17133. (#17621) 2019-10-30 18:35:55 -04:00
Thays Grazia ce7527fd20 [dim][regression] Explicit interface override (#17583) (#17626)
* Precedence order:
-> Override interface method in class
-> Method in class
-> DIM
2019-10-30 19:17:24 -03:00
Alexander Köplinger 010050adc8 [acceptance-tests] Bump mono/roslyn to get build fix
See https://github.com/mono/roslyn/commit/6bfcd4e770609a38b8523e83ce1ec943162f30bb

(cherry picked from commit 1340095581)
2019-10-29 21:43:29 +01:00
Aleksey Kliger (λgeek) 4847b8e7a7 [2019-10] Embedding API GC Unsafe transition fixes (#17586)
* [runtime] Make mono_thread_manage external only

runtime should use mono_thread_manage_internal

* [runtime] Do an unbalanced GC Unsafe transition in mono_jit_cleanup

After mini_cleanup, we don't have GC thread states anymore because all that
stuff was cleaned up, so MONO_EXIT_GC_UNSAFE would assert

* [runtime] Mark mono_runtime_quit external only.

Runtime should use mono_runtime_quit_internal.

After we call the quit_function (aka mini_cleanup) we don't have any GC thread
states anymore because all that stuff got cleaned up.  So MONO_EXIT_GC_UNSAFE
can't work.
2019-10-28 17:16:42 -04:00
Aleksey Kliger 1de5d71e49 [2019-08][merp] Install sigterm handler in EnableMicrosoftTelemetry
Partly revert https://github.com/mono/mono/pull/17296 backports.

Follow-up work for backports of https://github.com/mono/mono/pull/17537 backports.

Addresses https://github.com/mono/mono/issues/17419
2019-10-28 14:31:40 -04:00
monojenkins c45cf8ede2 [2019-10] [merp] Introduce a new 'dump mode' that allows different signal behavior when dumping (#17567)
* [merp] Introduce a new 'dump mode' that allows different signal behavior when dumping

The primary reason for this is gaining the ability to interpret SIGTERM properly as a crashing signal when outside of 'dump mode', and as a utility signal during the 'thread summarizer' dumping process.
2019-10-26 18:49:06 -04:00
monojenkins 098d12c616 [2019-10] Cleaning up SslStream, MobileAuthenticatedStream and TaskToApm. (#17552)
* Cleaning up SslStream, MobileAuthenticatedStream and TaskToApm.

### Overview

After the removal of the Legacy TLS Provider, we can make some cleanups and
improvements to the `SslStream` class.  Since both the remaining providers
use the internal `MobileAuthenticatedStream` and support Task-async code,
we can get rid of some of the Begin/End async logic and the the underlying
`Stream` class handle it instead.

This also fixes a nasty issue with some of those task objects leaking
unobserved exceptions.  The problem was that `SslStream.Dispose()` needs to
clear out all resources, but in doing so also nulls out the `Impl` handle to
the `MobileAuthenticatedStream` - so a subsequent `End*()` call will not
reach it's corresponding `TaskToApm.End()` method.

There are also some cleanups in the internal APIs that were only ever used
internally and not intended for public consumption.

### Mono.Security.dll

* `Mono.Security.Interface`: removed internal `ICertificateValidator2` interface.

* `Mono.Security.Interface.IMonoSslStream`: this internal interface is only used
  by the web-tests, which only use it as a way to get the `SslStream` instance,
  so all those `Begin/End` async methods are now gone.

* `Mono.Security.Interface.IMonoSslStream2`: removed another internal interface.

* `Mono.Security.Interface.MonoTlsProvider`: removed some `internal abstract`
  methods; these have been moved into a new `Mono.Net.Security.MobileTlsProvider`
  inside `System.dll`.

### System.dll

* `Mono.Net.Security.MobileTlsProvider`:
  New abstract internal base class, which received the aforementioned abstract
  internal methods.  The naming is such to make it consistent with the already
  existing `MobileTlsContext` and `MobileAuthenticatedStream`.

Since both `AppleTlsProvider` and `BtlsProvider` now have an abstract internal
base class inside `System.dll`, they can use the `ChainValidationHelper` class
directly and we can also avoid some `Mono.Security` dances like for instance
that `MonoSslPolicyErrors` enum.

This will also help make the code easier to read and maintainer.

* `Mono.AppleTls.AppleTlsProvider` and `Mono.Btls.MonoBtlsProvider`: change base
  class into `MobileTlsProvider` and reflect above mentioned overload changes.

* `Mono.AppleTls.AppleCertificateHelper`: use `ChainValidationHelper` as well.

* `Mono.Net.Security.ChainValidationHelper`: only implement `ICertificateValidator`.
  The `ICertificateValidator` interface is still required because it is in use by
  the web-tests, but the previous `ICertificateValidator2` was an internal dance.

* `Mono.Net.Security.MobileAuthenticatedStream`: largely cleaned up this class.
  - we now implement the current slimmer version of `IMonoSslStream`.
  - moved all those overloads into `SslStream` that only fill in default values for
    some of their arguments and then call another overloaded version of their own.
  - removed lots of `Begin/End` methods that are not used anymore.

* `Mono.Net.Security.MonoTlsProviderFactory`: use `MobileTlsStream` everywhere.

* `Mono.Net.Security.MonoTlsStream`: cleanup `SslStream` creation logic; instead
  of going throw `provider.CreateSslStream()`, we can now use an internal constructor
  directly, thus avoiding the `IMonoSslStream` interface while also making the code
  a lot easier to read and understand.

* `System.Net.Mail.SmtpClient`: same here.

* `System.Net.HttpWebRequest`: use `MobileTlsProvider`.

* `System.Net.Security.SslStream`: largely cleaned up this class.
  - we now use `MobileAuthenticatedStream` directly instead of the `IMonoSslStream`
    interface and therefore could also get rid of `IMonoSslStream2`.
  - cleanup constructor logic to allow the internal constructor being used with a
    `MobileTlsProvider` instead of going through `provider.CreateSslStream()`.
  - all those overloads that are only filling in default values for some of their
    arguments before calling another overloaded version of their own now live here
    instead of in the `MobileAuthenticatedStream` class.  The reason is to simply that
    `MobileAuthenticatedStream` is already quite a complex and difficult class, and
    removing some of that complexity out of it will make it easier to understand.
  - handle the `TaskToApm.Begin()` / `TaskToApm.End()` here to ensure that we are not
    leaking any task objects with unobserved exceptions.
  - removed `BeginRead()` and `BeginWrite()` overloads to let the underlying `Stream`
    class handle these.

* [csproj] Update project files

* Bump api-snapshot
2019-10-25 10:21:25 +02:00
Steve Pfister 1553db019d Added missing SR.missing.cs from the backport 2019-10-24 21:31:28 -05:00
Steve Pfister 456c422eb4 Bump to mono/corefx@fb41040
Includes upstream corefx changes that makes NTLM auth work for more scenarios.

Backport of https://github.com/mono/mono/pull/17530
2019-10-24 21:31:28 -05:00
monojenkins 0c421f48b9 [2019-10] [reflection] mono_method_get_base_method on a GTD should use canonical ginst (#17492)
* [test] GetCustomAttributes on generic type definition

* [reflection] mono_method_get_base_method on a GTD should use canonical ginst

The issue is in how we pass along the generic instantiation.  So there are two
parts here: we start with a method on a GTD which has to decompose into the GTD
and it's instantiation with its own generic parameters, and then we go up to
its parent and grandparent inflating and decomposing the resulting
instantiation. The instantiations keep passing the last parameter as the number
of parameters shrinks so that the gparam index from the original type is now
out of bounds for the parent and grandparent.  If we mess up, we'll get a
BadImageFormatException from the runtime

Fixes https://github.com/mono/mono/issues/17278
2019-10-24 18:02:24 +02:00
monojenkins 3ecf0beab9 [2019-10] [debugger] Changing how debugger handles exception w… (#17523)
* Removing all fixes to fix #15203 and #17083, and trying a new approach to fix this #17084, together.

The thing is when we are executing on hybrid suspend the caller is executed inside try catch in the runtime_invoke_ method that is generated. And this try catch should be ignored for the debugger exception, otherwise it's the last try catch in main thread, but should always be considered to generate the stack trace.

Fixes #17084

* This test check the case that we were missing. On preemptive this test always runs perfectly, on Hybrid, never run well until this PR.

* Changing how call unit test. Changing variable name.
2019-10-24 09:13:55 -04:00
Marius Ungureanu 1b4cf8fadd Bump Bockbuild to pick-up gtk# binding change (#17486)
Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1005448
Which causes quite a few broken clipboard bugs and possible memory corruption

(cherry picked from commit 989333d6ae)
2019-10-23 14:35:54 +02:00
Aleksey Kliger (λgeek) d75c87694b [2019-10][bcl][jit] implement Interlocked.Exchange<T> in terms of object (#17372)
* [bcl][jit] implement Interlocked.Exchange<T> in terms of object

Exchange<T> is supposed to be picked up as an intrinsic.  But if it isn't,
since T has a class constraint, call the `Exchange (ref object, ref object, ref
object)` overload instead.

This works around a limitation in the JIT:
https://github.com/mono/mono/blob/82a07273c22b996b08fa88ee2e6632d782ac2242/mono/mini/mini-trampolines.c#L704-L713

if we're in the common call trampoline, and the caller is generic method and
the callee is a generic method, if we're using generic sharing for the caller,
but there's no generic jit info for the callee, we will not patch the call
site.

In this case we had Exchange<T> calling Exchange_T<T>
where the callee is an icall (and evidently didn't have generic jit info).

So every time we called Exchange<T>, we would go through the trampoline when
trying to call Exchange_T<T> without patching the call site.

Addresses part of https://github.com/mono/mono/issues/17334

* Bump mono corlib version

* Also drop CompareExchange_T<T>

* Sprinkle some Unsafe magic.

Mark the non-icall methods that we expect the JIT to treet as intrinsics with [Intrinsic]

* aot-runtime doesn't need Volatile.Read<T>/Write<T> code

Both of those methods are implemented as calls to the object overload of Volatile.Read/Write

* fix netcore build

* one more IntrinsicAttribute

* [bcl] Remove CompareExchange_T

In https://github.com/mono/mono/pull/17341 we change the caller of
CompareExchange_T<T>(ref T, ...) to call CompareExchange (ref object, ...), but
didn't delete the declaration.

It's already deleted in unmanaged and in the netcore version of this file.

* [bcl] Add null reference checks to Interlocked.Exchange<T>

and Interlocked.CompareExchange<T>

This is to mimic the old behavior in unmanaged when the intrinsic cannot be
used.

The issue was detected via the coreclr acceptance test:
https://github.com/mono/coreclr/blob/mono/tests/src/baseservices/threading/interlocked/exchange/exchangetneg.il

* and netcore

* Another Mono corlib version bump
2019-10-22 21:29:39 -04:00
monojenkins 1a511ea8f7 [2019-10] [jit] Avoid running mono_handle_native_crash () on the altstack, it can't produce a backtrace. AMD64 only for now. (#17470)
* [jit] Avoid running mono_handle_native_crash () on the altstack, it can't produce a backtrace. AMD64 only for now.

* Fix checks so stack overflows work again.
2019-10-22 11:55:21 -04:00
monojenkins 2783f7c2e6 [profiler] Fix coverage profiler on macos (#17421)
If we have coverage profiling enabled for a method (mono_profiler_coverage_instrumentation_enabled, with coverage_filter callback), then we should be able to allocate a coverage info structure (mono_profiler_coverage_alloc). After https://github.com/mono/mono/commit/52429673dc617fd437518757c04c7448211075e9, coverage_filter was reporting wrapper methods as ok to profile, while mono_profiler_coverage_alloc was refusing to allocate the necessary structure, leading to crashes.

Backport of #17396.
2019-10-21 17:59:54 +02:00
monojenkins 92cb296bf0 [2019-10] Remove the Legacy TLS Provider. (#17425)
* Remove the Legacy TLS Provider.

* `MonoTlsProviderFactory` now treats "legacy" as an alias for "default".

* `Mono.Net.Security/LegacySslStream`: Removed.  This class also wasn't using the
  `MobileAuthenticatedStream` base class, thus preventing cleanups simplifications
  in that area.

* `Mono.Net.Security/LegacyTlsProvider`: Removed.

* `Mono.Security/Mono.Security.Protocol.Tls*`: Removed all the old legacy code.

* `Mono.Security.Interface.MonoTlsProviderFactory`: Bump internal version to 4.

* [csproj] Update project files

* Bump API snapshot submodule
2019-10-21 17:52:36 +02:00
Thays Grazia 57660b72f4 [tests] Changing behavior of some tests in WatchOs
Needs this ifdefs because of this https://github.com/mono/mono/pull/17260.

Backport of https://github.com/mono/mono/pull/17423 and https://github.com/mono/mono/pull/17459
2019-10-21 16:22:44 +02:00
monojenkins e42ec96248 [2019-10] Enable GSS on Linux (#17409)
* Fix GSS on Linux

* fix build

* use gssapi_krb5

* enable on linux

* [csproj] Update project files

* enabled GSS for monodroid

* [csproj] Update project files
2019-10-18 11:33:51 +02:00
Zoltan Varga b19adbb585 [jit] Fix is_reference checks for intrinsics with byref parameters.
Found by https://github.com/mono/mono/issues/17335.
2019-10-18 11:15:18 +02:00
monojenkins 5fdab6d274 [2019-10] [corlib] Mark YieldAwaitable struct readonly (#17390)
* [corlib] Mark YieldAwaitable struct readonly

Make it consistent with .NET Standard/Core which makes future API Compat runs report one less difference.

* Bump API snapshot submodule
2019-10-17 17:49:33 +02:00
Filip Navara 893cf3ae31 Fix SafeHandle marshalling in ref/in/out parameters (#17330) (#17356)
* Fix SafeHandle marshalling in ref/in/out parameters

* Reorder code to make it exception safe, update comments

* Revert the code reordering because it breaks the invariant that new handle returned from native code should always create new SafeHandle on the managed side

* Fix test_0_safehandle_ref test. The test was expecting incorrect behavior, verified on .NET Core 3 and .NET Framework 4.8.

* Address PR feedback

* Fix cut & paste error

* Fix build

* Really fix the test_0_safehandle_ref tests

* Add more tests for SafeHandle marshalling

* Add exclusion for broken CoreFX test
2019-10-16 21:13:45 -04:00
monojenkins 5f655e63c5 Removing execution of network tests from WatchOs. (#17359) 2019-10-16 16:59:41 -03:00
Cody Russell 836d4f5f88 [GTK] Bump bockbuild for GtkViewport autoscrolling patch. (#17321)
(cherry picked from commit 37dc33a257)
2019-10-16 16:47:11 +02:00
monojenkins 46175a45bd [bcl] add WriteLine(string) override to CStreamWriter needed due to corefx import (#17337)
In https://github.com/mono/mono/commit/fd424c5dd07b2dbbd4aafbf9165a42166d789438 we switched over to the `TextWriter.cs`/`StreamWriter.cs` implementation of corefx. One subtle difference is that an override for `WriteLine(string)` in `StreamWriter` was introduced:
https://github.com/mono/corefx/blob/8e3b279377d1f01d2d089f24548e33855bf6502e/src/Common/src/CoreLib/System/IO/StreamWriter.cs#L526-L531
Previously the definition in `TextWriter` was used, which would call the base case `Write(char[])`.  The new override however won't call the base implementation at all, but directly uses the `Span`-variant.

This is a problem for our `CStreamWriter` implementation, since `WriteLine(string)` won't end up in the special handling for `Write(char[])`, which accounts for terminal cursor changes.

This is the real fix for https://github.com/mono/mono/issues/16701

This also reverts commit 68f5613422. ("[TermInfoDriver] update top/left value on Console.{CursorTop,CursorLeft} access (#16745)")
While it kind of masked the issue, it also posed a performance issue on some terminals (e.g. GNOME Terminal).
2019-10-15 22:29:54 +02:00
Aleksey Kliger (λgeek) bca33c0ec4 Update MERP event type to MonoAppCrash (#17291)
* Update parameters in MERP WerReportMetadata xml

To enable backend analysis, we need to update our parameters to match our back end event type, which is MonoAppCrash.

It doesn't make sense to me that the previous implementation constructed the XML here in Mono, but depended on the user (VSMac in this case) to add the "correct" event type.  The parameters in the XML, must match exactly what is expected for the given EventType, and so we should ensure they are always in-sync by defining them here.  Thus, I removed the usage of `eventType` in `mono_merp_enable` and hard coded the expected eventType.

* [merp] Don't pass eventType from managed

The eventType must me MONO_MERP_EVENT_TYPE_STR ("MonoAppCrash") - the backend
determines the format of the other fields based on the event type, so it
doesn't make sense to pass other values from managed since the runtime controls
the other fields.

For compatability Mono.Runtime.EnableMicrosoftTelemetry will still take a
string parameter (now called "unused" instead of "eventType_str") but it will
not pass it down to the internal call.

* Bump corlib version

* [merp] Revert paramerters in WerReportMetadata.xml

Still need event type to be `MonoAppCrash` but the parameters will be the same as before.
2019-10-15 14:42:16 -04:00
Aleksey Kliger e53a3041c0 [merp] Register SIGTERM handler in dump_native_stacktrace
Previously it was installed by EnableMicrosoftTelemetry, which is too early.
Now we get here without a handler installed even when mono_merp_enabled returns true.
2019-10-14 19:48:15 -05:00
Aleksey Kliger 09437dfdc7 [merp] Don't call install_state_summarizer in EnableMicrosoftTelemetry
install_state_summarizer installs a SIGTERM handler. Unfortunately
sigterm_signal_handler assumes that it will only be called when a crash is
already in progress (it assumes it won't be the supervisor, and so it doesn't
setup the memory for capturing a crash report among other things).
2019-10-14 19:48:15 -05:00
Alexander Köplinger f1303dd529 [ci] Restore previous values for no Xcode in CI_TAGS
It is still used by the non-pipeline PR builds (we should unify this at some point).

(cherry picked from commit 1a21ad7dd0)
2019-10-14 20:39:38 +02:00
Alexander Köplinger cd2f8bc293 [ci] Fix ios versions in Mono SDKs
(cherry picked from commit 62963dcfd9159821b99a68781e4adebebba0c98f)
2019-10-14 18:51:15 +02:00
Alexander Köplinger fa2ee06b70 Fix typo in last commit 2019-10-14 18:42:59 +02:00
Alexander Köplinger 6ba65ad1e2 [ci] Use Xcode11.1 for XI/XM Mono SDK builds (#17313)
As requested by the xamarin-macios team.

(cherry picked from commit 850def2f3b)
2019-10-14 18:38:50 +02:00
monojenkins 937cfd1bb6 [sdks] properly shutdown runtime for Mono.Debugger.Soft test app (#17293)
mini_jit_cleanup will cause mono_runtime_try_shutdown to be called before
mono_runtime_quit which will set the shutting down flags in the runtime.
2019-10-14 11:50:08 +02:00
monojenkins 329a1867e5 [2019-10] [merp] Print missing status marker file for stage 1 (setup) (#17221)
* [merp] Print missing status marker file for stage 1 (setup)

* Zeroing is not necessary, snprintf() always null-terminates in this case

* Remove unused variable
2019-10-11 13:53:37 -04:00
monojenkins 3a7e35c658 [2019-10] [System.Net.Http] Make HttpClientHandler on WatchOS always fallback (#17268)
* [System.Net.Http] Make HttpClientHandler on WatchOS always fallback

to platform handler. This simplifies HttpClientHandler in shared libraries
and the "default" socket handler would always throw PNSE anyway

* [csproj] Update project files
2019-10-11 09:47:26 +02:00
Alexander Köplinger 4c611593ac [tests] Bump corefx to get Azure testhost change (#17275)
* Bump corefx to get Azure testhost change

See https://github.com/mono/corefx/pull/360

* Update ClientWebSocketTest as well

(cherry picked from commit d457346e06)
2019-10-11 09:35:51 +02:00
monojenkins 91fe0b731b Update Linker. This fixes a Xamarin.Android breakage (#17273) 2019-10-10 16:26:06 -04:00
monojenkins 140dcdb7a3 [sgen] Fix invalid value passed to write barrier (#17248)
When doing memory copy dest is the destination address and src is the source address. If we are copying a single reference, we need to emit a write barrier and pass to the write barrier the value, not the pointer where the value is stored.
2019-10-09 14:51:59 +03:00
monojenkins 5cda28e320 [2019-10] Add drawing type converters to mobile profiles (#17239)
* Add drawing type converters to mobile profiles

Needed for https://github.com/xamarin/xamarin-android/issues/3726

* Bump API snapshot submodule

* [csproj] Update project files
2019-10-09 12:16:00 +02:00
monojenkins e1b0e94040 Revert mono_runtime_set_main_args in 44ff0597b8. It breaks Xamarin.Android. (#17234) 2019-10-09 00:53:53 -04:00
Jo Shields af8d610864 Bump version to 6.8 (#17206)
* Bump version to 6.8

* Add missing new linker source file

(cherry picked from commit a4e531d1f86fe0ff8a18764f30d97610cc2e1eb3)

* [csproj] Update project files

* No monolinker on MCS mode, new linker version needs Roslyn

(cherry picked from commit 6539e12e4050fc68d5aa11fdb4edfa582bb1d11e)
2019-10-07 22:35:13 +02:00
monojenkins 58eda9c781 [IO] Remove read-only logic in mono_w32_get_disk_free_space (#17208)
[2019-10] [IO] Remove read-only logic in mono_w32_get_disk_free_space

Fixes #17151

This brings us in line with GetDiskFreeSpaceExW on Windows as well as .NET Core.

I checked with the Android folks and it seems like this won't fail their test - all they check is that the returned value isn't `long.MaxValue`.

Backport of #17177.

/cc @akoeplinger @CoffeeFlux
2019-10-07 20:05:58 +02:00
331 changed files with 4608 additions and 13926 deletions

No files matched your search

+2 -1
View File
@@ -110,6 +110,8 @@
/mono/sgen @BrzVlad @lambdageek
/mono/tools/offsets-tool @lewurm @rolfbjarne
/mono/utils @vargaz @lewurm @lambdageek
/mono/utils/atomic* @lewurm @vargaz
/mono/utils/mono-hwcap* @lewurm @vargaz
@@ -150,6 +152,5 @@
/tools @lambdageek @vargaz
/tools/locale-builder @marek-safar @egorbo
/tools/nuget-hash-extractor @marek-safar @radical @akoeplinger
/tools/offsets-tool @lewurm @rolfbjarne
/tools/pedump @lambdageek @lewurm
/tools/sgen @brzvlad @vargaz @naricc
-2
View File
@@ -139,8 +139,6 @@ llvm/usr/
sdks/builds/llvm-*/
sdks/builds/android-*/
mcs/build/compiler-server.log
tools/offsets-tool-py/offtool/
##############################################################################
# Arcade output directories
+1 -1
View File
@@ -2,7 +2,7 @@
{
"name": "roslyn",
"url": "git://github.com/mono/roslyn.git",
"rev": "13a40eedacc799a78710aba5c8e4b2dcc80a7e61",
"rev": "6bfcd4e770609a38b8523e83ce1ec943162f30bb",
"remote-branch": "origin/mono-testing",
"branch": "mono-testing",
"directory": "roslyn"
+21 -13
View File
@@ -4,7 +4,7 @@
# This line is parsed by tools besides autoconf, such as msvc/mono.winconfig.targets.
# It should remain in the format they expect.
#
AC_INIT(mono, [6.7.0],
AC_INIT(mono, [6.8.0],
[https://github.com/mono/mono/issues/new])
AC_CONFIG_SRCDIR([README.md])
@@ -74,7 +74,7 @@ MONO_VERSION_BUILD=`echo $VERSION | cut -d . -f 3`
# This line is parsed by tools besides autoconf, such as msvc/mono.winconfig.targets.
# It should remain in the format they expect.
#
MONO_CORLIB_VERSION=de62d46f-9502-49c7-9842-841f367a6a3a
MONO_CORLIB_VERSION=ABB721D6-116A-4555-B4FD-9248146D2051
#
# Put a quoted #define in config.h.
@@ -1354,7 +1354,7 @@ enable_cooperative_suspend_default=no
enable_hybrid_suspend_default=no
# For the sake of clearer error messages, these numbers should all be different from each other.
INVARIANT_AOT_OPTIONS=nimt-trampolines=2000,ntrampolines=10000,nrgctx-fetch-trampolines=256,ngsharedvt-trampolines=4400,nftnptr-arg-trampolines=4000
INVARIANT_AOT_OPTIONS=nimt-trampolines=2000,ntrampolines=10000,nrgctx-fetch-trampolines=256,ngsharedvt-trampolines=4400,nftnptr-arg-trampolines=4000,nrgctx-trampolines=21000
AOT_BUILD_ATTRS=$INVARIANT_AOT_OPTIONS
@@ -2951,13 +2951,6 @@ if test x$host_win32 = xno; then
AC_SEARCH_LIBS(shm_open, pthread rt posix4)
AC_CHECK_FUNCS(shm_open)
dnl ********************************
dnl *** Checks for gettext lib ***
dnl ********************************
# This is needed for some hackery for AIX;
# Mono itself doesn't use it, but DllMap includes it
AC_SEARCH_LIBS([gettext], [intl])
dnl ********************************
dnl *** Checks for timezone stuff **
dnl ********************************
@@ -3411,6 +3404,15 @@ if test x$host_win32 = xno; then
AC_CHECK_DECL(ICANON, [AC_DEFINE(HAVE_ICANON, 1, [ICANON])], [], [[#include <termios.h>]])
AC_CHECK_DECL(TCSANOW, [AC_DEFINE(HAVE_TCSANOW, 1, [TCSANOW])], [], [[#include <termios.h>]])
AC_CHECK_DECL(lchflags, [AC_DEFINE(HAVE_LCHFLAGS, 1, [lchflags])], [],
[[#include <sys/types.h>
#include <sys/stat.h>]])
AC_CHECK_MEMBER(struct stat.st_flags,
[AC_DEFINE(HAVE_STAT_FLAGS, 1, [struct stat.st_flags])],
[],
[#include <sys/types.h>
#include <sys/stat.h>])
AC_CHECK_MEMBER(struct stat.st_birthtimespec,
[AC_DEFINE(HAVE_STAT_BIRTHTIME, 1, [struct stat.st_birthtimespec])],
[],
@@ -3798,6 +3800,7 @@ if test x$host_win32 = xno; then
AC_DEFINE(HAVE_GSSFW_HEADERS, 1, [GSS/GSS.h])
AC_DEFINE(HAVE_GSS_SPNEGO_MECHANISM, 1, [GSS_SPNEGO_MECHANISM])
enable_gss=yes
AC_DEFINE(ENABLE_GSS, 1, [ENABLE_GSS])
], [
AC_MSG_RESULT(no)
])
@@ -3809,6 +3812,7 @@ if test x$host_win32 = xno; then
],[
AC_MSG_RESULT(yes)
enable_gss=yes
AC_DEFINE(ENABLE_GSS, 1, [ENABLE_GSS])
], [
AC_MSG_RESULT(no)
])
@@ -6055,8 +6059,8 @@ fi
AC_SUBST(mono_runtime)
AC_SUBST(mono_runtime_wrapper)
CSC_LOCATION=`cd $srcdir && pwd`/external/roslyn-binaries/Microsoft.Net.Compilers/3.3.0/csc.exe
VBCS_LOCATION=`cd $srcdir && pwd`/external/roslyn-binaries/Microsoft.Net.Compilers/3.3.0/VBCSCompiler.exe
CSC_LOCATION=`cd $srcdir && pwd`/external/roslyn-binaries/Microsoft.Net.Compilers/3.5.0/csc.exe
VBCS_LOCATION=`cd $srcdir && pwd`/external/roslyn-binaries/Microsoft.Net.Compilers/3.5.0/VBCSCompiler.exe
if test $csc_compiler = mcs; then
CSC=$mcs_topdir/class/lib/build/mcs.exe
@@ -6422,7 +6426,11 @@ elif test x$host_linux = xyes; then
MONO_NATIVE_CXXFLAGS=$CXXFLAGS
MONO_NATIVE_CFLAGS=$CFLAGS
MONO_NATIVE_LDFLAGS=$LDFLAGS
if test x$enable_gss = xyes; then
MONO_NATIVE_LDFLAGS="$MONO_NATIVE_LDFLAGS -lgssapi_krb5"
else
AC_MSG_WARN([GSS is not enabled, it requires libkrb5-dev package])
fi
mono_native=yes
mono_native_compat=no
MONO_NATIVE_PLATFORM=linux
+1 -1
+1 -1
+1 -1
+1
View File
@@ -38,5 +38,6 @@ NO_CONSOLE = yes
ifeq ($(HOST_PLATFORM),win32)
PROFILE_MCS_FLAGS += -d:MOBILE_DESKTOP_HOST -d:WIN_PLATFORM
endif
ENABLE_GSS=1
PROFILE_TEST_HARNESS_EXCLUDES = MobileNotWorking PKITS InetAccess AndroidNotWorking
+4
View File
@@ -23,3 +23,7 @@ ifeq ($(HOST_PLATFORM),macos)
MONO_FEATURE_APPLETLS=1
ENABLE_GSS=1
endif
ifeq ($(HOST_PLATFORM),linux)
ENABLE_GSS=1
endif
+1
View File
@@ -44,4 +44,5 @@ NO_CONSOLE = yes
NO_MULTIPLE_APPDOMAINS = yes
NO_THREAD_ABORT = yes
NO_THREAD_SUSPEND_RESUME = yes
PROFILE_DISABLE_BTLS = yes
WASM = yes
+56 -41
View File
@@ -89,26 +89,32 @@ endif
test_lib = $(PROFILE)_$(ASSEMBLY:$(ASSEMBLY_EXT)=_test.dll)
test_lib_output = $(test_lib_dir)/$(test_lib)
test_sourcefile_base_excludes = $(test_lib).exclude.sources
test_library = $(ASSEMBLY:$(ASSEMBLY_EXT)=)_test$(ASSEMBLY_EXT)
test_response = $(depsdir)/$(PROFILE_PLATFORM)_$(PROFILE)_$(test_library).response
test_makefrag = $(depsdir)/$(PROFILE_PLATFORM)_$(PROFILE)_$(test_library).makefrag
test_pdb = $(test_lib:.dll=.pdb)
test_flags = $(test_nunit_ref) $(TEST_MCS_FLAGS) $(TEST_LIB_MCS_FLAGS)
ifndef NO_BUILD
test_flags += -r:$(the_assembly)
test_assembly_dep = $(the_assembly)
endif
tests_CLEAN_FILES += $(test_lib_output) $(test_lib_output:$(ASSEMBLY_EXT)=.pdb)
tests_CLEAN_FILES += $(test_lib_output) $(test_response) $(test_makefrag)
xtest_sourcefile_base = $(PROFILE_PLATFORM)_$(PROFILE)_$(ASSEMBLY:$(ASSEMBLY_EXT)=_xtest.dll.sources)
xtest_sourcefile_base_excludes_full = $(PROFILE_PLATFORM)_$(PROFILE)_$(ASSEMBLY:$(ASSEMBLY_EXT)=_xtest.dll.exclude.sources)
xtest_sourcefile_base_excludes = $(xtest_sourcefile_base_excludes_full:_%=%)
xunit_test_lib = $(PROFILE)_$(ASSEMBLY:$(ASSEMBLY_EXT)=_xunit-test.dll)
xtest_lib_output = $(test_lib_dir)/$(xunit_test_lib)
xtest_response = $(depsdir)/$(xunit_test_lib).response
xtest_makefrag = $(depsdir)/$(xunit_test_lib).makefrag
xtest_flags = -r:$(the_assembly) $(xunit_libs_ref) $(XTEST_MCS_FLAGS) $(XTEST_LIB_MCS_FLAGS) /unsafe
xtest_library = $(ASSEMBLY:$(ASSEMBLY_EXT)=)_xtest$(ASSEMBLY_EXT)
xtest_response = $(depsdir)/$(PROFILE_PLATFORM)_$(PROFILE)_$(xtest_library).response
xtest_makefrag = $(depsdir)/$(PROFILE_PLATFORM)_$(PROFILE)_$(xtest_library).makefrag
xtest_flags = $(xunit_libs_ref) $(XTEST_MCS_FLAGS) $(XTEST_LIB_MCS_FLAGS) /unsafe
ifndef NO_BUILD
xtest_flags += -r:$(the_assembly)
xtest_assembly_dep = $(the_assembly)
endif
ifeq ($(wildcard $(xtest_sourcefile_base)),)
xtest_sourcefile_base = $(ASSEMBLY:$(ASSEMBLY_EXT)=_xtest.dll.sources)
@@ -140,6 +146,10 @@ test_assemblies :=
ifdef HAVE_CS_TESTS
test_assemblies += $(test_lib_output)
ifdef TEST_SPLIT_ASSEMBLIES
test_assemblies += $(test_lib_output:.dll=.part1.dll) $(test_lib_output:.dll=.part2.dll)
endif
check: run-test
test-local: $(test_assemblies) $(test_lib_dir)/nunit-excludes.txt
run-test-local: run-test-lib
@@ -262,44 +272,34 @@ endif
TEST_FILES =
ifdef HAVE_CS_TESTS
TEST_FILES += `sed -e '/^$$/d' -e 's,^../,,' -e '/^\#.*$$/d' -et -e 's,^,Test/,' $(test_sourcefile_base)`
endif
ifdef HAVE_CS_TESTS
TEST_FILES += `sed -e '/^$$/d' -e 's,^../,,' -e '/^\#.*$$/d' -et -e 's,^,Test/,' $(test_sourcefile_base)`
$(test_lib_dir):
mkdir -p $@
test_library = $(ASSEMBLY:$(ASSEMBLY_EXT)=)_test$(ASSEMBLY_EXT)
test_sourcefile = $(depsdir)/$(PROFILE_PLATFORM)_$(PROFILE)_$(test_library).sources
$(test_sourcefile): $(test_sourcefile_base) $(wildcard *_test.dll.sources) $(wildcard *_test.dll.exclude.sources) $(depsdir)/.stamp
$(GENSOURCES) --basedir:./Test --strict --platformsdir:$(topdir)/build "$@" "$(test_library)" "$(PROFILE_PLATFORM)" "$(PROFILE)"
test_response = $(depsdir)/$(PROFILE_PLATFORM)_$(PROFILE)_$(test_library).response
$(test_response): $(test_sourcefile) $(topdir)/build/tests.make $(depsdir)/.stamp
$(PLATFORM_CHANGE_SEPARATOR_CMD) <$(test_sourcefile) >$@
test_makefrag = $(depsdir)/$(PROFILE_PLATFORM)_$(PROFILE)_$(test_library).makefrag
$(test_makefrag): $(test_sourcefile) $(topdir)/build/tests.make $(depsdir)/.stamp
@echo Creating $@ ...
@sed 's,^,$(build_lib): ,' $< >$@
@if test ! -f $(test_sourcefile).makefrag; then :; else \
cat $(test_sourcefile).makefrag >> $@ ; \
echo '$@: $(test_sourcefile).makefrag' >> $@; \
echo '$(test_sourcefile).makefrag:' >> $@; fi
$(test_lib_output): $(test_assembly_dep) $(test_response) $(test_nunit_dep) $(test_lib_output).nunitlite.config | $(test_lib_dir)
$(TEST_COMPILE) $(LIBRARY_FLAGS) -target:library -out:$@ $(test_flags) $(LOCAL_TEST_COMPILER_ONDOTNET_FLAGS) @$(test_response)
tests_CLEAN_FILES += $(test_sourcefile) $(test_response) $(test_makefrag)
ifdef TEST_SPLIT_ASSEMBLIES
$(test_lib_output:.dll=.part1.dll): $(test_lib_output) $(test_response).part1
$(TEST_COMPILE) $(LIBRARY_FLAGS) -target:library -out:$@ $(test_flags) $(LOCAL_TEST_COMPILER_ONDOTNET_FLAGS) @$(test_response).part1
$(test_lib_output:.dll=.part2.dll): $(test_lib_output) $(test_response).part2
$(TEST_COMPILE) $(LIBRARY_FLAGS) -target:library -out:$@ $(test_flags) $(LOCAL_TEST_COMPILER_ONDOTNET_FLAGS) @$(test_response).part2
tests_CLEAN_FILES += $(test_response).part1 $(test_response).part2
endif
$(test_response): $(test_sourcefile_base) $(wildcard *_test.dll.sources) $(wildcard *_test.dll.exclude.sources) $(topdir)/build/tests.make $(depsdir)/.stamp
$(GENSOURCES) --basedir:./Test --strict --platformsdir:$(topdir)/build "$@" "$(test_library)" "$(PROFILE_PLATFORM)" "$(PROFILE)"
$(test_makefrag): $(test_response)
@echo Creating $@ ...
@sed 's,^,$(test_lib_output) $(test_lib_output:.dll=.part1.dll) $(test_lib_output:.dll=.part2.dll): ,' $< >$@
-include $(test_makefrag)
build-test-lib: $(test_lib_output)
@echo Building testing lib
endif
@@ -336,8 +336,15 @@ ifdef COVERAGE
XTEST_COVERAGE_FLAGS = -O=-aot --profile=coverage:output=$(topdir)/class/lib/$(PROFILE_DIRECTORY)/coverage_xunit_$(ASSEMBLY).xml
endif
xtest_assemblies += $(xtest_lib_output)
ifdef XTEST_SPLIT_ASSEMBLIES
xtest_assemblies += $(xtest_lib_output:.dll=.part1.dll) $(xtest_lib_output:.dll=.part2.dll)
endif
check: run-xunit-test-local
xunit-test-local: $(xtest_lib_output) $(test_lib_dir)/xunit-excludes.txt $(test_lib_dir)/Xunit.NetCore.Extensions.dll $(test_lib_dir)/xunit.execution.dotnet.dll
xunit-test-local: $(xtest_assemblies) $(test_lib_dir)/xunit-excludes.txt $(test_lib_dir)/Xunit.NetCore.Extensions.dll $(test_lib_dir)/xunit.execution.dotnet.dll
run-xunit-test-local: run-xunit-test-lib
$(test_lib_dir)/xunit-excludes.txt: $(topdir)/build/tests.make | $(test_lib_dir)
@@ -360,19 +367,27 @@ run-xunit-test-lib: xunit-test-local
$(XTEST_REMOTE_EXECUTOR): $(topdir)/../external/corefx/src/Common/tests/System/Diagnostics/RemoteExecutorConsoleApp/RemoteExecutorConsoleApp.cs | $(test_lib_dir)
$(TEST_COMPILE) -r:$(topdir)/class/lib/$(PROFILE)/mscorlib.dll $< -out:$@
$(xtest_lib_output): $(the_assembly) $(xtest_response) $(xunit_libs_dep) $(xunit_src) $(XTEST_REMOTE_EXECUTOR) | $(test_lib_dir)
$(xtest_lib_output): $(xtest_assembly_dep) $(xtest_response) $(xunit_libs_dep) $(xunit_src) $(XTEST_REMOTE_EXECUTOR) | $(test_lib_dir)
$(TEST_COMPILE) $(LIBRARY_FLAGS) $(XTEST_LIB_FLAGS) -target:library -out:$@ $(xtest_flags) @$(xtest_response) $(xunit_src)
xtest_response_preprocessed = $(xtest_response)_preprocessed
ifdef XTEST_SPLIT_ASSEMBLIES
$(xtest_lib_output:.dll=.part1.dll): $(xtest_lib_output) $(xtest_response).part1
$(TEST_COMPILE) $(LIBRARY_FLAGS) $(XTEST_LIB_FLAGS) -target:library -out:$@ $(xtest_flags) @$(xtest_response).part1 $(xunit_src)
$(xtest_lib_output:.dll=.part2.dll): $(xtest_lib_output) $(xtest_response).part2
$(TEST_COMPILE) $(LIBRARY_FLAGS) $(XTEST_LIB_FLAGS) -target:library -out:$@ $(xtest_flags) @$(xtest_response).part2 $(xunit_src)
xtests_CLEAN_FILES += $(xtest_response).part1 $(xtest_response).part2
endif
# This handles .excludes/.sources pairs, as well as resolving the
# includes that occur in .sources files
$(xtest_response): $(xtest_sourcefile_base) $(wildcard *xtest.dll.sources) $(wildcard $(xtest_sourcefile_base_excludes))
$(GENSOURCES) --strict --platformsdir:$(topdir)/build "$@" "$(xtest_sourcefile_base)" "$(xtest_sourcefile_base_excludes)"
# includes that occur in .sources files. It also handles splitting test assemblies into multiple parts.
$(xtest_response): $(xtest_sourcefile_base) $(wildcard *_xtest.dll.sources) $(wildcard *_xtest.dll.exclude.sources) $(topdir)/build/tests.make $(depsdir)/.stamp
$(GENSOURCES) --strict --platformsdir:$(topdir)/build "$@" "$(xtest_library)" "$(PROFILE_PLATFORM)" "$(PROFILE)"
$(xtest_makefrag): $(xtest_response)
$(xtest_makefrag): $(xtest_response) $(xtest_response_parts)
@echo Creating $@ ...
@sed 's,^,$(xtest_lib_output): ,' $< >$@
@sed 's,^,$(xtest_lib_output) $(xtest_lib_output:.dll=.part1.dll) $(xtest_lib_output:.dll=.part2.dll): ,' $< >$@
-include $(xtest_makefrag)
@@ -29,72 +29,72 @@
<PropertyGroup Condition=" '$(Platform)' == 'monodroid' ">
<OutputPath>./../../../class/lib/monodroid/Facades</OutputPath>
<IntermediateOutputPath>./../../../class/obj/$(AssemblyName)-Facades</IntermediateOutputPath>
<DefineConstants>NET_1_1;NET_2_0;NET_2_1;NET_3_5;NET_4_0;NET_4_5;MONO;MOBILE;MOBILE_LEGACY;MOBILE_DYNAMIC;MONODROID;ANDROID</DefineConstants>
<DefineConstants>NET_1_1;NET_2_0;NET_2_1;NET_3_5;NET_4_0;NET_4_5;MONO;MOBILE;MOBILE_LEGACY;MOBILE_DYNAMIC;MONODROID;ANDROID;FEATURE_TYPECONVERTER</DefineConstants>
</PropertyGroup>
<PropertyGroup Condition=" '$(Platform)' == 'monotouch' ">
<OutputPath>./../../../class/lib/monotouch/Facades</OutputPath>
<IntermediateOutputPath>./../../../class/obj/$(AssemblyName)-Facades</IntermediateOutputPath>
<DefineConstants>NET_1_1;NET_2_0;NET_2_1;NET_3_5;NET_4_0;NET_4_5;MOBILE;MOBILE_LEGACY;MONO;MONOTOUCH;DISABLE_COM;FEATURE_INTERCEPTABLE_THREADPOOL_CALLBACK;FULL_AOT_RUNTIME</DefineConstants>
<DefineConstants>NET_1_1;NET_2_0;NET_2_1;NET_3_5;NET_4_0;NET_4_5;MOBILE;MOBILE_LEGACY;MONO;MONOTOUCH;DISABLE_COM;FEATURE_INTERCEPTABLE_THREADPOOL_CALLBACK;FULL_AOT_RUNTIME;FEATURE_TYPECONVERTER</DefineConstants>
</PropertyGroup>
<PropertyGroup Condition=" '$(Platform)' == 'monotouch_watch' ">
<OutputPath>./../../../class/lib/monotouch_watch/Facades</OutputPath>
<IntermediateOutputPath>./../../../class/obj/$(AssemblyName)-Facades</IntermediateOutputPath>
<DefineConstants>NET_1_1;NET_2_0;NET_2_1;NET_3_5;NET_4_0;NET_4_5;MOBILE;MOBILE_LEGACY;MONO;MONOTOUCH;DISABLE_COM;FEATURE_INTERCEPTABLE_THREADPOOL_CALLBACK;FULL_AOT_RUNTIME;FEATURE_NO_BSD_SOCKETS;MONOTOUCH_WATCH</DefineConstants>
<DefineConstants>NET_1_1;NET_2_0;NET_2_1;NET_3_5;NET_4_0;NET_4_5;MOBILE;MOBILE_LEGACY;MONO;MONOTOUCH;DISABLE_COM;FEATURE_INTERCEPTABLE_THREADPOOL_CALLBACK;FULL_AOT_RUNTIME;FEATURE_NO_BSD_SOCKETS;MONOTOUCH_WATCH;FEATURE_TYPECONVERTER</DefineConstants>
</PropertyGroup>
<PropertyGroup Condition=" '$(Platform)' == 'monotouch_tv' ">
<OutputPath>./../../../class/lib/monotouch_tv/Facades</OutputPath>
<IntermediateOutputPath>./../../../class/obj/$(AssemblyName)-Facades</IntermediateOutputPath>
<DefineConstants>NET_1_1;NET_2_0;NET_2_1;NET_3_5;NET_4_0;NET_4_5;MOBILE;MOBILE_LEGACY;MONO;MONOTOUCH;DISABLE_COM;FEATURE_INTERCEPTABLE_THREADPOOL_CALLBACK;FULL_AOT_RUNTIME;MONOTOUCH_TV</DefineConstants>
<DefineConstants>NET_1_1;NET_2_0;NET_2_1;NET_3_5;NET_4_0;NET_4_5;MOBILE;MOBILE_LEGACY;MONO;MONOTOUCH;DISABLE_COM;FEATURE_INTERCEPTABLE_THREADPOOL_CALLBACK;FULL_AOT_RUNTIME;MONOTOUCH_TV;FEATURE_TYPECONVERTER</DefineConstants>
</PropertyGroup>
<PropertyGroup Condition=" '$(Platform)' == 'testing_aot_full_interp' ">
<OutputPath>./../../../class/lib/testing_aot_full_interp/Facades</OutputPath>
<IntermediateOutputPath>./../../../class/obj/$(AssemblyName)-Facades</IntermediateOutputPath>
<DefineConstants>NET_1_1;NET_2_0;NET_2_1;NET_3_5;NET_4_0;NET_4_5;MONO;MOBILE;MOBILE_LEGACY;DISABLE_REMOTING;DISABLE_SECURITY;FULL_AOT_INTERP;DISABLE_COM</DefineConstants>
<DefineConstants>NET_1_1;NET_2_0;NET_2_1;NET_3_5;NET_4_0;NET_4_5;MONO;MOBILE;MOBILE_LEGACY;DISABLE_REMOTING;DISABLE_SECURITY;FULL_AOT_INTERP;DISABLE_COM;FEATURE_TYPECONVERTER</DefineConstants>
</PropertyGroup>
<PropertyGroup Condition=" '$(Platform)' == 'testing_aot_hybrid' ">
<OutputPath>./../../../class/lib/testing_aot_hybrid/Facades</OutputPath>
<IntermediateOutputPath>./../../../class/obj/$(AssemblyName)-Facades</IntermediateOutputPath>
<DefineConstants>NET_1_1;NET_2_0;NET_2_1;NET_3_5;NET_4_0;NET_4_5;MONO;MOBILE;MOBILE_LEGACY;DISABLE_REMOTING;DISABLE_SECURITY;MOBILE_DYNAMIC</DefineConstants>
<DefineConstants>NET_1_1;NET_2_0;NET_2_1;NET_3_5;NET_4_0;NET_4_5;MONO;MOBILE;MOBILE_LEGACY;DISABLE_REMOTING;DISABLE_SECURITY;MOBILE_DYNAMIC;FEATURE_TYPECONVERTER</DefineConstants>
</PropertyGroup>
<PropertyGroup Condition=" '$(Platform)' == 'testing_aot_full' ">
<OutputPath>./../../../class/lib/testing_aot_full/Facades</OutputPath>
<IntermediateOutputPath>./../../../class/obj/$(AssemblyName)-Facades</IntermediateOutputPath>
<DefineConstants>NET_1_1;NET_2_0;NET_2_1;NET_3_5;NET_4_0;NET_4_5;MONO;MOBILE;MOBILE_LEGACY;DISABLE_REMOTING;DISABLE_SECURITY;FULL_AOT_DESKTOP;FULL_AOT_RUNTIME;DISABLE_COM</DefineConstants>
<DefineConstants>NET_1_1;NET_2_0;NET_2_1;NET_3_5;NET_4_0;NET_4_5;MONO;MOBILE;MOBILE_LEGACY;DISABLE_REMOTING;DISABLE_SECURITY;FULL_AOT_DESKTOP;FULL_AOT_RUNTIME;DISABLE_COM;FEATURE_TYPECONVERTER</DefineConstants>
</PropertyGroup>
<PropertyGroup Condition=" '$(Platform)' == 'winaot' ">
<OutputPath>./../../../class/lib/winaot/Facades</OutputPath>
<IntermediateOutputPath>./../../../class/obj/$(AssemblyName)-Facades</IntermediateOutputPath>
<DefineConstants>NET_1_1;NET_2_0;NET_2_1;NET_3_5;NET_4_0;NET_4_5;MONO;MOBILE;MOBILE_LEGACY;DISABLE_COM;WIN_PLATFORM;WINAOT;FULL_AOT_DESKTOP;FULL_AOT_RUNTIME</DefineConstants>
<DefineConstants>NET_1_1;NET_2_0;NET_2_1;NET_3_5;NET_4_0;NET_4_5;MONO;MOBILE;MOBILE_LEGACY;DISABLE_COM;WIN_PLATFORM;WINAOT;FULL_AOT_DESKTOP;FULL_AOT_RUNTIME;FEATURE_TYPECONVERTER</DefineConstants>
</PropertyGroup>
<PropertyGroup Condition=" '$(Platform)' == 'testing_winaot_interp' ">
<OutputPath>./../../../class/lib/testing_winaot_interp/Facades</OutputPath>
<IntermediateOutputPath>./../../../class/obj/$(AssemblyName)-Facades</IntermediateOutputPath>
<DefineConstants>NET_1_1;NET_2_0;NET_2_1;NET_3_5;NET_4_0;NET_4_5;MONO;MOBILE;MOBILE_LEGACY;DISABLE_COM;WIN_PLATFORM;WINAOT;FULL_AOT_INTERP;DISABLE_SECURITY;DISABLE_REMOTING</DefineConstants>
<DefineConstants>NET_1_1;NET_2_0;NET_2_1;NET_3_5;NET_4_0;NET_4_5;MONO;MOBILE;MOBILE_LEGACY;DISABLE_COM;WIN_PLATFORM;WINAOT;FULL_AOT_INTERP;DISABLE_SECURITY;DISABLE_REMOTING;FEATURE_TYPECONVERTER</DefineConstants>
</PropertyGroup>
<PropertyGroup Condition=" '$(Platform)' == 'xammac' ">
<OutputPath>./../../../class/lib/xammac/Facades</OutputPath>
<IntermediateOutputPath>./../../../class/obj/$(AssemblyName)-Facades</IntermediateOutputPath>
<DefineConstants>NET_1_1;NET_2_0;NET_2_1;NET_3_5;NET_4_0;NET_4_5;MONO;MOBILE;MOBILE_DYNAMIC;XAMMAC;FEATURE_INTERCEPTABLE_THREADPOOL_CALLBACK;XAMARIN_MODERN</DefineConstants>
<DefineConstants>NET_1_1;NET_2_0;NET_2_1;NET_3_5;NET_4_0;NET_4_5;MONO;MOBILE;MOBILE_DYNAMIC;XAMMAC;FEATURE_INTERCEPTABLE_THREADPOOL_CALLBACK;XAMARIN_MODERN;FEATURE_TYPECONVERTER</DefineConstants>
</PropertyGroup>
<PropertyGroup Condition=" '$(Platform)' == 'xammac_net_4_5' ">
<OutputPath>./../../../class/lib/xammac_net_4_5/Facades</OutputPath>
<IntermediateOutputPath>./../../../class/obj/$(AssemblyName)-Facades</IntermediateOutputPath>
<DefineConstants>NET_4_0;NET_4_5;NET_4_6;MONO;FEATURE_INTERCEPTABLE_THREADPOOL_CALLBACK;NO_SYSTEM_DRAWING_DEPENDENCY;NO_WINFORMS_DEPENDENCY;NO_SYSTEM_WEB_DEPENDENCY;XAMMAC_4_5;XAMARIN_MODERN</DefineConstants>
<DefineConstants>NET_4_0;NET_4_5;NET_4_6;MONO;FEATURE_INTERCEPTABLE_THREADPOOL_CALLBACK;NO_SYSTEM_DRAWING_DEPENDENCY;NO_WINFORMS_DEPENDENCY;NO_SYSTEM_WEB_DEPENDENCY;XAMMAC_4_5;XAMARIN_MODERN;FEATURE_TYPECONVERTER</DefineConstants>
</PropertyGroup>
<PropertyGroup Condition=" '$(Platform)' == 'orbis' ">
<OutputPath>./../../../class/lib/orbis/Facades</OutputPath>
<IntermediateOutputPath>./../../../class/obj/$(AssemblyName)-Facades</IntermediateOutputPath>
<DefineConstants>NET_1_1;NET_2_0;NET_2_1;NET_3_5;NET_4_0;NET_4_5;MONO;MOBILE;MOBILE_LEGACY;FULL_AOT_DESKTOP;FULL_AOT_RUNTIME;ORBIS;DISABLE_COM</DefineConstants>
<DefineConstants>NET_1_1;NET_2_0;NET_2_1;NET_3_5;NET_4_0;NET_4_5;MONO;MOBILE;MOBILE_LEGACY;FULL_AOT_DESKTOP;FULL_AOT_RUNTIME;ORBIS;DISABLE_COM;FEATURE_TYPECONVERTER</DefineConstants>
</PropertyGroup>
<PropertyGroup Condition=" '$(Platform)' == 'unreal' ">
<OutputPath>./../../../class/lib/unreal/Facades</OutputPath>
<IntermediateOutputPath>./../../../class/obj/$(AssemblyName)-Facades</IntermediateOutputPath>
<DefineConstants>NET_1_1;NET_2_0;NET_2_1;MOBILE;MOBILE_DYNAMIC;NET_3_5;NET_4_0;NET_4_5;MONO</DefineConstants>
<DefineConstants>NET_1_1;NET_2_0;NET_2_1;MOBILE;MOBILE_DYNAMIC;NET_3_5;NET_4_0;NET_4_5;MONO;FEATURE_TYPECONVERTER</DefineConstants>
</PropertyGroup>
<PropertyGroup Condition=" '$(Platform)' == 'wasm' ">
<OutputPath>./../../../class/lib/wasm/Facades</OutputPath>
<IntermediateOutputPath>./../../../class/obj/$(AssemblyName)-Facades</IntermediateOutputPath>
<DefineConstants>NET_1_1;NET_2_0;NET_2_1;NET_3_5;NET_4_0;NET_4_5;MONO;MOBILE;MOBILE_LEGACY;FULL_AOT_DESKTOP;FULL_AOT_RUNTIME;WASM;DISABLE_COM;FEATURE_NO_BSD_SOCKETS;DISABLE_REMOTING;DISABLE_SECURITY</DefineConstants>
<DefineConstants>NET_1_1;NET_2_0;NET_2_1;NET_3_5;NET_4_0;NET_4_5;MONO;MOBILE;MOBILE_LEGACY;FULL_AOT_DESKTOP;FULL_AOT_RUNTIME;WASM;DISABLE_COM;FEATURE_NO_BSD_SOCKETS;DISABLE_REMOTING;DISABLE_SECURITY;FEATURE_TYPECONVERTER</DefineConstants>
</PropertyGroup>
<!-- @ALL_PROFILE_PROPERTIES@ -->
<PropertyGroup Condition=" '$(Configuration)' == 'Debug' ">
@@ -13,7 +13,7 @@ KEYFILE = ../../Open.snk
LIBRARY_SNK = $(KEYFILE)
SIGN_FLAGS = /delaysign /nowarn:1616,1699
LIB_REFS = System
LIB_MCS_FLAGS = $(SIGN_FLAGS) $(EXTRA_LIB_MCS_FLAGS)
LIB_MCS_FLAGS = $(SIGN_FLAGS) $(EXTRA_LIB_MCS_FLAGS) -d:FEATURE_TYPECONVERTER
ifneq (,$(filter build net_4_x, $(PROFILE)))
$(error This profile shouldn't build System.Drawing.Common.dll, it already has System.Drawing.dll)
@@ -27,14 +27,28 @@
[assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Security.Cryptography.Pkcs.CmsRecipient))]
[assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Security.Cryptography.Pkcs.CmsRecipientCollection))]
[assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Security.Cryptography.Pkcs.CmsRecipientEnumerator))]
[assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Security.Cryptography.Pkcs.CmsSigner))]
[assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Security.Cryptography.Pkcs.ContentInfo))]
[assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Security.Cryptography.Pkcs.EnvelopedCms))]
[assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Security.Cryptography.Pkcs.KeyAgreeRecipientInfo))]
[assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Security.Cryptography.Pkcs.KeyTransRecipientInfo))]
[assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Security.Cryptography.Pkcs.Pkcs12Builder))]
[assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Security.Cryptography.Pkcs.Pkcs12CertBag))]
[assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Security.Cryptography.Pkcs.Pkcs12ConfidentialityMode))]
[assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Security.Cryptography.Pkcs.Pkcs12Info))]
[assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Security.Cryptography.Pkcs.Pkcs12IntegrityMode))]
[assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Security.Cryptography.Pkcs.Pkcs12KeyBag))]
[assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Security.Cryptography.Pkcs.Pkcs12SafeBag))]
[assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Security.Cryptography.Pkcs.Pkcs12SafeContents))]
[assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Security.Cryptography.Pkcs.Pkcs12SafeContentsBag))]
[assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Security.Cryptography.Pkcs.Pkcs12SecretBag))]
[assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Security.Cryptography.Pkcs.Pkcs12ShroudedKeyBag))]
[assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Security.Cryptography.Pkcs.Pkcs8PrivateKeyInfo))]
[assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Security.Cryptography.Pkcs.Pkcs9AttributeObject))]
[assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Security.Cryptography.Pkcs.Pkcs9ContentType))]
[assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Security.Cryptography.Pkcs.Pkcs9DocumentDescription))]
[assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Security.Cryptography.Pkcs.Pkcs9DocumentName))]
[assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Security.Cryptography.Pkcs.Pkcs9LocalKeyId))]
[assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Security.Cryptography.Pkcs.Pkcs9MessageDigest))]
[assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Security.Cryptography.Pkcs.Pkcs9SigningTime))]
[assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Security.Cryptography.Pkcs.PublicKeyInfo))]
@@ -42,10 +56,15 @@
[assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Security.Cryptography.Pkcs.RecipientInfoCollection))]
[assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Security.Cryptography.Pkcs.RecipientInfoEnumerator))]
[assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Security.Cryptography.Pkcs.RecipientInfoType))]
[assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Security.Cryptography.Pkcs.Rfc3161TimestampRequest))]
[assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Security.Cryptography.Pkcs.Rfc3161TimestampToken))]
[assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Security.Cryptography.Pkcs.Rfc3161TimestampTokenInfo))]
[assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Security.Cryptography.Pkcs.SignedCms))]
[assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Security.Cryptography.Pkcs.SignerInfo))]
[assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Security.Cryptography.Pkcs.SignerInfoCollection))]
[assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Security.Cryptography.Pkcs.SignerInfoEnumerator))]
[assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Security.Cryptography.Pkcs.SubjectIdentifier))]
[assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Security.Cryptography.Pkcs.SubjectIdentifierOrKey))]
[assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Security.Cryptography.Pkcs.SubjectIdentifierOrKeyType))]
[assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Security.Cryptography.Pkcs.SubjectIdentifierType))]
[assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Security.Cryptography.Xml.X509IssuerSerial))]
@@ -350,6 +350,17 @@ class TestIfaces : ITest
}
}
public class RuntimeInvokeWithThrowClass
{
public RuntimeInvokeWithThrowClass()
{
}
public void RuntimeInvokeThrowMethod()
{
throw new Exception("thays");
}
}
public sealed class DebuggerTaskScheduler : TaskScheduler, IDisposable
{
private readonly BlockingCollection<Task> _tasks = new BlockingCollection<Task>();
@@ -543,6 +554,10 @@ public class Tests : TestsBase, ITest2
run_step_out_void_async();
return 0;
}
if (args.Length > 0 && args [0] == "runtime_invoke_hybrid_exceptions") {
runtime_invoke_hybrid_exceptions();
return 0;
}
assembly_load ();
breakpoints ();
single_stepping ();
@@ -589,6 +604,7 @@ public class Tests : TestsBase, ITest2
if_property_stepping();
fixed_size_array();
test_new_exception_filter();
test_async_debug_generics();
return 3;
}
@@ -888,6 +904,17 @@ public class Tests : TestsBase, ITest2
}
}
[MethodImplAttribute (MethodImplOptions.NoInlining)]
public static void test_async_debug_generics () {
ExecuteAsync_Broken<object>().Wait ();
}
async static Task<T> ExecuteAsync_Broken<T>()
{
await Task.Delay(2);
return default;
}
[MethodImplAttribute (MethodImplOptions.NoInlining)]
public static void inspect_enumerator_in_generic_struct() {
TestEnumeratorInsideGenericStruct<String, String> generic_struct = new TestEnumeratorInsideGenericStruct<String, String>(new KeyValuePair<string, string>("0", "f1"));
@@ -2191,6 +2218,16 @@ public class Tests : TestsBase, ITest2
public static ref BlittableStruct get_ref_struct() {
return ref ref_return_struct;
}
[MethodImplAttribute (MethodImplOptions.NoInlining)]
public static void runtime_invoke_hybrid_exceptions () {
Type rtType = Type.GetType("RuntimeInvokeWithThrowClass");
ConstructorInfo rtConstructor = rtType.GetConstructor(Type.EmptyTypes);
object rtObject = rtConstructor.Invoke(new object[] { });
MethodInfo rtMethod = rtType.GetMethod("RuntimeInvokeThrowMethod");
rtMethod.Invoke(rtObject, new object[] { });
}
}
public class SentinelClass : MarshalByRefObject {
+23 -1
View File
@@ -5139,7 +5139,29 @@ public class DebuggerTests
ev = GetNextEvent ();
}
[Test]
public void TestRuntimeInvokeHybridSuspendExceptions () {
TearDown ();
Start (dtest_app_path, "runtime_invoke_hybrid_exceptions", forceExit: true);
var req2 = vm.CreateExceptionRequest (null, false, true, false);
req2.Enable ();
vm.Resume ();
var ev = GetNextEvent ();
Assert.IsInstanceOfType (typeof (ExceptionEvent), ev);
vm.Exit (0);
vm = null;
}
[Test]
public void TestAsyncDebugGenerics () {
Event e = run_until ("test_async_debug_generics");
e = step_in_await ("test_async_debug_generics", e);
e = step_in_await ("MoveNext", e);
e = step_in_await ("MoveNext", e);
e = step_in_await ("MoveNext", e);
e = step_in_await ("MoveNext", e);
}
#endif
} // class DebuggerTests
} // namespace
@@ -43,33 +43,16 @@ namespace Mono.Messaging.RabbitMQ {
public class RabbitMQMessagingProvider : IMessagingProvider {
private int txCounter = 0;
private readonly uint localIp;
private readonly Guid localId;
private readonly MessagingContextPool contextPool;
public RabbitMQMessagingProvider ()
{
localIp = GetLocalIP ();
localId = Guid.NewGuid ();
contextPool = new MessagingContextPool (new MessageFactory (this),
CreateConnection);
}
private static uint GetLocalIP ()
{
String strHostName = Dns.GetHostName ();
IPHostEntry ipEntry = Dns.GetHostByName (strHostName);
foreach (IPAddress ip in ipEntry.AddressList) {
if (AddressFamily.InterNetwork == ip.AddressFamily) {
byte[] addr = ip.GetAddressBytes ();
uint localIP = 0;
for (int i = 0; i < 4 && i < addr.Length; i++) {
localIP += (uint) (addr[i] << 8 * (3 - i));
}
return localIP;
}
}
return 0;
}
public IMessage CreateMessage ()
{
return new MessageBase ();
@@ -78,7 +61,7 @@ namespace Mono.Messaging.RabbitMQ {
public IMessageQueueTransaction CreateMessageQueueTransaction ()
{
Interlocked.Increment (ref txCounter);
string txId = localIp.ToString () + txCounter.ToString ();
string txId = localId.ToString () + "_" + txCounter.ToString ();
return new RabbitMQMessageQueueTransaction (txId, contextPool);
}
@@ -96,14 +96,6 @@ namespace Mono.Security.Interface
ValidationResult ValidateCertificate (string targetHost, bool serverMode, X509CertificateCollection certificates);
}
internal interface ICertificateValidator2 : ICertificateValidator
{
/*
* Internal use only.
*/
ValidationResult ValidateCertificate (string targetHost, bool serverMode, X509Certificate leaf, X509Chain chain);
}
public static class CertificateValidationHelper
{
const string SecurityLibrary = "/System/Library/Frameworks/Security.framework/Security";
@@ -42,59 +42,11 @@ namespace Mono.Security.Interface
get;
}
void AuthenticateAsClient (string targetHost);
void AuthenticateAsClient (string targetHost, X509CertificateCollection clientCertificates, bool checkCertificateRevocation);
void AuthenticateAsClient (string targetHost, X509CertificateCollection clientCertificates, SSA.SslProtocols enabledSslProtocols, bool checkCertificateRevocation);
IAsyncResult BeginAuthenticateAsClient (string targetHost, AsyncCallback asyncCallback, object asyncState);
IAsyncResult BeginAuthenticateAsClient (string targetHost, X509CertificateCollection clientCertificates, bool checkCertificateRevocation, AsyncCallback asyncCallback, object asyncState);
IAsyncResult BeginAuthenticateAsClient (string targetHost, X509CertificateCollection clientCertificates, SSA.SslProtocols enabledSslProtocols, bool checkCertificateRevocation, AsyncCallback asyncCallback, object asyncState);
void EndAuthenticateAsClient (IAsyncResult asyncResult);
void AuthenticateAsServer (X509Certificate serverCertificate);
void AuthenticateAsServer (X509Certificate serverCertificate, bool clientCertificateRequired, bool checkCertificateRevocation);
void AuthenticateAsServer (X509Certificate serverCertificate, bool clientCertificateRequired, SSA.SslProtocols enabledSslProtocols, bool checkCertificateRevocation);
IAsyncResult BeginAuthenticateAsServer (X509Certificate serverCertificate, AsyncCallback asyncCallback, object asyncState);
IAsyncResult BeginAuthenticateAsServer (X509Certificate serverCertificate, bool clientCertificateRequired, bool checkCertificateRevocation, AsyncCallback asyncCallback, object asyncState);
IAsyncResult BeginAuthenticateAsServer (X509Certificate serverCertificate, bool clientCertificateRequired, SSA.SslProtocols enabledSslProtocols, bool checkCertificateRevocation, AsyncCallback asyncCallback, object asyncState);
void EndAuthenticateAsServer (IAsyncResult asyncResult);
Task AuthenticateAsClientAsync (string targetHost);
Task AuthenticateAsClientAsync (string targetHost, X509CertificateCollection clientCertificates, bool checkCertificateRevocation);
Task AuthenticateAsClientAsync (string targetHost, X509CertificateCollection clientCertificates, SSA.SslProtocols enabledSslProtocols, bool checkCertificateRevocation);
Task AuthenticateAsServerAsync (X509Certificate serverCertificate);
Task AuthenticateAsServerAsync (X509Certificate serverCertificate, bool clientCertificateRequired, bool checkCertificateRevocation);
Task AuthenticateAsServerAsync (X509Certificate serverCertificate, bool clientCertificateRequired, SSA.SslProtocols enabledSslProtocols, bool checkCertificateRevocation);
int Read (byte[] buffer, int offset, int count);
void Write (byte[] buffer);
void Write (byte[] buffer, int offset, int count);
IAsyncResult BeginRead (byte[] buffer, int offset, int count, AsyncCallback asyncCallback, object asyncState);
int EndRead (IAsyncResult asyncResult);
IAsyncResult BeginWrite (byte[] buffer, int offset, int count, AsyncCallback asyncCallback, object asyncState);
void EndWrite (IAsyncResult asyncResult);
Task<int> ReadAsync (byte[] buffer, int offset, int count, CancellationToken cancellationToken);
Task WriteAsync (byte[] buffer, int offset, int count, CancellationToken cancellationToken);
@@ -215,12 +167,5 @@ namespace Mono.Security.Interface
Task RenegotiateAsync (CancellationToken cancellationToken);
}
interface IMonoSslStream2 : IMonoSslStream
{
Task AuthenticateAsClientAsync (IMonoSslClientAuthenticationOptions sslClientAuthenticationOptions, CancellationToken cancellationToken);
Task AuthenticateAsServerAsync (IMonoSslServerAuthenticationOptions sslServerAuthenticationOptions, CancellationToken cancellationToken);
}
}
@@ -121,10 +121,6 @@ namespace Mono.Security.Interface
Stream innerStream, bool leaveInnerStreamOpen,
MonoTlsSettings settings = null);
internal abstract IMonoSslStream CreateSslStreamInternal (
SslStream sslStream, Stream innerStream, bool leaveInnerStreamOpen,
MonoTlsSettings settings);
#endregion
#region Native Certificate Implementation
@@ -133,34 +129,6 @@ namespace Mono.Security.Interface
get { return false; }
}
internal virtual X509Certificate2Impl GetNativeCertificate (
byte[] data, string password, X509KeyStorageFlags flags)
{
throw new InvalidOperationException ();
}
internal virtual X509Certificate2Impl GetNativeCertificate (
X509Certificate certificate)
{
throw new InvalidOperationException ();
}
#endregion
#region Certificate Validation
/*
* If @serverMode is true, then we're a server and want to validate a certificate
* that we received from a client.
*
* On OS X and Mobile, the @chain will be initialized with the @certificates, but not actually built.
*
* Returns `true` if certificate validation has been performed and `false` to invoke the
* default system validator.
*/
internal abstract bool ValidateCertificate (
ICertificateValidator2 validator, string targetHost, bool serverMode,
X509CertificateCollection certificates, bool wantsChain, ref X509Chain chain,
ref MonoSslPolicyErrors errors, ref int status11);
#endregion
#region Misc
@@ -183,9 +183,10 @@ namespace Mono.Security.Interface
* - 1: everything up until May 2018
* - 2: the new ServicePointScheduler changes have landed
* - 3: full support for Client Certificates
* - 4: Legacy TLS Removal
*
*/
internal const int InternalVersion = 3;
internal const int InternalVersion = 4;
#endregion
}
@@ -1,149 +0,0 @@
// Transport Security Layer (TLS)
// Copyright (c) 2003-2004 Carlos Guzman Alvarez
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Security.Cryptography.X509Certificates;
using Mono.Security.Protocol.Tls;
namespace Mono.Security.Protocol.Tls.Handshake.Client
{
internal class TlsClientCertificate : HandshakeMessage
{
private bool clientCertSelected;
private X509Certificate clientCert;
#region Constructors
public TlsClientCertificate(Context context)
: base(context, HandshakeType.Certificate)
{
}
#endregion
#region Properties
public X509Certificate ClientCertificate {
get {
if (!clientCertSelected)
{
GetClientCertificate ();
clientCertSelected = true;
}
return clientCert;
}
}
#endregion
#region Methods
public override void Update()
{
base.Update();
this.Reset();
}
#endregion
#region Protected Methods
private void GetClientCertificate ()
{
// TODO: Client certificate selection is unfinished
ClientContext context = (ClientContext)this.Context;
// note: the server may ask for mutual authentication
// but may not require it (i.e. it can be optional).
if (context.ClientSettings.Certificates != null &&
context.ClientSettings.Certificates.Count > 0)
{
clientCert = context.SslStream.RaiseClientCertificateSelection(
this.Context.ClientSettings.Certificates,
new X509Certificate(this.Context.ServerSettings.Certificates[0].RawData),
this.Context.ClientSettings.TargetHost,
null);
// Note: the application code can raise it's
// own exception to stop the connection too.
}
// Update the selected client certificate
context.ClientSettings.ClientCertificate = clientCert;
}
private void SendCertificates ()
{
TlsStream chain = new TlsStream ();
X509Certificate currentCert = this.ClientCertificate;
while (currentCert != null) {
byte[] rawCert = currentCert.GetRawCertData ();
chain.WriteInt24 (rawCert.Length);
chain.Write(rawCert);
currentCert = FindParentCertificate (currentCert);
}
this.WriteInt24 ((int)chain.Length);
this.Write (chain.ToArray ());
}
protected override void ProcessAsSsl3()
{
if (this.ClientCertificate != null) {
SendCertificates ();
} else {
// an Alert warning for NoCertificate (41)
// should be sent from here - but that would
// break the current message handling
}
}
protected override void ProcessAsTls1()
{
if (this.ClientCertificate != null) {
SendCertificates ();
} else {
// return message with empty certificate (see 7.4.6 in RFC2246)
this.WriteInt24 (0);
}
}
private X509Certificate FindParentCertificate (X509Certificate cert)
{
#pragma warning disable 618
// This certificate is the root certificate
if (cert.GetName () == cert.GetIssuerName ())
return null;
foreach (X509Certificate certificate in this.Context.ClientSettings.Certificates) {
if (certificate.GetName () == cert.GetIssuerName ())
return certificate;
}
return null;
#pragma warning restore 618
}
#endregion
}
}
@@ -1,220 +0,0 @@
// Transport Security Layer (TLS)
// Copyright (c) 2003-2004 Carlos Guzman Alvarez
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Security.Cryptography.X509Certificates;
using System.Security.Cryptography;
using Mono.Security.Cryptography;
namespace Mono.Security.Protocol.Tls.Handshake.Client
{
internal class TlsClientCertificateVerify : HandshakeMessage
{
#region Constructors
public TlsClientCertificateVerify(Context context)
: base(context, HandshakeType.CertificateVerify)
{
}
#endregion
#region Methods
public override void Update()
{
base.Update();
this.Reset();
}
#endregion
#region Protected Methods
protected override void ProcessAsSsl3()
{
AsymmetricAlgorithm privKey = null;
ClientContext context = (ClientContext)this.Context;
privKey = context.SslStream.RaisePrivateKeySelection(
context.ClientSettings.ClientCertificate,
context.ClientSettings.TargetHost);
if (privKey == null)
{
throw new TlsException(AlertDescription.UserCancelled, "Client certificate Private Key unavailable.");
}
else
{
SslHandshakeHash hash = new SslHandshakeHash(context.MasterSecret);
hash.TransformFinalBlock(
context.HandshakeMessages.ToArray(),
0,
(int)context.HandshakeMessages.Length);
// CreateSignature uses ((RSA)privKey).DecryptValue which is not implemented
// in RSACryptoServiceProvider. Other implementations likely implement DecryptValue
// so we will try the CreateSignature method.
byte[] signature = null;
if (!(privKey is RSACryptoServiceProvider))
{
try
{
signature = hash.CreateSignature((RSA)privKey);
}
catch (NotImplementedException)
{ }
}
// If DecryptValue is not implemented, then try to export the private
// key and let the RSAManaged class do the DecryptValue
if (signature == null)
{
// RSAManaged of the selected ClientCertificate
// (at this moment the first one)
RSA rsa = this.getClientCertRSA((RSA)privKey);
// Write message
signature = hash.CreateSignature(rsa);
}
this.Write((short)signature.Length);
this.Write(signature, 0, signature.Length);
}
}
protected override void ProcessAsTls1()
{
AsymmetricAlgorithm privKey = null;
ClientContext context = (ClientContext)this.Context;
privKey = context.SslStream.RaisePrivateKeySelection(
context.ClientSettings.ClientCertificate,
context.ClientSettings.TargetHost);
if (privKey == null)
{
throw new TlsException(AlertDescription.UserCancelled, "Client certificate Private Key unavailable.");
}
else
{
// Compute handshake messages hash
MD5SHA1 hash = new MD5SHA1();
hash.ComputeHash(
context.HandshakeMessages.ToArray(),
0,
(int)context.HandshakeMessages.Length);
// CreateSignature uses ((RSA)privKey).DecryptValue which is not implemented
// in RSACryptoServiceProvider. Other implementations likely implement DecryptValue
// so we will try the CreateSignature method.
byte[] signature = null;
if (!(privKey is RSACryptoServiceProvider))
{
try
{
signature = hash.CreateSignature((RSA)privKey);
}
catch (NotImplementedException)
{ }
}
// If DecryptValue is not implemented, then try to export the private
// key and let the RSAManaged class do the DecryptValue
if (signature == null)
{
// RSAManaged of the selected ClientCertificate
// (at this moment the first one)
RSA rsa = this.getClientCertRSA((RSA)privKey);
// Write message
signature = hash.CreateSignature(rsa);
}
this.Write((short)signature.Length);
this.Write(signature, 0, signature.Length);
}
}
#endregion
#region Private methods
private RSA getClientCertRSA(RSA privKey)
{
RSAParameters rsaParams = new RSAParameters();
RSAParameters privateParams = privKey.ExportParameters(true);
// for RSA m_publickey contains 2 ASN.1 integers
// the modulus and the public exponent
ASN1 pubkey = new ASN1 (this.Context.ClientSettings.Certificates[0].GetPublicKey());
ASN1 modulus = pubkey [0];
if ((modulus == null) || (modulus.Tag != 0x02))
{
return null;
}
ASN1 exponent = pubkey [1];
if (exponent.Tag != 0x02)
{
return null;
}
rsaParams.Modulus = this.getUnsignedBigInteger(modulus.Value);
rsaParams.Exponent = exponent.Value;
// Set private key parameters
rsaParams.D = privateParams.D;
rsaParams.DP = privateParams.DP;
rsaParams.DQ = privateParams.DQ;
rsaParams.InverseQ = privateParams.InverseQ;
rsaParams.P = privateParams.P;
rsaParams.Q = privateParams.Q;
// BUG: MS BCL 1.0 can't import a key which
// isn't the same size as the one present in
// the container.
int keySize = (rsaParams.Modulus.Length << 3);
RSAManaged rsa = new RSAManaged(keySize);
rsa.ImportParameters (rsaParams);
return (RSA)rsa;
}
private byte[] getUnsignedBigInteger(byte[] integer)
{
if (integer [0] == 0x00)
{
// this first byte is added so we're sure it's an unsigned integer
// however we can't feed it into RSAParameters or DSAParameters
int length = integer.Length - 1;
byte[] uinteger = new byte [length];
Buffer.BlockCopy (integer, 1, uinteger, 0, length);
return uinteger;
}
else
{
return integer;
}
}
#endregion
}
}
@@ -1,87 +0,0 @@
// Transport Security Layer (TLS)
// Copyright (c) 2003-2004 Carlos Guzman Alvarez
// Copyright (C) 2006 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Security.Cryptography;
using Mono.Security.Cryptography;
namespace Mono.Security.Protocol.Tls.Handshake.Client
{
internal class TlsClientFinished : HandshakeMessage
{
#region Constructors
public TlsClientFinished(Context context)
: base(context, HandshakeType.Finished)
{
}
#endregion
#region Methods
public override void Update()
{
base.Update();
this.Reset();
}
#endregion
#region Protected Methods
static private byte[] Ssl3Marker = new byte [4] { 0x43, 0x4c, 0x4e, 0x54 };
protected override void ProcessAsSsl3()
{
// Compute handshake messages hashes
HashAlgorithm hash = new SslHandshakeHash(this.Context.MasterSecret);
byte[] data = this.Context.HandshakeMessages.ToArray ();
hash.TransformBlock (data, 0, data.Length, data, 0);
hash.TransformBlock (Ssl3Marker, 0, Ssl3Marker.Length, Ssl3Marker, 0);
// hack to avoid memory allocation
hash.TransformFinalBlock (CipherSuite.EmptyArray, 0, 0);
this.Write (hash.Hash);
}
protected override void ProcessAsTls1()
{
// Compute handshake messages hash
HashAlgorithm hash = new MD5SHA1();
// note: we could call HashAlgorithm.ComputeHash(Stream) but that would allocate (on Mono)
// a 4096 bytes buffer to process the hash - which is bigger than HandshakeMessages
byte[] data = this.Context.HandshakeMessages.ToArray ();
byte[] digest = hash.ComputeHash (data, 0, data.Length);
// Write message
Write(this.Context.Write.Cipher.PRF(this.Context.MasterSecret, "client finished", digest, 12));
}
#endregion
}
}
@@ -1,139 +0,0 @@
// Transport Security Layer (TLS)
// Copyright (c) 2003-2004 Carlos Guzman Alvarez
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Net;
using System.Security.Cryptography;
namespace Mono.Security.Protocol.Tls.Handshake.Client
{
internal class TlsClientHello : HandshakeMessage
{
#region Fields
private byte[] random;
#endregion
#region Constructors
public TlsClientHello(Context context)
: base(context, HandshakeType.ClientHello)
{
}
#endregion
#region Methods
public override void Update()
{
ClientContext context = (ClientContext)this.Context;
base.Update();
context.ClientRandom = random;
context.ClientHelloProtocol = this.Context.Protocol;
random = null;
}
#endregion
#region Protected Methods
protected override void ProcessAsSsl3()
{
// Client Version
this.Write(this.Context.Protocol);
// Random bytes - Unix time + Radom bytes [28]
TlsStream clientRandom = new TlsStream();
clientRandom.Write(this.Context.GetUnixTime());
clientRandom.Write(this.Context.GetSecureRandomBytes(28));
this.random = clientRandom.ToArray();
clientRandom.Reset();
this.Write(this.random);
// Session id
// Check if we have a cache session we could reuse
this.Context.SessionId = ClientSessionCache.FromHost (this.Context.ClientSettings.TargetHost);
if (this.Context.SessionId != null)
{
this.Write((byte)this.Context.SessionId.Length);
if (this.Context.SessionId.Length > 0)
{
this.Write(this.Context.SessionId);
}
}
else
{
this.Write((byte)0);
}
// Write length of Cipher suites
this.Write((short)(this.Context.SupportedCiphers.Count*2));
// Write Supported Cipher suites
for (int i = 0; i < this.Context.SupportedCiphers.Count; i++)
{
this.Write((short)this.Context.SupportedCiphers[i].Code);
}
// Compression methods length
this.Write((byte)1);
// Compression methods ( 0 = none )
this.Write((byte)this.Context.CompressionMethod);
}
protected override void ProcessAsTls1()
{
ProcessAsSsl3 ();
// If applicable add the "server_name" extension to the hello message
// http://www.ietf.org/rfc/rfc3546.txt
string host = Context.ClientSettings.TargetHost;
// Our TargetHost might be an address (not a host *name*) - see bug #8553
// RFC3546 -> Literal IPv4 and IPv6 addresses are not permitted in "HostName".
IPAddress addr;
if (IPAddress.TryParse (host, out addr))
return;
TlsStream extensions = new TlsStream ();
byte[] server_name = System.Text.Encoding.UTF8.GetBytes (host);
extensions.Write ((short) 0x0000); // ExtensionType: server_name (0)
extensions.Write ((short) (server_name.Length + 5)); // ServerNameList (length)
extensions.Write ((short) (server_name.Length + 3)); // ServerName (length)
extensions.Write ((byte) 0x00); // NameType: host_name (0)
extensions.Write ((short) server_name.Length); // HostName (length)
extensions.Write (server_name); // HostName (UTF8)
this.Write ((short) extensions.Length);
this.Write (extensions.ToArray ());
}
#endregion
}
}
@@ -1,98 +0,0 @@
// Transport Security Layer (TLS)
// Copyright (c) 2003-2004 Carlos Guzman Alvarez
// Copyright (C) 2006 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Security.Cryptography;
using Mono.Security.Cryptography;
namespace Mono.Security.Protocol.Tls.Handshake.Client
{
internal class TlsClientKeyExchange : HandshakeMessage
{
#region Constructors
public TlsClientKeyExchange (Context context) :
base(context, HandshakeType.ClientKeyExchange)
{
}
#endregion
#region Protected Methods
protected override void ProcessAsSsl3()
{
// a large chunk of code is common to both SSL3 and TLS1
// SSL3 doesn't send the length of the buffer
ProcessCommon (false);
}
protected override void ProcessAsTls1()
{
// a large chunk of code is common to both SSL3 and TLS1
// TLS1 does send the length of the buffer
ProcessCommon (true);
}
public void ProcessCommon (bool sendLength)
{
// Compute pre master secret
byte[] preMasterSecret = this.Context.Negotiating.Cipher.CreatePremasterSecret ();
// Create a new RSA key
RSA rsa = null;
if (this.Context.ServerSettings.ServerKeyExchange)
{
// this is the case for "exportable" ciphers
rsa = new RSAManaged ();
rsa.ImportParameters (this.Context.ServerSettings.RsaParameters);
}
else
{
rsa = this.Context.ServerSettings.CertificateRSA;
}
// Encrypt premaster_sercret
RSAPKCS1KeyExchangeFormatter formatter = new RSAPKCS1KeyExchangeFormatter (rsa);
// Write the preMasterSecret encrypted
byte[] buffer = formatter.CreateKeyExchange (preMasterSecret);
if (sendLength)
this.Write ((short) buffer.Length);
this.Write (buffer);
// Create master secret
this.Context.Negotiating.Cipher.ComputeMasterSecret (preMasterSecret);
// Create keys
this.Context.Negotiating.Cipher.ComputeKeys ();
// Clear resources
rsa.Clear ();
}
#endregion
}
}
@@ -1,450 +0,0 @@
// Transport Security Layer (TLS)
// Copyright (c) 2003-2004 Carlos Guzman Alvarez
// Copyright (C) 2004, 2006-2010 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Net;
using System.Collections;
using System.Globalization;
using System.Text.RegularExpressions;
using System.Security.Cryptography;
using X509Cert = System.Security.Cryptography.X509Certificates;
using Mono.Security.X509;
using Mono.Security.X509.Extensions;
using Mono.Security.Interface;
namespace Mono.Security.Protocol.Tls.Handshake.Client
{
internal class TlsServerCertificate : HandshakeMessage
{
#region Fields
private X509CertificateCollection certificates;
#endregion
#region Constructors
public TlsServerCertificate(Context context, byte[] buffer)
: base(context, HandshakeType.Certificate, buffer)
{
}
#endregion
#region Methods
public override void Update()
{
base.Update();
this.Context.ServerSettings.Certificates = this.certificates;
this.Context.ServerSettings.UpdateCertificateRSA();
}
#endregion
#region Protected Methods
protected override void ProcessAsSsl3()
{
this.ProcessAsTls1();
}
protected override void ProcessAsTls1()
{
this.certificates = new X509CertificateCollection();
int readed = 0;
int length = this.ReadInt24();
while (readed < length)
{
// Read certificate length
int certLength = ReadInt24();
// Increment readed
readed += 3;
if (certLength > 0)
{
// Read certificate data
byte[] buffer = this.ReadBytes(certLength);
// Create a new X509 Certificate
X509Certificate certificate = new X509Certificate(buffer);
certificates.Add(certificate);
readed += certLength;
DebugHelper.WriteLine(
String.Format("Server Certificate {0}", certificates.Count),
buffer);
}
}
this.validateCertificates(certificates);
}
#endregion
#region Private Methods
// Note: this method only works for RSA certificates
// DH certificates requires some changes - does anyone use one ?
private bool checkCertificateUsage (X509Certificate cert)
{
ClientContext context = (ClientContext)this.Context;
// certificate extensions are required for this
// we "must" accept older certificates without proofs
if (cert.Version < 3)
return true;
KeyUsages ku = KeyUsages.none;
switch (context.Negotiating.Cipher.ExchangeAlgorithmType)
{
case ExchangeAlgorithmType.RsaSign:
ku = KeyUsages.digitalSignature;
break;
case ExchangeAlgorithmType.RsaKeyX:
ku = KeyUsages.keyEncipherment;
break;
case ExchangeAlgorithmType.DiffieHellman:
ku = KeyUsages.keyAgreement;
break;
case ExchangeAlgorithmType.Fortezza:
return false; // unsupported certificate type
}
KeyUsageExtension kux = null;
ExtendedKeyUsageExtension eku = null;
X509Extension xtn = cert.Extensions ["2.5.29.15"];
if (xtn != null)
kux = new KeyUsageExtension (xtn);
xtn = cert.Extensions ["2.5.29.37"];
if (xtn != null)
eku = new ExtendedKeyUsageExtension (xtn);
if ((kux != null) && (eku != null))
{
// RFC3280 states that when both KeyUsageExtension and
// ExtendedKeyUsageExtension are present then BOTH should
// be valid
if (!kux.Support (ku))
return false;
return (eku.KeyPurpose.Contains ("1.3.6.1.5.5.7.3.1") ||
eku.KeyPurpose.Contains ("2.16.840.1.113730.4.1"));
}
else if (kux != null)
{
return kux.Support (ku);
}
else if (eku != null)
{
// Server Authentication (1.3.6.1.5.5.7.3.1) or
// Netscape Server Gated Crypto (2.16.840.1.113730.4)
return (eku.KeyPurpose.Contains ("1.3.6.1.5.5.7.3.1") ||
eku.KeyPurpose.Contains ("2.16.840.1.113730.4.1"));
}
// last chance - try with older (deprecated) Netscape extensions
xtn = cert.Extensions ["2.16.840.1.113730.1.1"];
if (xtn != null)
{
NetscapeCertTypeExtension ct = new NetscapeCertTypeExtension (xtn);
return ct.Support (NetscapeCertTypeExtension.CertTypes.SslServer);
}
// if the CN=host (checked later) then we assume this is meant for SSL/TLS
// e.g. the new smtp.gmail.com certificate
return true;
}
private void validateCertificates(X509CertificateCollection certificates)
{
ClientContext context = (ClientContext)this.Context;
AlertDescription description = AlertDescription.BadCertificate;
#if INSIDE_SYSTEM
// This helps the linker to remove a lot of validation code that will never be used since
// System.dll will, for OSX and iOS, uses the operating system X.509 certificate validations
RemoteValidation (context, description);
#else
if (context.SslStream.HaveRemoteValidation2Callback)
RemoteValidation (context, description);
else
LocalValidation (context, description);
#endif
}
void RemoteValidation (ClientContext context, AlertDescription description)
{
ValidationResult res = context.SslStream.RaiseServerCertificateValidation2 (certificates);
if (res.Trusted)
return;
long error = res.ErrorCode;
switch (error) {
case 0x800B0101:
description = AlertDescription.CertificateExpired;
break;
case 0x800B010A:
description = AlertDescription.UnknownCA;
break;
case 0x800B0109:
description = AlertDescription.UnknownCA;
break;
default:
description = AlertDescription.CertificateUnknown;
break;
}
string err = String.Format ("Invalid certificate received from server. Error code: 0x{0:x}", error);
throw new TlsException (description, err);
}
void LocalValidation (ClientContext context, AlertDescription description)
{
// the leaf is the web server certificate
X509Certificate leaf = certificates [0];
X509Cert.X509Certificate cert = new X509Cert.X509Certificate (leaf.RawData);
ArrayList errors = new ArrayList();
// SSL specific check - not all certificates can be
// used to server-side SSL some rules applies after
// all ;-)
if (!checkCertificateUsage (leaf))
{
// WinError.h CERT_E_PURPOSE 0x800B0106
errors.Add ((int)-2146762490);
}
// SSL specific check - does the certificate match
// the host ?
if (!checkServerIdentity (leaf))
{
// WinError.h CERT_E_CN_NO_MATCH 0x800B010F
errors.Add ((int)-2146762481);
}
// Note: building and verifying a chain can take much time
// so we do it last (letting simple things fails first)
// Note: In TLS the certificates MUST be in order (and
// optionally include the root certificate) so we're not
// building the chain using LoadCertificate (it's faster)
// Note: IIS doesn't seem to send the whole certificate chain
// but only the server certificate :-( it's assuming that you
// already have this chain installed on your computer. duh!
// http://groups.google.ca/groups?q=IIS+server+certificate+chain&hl=en&lr=&ie=UTF-8&oe=UTF-8&selm=85058s%24avd%241%40nnrp1.deja.com&rnum=3
// we must remove the leaf certificate from the chain
X509CertificateCollection chain = new X509CertificateCollection (certificates);
chain.Remove (leaf);
X509Chain verify = new X509Chain (chain);
bool result = false;
try
{
result = verify.Build (leaf);
}
catch (Exception)
{
result = false;
}
if (!result)
{
switch (verify.Status)
{
case X509ChainStatusFlags.InvalidBasicConstraints:
// WinError.h TRUST_E_BASIC_CONSTRAINTS 0x80096019
errors.Add ((int)-2146869223);
break;
case X509ChainStatusFlags.NotSignatureValid:
// WinError.h TRUST_E_BAD_DIGEST 0x80096010
errors.Add ((int)-2146869232);
break;
case X509ChainStatusFlags.NotTimeNested:
// WinError.h CERT_E_VALIDITYPERIODNESTING 0x800B0102
errors.Add ((int)-2146762494);
break;
case X509ChainStatusFlags.NotTimeValid:
// WinError.h CERT_E_EXPIRED 0x800B0101
description = AlertDescription.CertificateExpired;
errors.Add ((int)-2146762495);
break;
case X509ChainStatusFlags.PartialChain:
// WinError.h CERT_E_CHAINING 0x800B010A
description = AlertDescription.UnknownCA;
errors.Add ((int)-2146762486);
break;
case X509ChainStatusFlags.UntrustedRoot:
// WinError.h CERT_E_UNTRUSTEDROOT 0x800B0109
description = AlertDescription.UnknownCA;
errors.Add ((int)-2146762487);
break;
default:
// unknown error
description = AlertDescription.CertificateUnknown;
errors.Add ((int)verify.Status);
break;
}
}
int[] certificateErrors = (int[])errors.ToArray(typeof(int));
if (!context.SslStream.RaiseServerCertificateValidation(
cert,
certificateErrors))
{
throw new TlsException(
description,
"Invalid certificate received from server.");
}
}
// RFC2818 - HTTP Over TLS, Section 3.1
// http://www.ietf.org/rfc/rfc2818.txt
//
// 1. if present MUST use subjectAltName dNSName as identity
// 1.1. if multiples entries a match of any one is acceptable
// 1.2. wildcard * is acceptable
// 2. URI may be an IP address -> subjectAltName.iPAddress
// 2.1. exact match is required
// 3. Use of the most specific Common Name (CN=) in the Subject
// 3.1 Existing practice but DEPRECATED
private bool checkServerIdentity (X509Certificate cert)
{
ClientContext context = (ClientContext)this.Context;
string targetHost = context.ClientSettings.TargetHost;
X509Extension ext = cert.Extensions ["2.5.29.17"];
// 1. subjectAltName
if (ext != null)
{
SubjectAltNameExtension subjectAltName = new SubjectAltNameExtension (ext);
// 1.1 - multiple dNSName
foreach (string dns in subjectAltName.DNSNames)
{
// 1.2 TODO - wildcard support
if (Match (targetHost, dns))
return true;
}
// 2. ipAddress
foreach (string ip in subjectAltName.IPAddresses)
{
// 2.1. Exact match required
if (ip == targetHost)
return true;
}
}
// 3. Common Name (CN=)
return checkDomainName (cert.SubjectName);
}
private bool checkDomainName(string subjectName)
{
ClientContext context = (ClientContext)this.Context;
string domainName = String.Empty;
Regex search = new Regex(@"CN\s*=\s*([^,]*)");
MatchCollection elements = search.Matches(subjectName);
if (elements.Count == 1)
{
if (elements[0].Success)
{
domainName = elements[0].Groups[1].Value.ToString();
}
}
return Match (context.ClientSettings.TargetHost, domainName);
}
// ensure the pattern is valid wrt to RFC2595 and RFC2818
// http://www.ietf.org/rfc/rfc2595.txt
// http://www.ietf.org/rfc/rfc2818.txt
static bool Match (string hostname, string pattern)
{
// check if this is a pattern
int index = pattern.IndexOf ('*');
if (index == -1) {
// not a pattern, do a direct case-insensitive comparison
return (String.Compare (hostname, pattern, true, CultureInfo.InvariantCulture) == 0);
}
// check pattern validity
// A "*" wildcard character MAY be used as the left-most name component in the certificate.
// unless this is the last char (valid)
if (index != pattern.Length - 1) {
// then the next char must be a dot .'.
if (pattern [index + 1] != '.')
return false;
}
// only one (A) wildcard is supported
int i2 = pattern.IndexOf ('*', index + 1);
if (i2 != -1)
return false;
// match the end of the pattern
string end = pattern.Substring (index + 1);
int length = hostname.Length - end.Length;
// no point to check a pattern that is longer than the hostname
if (length <= 0)
return false;
if (String.Compare (hostname, length, end, 0, end.Length, true, CultureInfo.InvariantCulture) != 0)
return false;
// special case, we start with the wildcard
if (index == 0) {
// ensure we hostname non-matched part (start) doesn't contain a dot
int i3 = hostname.IndexOf ('.');
return ((i3 == -1) || (i3 >= (hostname.Length - end.Length)));
}
// match the start of the pattern
string start = pattern.Substring (0, index);
return (String.Compare (hostname, 0, start, 0, start.Length, true, CultureInfo.InvariantCulture) == 0);
}
#endregion
}
}
@@ -1,111 +0,0 @@
// Transport Security Layer (TLS)
// Copyright (c) 2003-2004 Carlos Guzman Alvarez
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Text;
using Mono.Security;
namespace Mono.Security.Protocol.Tls.Handshake.Client
{
internal class TlsServerCertificateRequest : HandshakeMessage
{
#region Fields
private ClientCertificateType[] certificateTypes;
private string[] distinguisedNames;
#endregion
#region Constructors
public TlsServerCertificateRequest(Context context, byte[] buffer)
: base(context, HandshakeType.CertificateRequest, buffer)
{
}
#endregion
#region Methods
public override void Update()
{
base.Update();
this.Context.ServerSettings.CertificateTypes = this.certificateTypes;
this.Context.ServerSettings.DistinguisedNames = this.distinguisedNames;
this.Context.ServerSettings.CertificateRequest = true;
}
#endregion
#region Protected Methods
protected override void ProcessAsSsl3()
{
this.ProcessAsTls1();
}
protected override void ProcessAsTls1()
{
// Read requested certificate types
int typesCount = this.ReadByte();
this.certificateTypes = new ClientCertificateType[typesCount];
for (int i = 0; i < typesCount; i++)
{
this.certificateTypes[i] = (ClientCertificateType)this.ReadByte();
}
/*
* Read requested certificate authorities (Distinguised Names)
*
* Name ::= SEQUENCE OF RelativeDistinguishedName
*
* RelativeDistinguishedName ::= SET OF AttributeValueAssertion
*
* AttributeValueAssertion ::= SEQUENCE {
* attributeType OBJECT IDENTIFIER
* attributeValue ANY }
*/
if (this.ReadInt16() != 0)
{
ASN1 rdn = new ASN1(this.ReadBytes(this.ReadInt16()));
distinguisedNames = new string[rdn.Count];
for (int i = 0; i < rdn.Count; i++)
{
// element[0] = attributeType
// element[1] = attributeValue
ASN1 element = new ASN1(rdn[i].Value);
distinguisedNames[i] = Encoding.UTF8.GetString(element[1].Value);
}
}
}
#endregion
}
}
@@ -1,102 +0,0 @@
// Transport Security Layer (TLS)
// Copyright (c) 2003-2004 Carlos Guzman Alvarez
// Copyright (C) 2006 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Security.Cryptography;
using Mono.Security.Cryptography;
namespace Mono.Security.Protocol.Tls.Handshake.Client
{
internal class TlsServerFinished : HandshakeMessage
{
#region Constructors
public TlsServerFinished(Context context, byte[] buffer)
: base(context, HandshakeType.Finished, buffer)
{
}
#endregion
#region Methods
public override void Update()
{
base.Update();
// Hahdshake is finished
this.Context.HandshakeState = HandshakeState.Finished;
}
#endregion
#region Protected Methods
static private byte[] Ssl3Marker = new byte [4] { 0x53, 0x52, 0x56, 0x52 };
protected override void ProcessAsSsl3()
{
// Compute handshake messages hashes
HashAlgorithm hash = new SslHandshakeHash(this.Context.MasterSecret);
byte[] data = this.Context.HandshakeMessages.ToArray ();
hash.TransformBlock (data, 0, data.Length, data, 0);
hash.TransformBlock (Ssl3Marker, 0, Ssl3Marker.Length, Ssl3Marker, 0);
// hack to avoid memory allocation
hash.TransformFinalBlock (CipherSuite.EmptyArray, 0, 0);
byte[] serverHash = this.ReadBytes((int)Length);
byte[] clientHash = hash.Hash;
// Check server prf against client prf
if (!Compare (clientHash, serverHash))
{
// TODO: Review that selected alert is correct
throw new TlsException(AlertDescription.InsuficientSecurity, "Invalid ServerFinished message received.");
}
}
protected override void ProcessAsTls1()
{
byte[] serverPRF = this.ReadBytes((int)Length);
HashAlgorithm hash = new MD5SHA1();
// note: we could call HashAlgorithm.ComputeHash(Stream) but that would allocate (on Mono)
// a 4096 bytes buffer to process the hash - which is bigger than HandshakeMessages
byte[] data = this.Context.HandshakeMessages.ToArray ();
byte[] digest = hash.ComputeHash (data, 0, data.Length);
byte[] clientPRF = this.Context.Current.Cipher.PRF(this.Context.MasterSecret, "server finished", digest, 12);
// Check server prf against client prf
if (!Compare (clientPRF, serverPRF))
{
throw new TlsException("Invalid ServerFinished message received.");
}
}
#endregion
}
}
@@ -1,150 +0,0 @@
// Transport Security Layer (TLS)
// Copyright (c) 2003-2004 Carlos Guzman Alvarez
// Copyright (C) 2006 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
namespace Mono.Security.Protocol.Tls.Handshake.Client
{
internal class TlsServerHello : HandshakeMessage
{
#region Fields
private SecurityCompressionType compressionMethod;
private byte[] random;
private byte[] sessionId;
private CipherSuite cipherSuite;
#endregion
#region Constructors
public TlsServerHello(Context context, byte[] buffer)
: base(context, HandshakeType.ServerHello, buffer)
{
}
#endregion
#region Methods
public override void Update()
{
base.Update();
this.Context.SessionId = this.sessionId;
this.Context.ServerRandom = this.random;
this.Context.Negotiating.Cipher = this.cipherSuite;
this.Context.CompressionMethod = this.compressionMethod;
this.Context.ProtocolNegotiated = true;
DebugHelper.WriteLine("Selected Cipher Suite {0}", this.cipherSuite.Name);
DebugHelper.WriteLine("Client random", this.Context.ClientRandom);
DebugHelper.WriteLine("Server random", this.Context.ServerRandom);
// Compute ClientRandom + ServerRandom
int clen = this.Context.ClientRandom.Length;
int slen = this.Context.ServerRandom.Length;
int rlen = clen + slen;
byte[] cs = new byte[rlen];
Buffer.BlockCopy (this.Context.ClientRandom, 0, cs, 0, clen);
Buffer.BlockCopy (this.Context.ServerRandom, 0, cs, clen, slen);
this.Context.RandomCS = cs;
// Server Random + Client Random
byte[] sc = new byte[rlen];
Buffer.BlockCopy (this.Context.ServerRandom, 0, sc, 0, slen);
Buffer.BlockCopy (this.Context.ClientRandom, 0, sc, slen, clen);
this.Context.RandomSC = sc;
}
#endregion
#region Protected Methods
protected override void ProcessAsSsl3()
{
this.ProcessAsTls1();
}
protected override void ProcessAsTls1()
{
// Read protocol version
this.processProtocol(this.ReadInt16());
// Read random - Unix time + Random bytes
this.random = this.ReadBytes(32);
// Read Session id
int length = (int) ReadByte ();
if (length > 0)
{
this.sessionId = this.ReadBytes(length);
ClientSessionCache.Add (this.Context.ClientSettings.TargetHost, this.sessionId);
this.Context.AbbreviatedHandshake = Compare (this.sessionId, this.Context.SessionId);
}
else
{
this.Context.AbbreviatedHandshake = false;
}
// Read cipher suite
short cipherCode = this.ReadInt16();
if (this.Context.SupportedCiphers.IndexOf(cipherCode) == -1)
{
// The server has sent an invalid ciphersuite
throw new TlsException(AlertDescription.InsuficientSecurity, "Invalid cipher suite received from server");
}
this.cipherSuite = this.Context.SupportedCiphers[cipherCode];
// Read compression methods ( always 0 )
this.compressionMethod = (SecurityCompressionType)this.ReadByte();
}
#endregion
#region Private Methods
private void processProtocol(short protocol)
{
SecurityProtocolType serverProtocol = this.Context.DecodeProtocolCode(protocol);
if ((serverProtocol & this.Context.SecurityProtocolFlags) == serverProtocol ||
(this.Context.SecurityProtocolFlags & SecurityProtocolType.Default) == SecurityProtocolType.Default)
{
this.Context.SecurityProtocol = serverProtocol;
this.Context.SupportedCiphers = CipherSuiteFactory.GetSupportedCiphers (false, serverProtocol);
DebugHelper.WriteLine("Selected protocol {0}", serverProtocol);
}
else
{
throw new TlsException(
AlertDescription.ProtocolVersion,
"Incorrect protocol version received from server");
}
}
#endregion
}
}
@@ -1,52 +0,0 @@
// Transport Security Layer (TLS)
// Copyright (c) 2003-2004 Carlos Guzman Alvarez
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
namespace Mono.Security.Protocol.Tls.Handshake.Client
{
internal class TlsServerHelloDone : HandshakeMessage
{
#region Constructors
public TlsServerHelloDone(Context context, byte[] buffer)
: base(context, HandshakeType.ServerHelloDone, buffer)
{
}
#endregion
#region Protected Methods
protected override void ProcessAsSsl3()
{
}
protected override void ProcessAsTls1()
{
}
#endregion
}
}
@@ -1,121 +0,0 @@
// Transport Security Layer (TLS)
// Copyright (c) 2003-2004 Carlos Guzman Alvarez
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Security.Cryptography;
using Mono.Security.Cryptography;
using Mono.Security.X509;
namespace Mono.Security.Protocol.Tls.Handshake.Client
{
internal class TlsServerKeyExchange : HandshakeMessage
{
#region Fields
private RSAParameters rsaParams;
private byte[] signedParams;
#endregion
#region Constructors
public TlsServerKeyExchange(Context context, byte[] buffer)
: base(context, HandshakeType.ServerKeyExchange, buffer)
{
this.verifySignature();
}
#endregion
#region Methods
public override void Update()
{
base.Update();
this.Context.ServerSettings.ServerKeyExchange = true;
this.Context.ServerSettings.RsaParameters = this.rsaParams;
this.Context.ServerSettings.SignedParams = this.signedParams;
}
#endregion
#region Protected Methods
protected override void ProcessAsSsl3()
{
this.ProcessAsTls1();
}
protected override void ProcessAsTls1()
{
this.rsaParams = new RSAParameters();
// Read modulus
this.rsaParams.Modulus = this.ReadBytes(this.ReadInt16());
// Read exponent
this.rsaParams.Exponent = this.ReadBytes(this.ReadInt16());
// Read signed params
this.signedParams = this.ReadBytes(this.ReadInt16());
}
#endregion
#region Private Methods
private void verifySignature()
{
MD5SHA1 hash = new MD5SHA1();
// Calculate size of server params
int size = rsaParams.Modulus.Length + rsaParams.Exponent.Length + 4;
// Create server params array
TlsStream stream = new TlsStream();
stream.Write(this.Context.RandomCS);
stream.Write(this.ToArray(), 0, size);
hash.ComputeHash(stream.ToArray());
stream.Reset();
bool isValidSignature = hash.VerifySignature(
this.Context.ServerSettings.CertificateRSA,
this.signedParams);
if (!isValidSignature)
{
throw new TlsException(
AlertDescription.DecodeError,
"Data was not signed with the server certificate.");
}
}
#endregion
}
}
@@ -1,276 +0,0 @@
// Transport Security Layer (TLS)
// Copyright (c) 2003-2004 Carlos Guzman Alvarez
// Copyright (C) 2006 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections;
using SSCX = System.Security.Cryptography.X509Certificates;
using Mono.Security.X509;
using Mono.Security.X509.Extensions;
namespace Mono.Security.Protocol.Tls.Handshake.Server
{
internal class TlsClientCertificate : HandshakeMessage
{
#region Fields
private X509CertificateCollection clientCertificates;
#endregion
#region Constructors
public TlsClientCertificate(Context context, byte[] buffer)
: base(context, HandshakeType.Certificate, buffer)
{
}
#endregion
#region Methods
public override void Update()
{
foreach (X509Certificate certificate in clientCertificates) {
this.Context.ClientSettings.Certificates.Add (new SSCX.X509Certificate (certificate.RawData));
}
}
public bool HasCertificate {
get { return clientCertificates.Count > 0; }
}
#endregion
#region Protected Methods
protected override void ProcessAsSsl3()
{
this.ProcessAsTls1();
}
protected override void ProcessAsTls1()
{
int bytesRead = 0;
int length = this.ReadInt24 ();
this.clientCertificates = new X509CertificateCollection ();
while (length > bytesRead) {
int certLength = this.ReadInt24 ();
bytesRead += certLength + 3;
byte[] cert = this.ReadBytes (certLength);
this.clientCertificates.Add (new X509Certificate (cert));
}
if (this.clientCertificates.Count > 0)
{
this.validateCertificates (this.clientCertificates);
}
else if ((this.Context as ServerContext).ClientCertificateRequired)
{
throw new TlsException (AlertDescription.NoCertificate);
}
}
#endregion
#region Private Methods
private bool checkCertificateUsage (X509Certificate cert)
{
ServerContext context = (ServerContext)this.Context;
// certificate extensions are required for this
// we "must" accept older certificates without proofs
if (cert.Version < 3)
return true;
KeyUsages ku = KeyUsages.none;
switch (context.Negotiating.Cipher.ExchangeAlgorithmType)
{
case ExchangeAlgorithmType.RsaSign:
case ExchangeAlgorithmType.RsaKeyX:
ku = KeyUsages.digitalSignature;
break;
case ExchangeAlgorithmType.DiffieHellman:
ku = KeyUsages.keyAgreement;
break;
case ExchangeAlgorithmType.Fortezza:
return false; // unsupported certificate type
}
KeyUsageExtension kux = null;
ExtendedKeyUsageExtension eku = null;
X509Extension xtn = cert.Extensions["2.5.29.15"];
if (xtn != null)
kux = new KeyUsageExtension (xtn);
xtn = cert.Extensions["2.5.29.37"];
if (xtn != null)
eku = new ExtendedKeyUsageExtension (xtn);
if ((kux != null) && (eku != null))
{
// RFC3280 states that when both KeyUsageExtension and
// ExtendedKeyUsageExtension are present then BOTH should
// be valid
return (kux.Support (ku) &&
eku.KeyPurpose.Contains ("1.3.6.1.5.5.7.3.2"));
}
else if (kux != null)
{
return kux.Support (ku);
}
else if (eku != null)
{
// Client Authentication (1.3.6.1.5.5.7.3.2)
return eku.KeyPurpose.Contains ("1.3.6.1.5.5.7.3.2");
}
// last chance - try with older (deprecated) Netscape extensions
xtn = cert.Extensions["2.16.840.1.113730.1.1"];
if (xtn != null)
{
NetscapeCertTypeExtension ct = new NetscapeCertTypeExtension (xtn);
return ct.Support (NetscapeCertTypeExtension.CertTypes.SslClient);
}
// certificate isn't valid for SSL server usage
return false;
}
private void validateCertificates (X509CertificateCollection certificates)
{
ServerContext context = (ServerContext)this.Context;
AlertDescription description = AlertDescription.BadCertificate;
SSCX.X509Certificate client = null;
int[] certificateErrors = null;
// note: certificate may be null is no certificate is sent
// (e.g. optional mutual authentication)
if (certificates.Count > 0) {
X509Certificate leaf = certificates[0];
ArrayList errors = new ArrayList ();
// SSL specific check - not all certificates can be
// used to server-side SSL some rules applies after
// all ;-)
if (!checkCertificateUsage (leaf))
{
// WinError.h CERT_E_PURPOSE 0x800B0106
errors.Add ((int)-2146762490);
}
X509Chain verify;
// was a chain supplied ? if so use it, if not
if (certificates.Count > 1) {
// if so use it (and don't build our own)
X509CertificateCollection chain = new X509CertificateCollection (certificates);
chain.Remove (leaf);
verify = new X509Chain (chain);
} else {
// if not, then let's build our own (based on what's available in the stores)
verify = new X509Chain ();
}
bool result = false;
try
{
result = verify.Build (leaf);
}
catch (Exception)
{
result = false;
}
if (!result)
{
switch (verify.Status)
{
case X509ChainStatusFlags.InvalidBasicConstraints:
// WinError.h TRUST_E_BASIC_CONSTRAINTS 0x80096019
errors.Add ((int)-2146869223);
break;
case X509ChainStatusFlags.NotSignatureValid:
// WinError.h TRUST_E_BAD_DIGEST 0x80096010
errors.Add ((int)-2146869232);
break;
case X509ChainStatusFlags.NotTimeNested:
// WinError.h CERT_E_VALIDITYPERIODNESTING 0x800B0102
errors.Add ((int)-2146762494);
break;
case X509ChainStatusFlags.NotTimeValid:
// WinError.h CERT_E_EXPIRED 0x800B0101
description = AlertDescription.CertificateExpired;
errors.Add ((int)-2146762495);
break;
case X509ChainStatusFlags.PartialChain:
// WinError.h CERT_E_CHAINING 0x800B010A
description = AlertDescription.UnknownCA;
errors.Add ((int)-2146762486);
break;
case X509ChainStatusFlags.UntrustedRoot:
// WinError.h CERT_E_UNTRUSTEDROOT 0x800B0109
description = AlertDescription.UnknownCA;
errors.Add ((int)-2146762487);
break;
default:
// unknown error
description = AlertDescription.CertificateUnknown;
errors.Add ((int)verify.Status);
break;
}
}
client = new SSCX.X509Certificate (leaf.RawData);
certificateErrors = (int[])errors.ToArray (typeof (int));
}
else
{
certificateErrors = new int[0];
}
SSCX.X509CertificateCollection certCollection = new SSCX.X509CertificateCollection ();
foreach (X509Certificate certificate in certificates) {
certCollection.Add (new SSCX.X509Certificate (certificate.RawData));
}
if (!context.SslStream.RaiseClientCertificateValidation(client, certificateErrors))
{
throw new TlsException (
description,
"Invalid certificate received from client.");
}
this.Context.ClientSettings.ClientCertificate = client;
}
#endregion
}
}
@@ -1,86 +0,0 @@
// Transport Security Layer (TLS)
// Copyright (c) 2003-2004 Carlos Guzman Alvarez
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Security.Cryptography.X509Certificates;
using System.Security.Cryptography;
using Mono.Security.Cryptography;
namespace Mono.Security.Protocol.Tls.Handshake.Server
{
internal class TlsClientCertificateVerify : HandshakeMessage
{
#region Constructors
public TlsClientCertificateVerify(Context context, byte[] buffer)
: base(context, HandshakeType.CertificateVerify, buffer)
{
}
#endregion
#region Protected Methods
protected override void ProcessAsSsl3()
{
ServerContext context = (ServerContext)this.Context;
int length = this.ReadInt16 ();
byte[] signature = this.ReadBytes (length);
// Verify signature
SslHandshakeHash hash = new SslHandshakeHash(context.MasterSecret);
hash.TransformFinalBlock(
context.HandshakeMessages.ToArray(),
0,
(int)context.HandshakeMessages.Length);
if (!hash.VerifySignature(context.ClientSettings.CertificateRSA, signature))
{
throw new TlsException(AlertDescription.HandshakeFailiure, "Handshake Failure.");
}
}
protected override void ProcessAsTls1()
{
ServerContext context = (ServerContext)this.Context;
int length = this.ReadInt16 ();
byte[] signature = this.ReadBytes (length);
// Verify signature
MD5SHA1 hash = new MD5SHA1();
hash.ComputeHash(
context.HandshakeMessages.ToArray(),
0,
(int)context.HandshakeMessages.Length);
if (!hash.VerifySignature(context.ClientSettings.CertificateRSA, signature))
{
throw new TlsException (AlertDescription.HandshakeFailiure, "Handshake Failure.");
}
}
#endregion
}
}
@@ -1,88 +0,0 @@
// Transport Security Layer (TLS)
// Copyright (c) 2003-2004 Carlos Guzman Alvarez
// Copyright (C) 2006 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Security.Cryptography;
using Mono.Security.Cryptography;
namespace Mono.Security.Protocol.Tls.Handshake.Server
{
internal class TlsClientFinished : HandshakeMessage
{
#region Constructors
public TlsClientFinished(Context context, byte[] buffer)
: base(context, HandshakeType.Finished, buffer)
{
}
#endregion
#region Protected Methods
protected override void ProcessAsSsl3()
{
// Compute handshake messages hashes
HashAlgorithm hash = new SslHandshakeHash(this.Context.MasterSecret);
TlsStream data = new TlsStream();
data.Write(this.Context.HandshakeMessages.ToArray());
data.Write((int)0x434C4E54);
hash.TransformFinalBlock(data.ToArray(), 0, (int)data.Length);
data.Reset();
byte[] clientHash = this.ReadBytes((int)Length);
byte[] serverHash = hash.Hash;
// Check client prf against server prf
if (!Compare (clientHash, serverHash))
{
throw new TlsException(AlertDescription.DecryptError, "Decrypt error.");
}
}
protected override void ProcessAsTls1()
{
byte[] clientPRF = this.ReadBytes((int)this.Length);
HashAlgorithm hash = new MD5SHA1();
byte[] data = this.Context.HandshakeMessages.ToArray ();
byte[] digest = hash.ComputeHash (data, 0, data.Length);
byte[] serverPRF = this.Context.Current.Cipher.PRF(
this.Context.MasterSecret, "client finished", digest, 12);
// Check client prf against server prf
if (!Compare (clientPRF, serverPRF))
{
throw new TlsException(AlertDescription.DecryptError, "Decrypt error.");
}
}
#endregion
}
}
@@ -1,152 +0,0 @@
// Transport Security Layer (TLS)
// Copyright (c) 2003-2004 Carlos Guzman Alvarez
// Copyright (C) 2006 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Security.Cryptography;
namespace Mono.Security.Protocol.Tls.Handshake.Server
{
internal class TlsClientHello : HandshakeMessage
{
#region Private Fields
private byte[] random;
private byte[] sessionId;
private short[] cipherSuites;
private byte[] compressionMethods;
#endregion
#region Constructors
public TlsClientHello(Context context, byte[] buffer)
: base(context, HandshakeType.ClientHello, buffer)
{
}
#endregion
#region Methods
public override void Update()
{
base.Update();
this.selectCipherSuite();
this.selectCompressionMethod();
this.Context.SessionId = this.sessionId;
this.Context.ClientRandom = this.random;
this.Context.ProtocolNegotiated = true;
}
#endregion
#region Protected Methods
protected override void ProcessAsSsl3()
{
this.ProcessAsTls1();
}
protected override void ProcessAsTls1()
{
// Client Version
this.processProtocol(this.ReadInt16());
// Random bytes - Unix time + Radom bytes [28]
this.random = this.ReadBytes(32);
// Session id
// Send the session ID empty
this.sessionId = this.ReadBytes(this.ReadByte());
// Read Supported Cipher Suites count
this.cipherSuites = new short[this.ReadInt16()/2];
// Read Cipher Suites
for (int i = 0; i < this.cipherSuites.Length; i++)
{
this.cipherSuites[i] = this.ReadInt16();
}
// Compression methods length
this.compressionMethods = new byte[this.ReadByte()];
for (int i = 0; i < this.compressionMethods.Length; i++)
{
this.compressionMethods[i] = this.ReadByte();
}
}
#endregion
#region Private Methods
private void processProtocol(short protocol)
{
// a server MUST reply with the hight version supported (`true` for fallback)
// so a TLS 1.2 client (like Google Chrome) will be returned that the server uses TLS 1.0
// instead of an alert about the protocol
SecurityProtocolType clientProtocol = Context.DecodeProtocolCode (protocol, true);
if ((clientProtocol & this.Context.SecurityProtocolFlags) == clientProtocol ||
(this.Context.SecurityProtocolFlags & SecurityProtocolType.Default) == SecurityProtocolType.Default)
{
this.Context.SecurityProtocol = clientProtocol;
this.Context.SupportedCiphers = CipherSuiteFactory.GetSupportedCiphers (true, clientProtocol);
}
else
{
throw new TlsException(AlertDescription.ProtocolVersion, "Incorrect protocol version received from server");
}
}
private void selectCipherSuite()
{
int index = 0;
for (int i = 0; i < this.cipherSuites.Length; i++)
{
if ((index = this.Context.SupportedCiphers.IndexOf(this.cipherSuites[i])) != -1)
{
this.Context.Negotiating.Cipher = this.Context.SupportedCiphers[index];
break;
}
}
if (this.Context.Negotiating.Cipher == null)
{
throw new TlsException(AlertDescription.InsuficientSecurity, "Insuficient Security");
}
}
private void selectCompressionMethod()
{
this.Context.CompressionMethod = SecurityCompressionType.None;
}
#endregion
}
}
@@ -1,116 +0,0 @@
// Transport Security Layer (TLS)
// Copyright (c) 2003-2004 Carlos Guzman Alvarez
// Copyright (C) 2006 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.IO;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
namespace Mono.Security.Protocol.Tls.Handshake.Server
{
internal class TlsClientKeyExchange : HandshakeMessage
{
#region Constructors
public TlsClientKeyExchange(Context context, byte[] buffer) :
base(context,
HandshakeType.ClientKeyExchange,
buffer)
{
}
#endregion
#region Protected Methods
protected override void ProcessAsSsl3()
{
AsymmetricAlgorithm privKey = null;
ServerContext context = (ServerContext)this.Context;
// Select the private key information
privKey = context.SslStream.RaisePrivateKeySelection(
new X509Certificate(context.ServerSettings.Certificates[0].RawData),
null);
if (privKey == null)
{
throw new TlsException(AlertDescription.UserCancelled, "Server certificate Private Key unavailable.");
}
// Read client premaster secret
byte[] clientSecret = this.ReadBytes((int)this.Length);
// Decrypt premaster secret
RSAPKCS1KeyExchangeDeformatter deformatter = new RSAPKCS1KeyExchangeDeformatter(privKey);
byte[] preMasterSecret = deformatter.DecryptKeyExchange(clientSecret);
// Create master secret
this.Context.Negotiating.Cipher.ComputeMasterSecret(preMasterSecret);
// Create keys
this.Context.Negotiating.Cipher.ComputeKeys ();
// Initialize Cipher Suite
this.Context.Negotiating.Cipher.InitializeCipher ();
}
protected override void ProcessAsTls1()
{
AsymmetricAlgorithm privKey = null;
ServerContext context = (ServerContext)this.Context;
// Select the private key information
// Select the private key information
privKey = context.SslStream.RaisePrivateKeySelection(
new X509Certificate(context.ServerSettings.Certificates[0].RawData),
null);
if (privKey == null)
{
throw new TlsException(AlertDescription.UserCancelled, "Server certificate Private Key unavailable.");
}
// Read client premaster secret
byte[] clientSecret = this.ReadBytes(this.ReadInt16());
// Decrypt premaster secret
RSAPKCS1KeyExchangeDeformatter deformatter = new RSAPKCS1KeyExchangeDeformatter(privKey);
byte[] preMasterSecret = deformatter.DecryptKeyExchange(clientSecret);
// Create master secret
this.Context.Negotiating.Cipher.ComputeMasterSecret(preMasterSecret);
// Create keys
this.Context.Negotiating.Cipher.ComputeKeys();
// Initialize Cipher Suite
this.Context.Negotiating.Cipher.InitializeCipher();
}
#endregion
}
}
@@ -1,74 +0,0 @@
// Transport Security Layer (TLS)
// Copyright (c) 2003-2004 Carlos Guzman Alvarez
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections;
using System.Text.RegularExpressions;
using System.Security.Cryptography;
using X509Cert = System.Security.Cryptography.X509Certificates;
using Mono.Security.X509;
namespace Mono.Security.Protocol.Tls.Handshake.Server
{
internal class TlsServerCertificate : HandshakeMessage
{
#region Constructors
public TlsServerCertificate(Context context)
: base(context, HandshakeType.Certificate)
{
}
#endregion
#region Protected Methods
protected override void ProcessAsSsl3()
{
this.ProcessAsTls1();
}
protected override void ProcessAsTls1()
{
TlsStream certs = new TlsStream();
foreach (X509Certificate certificate in this.Context.ServerSettings.Certificates)
{
// Write certificate length
certs.WriteInt24(certificate.RawData.Length);
// Write certificate data
certs.Write(certificate.RawData);
}
this.WriteInt24(Convert.ToInt32(certs.Length));
this.Write(certs.ToArray());
certs.Close();
}
#endregion
}
}
@@ -1,107 +0,0 @@
// Transport Security Layer (TLS)
// Copyright (c) 2003-2004 Carlos Guzman Alvarez
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Text;
using Mono.Security;
using Mono.Security.X509;
namespace Mono.Security.Protocol.Tls.Handshake.Server
{
internal class TlsServerCertificateRequest : HandshakeMessage
{
#region Constructors
public TlsServerCertificateRequest(Context context)
: base(context, HandshakeType.CertificateRequest)
{
}
#endregion
#region Protected Methods
protected override void ProcessAsSsl3()
{
this.ProcessAsTls1();
}
protected override void ProcessAsTls1()
{
ServerContext context = (ServerContext)this.Context;
int count = context.ServerSettings.CertificateTypes.Length;
this.WriteByte(Convert.ToByte(count));
// Write requested certificate types
for (int i = 0; i < count; i++)
{
this.WriteByte((byte)context.ServerSettings.CertificateTypes[i]);
}
/*
* Write requested certificate authorities (Distinguised Names)
*
* Name ::= SEQUENCE OF RelativeDistinguishedName
*
* RelativeDistinguishedName ::= SET OF AttributeValueAssertion
*
* AttributeValueAssertion ::= SEQUENCE {
* attributeType OBJECT IDENTIFIER
* attributeValue ANY }
*/
/*
* From RFC 5246:
* If the certificate_authorities list is empty, then the client MAY
* send any certificate of the appropriate ClientCertificateType,
* unless there is some external arrangement to the contrary.
*
* Better let the client choose which certificate instead of sending down
* a potentially large list of DNs.
if (context.ServerSettings.DistinguisedNames.Length > 0)
{
TlsStream list = new TlsStream ();
// this is the worst formating ever :-|
foreach (string dn in context.ServerSettings.DistinguisedNames)
{
byte[] name = X501.FromString (dn).GetBytes ();
list.Write ((short)name.Length);
list.Write (name);
}
this.Write ((short)list.Length);
this.Write (list.ToArray ());
}
else
{
*/
this.Write ((short)0);
//}
}
#endregion
}
}
@@ -1,75 +0,0 @@
// Transport Security Layer (TLS)
// Copyright (c) 2003-2004 Carlos Guzman Alvarez
// Copyright (C) 2006 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Security.Cryptography;
using Mono.Security.Cryptography;
namespace Mono.Security.Protocol.Tls.Handshake.Server
{
internal class TlsServerFinished : HandshakeMessage
{
#region Constructors
public TlsServerFinished(Context context)
: base(context, HandshakeType.Finished)
{
}
#endregion
#region Protected Methods
static private byte[] Ssl3Marker = new byte [4] { 0x53, 0x52, 0x56, 0x52 };
protected override void ProcessAsSsl3()
{
// Compute handshake messages hashes
HashAlgorithm hash = new SslHandshakeHash(this.Context.MasterSecret);
byte[] data = this.Context.HandshakeMessages.ToArray ();
hash.TransformBlock (data, 0, data.Length, data, 0);
hash.TransformBlock (Ssl3Marker, 0, Ssl3Marker.Length, Ssl3Marker, 0);
// hack to avoid memory allocation
hash.TransformFinalBlock (CipherSuite.EmptyArray, 0, 0);
this.Write(hash.Hash);
}
protected override void ProcessAsTls1()
{
// Compute handshake messages hash
HashAlgorithm hash = new MD5SHA1();
byte[] data = this.Context.HandshakeMessages.ToArray ();
byte[] digest = hash.ComputeHash (data, 0, data.Length);
// Write message
this.Write(this.Context.Current.Cipher.PRF(
this.Context.MasterSecret, "server finished", digest, 12));
}
#endregion
}
}
@@ -1,122 +0,0 @@
// Transport Security Layer (TLS)
// Copyright (c) 2003-2004 Carlos Guzman Alvarez
// Copyright (C) 2006 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
namespace Mono.Security.Protocol.Tls.Handshake.Server
{
internal class TlsServerHello : HandshakeMessage
{
#region Private Fields
private int unixTime;
private byte[] random;
#endregion
#region Constructors
public TlsServerHello(Context context)
: base(context, HandshakeType.ServerHello)
{
}
#endregion
#region Methods
public override void Update()
{
base.Update();
TlsStream random = new TlsStream();
// Compute Server Random
random.Write(this.unixTime);
random.Write(this.random);
this.Context.ServerRandom = random.ToArray();
// Compute ClientRandom + ServerRandom
random.Reset();
random.Write(this.Context.ClientRandom);
random.Write(this.Context.ServerRandom);
this.Context.RandomCS = random.ToArray();
// Server Random + Client Random
random.Reset();
random.Write(this.Context.ServerRandom);
random.Write(this.Context.ClientRandom);
this.Context.RandomSC = random.ToArray();
random.Reset();
}
#endregion
#region Protected Methods
protected override void ProcessAsSsl3()
{
this.ProcessAsTls1();
}
protected override void ProcessAsTls1()
{
// Write protocol version
this.Write(this.Context.Protocol);
// Write Unix time
this.unixTime = this.Context.GetUnixTime();
this.Write(this.unixTime);
// Write Random bytes
random = this.Context.GetSecureRandomBytes(28);
this.Write(this.random);
if (this.Context.SessionId == null)
{
this.WriteByte(0);
}
else
{
// Write Session ID length
this.WriteByte((byte)this.Context.SessionId.Length);
// Write Session ID
this.Write(this.Context.SessionId);
}
// Write selected cipher suite
this.Write(this.Context.Negotiating.Cipher.Code);
// Write selected compression method
this.WriteByte((byte)this.Context.CompressionMethod);
}
#endregion
}
}
@@ -1,52 +0,0 @@
// Transport Security Layer (TLS)
// Copyright (c) 2003-2004 Carlos Guzman Alvarez
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
namespace Mono.Security.Protocol.Tls.Handshake.Server
{
internal class TlsServerHelloDone : HandshakeMessage
{
#region Constructors
public TlsServerHelloDone(Context context)
: base(context, HandshakeType.ServerHelloDone)
{
}
#endregion
#region Protected Methods
protected override void ProcessAsSsl3()
{
}
protected override void ProcessAsTls1()
{
}
#endregion
}
}
@@ -1,110 +0,0 @@
// Transport Security Layer (TLS)
// Copyright (c) 2003-2004 Carlos Guzman Alvarez
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Security.Cryptography;
using SX509 = System.Security.Cryptography.X509Certificates;
using Mono.Security.Cryptography;
using Mono.Security.X509;
namespace Mono.Security.Protocol.Tls.Handshake.Server
{
internal class TlsServerKeyExchange : HandshakeMessage
{
#region Constructors
public TlsServerKeyExchange(Context context)
: base(context, HandshakeType.ServerKeyExchange)
{
}
#endregion
#region Methods
public override void Update()
{
throw new NotSupportedException();
}
#endregion
#region Protected Methods
protected override void ProcessAsSsl3()
{
this.ProcessAsTls1();
}
protected override void ProcessAsTls1()
{
ServerContext context = (ServerContext)this.Context;
// Select the private key information
RSA rsa = (RSA)context.SslStream.PrivateKeyCertSelectionDelegate(
new SX509.X509Certificate(context.ServerSettings.Certificates[0].RawData),
null);
RSAParameters rsaParams = rsa.ExportParameters(false);
// Write Modulus
this.WriteInt24(rsaParams.Modulus.Length);
this.Write(rsaParams.Modulus, 0, rsaParams.Modulus.Length);
// Write exponent
this.WriteInt24(rsaParams.Exponent.Length);
this.Write(rsaParams.Exponent, 0, rsaParams.Exponent.Length);
// Write signed params
byte[] signature = this.createSignature(rsa, this.ToArray());
this.WriteInt24(signature.Length);
this.Write(signature);
}
#endregion
#region Private Methods
private byte[] createSignature(RSA rsa, byte[] buffer)
{
MD5SHA1 hash = new MD5SHA1();
// Create server params array
TlsStream stream = new TlsStream();
stream.Write(this.Context.RandomCS);
stream.Write(buffer, 0, buffer.Length);
hash.ComputeHash(stream.ToArray());
stream.Reset();
return hash.CreateSignature(rsa);
}
#endregion
}
}
@@ -1,38 +0,0 @@
// Transport Security Layer (TLS)
// Copyright (c) 2003-2004 Carlos Guzman Alvarez
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
namespace Mono.Security.Protocol.Tls.Handshake
{
[Serializable]
internal enum ClientCertificateType
{
RSA = 1,
DSS = 2,
RSAFixed = 3,
DSSFixed = 4,
Unknown = 255
}
}
@@ -1,170 +0,0 @@
// Transport Security Layer (TLS)
// Copyright (c) 2003-2004 Carlos Guzman Alvarez
// Copyright (C) 2006 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
namespace Mono.Security.Protocol.Tls.Handshake
{
internal abstract class HandshakeMessage : TlsStream
{
#region Fields
private Context context;
private HandshakeType handshakeType;
private ContentType contentType;
private byte[] cache;
#endregion
#region Properties
public Context Context
{
get { return this.context; }
}
public HandshakeType HandshakeType
{
get { return this.handshakeType; }
}
public ContentType ContentType
{
get { return this.contentType; }
}
#endregion
#region Constructors
public HandshakeMessage(
Context context,
HandshakeType handshakeType)
: this(context, handshakeType, ContentType.Handshake)
{
}
public HandshakeMessage(
Context context,
HandshakeType handshakeType,
ContentType contentType) : base()
{
this.context = context;
this.handshakeType = handshakeType;
this.contentType = contentType;
}
public HandshakeMessage(
Context context,
HandshakeType handshakeType,
byte[] data) : base(data)
{
this.context = context;
this.handshakeType = handshakeType;
}
#endregion
#region Abstract Methods
protected abstract void ProcessAsTls1();
protected abstract void ProcessAsSsl3();
#endregion
#region Methods
public void Process()
{
switch (this.Context.SecurityProtocol)
{
case SecurityProtocolType.Tls:
case SecurityProtocolType.Default:
this.ProcessAsTls1();
break;
case SecurityProtocolType.Ssl3:
this.ProcessAsSsl3();
break;
case SecurityProtocolType.Ssl2:
default:
throw new NotSupportedException("Unsupported security protocol type");
}
}
public virtual void Update()
{
if (this.CanWrite)
{
// result may (should) be available from a previous call to EncodeMessage
if (cache == null)
cache = this.EncodeMessage ();
this.context.HandshakeMessages.Write (cache);
this.Reset();
cache = null;
}
}
public virtual byte[] EncodeMessage()
{
cache = null;
if (CanWrite)
{
byte[] hs = this.ToArray ();
int len = hs.Length;
cache = new byte[4 + len];
cache[0] = (byte) HandshakeType;
// Length as an Int24 in Network Order
cache[1] = (byte) (len >> 16);
cache[2] = (byte) (len >> 8);
cache[3] = (byte) len;
Buffer.BlockCopy (hs, 0, cache, 4, len);
}
return cache;
}
static public bool Compare (byte[] buffer1, byte[] buffer2)
{
// in our case both null can't exist (or be valid)
if ((buffer1 == null) || (buffer2 == null))
return false;
if (buffer1.Length != buffer2.Length)
return false;
for (int i = 0; i < buffer1.Length; i++) {
if (buffer1[i] != buffer2[i])
return false;
}
return true;
}
#endregion
}
}
@@ -1,44 +0,0 @@
// Transport Security Layer (TLS)
// Copyright (c) 2003-2004 Carlos Guzman Alvarez
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
namespace Mono.Security.Protocol.Tls.Handshake
{
[Serializable]
internal enum HandshakeType : byte
{
HelloRequest = 0,
ClientHello = 1,
ServerHello = 2,
Certificate = 11,
ServerKeyExchange = 12,
CertificateRequest = 13,
ServerHelloDone = 14,
CertificateVerify = 15,
ClientKeyExchange = 16,
Finished = 20,
None = 255
}
}
@@ -1,265 +0,0 @@
// Transport Security Layer (TLS)
// Copyright (c) 2003-2004 Carlos Guzman Alvarez
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
namespace Mono.Security.Protocol.Tls
{
#region Enumerations
[Serializable]
internal enum AlertLevel : byte
{
Warning = 1,
Fatal = 2
}
[Serializable]
internal enum AlertDescription : byte
{
CloseNotify = 0,
UnexpectedMessage = 10,
BadRecordMAC = 20,
DecryptionFailed = 21,
RecordOverflow = 22,
DecompressionFailiure = 30,
HandshakeFailiure = 40,
NoCertificate = 41, // should be used in SSL3
BadCertificate = 42,
UnsupportedCertificate = 43,
CertificateRevoked = 44,
CertificateExpired = 45,
CertificateUnknown = 46,
IlegalParameter = 47,
UnknownCA = 48,
AccessDenied = 49,
DecodeError = 50,
DecryptError = 51,
ExportRestriction = 60,
ProtocolVersion = 70,
InsuficientSecurity = 71,
InternalError = 80,
UserCancelled = 90,
NoRenegotiation = 100
}
#endregion
internal class Alert
{
#region Fields
private AlertLevel level;
private AlertDescription description;
#endregion
#region Properties
public AlertLevel Level
{
get { return this.level; }
}
public AlertDescription Description
{
get { return this.description; }
}
public string Message
{
get { return Alert.GetAlertMessage(this.description); }
}
public bool IsWarning
{
get { return this.level == AlertLevel.Warning ? true : false; }
}
/*
public bool IsFatal
{
get { return this.level == AlertLevel.Fatal ? true : false; }
}
*/
public bool IsCloseNotify
{
get
{
if (this.IsWarning &&
this.description == AlertDescription.CloseNotify)
{
return true;
}
return false;
}
}
#endregion
#region Constructors
public Alert(AlertDescription description)
{
this.description = description;
this.level = inferAlertLevel(description);
}
public Alert(
AlertLevel level,
AlertDescription description)
{
this.level = level;
this.description = description;
}
#endregion
#region Private Methods
private static AlertLevel inferAlertLevel(AlertDescription description)
{
switch (description)
{
case AlertDescription.CloseNotify:
case AlertDescription.NoRenegotiation:
case AlertDescription.UserCancelled:
return AlertLevel.Warning;
case AlertDescription.AccessDenied:
case AlertDescription.BadCertificate:
case AlertDescription.BadRecordMAC:
case AlertDescription.CertificateExpired:
case AlertDescription.CertificateRevoked:
case AlertDescription.CertificateUnknown:
case AlertDescription.DecodeError:
case AlertDescription.DecompressionFailiure:
case AlertDescription.DecryptError:
case AlertDescription.DecryptionFailed:
case AlertDescription.ExportRestriction:
case AlertDescription.HandshakeFailiure:
case AlertDescription.IlegalParameter:
case AlertDescription.InsuficientSecurity:
case AlertDescription.InternalError:
case AlertDescription.ProtocolVersion:
case AlertDescription.RecordOverflow:
case AlertDescription.UnexpectedMessage:
case AlertDescription.UnknownCA:
case AlertDescription.UnsupportedCertificate:
default:
return AlertLevel.Fatal;
}
}
#endregion
#region Static Methods
public static string GetAlertMessage(AlertDescription description)
{
#if (DEBUG)
switch (description)
{
case AlertDescription.AccessDenied:
return "An inappropriate message was received.";
case AlertDescription.BadCertificate:
return "TLSCiphertext decrypted in an invalid way.";
case AlertDescription.BadRecordMAC:
return "Record with an incorrect MAC.";
case AlertDescription.CertificateExpired:
return "Certificate has expired or is not currently valid";
case AlertDescription.CertificateRevoked:
return "Certificate was revoked by its signer.";
case AlertDescription.CertificateUnknown:
return "Certificate Unknown.";
case AlertDescription.CloseNotify:
return "Connection closed";
case AlertDescription.DecodeError:
return "A message could not be decoded because some field was out of the specified range or the length of the message was incorrect.";
case AlertDescription.DecompressionFailiure:
return "The decompression function received improper input (e.g. data that would expand to excessive length).";
case AlertDescription.DecryptError:
return "TLSCiphertext decrypted in an invalid way: either it wasn`t an even multiple of the block length or its padding values, when checked, weren`t correct.";
case AlertDescription.DecryptionFailed:
return "Handshake cryptographic operation failed, including being unable to correctly verify a signature, decrypt a key exchange, or validate finished message.";
case AlertDescription.ExportRestriction:
return "Negotiation not in compliance with export restrictions was detected.";
case AlertDescription.HandshakeFailiure:
return "Unable to negotiate an acceptable set of security parameters given the options available.";
case AlertDescription.IlegalParameter:
return "A field in the handshake was out of range or inconsistent with other fields.";
case AlertDescription.InsuficientSecurity:
return "Negotiation has failed specifically because the server requires ciphers more secure than those supported by the client.";
case AlertDescription.InternalError:
return "Internal error unrelated to the peer or the correctness of the protocol makes it impossible to continue.";
case AlertDescription.NoRenegotiation:
return "Invalid renegotiation.";
case AlertDescription.ProtocolVersion:
return "Unsupported protocol version.";
case AlertDescription.RecordOverflow:
return "Invalid length on TLSCiphertext record or TLSCompressed record.";
case AlertDescription.UnexpectedMessage:
return "Invalid message received.";
case AlertDescription.UnknownCA:
return "CA can't be identified as a trusted CA.";
case AlertDescription.UnsupportedCertificate:
return "Certificate was of an unsupported type.";
case AlertDescription.UserCancelled:
return "Handshake cancelled by user.";
default:
return "";
}
#else
return "The authentication or decryption has failed.";
#endif
}
#endregion
}
}
@@ -1,45 +0,0 @@
// Transport Security Layer (TLS)
// Copyright (c) 2003-2004 Carlos Guzman Alvarez
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
namespace Mono.Security.Protocol.Tls
{
#if INSIDE_SYSTEM
internal
#else
[Serializable]
public
#endif
enum CipherAlgorithmType
{
Des,
None,
Rc2,
Rc4,
Rijndael,
SkipJack,
TripleDes
}
}
@@ -1,594 +0,0 @@
// Transport Security Layer (TLS)
// Copyright (c) 2003-2004 Carlos Guzman Alvarez
// Copyright (C) 2006 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.IO;
using System.Text;
using System.Security.Cryptography;
using Mono.Security;
using Mono.Security.Cryptography;
using M = Mono.Security.Cryptography;
namespace Mono.Security.Protocol.Tls
{
internal abstract class CipherSuite
{
#region Static Fields
public static byte[] EmptyArray = new byte[0];
#endregion
#region Fields
private short code;
private string name;
private CipherAlgorithmType cipherAlgorithmType;
private HashAlgorithmType hashAlgorithmType;
private ExchangeAlgorithmType exchangeAlgorithmType;
private bool isExportable;
private CipherMode cipherMode;
private byte keyMaterialSize;
private int keyBlockSize;
private byte expandedKeyMaterialSize;
private short effectiveKeyBits;
private byte ivSize;
private byte blockSize;
private Context context;
private SymmetricAlgorithm encryptionAlgorithm;
private ICryptoTransform encryptionCipher;
private SymmetricAlgorithm decryptionAlgorithm;
private ICryptoTransform decryptionCipher;
private KeyedHashAlgorithm clientHMAC;
private KeyedHashAlgorithm serverHMAC;
#endregion
#region Protected Properties
protected ICryptoTransform EncryptionCipher
{
get { return this.encryptionCipher; }
}
protected ICryptoTransform DecryptionCipher
{
get { return this.decryptionCipher; }
}
protected KeyedHashAlgorithm ClientHMAC
{
get { return this.clientHMAC; }
}
protected KeyedHashAlgorithm ServerHMAC
{
get { return this.serverHMAC; }
}
#endregion
#region Properties
public CipherAlgorithmType CipherAlgorithmType
{
get { return this.cipherAlgorithmType; }
}
public string HashAlgorithmName
{
get
{
switch (this.hashAlgorithmType)
{
case HashAlgorithmType.Md5:
return "MD5";
case HashAlgorithmType.Sha1:
return "SHA1";
default:
return "None";
}
}
}
internal HashAlgorithm CreateHashAlgorithm ()
{
switch (hashAlgorithmType) {
case HashAlgorithmType.Md5:
return MD5.Create ();
case HashAlgorithmType.Sha1:
return SHA1.Create ();
default:
return null;
}
}
public HashAlgorithmType HashAlgorithmType
{
get { return this.hashAlgorithmType; }
}
public int HashSize
{
get
{
switch (this.hashAlgorithmType)
{
case HashAlgorithmType.Md5:
return 16;
case HashAlgorithmType.Sha1:
return 20;
default:
return 0;
}
}
}
public ExchangeAlgorithmType ExchangeAlgorithmType
{
get { return this.exchangeAlgorithmType; }
}
public CipherMode CipherMode
{
get { return this.cipherMode; }
}
public short Code
{
get { return this.code; }
}
public string Name
{
get { return this.name; }
}
public bool IsExportable
{
get { return this.isExportable; }
}
public byte KeyMaterialSize
{
get { return this.keyMaterialSize; }
}
public int KeyBlockSize
{
get { return this.keyBlockSize; }
}
public byte ExpandedKeyMaterialSize
{
get { return this.expandedKeyMaterialSize; }
}
public short EffectiveKeyBits
{
get { return this.effectiveKeyBits; }
}
public byte IvSize
{
get { return this.ivSize; }
}
/*
public byte BlockSize
{
get { return this.blockSize; }
}
*/
public Context Context
{
get { return this.context; }
set
{
this.context = value;
}
}
#endregion
#region Constructors
public CipherSuite(
short code, string name, CipherAlgorithmType cipherAlgorithmType,
HashAlgorithmType hashAlgorithmType, ExchangeAlgorithmType exchangeAlgorithmType,
bool exportable, bool blockMode, byte keyMaterialSize,
byte expandedKeyMaterialSize, short effectiveKeyBits,
byte ivSize, byte blockSize)
{
this.code = code;
this.name = name;
this.cipherAlgorithmType = cipherAlgorithmType;
this.hashAlgorithmType = hashAlgorithmType;
this.exchangeAlgorithmType = exchangeAlgorithmType;
this.isExportable = exportable;
if (blockMode)
{
this.cipherMode = CipherMode.CBC;
}
this.keyMaterialSize = keyMaterialSize;
this.expandedKeyMaterialSize= expandedKeyMaterialSize;
this.effectiveKeyBits = effectiveKeyBits;
this.ivSize = ivSize;
this.blockSize = blockSize;
this.keyBlockSize = (this.keyMaterialSize + this.HashSize + this.ivSize) << 1;
}
#endregion
#region Methods
internal void Write (byte[] array, int offset, short value)
{
if (offset > array.Length - 2)
throw new ArgumentException ("offset");
array [offset ] = (byte) (value >> 8);
array [offset + 1] = (byte) value;
}
internal void Write (byte[] array, int offset, ulong value)
{
if (offset > array.Length - 8)
throw new ArgumentException ("offset");
array [offset ] = (byte) (value >> 56);
array [offset + 1] = (byte) (value >> 48);
array [offset + 2] = (byte) (value >> 40);
array [offset + 3] = (byte) (value >> 32);
array [offset + 4] = (byte) (value >> 24);
array [offset + 5] = (byte) (value >> 16);
array [offset + 6] = (byte) (value >> 8);
array [offset + 7] = (byte) value;
}
public void InitializeCipher()
{
this.createEncryptionCipher();
this.createDecryptionCipher();
}
public byte[] EncryptRecord(byte[] fragment, byte[] mac)
{
// Encryption ( fragment + mac [+ padding + padding_length] )
int length = fragment.Length + mac.Length;
int padlen = 0;
if (this.CipherMode == CipherMode.CBC) {
// Calculate padding_length
length++; // keep an extra byte
padlen = (this.blockSize - length % this.blockSize);
if (padlen == this.blockSize) {
padlen = 0;
}
length += padlen;
}
byte[] plain = new byte [length];
Buffer.BlockCopy (fragment, 0, plain, 0, fragment.Length);
Buffer.BlockCopy (mac, 0, plain, fragment.Length, mac.Length);
if (padlen > 0) {
int start = fragment.Length + mac.Length;
for (int i = start; i < (start + padlen + 1); i++) {
plain[i] = (byte)padlen;
}
}
this.EncryptionCipher.TransformBlock (plain, 0, plain.Length, plain, 0);
return plain;
}
public void DecryptRecord(byte[] fragment, out byte[] dcrFragment, out byte[] dcrMAC)
{
int fragmentSize = 0;
int paddingLength = 0;
// Decrypt message fragment ( fragment + mac [+ padding + padding_length] )
this.DecryptionCipher.TransformBlock(fragment, 0, fragment.Length, fragment, 0);
// optimization: decrypt "in place", worst case: padding will reduce the size of the data
// this will cut in half the memory allocations (dcrFragment and dcrMAC remains)
// Calculate fragment size
if (this.CipherMode == CipherMode.CBC)
{
// Calculate padding_length
paddingLength = fragment[fragment.Length - 1];
fragmentSize = (fragment.Length - (paddingLength + 1)) - this.HashSize;
}
else
{
fragmentSize = fragment.Length - this.HashSize;
}
dcrFragment = new byte[fragmentSize];
dcrMAC = new byte[HashSize];
Buffer.BlockCopy(fragment, 0, dcrFragment, 0, dcrFragment.Length);
Buffer.BlockCopy(fragment, dcrFragment.Length, dcrMAC, 0, dcrMAC.Length);
}
#endregion
#region Abstract Methods
public abstract byte[] ComputeClientRecordMAC(ContentType contentType, byte[] fragment);
public abstract byte[] ComputeServerRecordMAC(ContentType contentType, byte[] fragment);
public abstract void ComputeMasterSecret(byte[] preMasterSecret);
public abstract void ComputeKeys();
#endregion
#region Key Generation Methods
public byte[] CreatePremasterSecret()
{
ClientContext context = (ClientContext)this.context;
// Generate random bytes (total size)
byte[] preMasterSecret = this.context.GetSecureRandomBytes (48);
// and replace the first two bytes with the protocol version
// (maximum support version not actual)
preMasterSecret [0] = (byte)(context.ClientHelloProtocol >> 8);
preMasterSecret [1] = (byte)context.ClientHelloProtocol;
return preMasterSecret;
}
public byte[] PRF(byte[] secret, string label, byte[] data, int length)
{
/* Secret Length calc exmplain from the RFC2246. Section 5
*
* S1 and S2 are the two halves of the secret and each is the same
* length. S1 is taken from the first half of the secret, S2 from the
* second half. Their length is created by rounding up the length of the
* overall secret divided by two; thus, if the original secret is an odd
* number of bytes long, the last byte of S1 will be the same as the
* first byte of S2.
*/
// split secret in 2
int secretLen = secret.Length >> 1;
// rounding up
if ((secret.Length & 0x1) == 0x1)
secretLen++;
// Seed
TlsStream seedStream = new TlsStream();
seedStream.Write(Encoding.ASCII.GetBytes(label));
seedStream.Write(data);
byte[] seed = seedStream.ToArray();
seedStream.Reset();
// Secret 1
byte[] secret1 = new byte[secretLen];
Buffer.BlockCopy(secret, 0, secret1, 0, secretLen);
// Secret2
byte[] secret2 = new byte[secretLen];
Buffer.BlockCopy(secret, (secret.Length - secretLen), secret2, 0, secretLen);
// Secret 1 processing
byte[] p_md5 = Expand (MD5.Create (), secret1, seed, length);
// Secret 2 processing
byte[] p_sha = Expand (SHA1.Create (), secret2, seed, length);
// Perfor XOR of both results
byte[] masterSecret = new byte[length];
for (int i = 0; i < masterSecret.Length; i++)
{
masterSecret[i] = (byte)(p_md5[i] ^ p_sha[i]);
}
return masterSecret;
}
public byte[] Expand (HashAlgorithm hash, byte[] secret, byte[] seed, int length)
{
int hashLength = hash.HashSize / 8;
int iterations = (int)(length / hashLength);
if ((length % hashLength) > 0)
{
iterations++;
}
M.HMAC hmac = new M.HMAC (hash, secret);
TlsStream resMacs = new TlsStream();
byte[][] hmacs = new byte[iterations + 1][];
hmacs[0] = seed;
for (int i = 1; i <= iterations; i++)
{
TlsStream hcseed = new TlsStream();
hmac.TransformFinalBlock(hmacs[i-1], 0, hmacs[i-1].Length);
hmacs[i] = hmac.Hash;
hcseed.Write(hmacs[i]);
hcseed.Write(seed);
hmac.TransformFinalBlock(hcseed.ToArray(), 0, (int)hcseed.Length);
resMacs.Write(hmac.Hash);
hcseed.Reset();
}
byte[] res = new byte[length];
Buffer.BlockCopy(resMacs.ToArray(), 0, res, 0, res.Length);
resMacs.Reset();
return res;
}
#endregion
#region Private Methods
private void createEncryptionCipher()
{
// Create and configure the symmetric algorithm
switch (this.cipherAlgorithmType)
{
case CipherAlgorithmType.Des:
this.encryptionAlgorithm = DES.Create();
break;
case CipherAlgorithmType.Rc2:
this.encryptionAlgorithm = RC2.Create();
break;
case CipherAlgorithmType.Rc4:
this.encryptionAlgorithm = new ARC4Managed();
break;
case CipherAlgorithmType.TripleDes:
this.encryptionAlgorithm = TripleDES.Create();
break;
case CipherAlgorithmType.Rijndael:
// only AES is really used - and we can use CommonCrypto for iOS and OSX this way
this.encryptionAlgorithm = Aes.Create();
break;
}
// If it's a block cipher
if (this.cipherMode == CipherMode.CBC)
{
// Configure encrypt algorithm
this.encryptionAlgorithm.Mode = this.cipherMode;
this.encryptionAlgorithm.Padding = PaddingMode.None;
this.encryptionAlgorithm.KeySize = this.expandedKeyMaterialSize * 8;
this.encryptionAlgorithm.BlockSize = this.blockSize * 8;
}
// Set the key and IV for the algorithm
if (this.context is ClientContext)
{
this.encryptionAlgorithm.Key = this.context.ClientWriteKey;
this.encryptionAlgorithm.IV = this.context.ClientWriteIV;
}
else
{
this.encryptionAlgorithm.Key = this.context.ServerWriteKey;
this.encryptionAlgorithm.IV = this.context.ServerWriteIV;
}
// Create encryption cipher
this.encryptionCipher = this.encryptionAlgorithm.CreateEncryptor();
// Create the HMAC algorithm
if (this.context is ClientContext)
{
this.clientHMAC = new M.HMAC(
CreateHashAlgorithm (),
this.context.Negotiating.ClientWriteMAC);
}
else
{
this.serverHMAC = new M.HMAC(
CreateHashAlgorithm (),
this.context.Negotiating.ServerWriteMAC);
}
}
private void createDecryptionCipher()
{
// Create and configure the symmetric algorithm
switch (this.cipherAlgorithmType)
{
case CipherAlgorithmType.Des:
this.decryptionAlgorithm = DES.Create();
break;
case CipherAlgorithmType.Rc2:
this.decryptionAlgorithm = RC2.Create();
break;
case CipherAlgorithmType.Rc4:
this.decryptionAlgorithm = new ARC4Managed();
break;
case CipherAlgorithmType.TripleDes:
this.decryptionAlgorithm = TripleDES.Create();
break;
case CipherAlgorithmType.Rijndael:
// only AES is really used - and we can use CommonCrypto for iOS and OSX this way
this.decryptionAlgorithm = Aes.Create();
break;
}
// If it's a block cipher
if (this.cipherMode == CipherMode.CBC)
{
// Configure encrypt algorithm
this.decryptionAlgorithm.Mode = this.cipherMode;
this.decryptionAlgorithm.Padding = PaddingMode.None;
this.decryptionAlgorithm.KeySize = this.expandedKeyMaterialSize * 8;
this.decryptionAlgorithm.BlockSize = this.blockSize * 8;
}
// Set the key and IV for the algorithm
if (this.context is ClientContext)
{
this.decryptionAlgorithm.Key = this.context.ServerWriteKey;
this.decryptionAlgorithm.IV = this.context.ServerWriteIV;
}
else
{
this.decryptionAlgorithm.Key = this.context.ClientWriteKey;
this.decryptionAlgorithm.IV = this.context.ClientWriteIV;
}
// Create decryption cipher
this.decryptionCipher = this.decryptionAlgorithm.CreateDecryptor();
// Create the HMAC
if (this.context is ClientContext)
{
this.serverHMAC = new M.HMAC(
CreateHashAlgorithm (),
this.context.Negotiating.ServerWriteMAC);
}
else
{
this.clientHMAC = new M.HMAC(
CreateHashAlgorithm (),
this.context.Negotiating.ClientWriteMAC);
}
}
#endregion
}
}
@@ -1,130 +0,0 @@
// Transport Security Layer (TLS)
// Copyright (c) 2003-2004 Carlos Guzman Alvarez
// Copyright 2013-2014 Xamarin Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
namespace Mono.Security.Protocol.Tls {
internal sealed class CipherSuiteCollection : List<CipherSuite> {
#region Fields
SecurityProtocolType protocol;
#endregion
#region Indexers
public CipherSuite this [string name] {
get {
int n = IndexOf (name);
return n == -1 ? null : this [n];
}
}
public CipherSuite this [short code] {
get {
int n = IndexOf (code);
return n == -1 ? null : this [n];
}
}
#endregion
#region Constructors
public CipherSuiteCollection (SecurityProtocolType protocol)
{
switch (protocol) {
case SecurityProtocolType.Default:
case SecurityProtocolType.Tls:
case SecurityProtocolType.Ssl3:
this.protocol = protocol;
break;
case SecurityProtocolType.Ssl2:
default:
throw new NotSupportedException ("Unsupported security protocol type.");
}
}
#endregion
#region Methods
public int IndexOf (string name)
{
int index = 0;
foreach (CipherSuite cipherSuite in this) {
if (String.CompareOrdinal (name, cipherSuite.Name) == 0)
return index;
index++;
}
return -1;
}
public int IndexOf (short code)
{
int index = 0;
foreach (CipherSuite cipherSuite in this) {
if (cipherSuite.Code == code)
return index;
index++;
}
return -1;
}
public void Add (
short code, string name, CipherAlgorithmType cipherType,
HashAlgorithmType hashType, ExchangeAlgorithmType exchangeType,
bool exportable, bool blockMode, byte keyMaterialSize,
byte expandedKeyMaterialSize, short effectiveKeyBytes,
byte ivSize, byte blockSize)
{
switch (protocol) {
case SecurityProtocolType.Default:
case SecurityProtocolType.Tls:
Add (new TlsCipherSuite (code, name, cipherType, hashType, exchangeType, exportable, blockMode,
keyMaterialSize, expandedKeyMaterialSize, effectiveKeyBytes, ivSize, blockSize));
break;
case SecurityProtocolType.Ssl3:
Add (new SslCipherSuite (code, name, cipherType, hashType, exchangeType, exportable, blockMode,
keyMaterialSize, expandedKeyMaterialSize, effectiveKeyBytes, ivSize, blockSize));
break;
}
}
public IList<string> GetNames ()
{
var list = new List<string> (Count);
foreach (CipherSuite cipherSuite in this)
list.Add (cipherSuite.Name);
return list;
}
#endregion
}
}
@@ -1,199 +0,0 @@
// Transport Security Layer (TLS)
// Copyright (c) 2003-2004 Carlos Guzman Alvarez
// Copyright 2013-2014 Xamarin Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Net;
namespace Mono.Security.Protocol.Tls
{
internal static class CipherSuiteFactory
{
#if false && !INSIDE_SYSTEM && !BOOTSTRAP_BASIC
static Type spm = typeof (ServicePointManager);
static PropertyInfo client_callback;
static PropertyInfo server_callback;
#endif
public static CipherSuiteCollection GetSupportedCiphers (bool server, SecurityProtocolType protocol)
{
switch (protocol) {
case SecurityProtocolType.Default:
case SecurityProtocolType.Tls:
return CipherSuiteFactory.GetTls1SupportedCiphers ();
case SecurityProtocolType.Ssl3:
return CipherSuiteFactory.GetSsl3SupportedCiphers ();
case SecurityProtocolType.Ssl2:
default:
throw new NotSupportedException ("Unsupported security protocol type");
}
}
#region Private Static Methods
private static CipherSuiteCollection GetTls1SupportedCiphers()
{
CipherSuiteCollection scs = new CipherSuiteCollection(SecurityProtocolType.Tls);
// Supported ciphers
scs.Add((0x00 << 0x08) | 0x35, "TLS_RSA_WITH_AES_256_CBC_SHA", CipherAlgorithmType.Rijndael, HashAlgorithmType.Sha1, ExchangeAlgorithmType.RsaKeyX, false, true, 32, 32, 256, 16, 16);
scs.Add((0x00 << 0x08) | 0x2F, "TLS_RSA_WITH_AES_128_CBC_SHA", CipherAlgorithmType.Rijndael, HashAlgorithmType.Sha1, ExchangeAlgorithmType.RsaKeyX, false, true, 16, 16, 128, 16, 16);
scs.Add((0x00 << 0x08) | 0x0A, "TLS_RSA_WITH_3DES_EDE_CBC_SHA", CipherAlgorithmType.TripleDes, HashAlgorithmType.Sha1, ExchangeAlgorithmType.RsaKeyX, false, true, 24, 24, 168, 8, 8);
scs.Add((0x00 << 0x08) | 0x05, "TLS_RSA_WITH_RC4_128_SHA", CipherAlgorithmType.Rc4, HashAlgorithmType.Sha1, ExchangeAlgorithmType.RsaKeyX, false, false, 16, 16, 128, 0, 0);
scs.Add((0x00 << 0x08) | 0x04, "TLS_RSA_WITH_RC4_128_MD5", CipherAlgorithmType.Rc4, HashAlgorithmType.Md5, ExchangeAlgorithmType.RsaKeyX, false, false, 16, 16, 128, 0, 0);
scs.Add((0x00 << 0x08) | 0x09, "TLS_RSA_WITH_DES_CBC_SHA", CipherAlgorithmType.Des, HashAlgorithmType.Sha1, ExchangeAlgorithmType.RsaKeyX, false, true, 8, 8, 56, 8, 8);
// Supported exportable ciphers
// scs.Add((0x00 << 0x08) | 0x03, "TLS_RSA_EXPORT_WITH_RC4_40_MD5", CipherAlgorithmType.Rc4, HashAlgorithmType.Md5, ExchangeAlgorithmType.RsaKeyX, true, false, 5, 16, 40, 0, 0);
// scs.Add((0x00 << 0x08) | 0x06, "TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5", CipherAlgorithmType.Rc2, HashAlgorithmType.Md5, ExchangeAlgorithmType.RsaKeyX, true, true, 5, 16, 40, 8, 8);
// scs.Add((0x00 << 0x08) | 0x08, "TLS_RSA_EXPORT_WITH_DES40_CBC_SHA", CipherAlgorithmType.Des, HashAlgorithmType.Sha1, ExchangeAlgorithmType.RsaKeyX, true, true, 5, 8, 40, 8, 8);
// scs.Add((0x00 << 0x08) | 0x60, "TLS_RSA_EXPORT_WITH_RC4_56_MD5", CipherAlgorithmType.Rc4, HashAlgorithmType.Md5, ExchangeAlgorithmType.RsaKeyX, true, false, 7, 16, 56, 0, 0);
// scs.Add((0x00 << 0x08) | 0x61, "TLS_RSA_EXPORT_WITH_RC2_CBC_56_MD5", CipherAlgorithmType.Rc2, HashAlgorithmType.Md5, ExchangeAlgorithmType.RsaKeyX, true, true, 7, 16, 56, 8, 8);
// 56 bits but we use 64 bits because of parity (DES is really 56 bits)
// scs.Add((0x00 << 0x08) | 0x62, "TLS_RSA_EXPORT_WITH_DES_CBC_56_SHA", CipherAlgorithmType.Des, HashAlgorithmType.Sha1, ExchangeAlgorithmType.RsaKeyX, true, true, 8, 8, 64, 8, 8);
// scs.Add((0x00 << 0x08) | 0x64, "TLS_RSA_EXPORT_WITH_RC4_56_SHA", CipherAlgorithmType.Rc4, HashAlgorithmType.Sha1, ExchangeAlgorithmType.RsaKeyX, true, false, 7, 16, 56, 0, 0);
// Default CipherSuite
// scs.Add(0, "TLS_NULL_WITH_NULL_NULL", CipherAlgorithmType.None, HashAlgorithmType.None, ExchangeAlgorithmType.None, true, false, 0, 0, 0, 0, 0);
// RSA Cipher Suites
// scs.Add((0x00 << 0x08) | 0x01, "TLS_RSA_WITH_NULL_MD5", CipherAlgorithmType.None, HashAlgorithmType.Md5, ExchangeAlgorithmType.None, true, false, 0, 0, 0, 0, 0);
// scs.Add((0x00 << 0x08) | 0x02, "TLS_RSA_WITH_NULL_SHA", CipherAlgorithmType.None, HashAlgorithmType.Sha1, ExchangeAlgorithmType.None, true, false, 0, 0, 0, 0, 0);
// scs.Add((0x00 << 0x08) | 0x03, "TLS_RSA_EXPORT_WITH_RC4_40_MD5", CipherAlgorithmType.Rc4, HashAlgorithmType.Md5, ExchangeAlgorithmType.RsaKeyX, true, false, 5, 16, 40, 0, 0);
// scs.Add((0x00 << 0x08) | 0x05, "TLS_RSA_WITH_RC4_128_SHA", CipherAlgorithmType.Rc4, HashAlgorithmType.Sha1, ExchangeAlgorithmType.RsaSign, false, false, 16, 16, 128, 0, 0);
// scs.Add((0x00 << 0x08) | 0x04, "TLS_RSA_WITH_RC4_128_MD5", CipherAlgorithmType.Rc4, HashAlgorithmType.Md5, ExchangeAlgorithmType.RsaSign, false, false, 16, 16, 128, 0, 0);
// scs.Add((0x00 << 0x08) | 0x06, "TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5", CipherAlgorithmType.Rc2, HashAlgorithmType.Md5, ExchangeAlgorithmType.RsaKeyX, true, true, 5, 16, 40, 8, 8);
// scs.Add((0x00 << 0x08) | 0x07, "TLS_RSA_WITH_IDEA_CBC_SHA", "IDEA", HashAlgorithmType.Sha1, ExchangeAlgorithmType.RsaSign, false, true, 16, 16, 128, 8, 8);
// scs.Add((0x00 << 0x08) | 0x08, "TLS_RSA_EXPORT_WITH_DES40_CBC_SHA", CipherAlgorithmType.Des, HashAlgorithmType.Sha1, ExchangeAlgorithmType.RsaKeyX, true, true, 5, 8, 40, 8, 8);
// scs.Add((0x00 << 0x08) | 0x09, "TLS_RSA_WITH_DES_CBC_SHA", CipherAlgorithmType.Des, HashAlgorithmType.Sha1, ExchangeAlgorithmType.RsaSign, false, true, 8, 8, 56, 8, 8);
// scs.Add((0x00 << 0x08) | 0x0A, "TLS_RSA_WITH_3DES_EDE_CBC_SHA", CipherAlgorithmType.TripleDes, HashAlgorithmType.Sha1, ExchangeAlgorithmType.RsaSign, false, true, 24, 24, 168, 8, 8);
// Diffie-Hellman Cipher Suites
// scs.Add((0x00 << 0x08) | 0x0B, "TLS_DH_DSS_EXPORT_WITH_DES40_CBC_SHA", CipherAlgorithmType.Des, HashAlgorithmType.Sha1, ExchangeAlgorithmType.DiffieHellman, true, true, 5, 8, 40, 8, 8);
// scs.Add((0x00 << 0x08) | 0x0C, "TLS_DH_DSS_WITH_DES_CBC_SHA", CipherAlgorithmType.Des, HashAlgorithmType.Sha1, false, ExchangeAlgorithmType.DiffieHellman, true, 8, 8, 56, 8, 8);
// scs.Add((0x00 << 0x08) | 0x0D, "TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA", CipherAlgorithmType.TripleDes, HashAlgorithmType.Sha1, ExchangeAlgorithmType.DiffieHellman, false, true, 24, 24, 168, 8, 8);
// scs.Add((0x00 << 0x08) | 0x0E, "TLS_DH_RSA_EXPORT_WITH_DES40_CBC_SHA", CipherAlgorithmType.Des, HashAlgorithmType.Sha1, ExchangeAlgorithmType.DiffieHellman, true, true, 5, 8, 40, 8, 8);
// scs.Add((0x00 << 0x08) | 0x0F, "TLS_DH_RSA_WITH_DES_CBC_SHA", CipherAlgorithmType.Des, HashAlgorithmType.Sha1, false, ExchangeAlgorithmType.DiffieHellman, true, 8, 8, 56, 8, 8);
// scs.Add((0x00 << 0x08) | 0x10, "TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA", CipherAlgorithmType.TripleDes, HashAlgorithmType.Sha1, ExchangeAlgorithmType.DiffieHellman, false, true, 24, 24, 168, 8, 8);
// scs.Add((0x00 << 0x08) | 0x11, "TLS_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA", CipherAlgorithmType.Des, HashAlgorithmType.Sha1, ExchangeAlgorithmType.DiffieHellman, true, true, 5, 8, 40, 8, 8);
// scs.Add((0x00 << 0x08) | 0x12, "TLS_DHE_DSS_WITH_DES_CBC_SHA", CipherAlgorithmType.Des, HashAlgorithmType.Sha1, ExchangeAlgorithmType.DiffieHellman, false, true, 8, 8, 56, 8, 8);
// scs.Add((0x00 << 0x08) | 0x13, "TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA", CipherAlgorithmType.TripleDes, HashAlgorithmType.Sha1, ExchangeAlgorithmType.DiffieHellman, false, true, 24, 24, 168, 8, 8);
// scs.Add((0x00 << 0x08) | 0x14, "TLS_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA", CipherAlgorithmType.Des, HashAlgorithmType.Sha1, ExchangeAlgorithmType.DiffieHellman, true, true, 5, 8, 40, 8, 8);
// scs.Add((0x00 << 0x08) | 0x15, "TLS_DHE_RSA_WITH_DES_CBC_SHA", HashAlgorithmType.Sha1, CipherAlgorithmType.Des, false, ExchangeAlgorithmType.DiffieHellman, true, 8, 8, 56, 8, 8);
// scs.Add((0x00 << 0x08) | 0x16, "TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA", CipherAlgorithmType.TripleDes, HashAlgorithmType.Sha1, ExchangeAlgorithmType.DiffieHellman, false, true, 24, 24, 168, 8, 8);
// Anonymous Diffie-Hellman Cipher Suites
// scs.Add((0x00 << 0x08) | 0x17, "TLS_DH_anon_EXPORT_WITH_RC4_40_MD5", CipherAlgorithmType.Rc4, HashAlgorithmType.Md5, ExchangeAlgorithmType.DiffieHellman, true, false, 5, 16, 40, 0, 0);
// scs.Add((0x00 << 0x08) | 0x18, "TLS_DH_anon_WITH_RC4_128_MD5", CipherAlgorithmType.Rc4, HashAlgorithmType.Md5, false, ExchangeAlgorithmType.DiffieHellman, false, 16, 16, 128, 0, 0);
// scs.Add((0x00 << 0x08) | 0x19, "TLS_DH_anon_EXPORT_WITH_DES40_CBC_SHA", CipherAlgorithmType.Des, HashAlgorithmType.Sha1, ExchangeAlgorithmType.DiffieHellman, false, true, 5, 8, 40, 8, 8);
// scs.Add((0x00 << 0x08) | 0x1A, "TLS_DH_anon_WITH_DES_CBC_SHA", "DES4", HashAlgorithmType.Sha1, ExchangeAlgorithmType.DiffieHellman, false, true, 8, 8, 56, 8, 8);
// scs.Add((0x00 << 0x08) | 0x1B, "TLS_DH_anon_WITH_3DES_EDE_CBC_SHA", CipherAlgorithmType.TripleDes, HashAlgorithmType.Sha1, ExchangeAlgorithmType.DiffieHellman, false, true, 24, 24, 168, 8, 8);
// AES CipherSuites
//
// Ref: RFC3268 - (http://www.ietf.org/rfc/rfc3268.txt)
// scs.Add((0x00 << 0x08) | 0x2F, "TLS_RSA_WITH_AES_128_CBC_SHA", CipherAlgorithmType.Rijndael, HashAlgorithmType.Sha1, ExchangeAlgorithmType.RsaSign, false, true, 16, 16, 128, 16, 16);
// scs.Add((0x00 << 0x08) | 0x30, "TLS_DH_DSS_WITH_AES_128_CBC_SHA", CipherAlgorithmType.Rijndael, HashAlgorithmType.Sha1, ExchangeAlgorithmType.DiffieHellman, false, true, 16, 16, 128, 8, 8);
// scs.Add((0x00 << 0x08) | 0x31, "TLS_DH_RSA_WITH_AES_128_CBC_SHA", CipherAlgorithmType.Rijndael, HashAlgorithmType.Sha1, ExchangeAlgorithmType.DiffieHellman, false, true, 16, 16, 128, 8, 8);
// scs.Add((0x00 << 0x08) | 0x32, "TLS_DHE_DSS_WITH_AES_128_CBC_SHA", CipherAlgorithmType.Rijndael, HashAlgorithmType.Sha1, ExchangeAlgorithmType.DiffieHellman, false, true, 16, 16, 128, 8, 8);
// scs.Add((0x00 << 0x08) | 0x33, "TLS_DHE_RSA_WITH_AES_128_CBC_SHA", CipherAlgorithmType.Rijndael, HashAlgorithmType.Sha1, ExchangeAlgorithmType.DiffieHellman, false, true, 16, 16, 128, 8, 8);
// scs.Add((0x00 << 0x08) | 0x34, "TLS_DH_anon_WITH_AES_128_CBC_SHA", CipherAlgorithmType.Rijndael, HashAlgorithmType.Sha1, ExchangeAlgorithmType.DiffieHellman, false, true, 16, 16, 128, 8, 8);
// scs.Add((0x00 << 0x08) | 0x35, "TLS_RSA_WITH_AES_256_CBC_SHA", CipherAlgorithmType.Rijndael, HashAlgorithmType.Sha1, ExchangeAlgorithmType.RsaSign, false, true, 32, 32, 256, 16, 16);
// scs.Add((0x00 << 0x08) | 0x36, "TLS_DH_DSS_WITH_AES_256_CBC_SHA", CipherAlgorithmType.Rijndael, HashAlgorithmType.Sha1, ExchangeAlgorithmType.DiffieHellman, false, true, 32, 32, 256, 16, 16);
// scs.Add((0x00 << 0x08) | 0x37, "TLS_DH_RSA_WITH_AES_256_CBC_SHA", CipherAlgorithmType.Rijndael, HashAlgorithmType.Sha1, ExchangeAlgorithmType.DiffieHellman, false, true, 32, 32, 256, 16, 16);
// scs.Add((0x00 << 0x08) | 0x38, "TLS_DHE_DSS_WITH_AES_256_CBC_SHA", CipherAlgorithmType.Rijndael, HashAlgorithmType.Sha1, ExchangeAlgorithmType.DiffieHellman, false, true, 32, 32, 256, 16, 16);
// scs.Add((0x00 << 0x08) | 0x39, "TLS_DHE_RSA_WITH_AES_256_CBC_SHA", CipherAlgorithmType.Rijndael, HashAlgorithmType.Sha1, ExchangeAlgorithmType.DiffieHellman, false, true, 32, 32, 256, 16, 16);
// scs.Add((0x00 << 0x08) | 0x3A, "TLS_DH_anon_WITH_AES_256_CBC_SHA", CipherAlgorithmType.Rijndael, HashAlgorithmType.Sha1, ExchangeAlgorithmType.DiffieHellman, false, true, 32, 32, 256, 16, 16);
return scs;
}
private static CipherSuiteCollection GetSsl3SupportedCiphers()
{
CipherSuiteCollection scs = new CipherSuiteCollection(SecurityProtocolType.Ssl3);
// Supported ciphers
scs.Add((0x00 << 0x08) | 0x35, "SSL_RSA_WITH_AES_256_CBC_SHA", CipherAlgorithmType.Rijndael, HashAlgorithmType.Sha1, ExchangeAlgorithmType.RsaKeyX, false, true, 32, 32, 256, 16, 16);
scs.Add((0x00 << 0x08) | 0x2F, "SSL_RSA_WITH_AES_128_CBC_SHA", CipherAlgorithmType.Rijndael, HashAlgorithmType.Sha1, ExchangeAlgorithmType.RsaKeyX, false, true, 16, 16, 128, 16, 16);
scs.Add((0x00 << 0x08) | 0x0A, "SSL_RSA_WITH_3DES_EDE_CBC_SHA", CipherAlgorithmType.TripleDes, HashAlgorithmType.Sha1, ExchangeAlgorithmType.RsaKeyX, false, true, 24, 24, 168, 8, 8);
scs.Add((0x00 << 0x08) | 0x05, "SSL_RSA_WITH_RC4_128_SHA", CipherAlgorithmType.Rc4, HashAlgorithmType.Sha1, ExchangeAlgorithmType.RsaKeyX, false, false, 16, 16, 128, 0, 0);
scs.Add((0x00 << 0x08) | 0x04, "SSL_RSA_WITH_RC4_128_MD5", CipherAlgorithmType.Rc4, HashAlgorithmType.Md5, ExchangeAlgorithmType.RsaKeyX, false, false, 16, 16, 128, 0, 0);
scs.Add((0x00 << 0x08) | 0x09, "SSL_RSA_WITH_DES_CBC_SHA", CipherAlgorithmType.Des, HashAlgorithmType.Sha1, ExchangeAlgorithmType.RsaKeyX, false, true, 8, 8, 56, 8, 8);
// Supported exportable ciphers
// scs.Add((0x00 << 0x08) | 0x03, "SSL_RSA_EXPORT_WITH_RC4_40_MD5", CipherAlgorithmType.Rc4, HashAlgorithmType.Md5, ExchangeAlgorithmType.RsaKeyX, true, false, 5, 16, 40, 0, 0);
// scs.Add((0x00 << 0x08) | 0x06, "SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5", CipherAlgorithmType.Rc2, HashAlgorithmType.Md5, ExchangeAlgorithmType.RsaKeyX, true, true, 5, 16, 40, 8, 8);
// scs.Add((0x00 << 0x08) | 0x08, "SSL_RSA_EXPORT_WITH_DES40_CBC_SHA", CipherAlgorithmType.Des, HashAlgorithmType.Sha1, ExchangeAlgorithmType.RsaKeyX, true, true, 5, 8, 40, 8, 8);
// scs.Add((0x00 << 0x08) | 0x60, "SSL_RSA_EXPORT_WITH_RC4_56_MD5", CipherAlgorithmType.Rc4, HashAlgorithmType.Md5, ExchangeAlgorithmType.RsaKeyX, true, false, 7, 16, 56, 0, 0);
// scs.Add((0x00 << 0x08) | 0x61, "SSL_RSA_EXPORT_WITH_RC2_CBC_56_MD5", CipherAlgorithmType.Rc2, HashAlgorithmType.Md5, ExchangeAlgorithmType.RsaKeyX, true, true, 7, 16, 56, 8, 8);
// 56 bits but we use 64 bits because of parity (DES is really 56 bits)
// scs.Add((0x00 << 0x08) | 0x62, "SSL_RSA_EXPORT_WITH_DES_CBC_56_SHA", CipherAlgorithmType.Des, HashAlgorithmType.Sha1, ExchangeAlgorithmType.RsaKeyX, true, true, 8, 8, 64, 8, 8);
// scs.Add((0x00 << 0x08) | 0x64, "SSL_RSA_EXPORT_WITH_RC4_56_SHA", CipherAlgorithmType.Rc4, HashAlgorithmType.Sha1, ExchangeAlgorithmType.RsaKeyX, true, false, 7, 16, 56, 0, 0);
// Default CipherSuite
// scs.Add(0, "SSL_NULL_WITH_NULL_NULL", CipherAlgorithmType.None, HashAlgorithmType.None, true, false, 0, 0, 0, 0, 0);
// RSA Cipher Suites
// scs.Add((0x00 << 0x08) | 0x01, "SSL_RSA_WITH_NULL_MD5", CipherAlgorithmType.None, HashAlgorithmType.Md5, ExchangeAlgorithmType.None, true, false, 0, 0, 0, 0, 0);
// scs.Add((0x00 << 0x08) | 0x02, "SSL_RSA_WITH_NULL_SHA", CipherAlgorithmType.None, HashAlgorithmType.Sha1, true, ExchangeAlgorithmType.None, false, 0, 0, 0, 0, 0);
// scs.Add((0x00 << 0x08) | 0x03, "SSL_RSA_EXPORT_WITH_RC4_40_MD5", CipherAlgorithmType.Rc4, HashAlgorithmType.Md5, ExchangeAlgorithmType.RsaKeyX, true, false, 5, 16, 40, 0, 0);
// scs.Add((0x00 << 0x08) | 0x05, "SSL_RSA_WITH_RC4_128_SHA", CipherAlgorithmType.Rc4, HashAlgorithmType.Sha1, ExchangeAlgorithmType.RsaSign, false, false, 16, 16, 128, 0, 0);
// scs.Add((0x00 << 0x08) | 0x04, "SSL_RSA_WITH_RC4_128_MD5", CipherAlgorithmType.Rc4, HashAlgorithmType.Md5, ExchangeAlgorithmType.RsaSign, false, false, 16, 16, 128, 0, 0);
// scs.Add((0x00 << 0x08) | 0x06, "SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5", CipherAlgorithmType.Rc2, HashAlgorithmType.Md5, ExchangeAlgorithmType.RsaKeyX, true, true, 5, 16, 40, 8, 8);
// scs.Add((0x00 << 0x08) | 0x07, "SSL_RSA_WITH_IDEA_CBC_SHA", "IDEA", HashAlgorithmType.Sha1, ExchangeAlgorithmType.RsaSign, false, true, 16, 16, 128, 8, 8);
// scs.Add((0x00 << 0x08) | 0x08, "SSL_RSA_EXPORT_WITH_DES40_CBC_SHA", CipherAlgorithmType.Des, HashAlgorithmType.Sha1, ExchangeAlgorithmType.RsaKeyEx, true, true, 5, 8, 40, 8, 8);
// scs.Add((0x00 << 0x08) | 0x09, "SSL_RSA_WITH_DES_CBC_SHA", CipherAlgorithmType.Des, HashAlgorithmType.Sha1, ExchangeAlgorithmType.RsaSign, false, true, 8, 8, 56, 8, 8);
// scs.Add((0x00 << 0x08) | 0x0A, "SSL_RSA_WITH_3DES_EDE_CBC_SHA", CipherAlgorithmType.TripleDes, HashAlgorithmType.Sha1, ExchangeAlgorithmType.RsaSign, false, true, 24, 24, 168, 8, 8);
// Diffie-Hellman Cipher Suites
// scs.Add((0x00 << 0x08) | 0x0B, "SSL_DH_DSS_EXPORT_WITH_DES40_CBC_SHA", CipherAlgorithmType.Des, HashAlgorithmType.Sha1, ExchangeAlgorithmType.DiffieHellman, true, true, 5, 8, 40, 8, 8);
// scs.Add((0x00 << 0x08) | 0x0C, "SSL_DH_DSS_WITH_DES_CBC_SHA", CipherAlgorithmType.Des, HashAlgorithmType.Sha1, ExchangeAlgorithmType.DiffieHellman, false, true, 8, 8, 56, 8, 8);
// scs.Add((0x00 << 0x08) | 0x0D, "SSL_DH_DSS_WITH_3DES_EDE_CBC_SHA", CipherAlgorithmType.TripleDes, HashAlgorithmType.Sha1, ExchangeAlgorithmType.DiffieHellman, false, true, 24, 24, 168, 8, 8);
// scs.Add((0x00 << 0x08) | 0x0E, "SSL_DH_RSA_EXPORT_WITH_DES40_CBC_SHA", CipherAlgorithmType.Des, HashAlgorithmType.Sha1, ExchangeAlgorithmType.DiffieHellman, true, true, 5, 8, 40, 8, 8);
// scs.Add((0x00 << 0x08) | 0x0F, "SSL_DH_RSA_WITH_DES_CBC_SHA", CipherAlgorithmType.Des, HashAlgorithmType.Sha1, ExchangeAlgorithmType.DiffieHellman, false, true, 8, 8, 56, 8, 8);
// scs.Add((0x00 << 0x08) | 0x10, "SSL_DH_RSA_WITH_3DES_EDE_CBC_SHA", CipherAlgorithmType.TripleDes, HashAlgorithmType.Sha1, ExchangeAlgorithmType.DiffieHellman, false, true, 24, 24, 168, 8, 8);
// scs.Add((0x00 << 0x08) | 0x11, "SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA", CipherAlgorithmType.Des, HashAlgorithmType.Sha1, ExchangeAlgorithmType.DiffieHellman, true, true, 5, 8, 40, 8, 8);
// scs.Add((0x00 << 0x08) | 0x12, "SSL_DHE_DSS_WITH_DES_CBC_SHA", CipherAlgorithmType.Des, HashAlgorithmType.Sha1, ExchangeAlgorithmType.DiffieHellman, false, true, 8, 8, 56, 8, 8);
// scs.Add((0x00 << 0x08) | 0x13, "SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA", CipherAlgorithmType.TripleDes, HashAlgorithmType.Sha1, ExchangeAlgorithmType.DiffieHellman, false, true, 24, 24, 168, 8, 8);
// scs.Add((0x00 << 0x08) | 0x14, "SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA", CipherAlgorithmType.Des, HashAlgorithmType.Sha1, ExchangeAlgorithmType.DiffieHellman, true, true, 5, 8, 40, 8, 8);
// scs.Add((0x00 << 0x08) | 0x15, "SSL_DHE_RSA_WITH_DES_CBC_SHA", HashAlgorithmType.Sha1, CipherAlgorithmType.Des, ExchangeAlgorithmType.DiffieHellman, false, true, 8, 8, 56, 8, 8);
// scs.Add((0x00 << 0x08) | 0x16, "SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA", CipherAlgorithmType.TripleDes, HashAlgorithmType.Sha1, ExchangeAlgorithmType.DiffieHellman, false, true, 24, 24, 168, 8, 8);
// Anonymous Diffie-Hellman Cipher Suites
// scs.Add((0x00 << 0x08) | 0x17, "SSL_DH_anon_EXPORT_WITH_RC4_40_MD5", CipherAlgorithmType.Rc4, HashAlgorithmType.Md5, ExchangeAlgorithmType.DiffieHellman, true, false, 5, 16, 40, 0, 0);
// scs.Add((0x00 << 0x08) | 0x18, "SSL_DH_anon_WITH_RC4_128_MD5", CipherAlgorithmType.Rc4, HashAlgorithmType.Md5, false, ExchangeAlgorithmType.DiffieHellman, false, 16, 16, 128, 0, 0);
// scs.Add((0x00 << 0x08) | 0x19, "SSL_DH_anon_EXPORT_WITH_DES40_CBC_SHA", CipherAlgorithmType.Des, HashAlgorithmType.Sha1, ExchangeAlgorithmType.DiffieHellman, false, true, 5, 8, 40, 8, 8);
// scs.Add((0x00 << 0x08) | 0x1A, "SSL_DH_anon_WITH_DES_CBC_SHA", "DES4", HashAlgorithmType.Sha1, ExchangeAlgorithmType.DiffieHellman, false, true, 8, 8, 56, 8, 8);
// scs.Add((0x00 << 0x08) | 0x1B, "SSL_DH_anon_WITH_3DES_EDE_CBC_SHA", CipherAlgorithmType.TripleDes, HashAlgorithmType.Sha1, ExchangeAlgorithmType.DiffieHellman, false, true, 24, 24, 168, 8, 8);
return scs;
}
#endregion
}
}
@@ -1,82 +0,0 @@
// Transport Security Layer (TLS)
// Copyright (c) 2003-2004 Carlos Guzman Alvarez
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
namespace Mono.Security.Protocol.Tls
{
internal class ClientContext : Context
{
#region Fields
private SslClientStream sslStream;
private short clientHelloProtocol;
#endregion
#region Properties
public SslClientStream SslStream
{
get { return this.sslStream; }
}
public short ClientHelloProtocol
{
get { return this.clientHelloProtocol; }
set { this.clientHelloProtocol = value; }
}
#endregion
#region Constructors
public ClientContext(
SslClientStream stream,
SecurityProtocolType securityProtocolType,
string targetHost,
X509CertificateCollection clientCertificates)
: base(securityProtocolType)
{
this.sslStream = stream;
this.ClientSettings.Certificates = clientCertificates;
this.ClientSettings.TargetHost = targetHost;
}
#endregion
#region Methods
public override void Clear()
{
this.clientHelloProtocol = 0;
base.Clear();
}
#endregion
}
}
@@ -1,195 +0,0 @@
// Transport Security Layer (TLS)
// Copyright (c) 2003-2004 Carlos Guzman Alvarez
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Globalization;
using System.IO;
using Mono.Security.Protocol.Tls.Handshake;
using Mono.Security.Protocol.Tls.Handshake.Client;
namespace Mono.Security.Protocol.Tls
{
internal class ClientRecordProtocol : RecordProtocol
{
#region Constructors
public ClientRecordProtocol(
Stream innerStream,
ClientContext context) : base(innerStream, context)
{
}
#endregion
#region Send Messages
public override HandshakeMessage GetMessage(HandshakeType type)
{
HandshakeMessage msg = this.createClientHandshakeMessage(type);
return msg;
}
#endregion
#region Handshake Processing Methods
protected override void ProcessHandshakeMessage(TlsStream handMsg)
{
HandshakeType handshakeType = (HandshakeType)handMsg.ReadByte();
HandshakeMessage message = null;
DebugHelper.WriteLine(">>>> Processing Handshake record ({0})", handshakeType);
// Read message length
int length = handMsg.ReadInt24();
// Read message data
byte[] data = null;
if (length > 0)
{
data = new byte[length];
handMsg.Read (data, 0, length);
}
// Create and process the server message
message = this.createServerHandshakeMessage(handshakeType, data);
if (message != null)
{
message.Process();
}
// Update the last handshake message
this.Context.LastHandshakeMsg = handshakeType;
// Update session
if (message != null)
{
message.Update();
this.Context.HandshakeMessages.WriteByte ((byte) handshakeType);
this.Context.HandshakeMessages.WriteInt24 (length);
if (length > 0)
{
this.Context.HandshakeMessages.Write (data, 0, data.Length);
}
}
}
#endregion
#region Client Handshake Message Factories
private HandshakeMessage createClientHandshakeMessage(HandshakeType type)
{
switch (type)
{
case HandshakeType.ClientHello:
return new TlsClientHello(this.context);
case HandshakeType.Certificate:
return new TlsClientCertificate(this.context);
case HandshakeType.ClientKeyExchange:
return new TlsClientKeyExchange(this.context);
case HandshakeType.CertificateVerify:
return new TlsClientCertificateVerify(this.context);
case HandshakeType.Finished:
return new TlsClientFinished(this.context);
default:
throw new InvalidOperationException("Unknown client handshake message type: " + type.ToString() );
}
}
private HandshakeMessage createServerHandshakeMessage(
HandshakeType type, byte[] buffer)
{
ClientContext context = (ClientContext)this.context;
var last = context.LastHandshakeMsg;
switch (type)
{
case HandshakeType.HelloRequest:
if (context.HandshakeState != HandshakeState.Started)
{
context.HandshakeState = HandshakeState.None;
// re-negotiation will occur at next read/write
// (i.e. not during an existing encode/decode op)
}
else
{
this.SendAlert(
AlertLevel.Warning,
AlertDescription.NoRenegotiation);
}
return null;
case HandshakeType.ServerHello:
if (last != HandshakeType.HelloRequest)
break;
return new TlsServerHello(this.context, buffer);
// Optional
case HandshakeType.Certificate:
if (last != HandshakeType.ServerHello)
break;
return new TlsServerCertificate(this.context, buffer);
// Optional
case HandshakeType.CertificateRequest:
if (last == HandshakeType.ServerKeyExchange || last == HandshakeType.Certificate)
return new TlsServerCertificateRequest(this.context, buffer);
break;
case HandshakeType.ServerHelloDone:
if (last == HandshakeType.CertificateRequest || last == HandshakeType.Certificate || last == HandshakeType.ServerHello)
return new TlsServerHelloDone(this.context, buffer);
break;
case HandshakeType.Finished:
// depends if a full (ServerHelloDone) or an abbreviated handshake (ServerHello) is being done
bool check = context.AbbreviatedHandshake ? (last == HandshakeType.ServerHello) : (last == HandshakeType.ServerHelloDone);
// ChangeCipherSpecDone is not an handshake message (it's a content type) but still needs to be happens before finished
if (check && context.ChangeCipherSpecDone) {
context.ChangeCipherSpecDone = false;
return new TlsServerFinished (this.context, buffer);
}
break;
default:
throw new TlsException(
AlertDescription.UnexpectedMessage,
String.Format(CultureInfo.CurrentUICulture,
"Unknown server handshake message received ({0})",
type.ToString()));
}
throw new TlsException (AlertDescription.HandshakeFailiure, String.Format ("Protocol error, unexpected protocol transition from {0} to {1}", last, type));
}
#endregion
}
}
@@ -1,254 +0,0 @@
//
// ClientSessionCache.cs: Client-side cache for re-using sessions
//
// Author:
// Sebastien Pouliot <[email protected]>
//
// Copyright (C) 2006 Novell (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections;
namespace Mono.Security.Protocol.Tls {
internal class ClientSessionInfo : IDisposable {
// (by default) we keep this item valid for 3 minutes (if unused)
private const int DefaultValidityInterval = 3 * 60;
private static readonly int ValidityInterval;
private bool disposed;
private DateTime validuntil;
private string host;
// see RFC2246 - Section 7
private byte[] sid;
private byte[] masterSecret;
static ClientSessionInfo ()
{
string user_cache_timeout = Environment.GetEnvironmentVariable ("MONO_TLS_SESSION_CACHE_TIMEOUT");
if (user_cache_timeout == null) {
ValidityInterval = DefaultValidityInterval;
} else {
try {
ValidityInterval = Int32.Parse (user_cache_timeout);
}
catch {
ValidityInterval = DefaultValidityInterval;
}
}
}
public ClientSessionInfo (string hostname, byte[] id)
{
host = hostname;
sid = id;
KeepAlive ();
}
~ClientSessionInfo ()
{
Dispose (false);
}
public string HostName {
get { return host; }
}
public byte[] Id {
get { return sid; }
}
public bool Valid {
get { return ((masterSecret != null) && (validuntil > DateTime.UtcNow)); }
}
public void GetContext (Context context)
{
CheckDisposed ();
if (context.MasterSecret != null)
masterSecret = (byte[]) context.MasterSecret.Clone ();
}
public void SetContext (Context context)
{
CheckDisposed ();
if (masterSecret != null)
context.MasterSecret = (byte[]) masterSecret.Clone ();
}
public void KeepAlive ()
{
CheckDisposed ();
validuntil = DateTime.UtcNow.AddSeconds (ValidityInterval);
}
public void Dispose ()
{
Dispose (true);
GC.SuppressFinalize (this);
}
private void Dispose (bool disposing)
{
if (!disposed) {
validuntil = DateTime.MinValue;
host = null;
sid = null;
if (masterSecret != null) {
Array.Clear (masterSecret, 0, masterSecret.Length);
masterSecret = null;
}
}
disposed = true;
}
private void CheckDisposed ()
{
if (disposed) {
string msg = Locale.GetText ("Cache session information were disposed.");
throw new ObjectDisposedException (msg);
}
}
}
// note: locking is aggressive but isn't used often (and we gain much more :)
internal class ClientSessionCache {
static Hashtable cache;
static object locker;
static ClientSessionCache ()
{
cache = new Hashtable ();
locker = new object ();
}
// note: we may have multiple connections with a host, so
// possibly multiple entries per host (each with a different
// id), so we do not use the host as the hashtable key
static public void Add (string host, byte[] id)
{
lock (locker) {
string uid = BitConverter.ToString (id);
ClientSessionInfo si = (ClientSessionInfo) cache[uid];
if (si == null) {
cache.Add (uid, new ClientSessionInfo (host, id));
} else if (si.HostName == host) {
// we already have this and it's still valid
// on the server, so we'll keep it a little longer
si.KeepAlive ();
} else {
// it's very unlikely but the same session id
// could be used by more than one host. In this
// case we replace the older one with the new one
si.Dispose ();
cache.Remove (uid);
cache.Add (uid, new ClientSessionInfo (host, id));
}
}
}
// return the first session us
static public byte[] FromHost (string host)
{
lock (locker) {
foreach (ClientSessionInfo si in cache.Values) {
if (si.HostName == host) {
if (si.Valid) {
// ensure it's still valid when we really need it
si.KeepAlive ();
return si.Id;
}
}
}
return null;
}
}
// only called inside the lock
static private ClientSessionInfo FromContext (Context context, bool checkValidity)
{
if (context == null)
return null;
byte[] id = context.SessionId;
if ((id == null) || (id.Length == 0))
return null;
// do we have a session cached for this host ?
string uid = BitConverter.ToString (id);
ClientSessionInfo si = (ClientSessionInfo) cache[uid];
if (si == null)
return null;
// In the unlikely case of multiple hosts using the same
// session id, we just act like we do not know about it
if (context.ClientSettings.TargetHost != si.HostName)
return null;
// yes, so what's its status ?
if (checkValidity && !si.Valid) {
si.Dispose ();
cache.Remove (uid);
return null;
}
// ok, it make sense
return si;
}
static public bool SetContextInCache (Context context)
{
lock (locker) {
// Don't check the validity because the masterKey of the ClientSessionInfo
// can still be null when this is called the first time
ClientSessionInfo csi = FromContext (context, false);
if (csi == null)
return false;
csi.GetContext (context);
csi.KeepAlive ();
return true;
}
}
static public bool SetContextFromCache (Context context)
{
lock (locker) {
ClientSessionInfo csi = FromContext (context, true);
if (csi == null)
return false;
csi.SetContext (context);
csi.KeepAlive ();
return true;
}
}
}
}
@@ -1,37 +0,0 @@
// Transport Security Layer (TLS)
// Copyright (c) 2003-2004 Carlos Guzman Alvarez
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
namespace Mono.Security.Protocol.Tls
{
[Serializable]
internal enum ContentType : byte
{
ChangeCipherSpec = 20,
Alert = 21,
Handshake = 22,
ApplicationData = 23,
}
}
@@ -1,519 +0,0 @@
// Transport Security Layer (TLS)
// Copyright (c) 2003-2004 Carlos Guzman Alvarez
// Copyright (C) 2006 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Text;
using System.Collections;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using Mono.Security.Cryptography;
using Mono.Security.Protocol.Tls.Handshake;
namespace Mono.Security.Protocol.Tls
{
internal abstract class Context
{
#region Internal Constants
internal const short MAX_FRAGMENT_SIZE = 16384; // 2^14
internal const short TLS1_PROTOCOL_CODE = (0x03 << 8) | 0x01;
internal const short SSL3_PROTOCOL_CODE = (0x03 << 8) | 0x00;
internal const long UNIX_BASE_TICKS = 621355968000000000;
#endregion
#region Fields
// Protocol version
private SecurityProtocolType securityProtocol;
// Sesison ID
private byte[] sessionId;
// Compression method
private SecurityCompressionType compressionMethod;
// Information sent and request by the server in the Handshake protocol
private TlsServerSettings serverSettings;
// Client configuration
private TlsClientSettings clientSettings;
// Cipher suite information
private SecurityParameters current;
private SecurityParameters negotiating;
private SecurityParameters read;
private SecurityParameters write;
private CipherSuiteCollection supportedCiphers;
// Last handshake message received
private HandshakeType lastHandshakeMsg;
// Handshake negotiation state
private HandshakeState handshakeState;
// Misc
private bool abbreviatedHandshake;
private bool receivedConnectionEnd;
private bool sentConnectionEnd;
private bool protocolNegotiated;
// Sequence numbers
private ulong writeSequenceNumber;
private ulong readSequenceNumber;
// Random data
private byte[] clientRandom;
private byte[] serverRandom;
private byte[] randomCS;
private byte[] randomSC;
// Key information
private byte[] masterSecret;
private byte[] clientWriteKey;
private byte[] serverWriteKey;
private byte[] clientWriteIV;
private byte[] serverWriteIV;
// Handshake hashes
private TlsStream handshakeMessages;
// Secure Random generator
private RandomNumberGenerator random;
// Record protocol
private RecordProtocol recordProtocol;
#endregion
#region Properties
public bool AbbreviatedHandshake
{
get { return abbreviatedHandshake; }
set { abbreviatedHandshake = value; }
}
public bool ProtocolNegotiated
{
get { return this.protocolNegotiated; }
set { this.protocolNegotiated = value; }
}
public bool ChangeCipherSpecDone { get; set; }
public SecurityProtocolType SecurityProtocol
{
get
{
if ((this.securityProtocol & SecurityProtocolType.Tls) == SecurityProtocolType.Tls ||
(this.securityProtocol & SecurityProtocolType.Default) == SecurityProtocolType.Default)
{
return SecurityProtocolType.Tls;
}
else
{
if ((this.securityProtocol & SecurityProtocolType.Ssl3) == SecurityProtocolType.Ssl3)
{
return SecurityProtocolType.Ssl3;
}
}
throw new NotSupportedException("Unsupported security protocol type");
}
set { this.securityProtocol = value; }
}
public SecurityProtocolType SecurityProtocolFlags
{
get { return this.securityProtocol; }
}
public short Protocol
{
get
{
switch (this.SecurityProtocol)
{
case SecurityProtocolType.Tls:
case SecurityProtocolType.Default:
return Context.TLS1_PROTOCOL_CODE;
case SecurityProtocolType.Ssl3:
return Context.SSL3_PROTOCOL_CODE;
case SecurityProtocolType.Ssl2:
default:
throw new NotSupportedException("Unsupported security protocol type");
}
}
}
public byte[] SessionId
{
get { return this.sessionId; }
set { this.sessionId = value; }
}
public SecurityCompressionType CompressionMethod
{
get { return this.compressionMethod; }
set { this.compressionMethod = value; }
}
public TlsServerSettings ServerSettings
{
get { return this.serverSettings; }
}
public TlsClientSettings ClientSettings
{
get { return this.clientSettings; }
}
public HandshakeType LastHandshakeMsg
{
get { return this.lastHandshakeMsg; }
set { this.lastHandshakeMsg = value; }
}
public HandshakeState HandshakeState
{
get { return this.handshakeState; }
set { this.handshakeState = value; }
}
public bool ReceivedConnectionEnd
{
get { return this.receivedConnectionEnd; }
set { this.receivedConnectionEnd = value; }
}
public bool SentConnectionEnd
{
get { return this.sentConnectionEnd; }
set { this.sentConnectionEnd = value; }
}
public CipherSuiteCollection SupportedCiphers
{
get { return supportedCiphers; }
set { supportedCiphers = value; }
}
public TlsStream HandshakeMessages
{
get { return this.handshakeMessages; }
}
public ulong WriteSequenceNumber
{
get { return this.writeSequenceNumber; }
set { this.writeSequenceNumber = value; }
}
public ulong ReadSequenceNumber
{
get { return this.readSequenceNumber; }
set { this.readSequenceNumber = value; }
}
public byte[] ClientRandom
{
get { return this.clientRandom; }
set { this.clientRandom = value; }
}
public byte[] ServerRandom
{
get { return this.serverRandom; }
set { this.serverRandom = value; }
}
public byte[] RandomCS
{
get { return this.randomCS; }
set { this.randomCS = value; }
}
public byte[] RandomSC
{
get { return this.randomSC; }
set { this.randomSC = value; }
}
public byte[] MasterSecret
{
get { return this.masterSecret; }
set { this.masterSecret = value; }
}
public byte[] ClientWriteKey
{
get { return this.clientWriteKey; }
set { this.clientWriteKey = value; }
}
public byte[] ServerWriteKey
{
get { return this.serverWriteKey; }
set { this.serverWriteKey = value; }
}
public byte[] ClientWriteIV
{
get { return this.clientWriteIV; }
set { this.clientWriteIV = value; }
}
public byte[] ServerWriteIV
{
get { return this.serverWriteIV; }
set { this.serverWriteIV = value; }
}
public RecordProtocol RecordProtocol
{
get { return this.recordProtocol; }
set { this.recordProtocol = value; }
}
#endregion
#region Constructors
public Context(SecurityProtocolType securityProtocolType)
{
this.SecurityProtocol = securityProtocolType;
this.compressionMethod = SecurityCompressionType.None;
this.serverSettings = new TlsServerSettings();
this.clientSettings = new TlsClientSettings();
this.handshakeMessages = new TlsStream();
this.sessionId = null;
this.handshakeState = HandshakeState.None;
this.random = RandomNumberGenerator.Create();
}
#endregion
#region Methods
public int GetUnixTime()
{
DateTime now = DateTime.UtcNow;
return (int)((now.Ticks - UNIX_BASE_TICKS) / TimeSpan.TicksPerSecond);
}
public byte[] GetSecureRandomBytes(int count)
{
byte[] secureBytes = new byte[count];
this.random.GetNonZeroBytes(secureBytes);
return secureBytes;
}
public virtual void Clear()
{
this.compressionMethod = SecurityCompressionType.None;
this.serverSettings = new TlsServerSettings();
this.clientSettings = new TlsClientSettings();
this.handshakeMessages = new TlsStream();
this.sessionId = null;
this.handshakeState = HandshakeState.None;
this.ClearKeyInfo();
}
public virtual void ClearKeyInfo()
{
// Clear Master Secret
if (masterSecret != null) {
Array.Clear (masterSecret, 0, masterSecret.Length);
masterSecret = null;
}
// Clear client and server random
if (clientRandom != null) {
Array.Clear (clientRandom, 0, clientRandom.Length);
clientRandom = null;
}
if (serverRandom != null) {
Array.Clear (serverRandom, 0, serverRandom.Length);
serverRandom = null;
}
if (randomCS != null) {
Array.Clear (randomCS, 0, randomCS.Length);
randomCS = null;
}
if (randomSC != null) {
Array.Clear (randomSC, 0, randomSC.Length);
randomSC = null;
}
// Clear client keys
if (clientWriteKey != null) {
Array.Clear (clientWriteKey, 0, clientWriteKey.Length);
clientWriteKey = null;
}
if (clientWriteIV != null) {
Array.Clear (clientWriteIV, 0, clientWriteIV.Length);
clientWriteIV = null;
}
// Clear server keys
if (serverWriteKey != null) {
Array.Clear (serverWriteKey, 0, serverWriteKey.Length);
serverWriteKey = null;
}
if (serverWriteIV != null) {
Array.Clear (serverWriteIV, 0, serverWriteIV.Length);
serverWriteIV = null;
}
// Reset handshake messages
this.handshakeMessages.Reset();
// Clear MAC keys if protocol is different than Ssl3
// SSLv3 needs them inside Mono.Security.Protocol.Tls.SslCipherSuite.Compute[Client|Server]RecordMAC
if (this.securityProtocol != SecurityProtocolType.Ssl3)
{
// this.clientWriteMAC = null;
// this.serverWriteMAC = null;
}
}
public SecurityProtocolType DecodeProtocolCode (short code, bool allowFallback = false)
{
switch (code)
{
case Context.TLS1_PROTOCOL_CODE:
return SecurityProtocolType.Tls;
case Context.SSL3_PROTOCOL_CODE:
return SecurityProtocolType.Ssl3;
default:
// if allowed we'll continue using TLS (1.0) even if the other side is capable of using a newer
// version of the TLS protocol
if (allowFallback && (code > (short) Context.TLS1_PROTOCOL_CODE))
return SecurityProtocolType.Tls;
throw new NotSupportedException("Unsupported security protocol type");
}
}
public void ChangeProtocol(short protocol)
{
SecurityProtocolType protocolType = this.DecodeProtocolCode(protocol);
if ((protocolType & this.SecurityProtocolFlags) == protocolType ||
(this.SecurityProtocolFlags & SecurityProtocolType.Default) == SecurityProtocolType.Default)
{
this.SecurityProtocol = protocolType;
this.SupportedCiphers = CipherSuiteFactory.GetSupportedCiphers ((this is ServerContext), protocolType);
}
else
{
throw new TlsException(AlertDescription.ProtocolVersion, "Incorrect protocol version received from server");
}
}
public SecurityParameters Current
{
get
{
if (current == null)
current = new SecurityParameters ();
if (current.Cipher != null)
current.Cipher.Context = this;
return current;
}
}
public SecurityParameters Negotiating
{
get
{
if (negotiating == null)
negotiating = new SecurityParameters ();
if (negotiating.Cipher != null)
negotiating.Cipher.Context = this;
return negotiating;
}
}
public SecurityParameters Read
{
get { return read; }
}
public SecurityParameters Write
{
get { return write; }
}
public void StartSwitchingSecurityParameters (bool client)
{
if (client) {
// everything we write from now on is encrypted
write = negotiating;
// but we still read with the older cipher until we
// receive the ChangeCipherSpec message
read = current;
} else {
// everything we read from now on is encrypted
read = negotiating;
// but we still write with the older cipher until we
// receive the ChangeCipherSpec message
write = current;
}
current = negotiating;
}
public void EndSwitchingSecurityParameters (bool client)
{
SecurityParameters temp;
if (client) {
temp = read;
// we now read with the new, negotiated, security parameters
read = current;
} else {
temp = write;
// we now write with the new, negotiated, security parameters
write = current;
}
// so we clear the old one (last reference)
if (temp != null)
temp.Clear ();
negotiating = temp;
// and are now ready for a future renegotiation
}
#endregion
}
}
@@ -1,95 +0,0 @@
// Transport Security Layer (TLS)
// Copyright (c) 2003-2004 Carlos Guzman Alvarez
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Diagnostics;
namespace Mono.Security.Protocol.Tls
{
internal class DebugHelper
{
private static bool isInitialized;
[Conditional("DEBUG")]
public static void Initialize()
{
if (!isInitialized)
{
#if !MOBILE
Debug.Listeners.Add(new TextWriterTraceListener(Console.Out));
// Debug.Listeners.Add(new TextWriterTraceListener(@"c:\ssl.log"));
Debug.AutoFlush = true;
Debug.Indent();
#endif
isInitialized = true;
}
}
[Conditional("DEBUG")]
public static void WriteLine(string format, params object[] args)
{
Initialize();
Debug.WriteLine(String.Format(format, args));
}
[Conditional("DEBUG")]
public static void WriteLine(string message)
{
Initialize();
Debug.WriteLine(message);
}
[Conditional("DEBUG")]
public static void WriteLine(string message, byte[] buffer)
{
Initialize();
DebugHelper.WriteLine(String.Format("{0} ({1} bytes))", message, buffer.Length));
DebugHelper.WriteBuffer(buffer);
}
[Conditional("DEBUG")]
public static void WriteBuffer(byte[] buffer)
{
Initialize();
DebugHelper.WriteBuffer(buffer, 0, buffer.Length);
}
[Conditional("DEBUG")]
public static void WriteBuffer(byte[] buffer, int index, int length)
{
Initialize();
for (int i = index; i < length; i += 16)
{
int count = (length - i) >= 16 ? 16 : (length - i);
string buf = "";
for (int j = 0; j < count; j++)
{
buf += buffer[i + j].ToString("x2") + " ";
}
Debug.WriteLine(buf);
}
}
}
}
@@ -1,43 +0,0 @@
// Transport Security Layer (TLS)
// Copyright (c) 2003-2004 Carlos Guzman Alvarez
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
namespace Mono.Security.Protocol.Tls
{
#if INSIDE_SYSTEM
internal
#else
[Serializable]
public
#endif
enum ExchangeAlgorithmType
{
DiffieHellman,
Fortezza,
None,
RsaKeyX,
RsaSign
}
}
@@ -1,36 +0,0 @@
// Transport Security Layer (TLS)
// Copyright (c) 2003-2004 Carlos Guzman Alvarez
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
namespace Mono.Security.Protocol.Tls
{
[Serializable]
internal enum HandshakeState
{
None,
Started,
Finished
}
}
@@ -1,41 +0,0 @@
// Transport Security Layer (TLS)
// Copyright (c) 2003-2004 Carlos Guzman Alvarez
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
namespace Mono.Security.Protocol.Tls
{
#if INSIDE_SYSTEM
internal
#else
[Serializable]
public
#endif
enum HashAlgorithmType
{
Md5,
None,
Sha1
}
}
@@ -1,122 +0,0 @@
//
// HttpsClientStream.cs: Glue between HttpWebRequest and SslClientStream to
// reduce reflection usage.
//
// Author:
// Sebastien Pouliot <[email protected]>
//
// Copyright (C) 2004-2007 Novell, Inc. (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.IO;
using System.Net;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using SNS = System.Net.Security;
using SNCX = System.Security.Cryptography.X509Certificates;
namespace Mono.Security.Protocol.Tls {
// Note: DO NOT REUSE this class - instead use SslClientStream
[Obsolete ("This class is obsolete and will be removed shortly.")]
internal class HttpsClientStream : SslClientStream {
private HttpWebRequest _request;
private int _status;
public HttpsClientStream (Stream stream, X509CertificateCollection clientCertificates,
HttpWebRequest request, byte [] buffer)
: base (stream, request.Address.Host, false, (Mono.Security.Protocol.Tls.SecurityProtocolType)
ServicePointManager.SecurityProtocol, clientCertificates)
{
// this constructor permit access to the WebRequest to call
// ICertificatePolicy.CheckValidationResult
_request = request;
_status = 0;
if (buffer != null)
InputBuffer.Write (buffer, 0, buffer.Length);
// also saved from reflection
base.CheckCertRevocationStatus = ServicePointManager.CheckCertificateRevocationList;
ClientCertSelection += delegate (X509CertificateCollection clientCerts, X509Certificate serverCertificate,
string targetHost, X509CertificateCollection serverRequestedCertificates) {
return ((clientCerts == null) || (clientCerts.Count == 0)) ? null : clientCerts [0];
};
PrivateKeySelection += delegate (X509Certificate certificate, string targetHost) {
X509Certificate2 cert = (certificate as X509Certificate2);
return (cert == null) ? null : cert.PrivateKey;
};
}
public bool TrustFailure {
get {
switch (_status) {
case -2146762486: // CERT_E_CHAINING 0x800B010A
case -2146762487: // CERT_E_UNTRUSTEDROOT 0x800B0109
return true;
default:
return false;
}
}
}
internal override bool RaiseServerCertificateValidation (X509Certificate certificate, int[] certificateErrors)
{
bool failed = (certificateErrors.Length > 0);
// only one problem can be reported by this interface
_status = ((failed) ? certificateErrors [0] : 0);
#pragma warning disable 618
if (ServicePointManager.CertificatePolicy != null) {
ServicePoint sp = _request.ServicePoint;
bool res = ServicePointManager.CertificatePolicy.CheckValidationResult (sp, certificate, _request, _status);
if (!res)
return false;
failed = true;
}
#pragma warning restore 618
if (HaveRemoteValidation2Callback)
return failed; // The validation already tried the 2.0 callback
SNS.RemoteCertificateValidationCallback cb = ServicePointManager.ServerCertificateValidationCallback;
if (cb != null) {
SNS.SslPolicyErrors ssl_errors = 0;
foreach (int i in certificateErrors) {
if (i == (int)-2146762490) // TODO: is this what happens when the purpose is wrong?
ssl_errors |= SNS.SslPolicyErrors.RemoteCertificateNotAvailable;
else if (i == (int) -2146762481)
ssl_errors |= SNS.SslPolicyErrors.RemoteCertificateNameMismatch;
else
ssl_errors |= SNS.SslPolicyErrors.RemoteCertificateChainErrors;
}
SNCX.X509Certificate2 cert2 = new SNCX.X509Certificate2 (certificate.GetRawCertData ());
SNCX.X509Chain chain = new SNCX.X509Chain ();
if (!chain.Build (cert2))
ssl_errors |= SNS.SslPolicyErrors.RemoteCertificateChainErrors;
return cb (_request, cert2, chain, ssl_errors);
}
return failed;
}
}
}
@@ -1,146 +0,0 @@
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
/* Transport Security Layer (TLS)
* Copyright (c) 2003-2004 Carlos Guzman Alvarez
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge,
* publish, distribute, sublicense, and/or sell copies of the Software,
* and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
using System;
using System.Security.Cryptography;
namespace Mono.Security.Protocol.Tls
{
internal class MD5SHA1 : HashAlgorithm
{
#region Fields
private HashAlgorithm md5;
private HashAlgorithm sha;
private bool hashing;
#endregion
#region Constructors
public MD5SHA1() : base()
{
this.md5 = MD5.Create();
this.sha = SHA1.Create();
// Set HashSizeValue
this.HashSizeValue = this.md5.HashSize + this.sha.HashSize;
}
#endregion
#region Methods
public override void Initialize()
{
this.md5.Initialize();
this.sha.Initialize();
this.hashing = false;
}
protected override byte[] HashFinal()
{
if (!hashing)
{
this.hashing = true;
}
// Finalize the original hash
this.md5.TransformFinalBlock(new byte[0], 0, 0);
this.sha.TransformFinalBlock(new byte[0], 0, 0);
byte[] hash = new byte[36];
Buffer.BlockCopy(this.md5.Hash, 0, hash, 0, 16);
Buffer.BlockCopy(this.sha.Hash, 0, hash, 16, 20);
return hash;
}
protected override void HashCore(
byte[] array,
int ibStart,
int cbSize)
{
if (!hashing)
{
hashing = true;
}
this.md5.TransformBlock(array, ibStart, cbSize, array, ibStart);
this.sha.TransformBlock(array, ibStart, cbSize, array, ibStart);
}
public byte[] CreateSignature(RSA rsa)
{
if (rsa == null)
{
throw new CryptographicUnexpectedOperationException ("missing key");
}
RSASslSignatureFormatter f = new RSASslSignatureFormatter(rsa);
f.SetHashAlgorithm("MD5SHA1");
return f.CreateSignature(this.Hash);
}
public bool VerifySignature(RSA rsa, byte[] rgbSignature)
{
if (rsa == null)
{
throw new CryptographicUnexpectedOperationException ("missing key");
}
if (rgbSignature == null)
{
throw new ArgumentNullException ("rgbSignature");
}
RSASslSignatureDeformatter d = new RSASslSignatureDeformatter(rsa);
d.SetHashAlgorithm("MD5SHA1");
return d.VerifySignature(this.Hash, rgbSignature);
}
#endregion
}
}
@@ -1,108 +0,0 @@
// Transport Security Layer (TLS)
// Copyright (c) 2003-2004 Carlos Guzman Alvarez
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Security.Cryptography;
namespace Mono.Security.Protocol.Tls
{
internal class RSASslSignatureDeformatter : AsymmetricSignatureDeformatter
{
#region Fields
private RSA key;
private HashAlgorithm hash;
#endregion
#region Constructors
public RSASslSignatureDeformatter()
{
}
public RSASslSignatureDeformatter(AsymmetricAlgorithm key)
{
this.SetKey(key);
}
#endregion
#region Methods
public override bool VerifySignature(
byte[] rgbHash,
byte[] rgbSignature)
{
if (this.key == null)
{
throw new CryptographicUnexpectedOperationException("The key is a null reference");
}
if (hash == null)
{
throw new CryptographicUnexpectedOperationException("The hash algorithm is a null reference.");
}
if (rgbHash == null)
{
throw new ArgumentNullException("The rgbHash parameter is a null reference.");
}
return Mono.Security.Cryptography.PKCS1.Verify_v15(
this.key,
this.hash,
rgbHash,
rgbSignature);
}
public override void SetHashAlgorithm(string strName)
{
#if INSIDE_SYSTEM
hash = new Mono.Security.Cryptography.MD5SHA1 ();
#else
switch (strName)
{
case "MD5SHA1":
this.hash = new MD5SHA1();
break;
default:
this.hash = HashAlgorithm.Create(strName);
break;
}
#endif
}
public override void SetKey(AsymmetricAlgorithm key)
{
if (!(key is RSA))
{
throw new ArgumentException("Specfied key is not an RSA key");
}
this.key = key as RSA;
}
#endregion
}
}
@@ -1,105 +0,0 @@
// Transport Security Layer (TLS)
// Copyright (c) 2003-2004 Carlos Guzman Alvarez
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Security.Cryptography;
namespace Mono.Security.Protocol.Tls
{
internal class RSASslSignatureFormatter : AsymmetricSignatureFormatter
{
#region Fields
private RSA key;
private HashAlgorithm hash;
#endregion
#region Constructors
public RSASslSignatureFormatter()
{
}
public RSASslSignatureFormatter(AsymmetricAlgorithm key)
{
this.SetKey(key);
}
#endregion
#region Methods
public override byte[] CreateSignature(byte[] rgbHash)
{
if (this.key == null)
{
throw new CryptographicUnexpectedOperationException("The key is a null reference");
}
if (hash == null)
{
throw new CryptographicUnexpectedOperationException("The hash algorithm is a null reference.");
}
if (rgbHash == null)
{
throw new ArgumentNullException("The rgbHash parameter is a null reference.");
}
return Mono.Security.Cryptography.PKCS1.Sign_v15(
this.key,
this.hash,
rgbHash);
}
public override void SetHashAlgorithm(string strName)
{
#if INSIDE_SYSTEM
hash = new Mono.Security.Cryptography.MD5SHA1 ();
#else
switch (strName)
{
case "MD5SHA1":
this.hash = new MD5SHA1();
break;
default:
this.hash = HashAlgorithm.Create(strName);
break;
}
#endif
}
public override void SetKey(AsymmetricAlgorithm key)
{
if (!(key is RSA))
{
throw new ArgumentException("Specfied key is not an RSA key");
}
this.key = key as RSA;
}
#endregion
}
}
@@ -1,965 +0,0 @@
// Transport Security Layer (TLS)
// Copyright (c) 2003-2004 Carlos Guzman Alvarez
// Copyright (C) 2006-2007 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections;
using System.IO;
using System.Threading;
using Mono.Security.Protocol.Tls.Handshake;
namespace Mono.Security.Protocol.Tls
{
internal abstract class RecordProtocol
{
#region Fields
private static ManualResetEvent record_processing = new ManualResetEvent (true);
protected Stream innerStream;
protected Context context;
#endregion
#region Properties
public Context Context
{
get { return this.context; }
set { this.context = value; }
}
#endregion
#region Constructors
public RecordProtocol(Stream innerStream, Context context)
{
this.innerStream = innerStream;
this.context = context;
this.context.RecordProtocol = this;
}
#endregion
#region Abstract Methods
public virtual void SendRecord(HandshakeType type)
{
IAsyncResult ar = this.BeginSendRecord(type, null, null);
this.EndSendRecord(ar);
}
protected abstract void ProcessHandshakeMessage(TlsStream handMsg);
protected virtual void ProcessChangeCipherSpec ()
{
Context ctx = this.Context;
// Reset sequence numbers
ctx.ReadSequenceNumber = 0;
if (ctx is ClientContext) {
ctx.EndSwitchingSecurityParameters (true);
} else {
ctx.StartSwitchingSecurityParameters (false);
}
ctx.ChangeCipherSpecDone = true;
}
public virtual HandshakeMessage GetMessage(HandshakeType type)
{
throw new NotSupportedException();
}
#endregion
#region Receive Record Async Result
private class ReceiveRecordAsyncResult : IAsyncResult
{
private object locker = new object ();
private AsyncCallback _userCallback;
private object _userState;
private Exception _asyncException;
private ManualResetEvent handle;
private byte[] _resultingBuffer;
private Stream _record;
private bool completed;
private byte[] _initialBuffer;
public ReceiveRecordAsyncResult(AsyncCallback userCallback, object userState, byte[] initialBuffer, Stream record)
{
_userCallback = userCallback;
_userState = userState;
_initialBuffer = initialBuffer;
_record = record;
}
public Stream Record
{
get { return _record; }
}
public byte[] ResultingBuffer
{
get { return _resultingBuffer; }
}
public byte[] InitialBuffer
{
get { return _initialBuffer; }
}
public object AsyncState
{
get { return _userState; }
}
public Exception AsyncException
{
get { return _asyncException; }
}
public bool CompletedWithError
{
get {
if (!IsCompleted)
return false; // Perhaps throw InvalidOperationExcetion?
return null != _asyncException;
}
}
public WaitHandle AsyncWaitHandle
{
get {
lock (locker) {
if (handle == null)
handle = new ManualResetEvent (completed);
}
return handle;
}
}
public bool CompletedSynchronously
{
get { return false; }
}
public bool IsCompleted
{
get {
lock (locker) {
return completed;
}
}
}
private void SetComplete(Exception ex, byte[] resultingBuffer)
{
lock (locker) {
if (completed)
return;
completed = true;
_asyncException = ex;
_resultingBuffer = resultingBuffer;
if (handle != null)
handle.Set ();
if (_userCallback != null)
_userCallback.BeginInvoke (this, null, null);
}
}
public void SetComplete(Exception ex)
{
SetComplete(ex, null);
}
public void SetComplete(byte[] resultingBuffer)
{
SetComplete(null, resultingBuffer);
}
public void SetComplete()
{
SetComplete(null, null);
}
}
#endregion
#region Receive Record Async Result
private class SendRecordAsyncResult : IAsyncResult
{
private object locker = new object ();
private AsyncCallback _userCallback;
private object _userState;
private Exception _asyncException;
private ManualResetEvent handle;
private HandshakeMessage _message;
private bool completed;
public SendRecordAsyncResult(AsyncCallback userCallback, object userState, HandshakeMessage message)
{
_userCallback = userCallback;
_userState = userState;
_message = message;
}
public HandshakeMessage Message
{
get { return _message; }
}
public object AsyncState
{
get { return _userState; }
}
public Exception AsyncException
{
get { return _asyncException; }
}
public bool CompletedWithError
{
get {
if (!IsCompleted)
return false; // Perhaps throw InvalidOperationExcetion?
return null != _asyncException;
}
}
public WaitHandle AsyncWaitHandle
{
get {
lock (locker) {
if (handle == null)
handle = new ManualResetEvent (completed);
}
return handle;
}
}
public bool CompletedSynchronously
{
get { return false; }
}
public bool IsCompleted
{
get {
lock (locker) {
return completed;
}
}
}
public void SetComplete(Exception ex)
{
lock (locker) {
if (completed)
return;
completed = true;
if (handle != null)
handle.Set ();
if (_userCallback != null)
_userCallback.BeginInvoke (this, null, null);
_asyncException = ex;
}
}
public void SetComplete()
{
SetComplete(null);
}
}
#endregion
#region Reveive Record Methods
public IAsyncResult BeginReceiveRecord(Stream record, AsyncCallback callback, object state)
{
if (this.context.ReceivedConnectionEnd)
{
throw new TlsException(
AlertDescription.InternalError,
"The session is finished and it's no longer valid.");
}
record_processing.Reset ();
byte[] recordTypeBuffer = new byte[1];
ReceiveRecordAsyncResult internalResult = new ReceiveRecordAsyncResult(callback, state, recordTypeBuffer, record);
record.BeginRead(internalResult.InitialBuffer, 0, internalResult.InitialBuffer.Length, new AsyncCallback(InternalReceiveRecordCallback), internalResult);
return internalResult;
}
private void InternalReceiveRecordCallback(IAsyncResult asyncResult)
{
ReceiveRecordAsyncResult internalResult = asyncResult.AsyncState as ReceiveRecordAsyncResult;
Stream record = internalResult.Record;
try
{
int bytesRead = internalResult.Record.EndRead(asyncResult);
//We're at the end of the stream. Time to bail.
if (bytesRead == 0)
{
internalResult.SetComplete((byte[])null);
return;
}
// Try to read the Record Content Type
int type = internalResult.InitialBuffer[0];
ContentType contentType = (ContentType)type;
byte[] buffer = this.ReadRecordBuffer(type, record);
if (buffer == null)
{
// record incomplete (at the moment)
internalResult.SetComplete((byte[])null);
return;
}
// Decrypt message contents if needed
if (contentType == ContentType.Alert && buffer.Length == 2)
{
}
else if ((this.Context.Read != null) && (this.Context.Read.Cipher != null))
{
buffer = this.decryptRecordFragment (contentType, buffer);
DebugHelper.WriteLine ("Decrypted record data", buffer);
}
// Process record
switch (contentType)
{
case ContentType.Alert:
this.ProcessAlert((AlertLevel)buffer [0], (AlertDescription)buffer [1]);
if (record.CanSeek)
{
// don't reprocess that memory block
record.SetLength (0);
}
buffer = null;
break;
case ContentType.ChangeCipherSpec:
this.ProcessChangeCipherSpec();
break;
case ContentType.ApplicationData:
break;
case ContentType.Handshake:
TlsStream message = new TlsStream (buffer);
while (!message.EOF)
{
this.ProcessHandshakeMessage(message);
}
break;
case (ContentType)0x80:
this.context.HandshakeMessages.Write (buffer);
break;
default:
throw new TlsException(
AlertDescription.UnexpectedMessage,
"Unknown record received from server.");
}
internalResult.SetComplete(buffer);
}
catch (Exception ex)
{
internalResult.SetComplete(ex);
}
}
public byte[] EndReceiveRecord(IAsyncResult asyncResult)
{
ReceiveRecordAsyncResult internalResult = asyncResult as ReceiveRecordAsyncResult;
if (null == internalResult)
throw new ArgumentException("Either the provided async result is null or was not created by this RecordProtocol.");
if (!internalResult.IsCompleted)
internalResult.AsyncWaitHandle.WaitOne();
if (internalResult.CompletedWithError)
throw internalResult.AsyncException;
byte[] result = internalResult.ResultingBuffer;
record_processing.Set ();
return result;
}
public byte[] ReceiveRecord(Stream record)
{
if (this.context.ReceivedConnectionEnd)
{
throw new TlsException(
AlertDescription.InternalError,
"The session is finished and it's no longer valid.");
}
record_processing.Reset ();
byte[] recordTypeBuffer = new byte[1];
int bytesRead = record.Read(recordTypeBuffer, 0, recordTypeBuffer.Length);
//We're at the end of the stream. Time to bail.
if (bytesRead == 0)
{
return null;
}
// Try to read the Record Content Type
int type = recordTypeBuffer[0];
ContentType contentType = (ContentType)type;
byte[] buffer = this.ReadRecordBuffer(type, record);
if (buffer == null)
{
// record incomplete (at the moment)
return null;
}
// Decrypt message contents if needed
if (contentType == ContentType.Alert && buffer.Length == 2)
{
}
else if ((this.Context.Read != null) && (this.Context.Read.Cipher != null))
{
buffer = this.decryptRecordFragment (contentType, buffer);
DebugHelper.WriteLine ("Decrypted record data", buffer);
}
// Process record
switch (contentType)
{
case ContentType.Alert:
this.ProcessAlert((AlertLevel)buffer [0], (AlertDescription)buffer [1]);
if (record.CanSeek)
{
// don't reprocess that memory block
record.SetLength (0);
}
buffer = null;
break;
case ContentType.ChangeCipherSpec:
this.ProcessChangeCipherSpec();
break;
case ContentType.ApplicationData:
break;
case ContentType.Handshake:
TlsStream message = new TlsStream (buffer);
while (!message.EOF)
{
this.ProcessHandshakeMessage(message);
}
break;
case (ContentType)0x80:
this.context.HandshakeMessages.Write (buffer);
break;
default:
throw new TlsException(
AlertDescription.UnexpectedMessage,
"Unknown record received from server.");
}
record_processing.Set ();
return buffer;
}
private byte[] ReadRecordBuffer (int contentType, Stream record)
{
if (!Enum.IsDefined(typeof(ContentType), (ContentType)contentType))
{
throw new TlsException(AlertDescription.DecodeError);
}
byte[] header = new byte[4];
if (record.Read (header, 0, 4) != 4)
throw new TlsException ("buffer underrun");
short protocol = (short)((header [0] << 8) | header [1]);
short length = (short)((header [2] << 8) | header [3]);
// process further only if the whole record is available
// note: the first 5 bytes aren't part of the length
if (record.CanSeek && (length + 5 > record.Length))
{
return null;
}
// Read Record data
int totalReceived = 0;
byte[] buffer = new byte[length];
while (totalReceived != length)
{
int justReceived = record.Read(buffer, totalReceived, buffer.Length - totalReceived);
//Make sure we get some data so we don't end up in an infinite loop here before shutdown.
if (0 == justReceived)
{
throw new TlsException(AlertDescription.CloseNotify, "Received 0 bytes from stream. It must be closed.");
}
totalReceived += justReceived;
}
// Check that the message has a valid protocol version
if (protocol != this.context.Protocol && this.context.ProtocolNegotiated)
{
throw new TlsException(
AlertDescription.ProtocolVersion, "Invalid protocol version on message received");
}
DebugHelper.WriteLine("Record data", buffer);
return buffer;
}
private void ProcessAlert(AlertLevel alertLevel, AlertDescription alertDesc)
{
switch (alertLevel)
{
case AlertLevel.Fatal:
throw new TlsException(alertLevel, alertDesc);
case AlertLevel.Warning:
default:
switch (alertDesc)
{
case AlertDescription.CloseNotify:
this.context.ReceivedConnectionEnd = true;
break;
}
break;
}
}
#endregion
#region Send Alert Methods
internal void SendAlert(ref Exception ex)
{
var tlsEx = ex as TlsException;
var alert = tlsEx != null ? tlsEx.Alert : new Alert(AlertDescription.InternalError);
try {
SendAlert(alert);
} catch (Exception alertEx) {
ex = new IOException (string.Format ("Error while sending TLS Alert ({0}:{1}): {2}", alert.Level, alert.Description, ex), alertEx);
}
}
public void SendAlert(AlertDescription description)
{
this.SendAlert(new Alert(description));
}
public void SendAlert(AlertLevel level, AlertDescription description)
{
this.SendAlert(new Alert(level, description));
}
public void SendAlert(Alert alert)
{
AlertLevel level;
AlertDescription description;
bool close;
if (alert == null) {
DebugHelper.WriteLine(">>>> Write Alert NULL");
level = AlertLevel.Fatal;
description = AlertDescription.InternalError;
close = true;
} else {
DebugHelper.WriteLine(">>>> Write Alert ({0}|{1})", alert.Description, alert.Message);
level = alert.Level;
description = alert.Description;
close = alert.IsCloseNotify;
}
// Write record
this.SendRecord (ContentType.Alert, new byte[2] { (byte) level, (byte) description });
if (close) {
this.context.SentConnectionEnd = true;
}
}
#endregion
#region Send Record Methods
public void SendChangeCipherSpec()
{
DebugHelper.WriteLine(">>>> Write Change Cipher Spec");
// Send Change Cipher Spec message with the current cipher
// or as plain text if this is the initial negotiation
this.SendRecord(ContentType.ChangeCipherSpec, new byte[] {1});
Context ctx = this.context;
// Reset sequence numbers
ctx.WriteSequenceNumber = 0;
// all further data sent will be encrypted with the negotiated
// security parameters (now the current parameters)
if (ctx is ClientContext) {
ctx.StartSwitchingSecurityParameters (true);
} else {
ctx.EndSwitchingSecurityParameters (false);
}
}
public void SendChangeCipherSpec(Stream recordStream)
{
DebugHelper.WriteLine(">>>> Write Change Cipher Spec");
byte[] record = this.EncodeRecord (ContentType.ChangeCipherSpec, new byte[] { 1 });
// Send Change Cipher Spec message with the current cipher
// or as plain text if this is the initial negotiation
recordStream.Write(record, 0, record.Length);
Context ctx = this.context;
// Reset sequence numbers
ctx.WriteSequenceNumber = 0;
// all further data sent will be encrypted with the negotiated
// security parameters (now the current parameters)
if (ctx is ClientContext) {
ctx.StartSwitchingSecurityParameters (true);
} else {
ctx.EndSwitchingSecurityParameters (false);
}
}
public IAsyncResult BeginSendChangeCipherSpec(AsyncCallback callback, object state)
{
DebugHelper.WriteLine (">>>> Write Change Cipher Spec");
// Send Change Cipher Spec message with the current cipher
// or as plain text if this is the initial negotiation
return this.BeginSendRecord (ContentType.ChangeCipherSpec, new byte[] { 1 }, callback, state);
}
public void EndSendChangeCipherSpec (IAsyncResult asyncResult)
{
this.EndSendRecord (asyncResult);
Context ctx = this.context;
// Reset sequence numbers
ctx.WriteSequenceNumber = 0;
// all further data sent will be encrypted with the negotiated
// security parameters (now the current parameters)
if (ctx is ClientContext) {
ctx.StartSwitchingSecurityParameters (true);
} else {
ctx.EndSwitchingSecurityParameters (false);
}
}
public IAsyncResult BeginSendRecord(HandshakeType handshakeType, AsyncCallback callback, object state)
{
HandshakeMessage msg = this.GetMessage(handshakeType);
msg.Process();
DebugHelper.WriteLine(">>>> Write handshake record ({0}|{1})", context.Protocol, msg.ContentType);
SendRecordAsyncResult internalResult = new SendRecordAsyncResult(callback, state, msg);
this.BeginSendRecord(msg.ContentType, msg.EncodeMessage(), new AsyncCallback(InternalSendRecordCallback), internalResult);
return internalResult;
}
private void InternalSendRecordCallback(IAsyncResult ar)
{
SendRecordAsyncResult internalResult = ar.AsyncState as SendRecordAsyncResult;
try
{
this.EndSendRecord(ar);
// Update session
internalResult.Message.Update();
// Reset message contents
internalResult.Message.Reset();
internalResult.SetComplete();
}
catch (Exception ex)
{
internalResult.SetComplete(ex);
}
}
public IAsyncResult BeginSendRecord(ContentType contentType, byte[] recordData, AsyncCallback callback, object state)
{
if (this.context.SentConnectionEnd)
{
throw new TlsException(
AlertDescription.InternalError,
"The session is finished and it's no longer valid.");
}
byte[] record = this.EncodeRecord(contentType, recordData);
return this.innerStream.BeginWrite(record, 0, record.Length, callback, state);
}
public void EndSendRecord(IAsyncResult asyncResult)
{
if (asyncResult is SendRecordAsyncResult)
{
SendRecordAsyncResult internalResult = asyncResult as SendRecordAsyncResult;
if (!internalResult.IsCompleted)
internalResult.AsyncWaitHandle.WaitOne();
if (internalResult.CompletedWithError)
throw internalResult.AsyncException;
}
else
{
this.innerStream.EndWrite(asyncResult);
}
}
public void SendRecord(ContentType contentType, byte[] recordData)
{
IAsyncResult ar = this.BeginSendRecord(contentType, recordData, null, null);
this.EndSendRecord(ar);
}
public byte[] EncodeRecord(ContentType contentType, byte[] recordData)
{
return this.EncodeRecord(
contentType,
recordData,
0,
recordData.Length);
}
public byte[] EncodeRecord(
ContentType contentType,
byte[] recordData,
int offset,
int count)
{
if (this.context.SentConnectionEnd)
{
throw new TlsException(
AlertDescription.InternalError,
"The session is finished and it's no longer valid.");
}
TlsStream record = new TlsStream();
int position = offset;
while (position < ( offset + count ))
{
short fragmentLength = 0;
byte[] fragment;
if ((count + offset - position) > Context.MAX_FRAGMENT_SIZE)
{
fragmentLength = Context.MAX_FRAGMENT_SIZE;
}
else
{
fragmentLength = (short)(count + offset - position);
}
// Fill the fragment data
fragment = new byte[fragmentLength];
Buffer.BlockCopy(recordData, position, fragment, 0, fragmentLength);
if ((this.Context.Write != null) && (this.Context.Write.Cipher != null))
{
// Encrypt fragment
fragment = this.encryptRecordFragment (contentType, fragment);
}
// Write tls message
record.Write((byte)contentType);
record.Write(this.context.Protocol);
record.Write((short)fragment.Length);
record.Write(fragment);
DebugHelper.WriteLine("Record data", fragment);
// Update buffer position
position += fragmentLength;
}
return record.ToArray();
}
public byte[] EncodeHandshakeRecord(HandshakeType handshakeType)
{
HandshakeMessage msg = this.GetMessage(handshakeType);
msg.Process();
var bytes = this.EncodeRecord (msg.ContentType, msg.EncodeMessage ());
msg.Update();
msg.Reset();
return bytes;
}
#endregion
#region Cryptography Methods
private byte[] encryptRecordFragment(
ContentType contentType,
byte[] fragment)
{
byte[] mac = null;
// Calculate message MAC
if (this.Context is ClientContext)
{
mac = this.context.Write.Cipher.ComputeClientRecordMAC(contentType, fragment);
}
else
{
mac = this.context.Write.Cipher.ComputeServerRecordMAC (contentType, fragment);
}
DebugHelper.WriteLine(">>>> Record MAC", mac);
// Encrypt the message
byte[] ecr = this.context.Write.Cipher.EncryptRecord (fragment, mac);
// Update sequence number
this.context.WriteSequenceNumber++;
return ecr;
}
private byte[] decryptRecordFragment(
ContentType contentType,
byte[] fragment)
{
byte[] dcrFragment = null;
byte[] dcrMAC = null;
try
{
this.context.Read.Cipher.DecryptRecord (fragment, out dcrFragment, out dcrMAC);
}
catch
{
if (this.context is ServerContext)
{
this.Context.RecordProtocol.SendAlert(AlertDescription.DecryptionFailed);
}
throw;
}
// Generate record MAC
byte[] mac = null;
if (this.Context is ClientContext)
{
mac = this.context.Read.Cipher.ComputeServerRecordMAC(contentType, dcrFragment);
}
else
{
mac = this.context.Read.Cipher.ComputeClientRecordMAC (contentType, dcrFragment);
}
DebugHelper.WriteLine(">>>> Record MAC", mac);
// Check record MAC
if (!Compare (mac, dcrMAC))
{
throw new TlsException(AlertDescription.BadRecordMAC, "Bad record MAC");
}
// Update sequence number
this.context.ReadSequenceNumber++;
return dcrFragment;
}
private bool Compare (byte[] array1, byte[] array2)
{
if (array1 == null)
return (array2 == null);
if (array2 == null)
return false;
if (array1.Length != array2.Length)
return false;
for (int i = 0; i < array1.Length; i++) {
if (array1[i] != array2[i])
return false;
}
return true;
}
#endregion
}
}
@@ -1,42 +0,0 @@
// Transport Security Layer (TLS)
// Copyright (c) 2003-2004 Carlos Guzman Alvarez
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
namespace Mono.Security.Protocol.Tls
{
// Information about compression methods allowed by TLS
// can be found in:
// draft-ietf-tls-compression-05.txt (http://www.ietf.org/internet-drafts/draft-ietf-tls-compression-05.txt)
#if INSIDE_SYSTEM
internal
#else
public
#endif
enum SecurityCompressionType
{
None = 0,
Zlib = 1
}
}
@@ -1,60 +0,0 @@
// Transport Security Layer (TLS)
// Copyright (C) 2006 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
namespace Mono.Security.Protocol.Tls {
// note: other things should be moved here
internal class SecurityParameters {
private CipherSuite cipher;
private byte[] clientWriteMAC;
private byte[] serverWriteMAC;
public SecurityParameters ()
{
}
public CipherSuite Cipher {
get { return cipher; }
set { cipher = value; }
}
public byte[] ClientWriteMAC {
get { return clientWriteMAC; }
set { clientWriteMAC = value; }
}
public byte[] ServerWriteMAC {
get { return serverWriteMAC; }
set { serverWriteMAC = value; }
}
public void Clear ()
{
// FIXME: clear cipher
cipher = null;
}
}
}
@@ -1,46 +0,0 @@
// Transport Security Layer (TLS)
// Copyright (c) 2003-2004 Carlos Guzman Alvarez
// Copyright (C) 2014 Xamarin Inc. (http://www.xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
namespace Mono.Security.Protocol.Tls
{
[Flags]
#if INSIDE_SYSTEM
internal
#else
[Serializable]
public
#endif
enum SecurityProtocolType
{
Default = -1073741824,
Ssl2 = 12,
Ssl3 = 48,
Tls = 192,
Tls11 = 768,
Tls12 = 3072,
}
}
@@ -1,118 +0,0 @@
// Transport Security Layer (TLS)
// Copyright (c) 2003-2004 Carlos Guzman Alvarez
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using Mono.Security.Protocol.Tls.Handshake;
using Mono.Security.Interface;
using MonoX509 = Mono.Security.X509;
namespace Mono.Security.Protocol.Tls
{
internal class ServerContext : Context
{
#region Fields
private SslServerStream sslStream;
private bool request_client_certificate;
private bool clientCertificateRequired;
#endregion
#region Properties
public SslServerStream SslStream
{
get { return this.sslStream; }
}
public bool ClientCertificateRequired
{
get { return this.clientCertificateRequired; }
}
public bool RequestClientCertificate {
get { return request_client_certificate; }
}
#endregion
#region Constructors
public ServerContext(
SslServerStream stream,
SecurityProtocolType securityProtocolType,
X509Certificate serverCertificate,
bool clientCertificateRequired,
bool requestClientCertificate)
: base(securityProtocolType)
{
this.sslStream = stream;
this.clientCertificateRequired = clientCertificateRequired;
this.request_client_certificate = requestClientCertificate;
// Convert the System.Security cert to a Mono Cert
MonoX509.X509Certificate cert = new MonoX509.X509Certificate(serverCertificate.GetRawCertData());
// Add server certificate to the certificate collection
this.ServerSettings.Certificates = new MonoX509.X509CertificateCollection();
this.ServerSettings.Certificates.Add(cert);
this.ServerSettings.UpdateCertificateRSA();
if (CertificateValidationHelper.SupportsX509Chain) {
// Build the chain for the certificate and if the chain is correct, add all certificates
// (except the root certificate [FIRST ONE] ... the client is supposed to know that one,
// otherwise the whole concept of a trusted chain doesn't work out ...
MonoX509.X509Chain chain = new MonoX509.X509Chain (MonoX509.X509StoreManager.IntermediateCACertificates);
if (chain.Build (cert)) {
for (int j = chain.Chain.Count - 1; j > 0; j--)
ServerSettings.Certificates.Add (chain.Chain [j]);
}
}
// Add requested certificate types
ServerSettings.CertificateTypes = new ClientCertificateType [ServerSettings.Certificates.Count];
for (int j = 0; j < this.ServerSettings.CertificateTypes.Length; j++)
ServerSettings.CertificateTypes [j] = ClientCertificateType.RSA;
if (CertificateValidationHelper.SupportsX509Chain) {
// Add certificate authorities
MonoX509.X509CertificateCollection trusted = MonoX509.X509StoreManager.TrustedRootCertificates;
string[] list = new string [trusted.Count];
int i = 0;
foreach (MonoX509.X509Certificate root in trusted) {
list [i++] = root.IssuerName;
}
this.ServerSettings.DistinguisedNames = list;
}
}
#endregion
}
}
@@ -1,173 +0,0 @@
// Transport Security Layer (TLS)
// Copyright (c) 2003-2004 Carlos Guzman Alvarez
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Globalization;
using System.IO;
using Mono.Security.Protocol.Tls.Handshake;
using Mono.Security.Protocol.Tls.Handshake.Server;
namespace Mono.Security.Protocol.Tls
{
internal class ServerRecordProtocol : RecordProtocol
{
TlsClientCertificate cert;
#region Constructors
public ServerRecordProtocol(
Stream innerStream,
ServerContext context) : base(innerStream, context)
{
}
#endregion
#region Send Messages
public override HandshakeMessage GetMessage(HandshakeType type)
{
// Create and process the record message
HandshakeMessage msg = this.createServerHandshakeMessage(type);
return msg;
}
#endregion
#region Handshake Processing Methods
protected override void ProcessHandshakeMessage(TlsStream handMsg)
{
HandshakeType handshakeType = (HandshakeType)handMsg.ReadByte();
HandshakeMessage message = null;
// Read message length
int length = handMsg.ReadInt24();
// Read message data
byte[] data = new byte[length];
handMsg.Read(data, 0, length);
// Create and process the server message
message = this.createClientHandshakeMessage(handshakeType, data);
message.Process();
// Update the last handshake message
this.Context.LastHandshakeMsg = handshakeType;
// Update session
if (message != null)
{
message.Update();
this.Context.HandshakeMessages.WriteByte ((byte) handshakeType);
this.Context.HandshakeMessages.WriteInt24 (length);
this.Context.HandshakeMessages.Write (data, 0, data.Length);
}
}
#endregion
#region Server Handshake Message Factories
private HandshakeMessage createClientHandshakeMessage(
HandshakeType type, byte[] buffer)
{
var last = context.LastHandshakeMsg;
switch (type)
{
case HandshakeType.ClientHello:
return new TlsClientHello(this.context, buffer);
case HandshakeType.Certificate:
if (last != HandshakeType.ClientHello)
break;
cert = new TlsClientCertificate(this.context, buffer);
return cert;
case HandshakeType.ClientKeyExchange:
if (last == HandshakeType.ClientHello || last == HandshakeType.Certificate)
return new TlsClientKeyExchange(this.context, buffer);
break;
case HandshakeType.CertificateVerify:
if (last == HandshakeType.ClientKeyExchange && cert != null)
return new TlsClientCertificateVerify(this.context, buffer);
break;
case HandshakeType.Finished:
// Certificates are optional, but if provided, they should send a CertificateVerify
bool hasCert = cert != null && cert.HasCertificate;
bool check = hasCert ? (last == HandshakeType.CertificateVerify) : (last == HandshakeType.ClientKeyExchange);
// ChangeCipherSpecDone is not an handshake message (it's a content type) but still needs to be happens before finished
if (check && context.ChangeCipherSpecDone) {
context.ChangeCipherSpecDone = false;
return new TlsClientFinished(this.context, buffer);
}
break;
default:
throw new TlsException(AlertDescription.UnexpectedMessage, String.Format(CultureInfo.CurrentUICulture,
"Unknown server handshake message received ({0})",
type.ToString()));
}
throw new TlsException (AlertDescription.HandshakeFailiure, String.Format ("Protocol error, unexpected protocol transition from {0} to {1}", last, type));
}
private HandshakeMessage createServerHandshakeMessage(
HandshakeType type)
{
switch (type)
{
case HandshakeType.HelloRequest:
this.SendRecord(HandshakeType.ClientHello);
return null;
case HandshakeType.ServerHello:
return new TlsServerHello(this.context);
case HandshakeType.Certificate:
return new TlsServerCertificate(this.context);
case HandshakeType.ServerKeyExchange:
return new TlsServerKeyExchange(this.context);
case HandshakeType.CertificateRequest:
return new TlsServerCertificateRequest(this.context);
case HandshakeType.ServerHelloDone:
return new TlsServerHelloDone(this.context);
case HandshakeType.Finished:
return new TlsServerFinished(this.context);
default:
throw new InvalidOperationException("Unknown server handshake message type: " + type.ToString() );
}
}
#endregion
}
}
@@ -1,251 +0,0 @@
// Transport Security Layer (TLS)
// Copyright (c) 2003-2004 Carlos Guzman Alvarez
// Copyright (C) 2006 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
namespace Mono.Security.Protocol.Tls
{
internal class SslCipherSuite : CipherSuite
{
#region Fields
private byte[] pad1;
private byte[] pad2;
private const int MacHeaderLength = 11;
private byte[] header;
#endregion
#region Constructors
public SslCipherSuite(
short code, string name, CipherAlgorithmType cipherAlgorithmType,
HashAlgorithmType hashAlgorithmType, ExchangeAlgorithmType exchangeAlgorithmType,
bool exportable, bool blockMode, byte keyMaterialSize,
byte expandedKeyMaterialSize, short effectiveKeyBytes,
byte ivSize, byte blockSize) :
base(code, name, cipherAlgorithmType, hashAlgorithmType,
exchangeAlgorithmType, exportable, blockMode, keyMaterialSize,
expandedKeyMaterialSize, effectiveKeyBytes, ivSize, blockSize)
{
int padLength = (hashAlgorithmType == HashAlgorithmType.Md5) ? 48 : 40;
// Fill pad arrays
this.pad1 = new byte[padLength];
this.pad2 = new byte[padLength];
/* Pad the key for inner and outer digest */
for (int i = 0; i < padLength; ++i)
{
this.pad1[i] = 0x36;
this.pad2[i] = 0x5C;
}
}
#endregion
#region MAC Generation Methods
public override byte[] ComputeServerRecordMAC(ContentType contentType, byte[] fragment)
{
HashAlgorithm hash = CreateHashAlgorithm ();
byte[] smac = this.Context.Read.ServerWriteMAC;
hash.TransformBlock (smac, 0, smac.Length, smac, 0);
hash.TransformBlock (pad1, 0, pad1.Length, pad1, 0);
if (header == null)
header = new byte [MacHeaderLength];
ulong seqnum = (Context is ClientContext) ? Context.ReadSequenceNumber : Context.WriteSequenceNumber;
Write (header, 0, seqnum);
header [8] = (byte) contentType;
Write (header, 9, (short)fragment.Length);
hash.TransformBlock (header, 0, header.Length, header, 0);
hash.TransformBlock (fragment, 0, fragment.Length, fragment, 0);
// hack, else the method will allocate a new buffer of the same length (negative half the optimization)
hash.TransformFinalBlock (CipherSuite.EmptyArray, 0, 0);
byte[] blockHash = hash.Hash;
hash.Initialize ();
hash.TransformBlock (smac, 0, smac.Length, smac, 0);
hash.TransformBlock (pad2, 0, pad2.Length, pad2, 0);
hash.TransformBlock (blockHash, 0, blockHash.Length, blockHash, 0);
// hack again
hash.TransformFinalBlock (CipherSuite.EmptyArray, 0, 0);
return hash.Hash;
}
public override byte[] ComputeClientRecordMAC(ContentType contentType, byte[] fragment)
{
HashAlgorithm hash = CreateHashAlgorithm ();
byte[] cmac = this.Context.Current.ClientWriteMAC;
hash.TransformBlock (cmac, 0, cmac.Length, cmac, 0);
hash.TransformBlock (pad1, 0, pad1.Length, pad1, 0);
if (header == null)
header = new byte [MacHeaderLength];
ulong seqnum = (Context is ClientContext) ? Context.WriteSequenceNumber : Context.ReadSequenceNumber;
Write (header, 0, seqnum);
header [8] = (byte) contentType;
Write (header, 9, (short)fragment.Length);
hash.TransformBlock (header, 0, header.Length, header, 0);
hash.TransformBlock (fragment, 0, fragment.Length, fragment, 0);
// hack, else the method will allocate a new buffer of the same length (negative half the optimization)
hash.TransformFinalBlock (CipherSuite.EmptyArray, 0, 0);
byte[] blockHash = hash.Hash;
hash.Initialize ();
hash.TransformBlock (cmac, 0, cmac.Length, cmac, 0);
hash.TransformBlock (pad2, 0, pad2.Length, pad2, 0);
hash.TransformBlock (blockHash, 0, blockHash.Length, blockHash, 0);
// hack again
hash.TransformFinalBlock (CipherSuite.EmptyArray, 0, 0);
return hash.Hash;
}
#endregion
#region Key Generation Methods
public override void ComputeMasterSecret(byte[] preMasterSecret)
{
TlsStream masterSecret = new TlsStream();
masterSecret.Write(this.prf(preMasterSecret, "A", this.Context.RandomCS));
masterSecret.Write(this.prf(preMasterSecret, "BB", this.Context.RandomCS));
masterSecret.Write(this.prf(preMasterSecret, "CCC", this.Context.RandomCS));
this.Context.MasterSecret = masterSecret.ToArray();
DebugHelper.WriteLine(">>>> MasterSecret", this.Context.MasterSecret);
}
public override void ComputeKeys()
{
// Compute KeyBlock
TlsStream tmp = new TlsStream();
char labelChar = 'A';
int count = 1;
while (tmp.Length < this.KeyBlockSize)
{
string label = String.Empty;
for (int i = 0; i < count; i++)
{
label += labelChar.ToString();
}
byte[] block = this.prf(this.Context.MasterSecret, label.ToString(), this.Context.RandomSC);
int size = (tmp.Length + block.Length) > this.KeyBlockSize ? (this.KeyBlockSize - (int)tmp.Length) : block.Length;
tmp.Write(block, 0, size);
labelChar++;
count++;
}
// Create keyblock
TlsStream keyBlock = new TlsStream(tmp.ToArray());
this.Context.Negotiating.ClientWriteMAC = keyBlock.ReadBytes(this.HashSize);
this.Context.Negotiating.ServerWriteMAC = keyBlock.ReadBytes(this.HashSize);
this.Context.ClientWriteKey = keyBlock.ReadBytes(this.KeyMaterialSize);
this.Context.ServerWriteKey = keyBlock.ReadBytes(this.KeyMaterialSize);
if (this.IvSize != 0)
{
this.Context.ClientWriteIV = keyBlock.ReadBytes(this.IvSize);
this.Context.ServerWriteIV = keyBlock.ReadBytes(this.IvSize);
}
else
{
this.Context.ClientWriteIV = CipherSuite.EmptyArray;
this.Context.ServerWriteIV = CipherSuite.EmptyArray;
}
DebugHelper.WriteLine(">>>> KeyBlock", keyBlock.ToArray());
DebugHelper.WriteLine(">>>> ClientWriteKey", this.Context.ClientWriteKey);
DebugHelper.WriteLine(">>>> ClientWriteIV", this.Context.ClientWriteIV);
DebugHelper.WriteLine(">>>> ClientWriteMAC", this.Context.Negotiating.ClientWriteMAC);
DebugHelper.WriteLine(">>>> ServerWriteKey", this.Context.ServerWriteKey);
DebugHelper.WriteLine(">>>> ServerWriteIV", this.Context.ServerWriteIV);
DebugHelper.WriteLine(">>>> ServerWriteMAC", this.Context.Negotiating.ServerWriteMAC);
ClientSessionCache.SetContextInCache (this.Context);
// Clear no more needed data
keyBlock.Reset();
tmp.Reset();
}
#endregion
#region Private Methods
private byte[] prf(byte[] secret, string label, byte[] random)
{
HashAlgorithm md5 = MD5.Create();
HashAlgorithm sha = SHA1.Create();
// Compute SHA hash
TlsStream block = new TlsStream();
block.Write(Encoding.ASCII.GetBytes(label));
block.Write(secret);
block.Write(random);
byte[] shaHash = sha.ComputeHash(block.ToArray(), 0, (int)block.Length);
block.Reset();
// Compute MD5 hash
block.Write(secret);
block.Write(shaHash);
byte[] result = md5.ComputeHash(block.ToArray(), 0, (int)block.Length);
// Free resources
block.Reset();
return result;
}
#endregion
}
}
@@ -1,659 +0,0 @@
// Transport Security Layer (TLS)
// Copyright (c) 2003-2004 Carlos Guzman Alvarez
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
using Mono.Security.Protocol.Tls.Handshake;
using Mono.Security.Interface;
namespace Mono.Security.Protocol.Tls
{
#region Delegates
#if INSIDE_SYSTEM
internal
#else
public
#endif
delegate bool CertificateValidationCallback(
X509Certificate certificate,
int[] certificateErrors);
#if INSIDE_SYSTEM
internal
#else
public
#endif
delegate ValidationResult CertificateValidationCallback2 (Mono.Security.X509.X509CertificateCollection collection);
#if INSIDE_SYSTEM
internal
#else
public
#endif
delegate X509Certificate CertificateSelectionCallback(
X509CertificateCollection clientCertificates,
X509Certificate serverCertificate,
string targetHost,
X509CertificateCollection serverRequestedCertificates);
#if INSIDE_SYSTEM
internal
#else
public
#endif
delegate AsymmetricAlgorithm PrivateKeySelectionCallback(
X509Certificate certificate,
string targetHost);
#endregion
#if INSIDE_SYSTEM
internal
#else
public
#endif
class SslClientStream : SslStreamBase
{
#region Internal Events
internal event CertificateValidationCallback ServerCertValidation;
internal event CertificateSelectionCallback ClientCertSelection;
internal event PrivateKeySelectionCallback PrivateKeySelection;
#endregion
#region Properties
// required by HttpsClientStream for proxy support
internal Stream InputBuffer
{
get { return base.inputBuffer; }
}
public X509CertificateCollection ClientCertificates
{
get { return this.context.ClientSettings.Certificates; }
}
public X509Certificate SelectedClientCertificate
{
get { return this.context.ClientSettings.ClientCertificate; }
}
#endregion
#region Callback Properties
public CertificateValidationCallback ServerCertValidationDelegate
{
get { return this.ServerCertValidation; }
set { this.ServerCertValidation = value; }
}
public CertificateSelectionCallback ClientCertSelectionDelegate
{
get { return this.ClientCertSelection; }
set { this.ClientCertSelection = value; }
}
public PrivateKeySelectionCallback PrivateKeyCertSelectionDelegate
{
get { return this.PrivateKeySelection; }
set { this.PrivateKeySelection = value; }
}
#endregion
public event CertificateValidationCallback2 ServerCertValidation2;
#region Constructors
public SslClientStream(
Stream stream,
string targetHost,
bool ownsStream)
: this(
stream, targetHost, ownsStream,
SecurityProtocolType.Default, null)
{
}
public SslClientStream(
Stream stream,
string targetHost,
X509Certificate clientCertificate)
: this(
stream, targetHost, false, SecurityProtocolType.Default,
new X509CertificateCollection(new X509Certificate[]{clientCertificate}))
{
}
public SslClientStream(
Stream stream,
string targetHost,
X509CertificateCollection clientCertificates) :
this(
stream, targetHost, false, SecurityProtocolType.Default,
clientCertificates)
{
}
public SslClientStream(
Stream stream,
string targetHost,
bool ownsStream,
SecurityProtocolType securityProtocolType)
: this(
stream, targetHost, ownsStream, securityProtocolType,
new X509CertificateCollection())
{
}
public SslClientStream(
Stream stream,
string targetHost,
bool ownsStream,
SecurityProtocolType securityProtocolType,
X509CertificateCollection clientCertificates):
base(stream, ownsStream)
{
if (targetHost == null || targetHost.Length == 0)
{
throw new ArgumentNullException("targetHost is null or an empty string.");
}
this.context = new ClientContext(
this,
securityProtocolType,
targetHost,
clientCertificates);
this.protocol = new ClientRecordProtocol(innerStream, (ClientContext)this.context);
}
#endregion
#region Finalizer
~SslClientStream()
{
base.Dispose(false);
}
#endregion
#region IDisposable Methods
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if (disposing)
{
this.ServerCertValidation = null;
this.ClientCertSelection = null;
this.PrivateKeySelection = null;
this.ServerCertValidation2 = null;
}
}
#endregion
#region Handshake Methods
/*
Client Server
ClientHello -------->
ServerHello
Certificate*
ServerKeyExchange*
CertificateRequest*
<-------- ServerHelloDone
Certificate*
ClientKeyExchange
CertificateVerify*
[ChangeCipherSpec]
Finished -------->
[ChangeCipherSpec]
<-------- Finished
Application Data <-------> Application Data
Fig. 1 - Message flow for a full handshake
*/
private void SafeEndReceiveRecord (IAsyncResult ar, bool ignoreEmpty = false)
{
byte[] record = this.protocol.EndReceiveRecord (ar);
if (!ignoreEmpty && ((record == null) || (record.Length == 0))) {
throw new TlsException (
AlertDescription.HandshakeFailiure,
"The server stopped the handshake.");
}
}
private enum NegotiateState
{
SentClientHello,
ReceiveClientHelloResponse,
SentCipherSpec,
ReceiveCipherSpecResponse,
SentKeyExchange,
ReceiveFinishResponse,
SentFinished,
};
private class NegotiateAsyncResult : IAsyncResult
{
private object locker = new object ();
private AsyncCallback _userCallback;
private object _userState;
private Exception _asyncException;
private ManualResetEvent handle;
private NegotiateState _state;
private bool completed;
public NegotiateAsyncResult(AsyncCallback userCallback, object userState, NegotiateState state)
{
_userCallback = userCallback;
_userState = userState;
_state = state;
}
public NegotiateState State
{
get { return _state; }
set { _state = value; }
}
public object AsyncState
{
get { return _userState; }
}
public Exception AsyncException
{
get { return _asyncException; }
}
public bool CompletedWithError
{
get {
if (!IsCompleted)
return false; // Perhaps throw InvalidOperationExcetion?
return null != _asyncException;
}
}
public WaitHandle AsyncWaitHandle
{
get {
lock (locker) {
if (handle == null)
handle = new ManualResetEvent (completed);
}
return handle;
}
}
public bool CompletedSynchronously
{
get { return false; }
}
public bool IsCompleted
{
get {
lock (locker) {
return completed;
}
}
}
public void SetComplete(Exception ex)
{
lock (locker) {
if (completed)
return;
completed = true;
if (handle != null)
handle.Set ();
if (_userCallback != null)
_userCallback.BeginInvoke (this, null, null);
_asyncException = ex;
}
}
public void SetComplete()
{
SetComplete(null);
}
}
internal override IAsyncResult BeginNegotiateHandshake(AsyncCallback callback, object state)
{
if (this.context.HandshakeState != HandshakeState.None) {
this.context.Clear ();
}
// Obtain supported cipher suites
this.context.SupportedCiphers = CipherSuiteFactory.GetSupportedCiphers (false, context.SecurityProtocol);
// Set handshake state
this.context.HandshakeState = HandshakeState.Started;
NegotiateAsyncResult result = new NegotiateAsyncResult (callback, state, NegotiateState.SentClientHello);
// Begin sending the client hello
this.protocol.BeginSendRecord (HandshakeType.ClientHello, NegotiateAsyncWorker, result);
return result;
}
internal override void EndNegotiateHandshake (IAsyncResult result)
{
NegotiateAsyncResult negotiate = result as NegotiateAsyncResult;
if (negotiate == null)
throw new ArgumentNullException ();
if (!negotiate.IsCompleted)
negotiate.AsyncWaitHandle.WaitOne();
if (negotiate.CompletedWithError)
throw negotiate.AsyncException;
}
private void NegotiateAsyncWorker (IAsyncResult result)
{
NegotiateAsyncResult negotiate = result.AsyncState as NegotiateAsyncResult;
try
{
switch (negotiate.State)
{
case NegotiateState.SentClientHello:
this.protocol.EndSendRecord (result);
// we are now ready to ready the receive the hello response.
negotiate.State = NegotiateState.ReceiveClientHelloResponse;
// Start reading the client hello response
this.protocol.BeginReceiveRecord (this.innerStream, NegotiateAsyncWorker, negotiate);
break;
case NegotiateState.ReceiveClientHelloResponse:
this.SafeEndReceiveRecord (result, true);
if (this.context.LastHandshakeMsg != HandshakeType.ServerHelloDone &&
(!this.context.AbbreviatedHandshake || this.context.LastHandshakeMsg != HandshakeType.ServerHello)) {
// Read next record (skip empty, e.g. warnings alerts)
this.protocol.BeginReceiveRecord (this.innerStream, NegotiateAsyncWorker, negotiate);
break;
}
// special case for abbreviated handshake where no ServerHelloDone is sent from the server
if (this.context.AbbreviatedHandshake) {
ClientSessionCache.SetContextFromCache (this.context);
this.context.Negotiating.Cipher.ComputeKeys ();
this.context.Negotiating.Cipher.InitializeCipher ();
negotiate.State = NegotiateState.SentCipherSpec;
// Send Change Cipher Spec message with the current cipher
// or as plain text if this is the initial negotiation
this.protocol.BeginSendChangeCipherSpec(NegotiateAsyncWorker, negotiate);
} else {
// Send client certificate if requested
// even if the server ask for it it _may_ still be optional
bool clientCertificate = this.context.ServerSettings.CertificateRequest;
using (var memstream = new MemoryStream())
{
// NOTE: sadly SSL3 and TLS1 differs in how they handle this and
// the current design doesn't allow a very cute way to handle
// SSL3 alert warning for NoCertificate (41).
if (this.context.SecurityProtocol == SecurityProtocolType.Ssl3)
{
clientCertificate = ((this.context.ClientSettings.Certificates != null) &&
(this.context.ClientSettings.Certificates.Count > 0));
// this works well with OpenSSL (but only for SSL3)
}
byte[] record = null;
if (clientCertificate)
{
record = this.protocol.EncodeHandshakeRecord(HandshakeType.Certificate);
memstream.Write(record, 0, record.Length);
}
// Send Client Key Exchange
record = this.protocol.EncodeHandshakeRecord(HandshakeType.ClientKeyExchange);
memstream.Write(record, 0, record.Length);
// Now initialize session cipher with the generated keys
this.context.Negotiating.Cipher.InitializeCipher();
// Send certificate verify if requested (optional)
if (clientCertificate && (this.context.ClientSettings.ClientCertificate != null))
{
record = this.protocol.EncodeHandshakeRecord(HandshakeType.CertificateVerify);
memstream.Write(record, 0, record.Length);
}
// send the chnage cipher spec.
this.protocol.SendChangeCipherSpec(memstream);
// Send Finished message
record = this.protocol.EncodeHandshakeRecord(HandshakeType.Finished);
memstream.Write(record, 0, record.Length);
negotiate.State = NegotiateState.SentKeyExchange;
// send all the records.
this.innerStream.BeginWrite (memstream.GetBuffer (), 0, (int)memstream.Length, NegotiateAsyncWorker, negotiate);
}
}
break;
case NegotiateState.SentKeyExchange:
this.innerStream.EndWrite (result);
negotiate.State = NegotiateState.ReceiveFinishResponse;
this.protocol.BeginReceiveRecord (this.innerStream, NegotiateAsyncWorker, negotiate);
break;
case NegotiateState.ReceiveFinishResponse:
this.SafeEndReceiveRecord (result);
// Read record until server finished is received
if (this.context.HandshakeState != HandshakeState.Finished) {
// If all goes well this will process messages:
// Change Cipher Spec
// Server finished
this.protocol.BeginReceiveRecord (this.innerStream, NegotiateAsyncWorker, negotiate);
}
else {
// Reset Handshake messages information
this.context.HandshakeMessages.Reset ();
// Clear Key Info
this.context.ClearKeyInfo();
negotiate.SetComplete ();
}
break;
case NegotiateState.SentCipherSpec:
this.protocol.EndSendChangeCipherSpec (result);
negotiate.State = NegotiateState.ReceiveCipherSpecResponse;
// Start reading the cipher spec response
this.protocol.BeginReceiveRecord (this.innerStream, NegotiateAsyncWorker, negotiate);
break;
case NegotiateState.ReceiveCipherSpecResponse:
this.SafeEndReceiveRecord (result, true);
if (this.context.HandshakeState != HandshakeState.Finished)
{
this.protocol.BeginReceiveRecord (this.innerStream, NegotiateAsyncWorker, negotiate);
}
else
{
negotiate.State = NegotiateState.SentFinished;
this.protocol.BeginSendRecord(HandshakeType.Finished, NegotiateAsyncWorker, negotiate);
}
break;
case NegotiateState.SentFinished:
this.protocol.EndSendRecord (result);
// Reset Handshake messages information
this.context.HandshakeMessages.Reset ();
// Clear Key Info
this.context.ClearKeyInfo();
negotiate.SetComplete ();
break;
}
}
catch (TlsException ex)
{
try {
Exception e = ex;
this.protocol.SendAlert(ref e);
} catch {
}
negotiate.SetComplete(new IOException("The authentication or decryption has failed.", ex));
}
catch (Exception ex)
{
try {
this.protocol.SendAlert(AlertDescription.InternalError);
} catch {
}
negotiate.SetComplete(new IOException("The authentication or decryption has failed.", ex));
}
}
#endregion
#region Event Methods
internal override X509Certificate OnLocalCertificateSelection(X509CertificateCollection clientCertificates, X509Certificate serverCertificate, string targetHost, X509CertificateCollection serverRequestedCertificates)
{
if (this.ClientCertSelection != null)
{
return this.ClientCertSelection(
clientCertificates,
serverCertificate,
targetHost,
serverRequestedCertificates);
}
return null;
}
internal override bool HaveRemoteValidation2Callback {
get { return ServerCertValidation2 != null; }
}
internal override ValidationResult OnRemoteCertificateValidation2 (Mono.Security.X509.X509CertificateCollection collection)
{
CertificateValidationCallback2 cb = ServerCertValidation2;
if (cb != null)
return cb (collection);
return null;
}
internal override bool OnRemoteCertificateValidation(X509Certificate certificate, int[] errors)
{
if (this.ServerCertValidation != null)
{
return this.ServerCertValidation(certificate, errors);
}
return (errors != null && errors.Length == 0);
}
internal virtual bool RaiseServerCertificateValidation(
X509Certificate certificate,
int[] certificateErrors)
{
return base.RaiseRemoteCertificateValidation(certificate, certificateErrors);
}
internal virtual ValidationResult RaiseServerCertificateValidation2 (Mono.Security.X509.X509CertificateCollection collection)
{
return base.RaiseRemoteCertificateValidation2 (collection);
}
internal X509Certificate RaiseClientCertificateSelection(
X509CertificateCollection clientCertificates,
X509Certificate serverCertificate,
string targetHost,
X509CertificateCollection serverRequestedCertificates)
{
return base.RaiseLocalCertificateSelection(clientCertificates, serverCertificate, targetHost, serverRequestedCertificates);
}
internal override AsymmetricAlgorithm OnLocalPrivateKeySelection(X509Certificate certificate, string targetHost)
{
if (this.PrivateKeySelection != null)
{
return this.PrivateKeySelection(certificate, targetHost);
}
return null;
}
internal AsymmetricAlgorithm RaisePrivateKeySelection(
X509Certificate certificate,
string targetHost)
{
return base.RaiseLocalPrivateKeySelection(certificate, targetHost);
}
#endregion
}
}
@@ -1,185 +0,0 @@
// Transport Security Layer (TLS)
// Copyright (c) 2003-2004 Carlos Guzman Alvarez
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Security.Cryptography;
namespace Mono.Security.Protocol.Tls
{
internal class SslHandshakeHash : System.Security.Cryptography.HashAlgorithm
{
#region Fields
private HashAlgorithm md5;
private HashAlgorithm sha;
private bool hashing;
private byte[] secret;
private byte[] innerPadMD5;
private byte[] outerPadMD5;
private byte[] innerPadSHA;
private byte[] outerPadSHA;
#endregion
#region Constructors
public SslHandshakeHash(byte[] secret)
{
// Create md5 and sha1 hashes
this.md5 = MD5.Create ();
this.sha = SHA1.Create ();
// Set HashSizeValue
this.HashSizeValue = md5.HashSize + sha.HashSize;
// Update secret
this.secret = secret;
this.Initialize();
}
#endregion
#region Methods
public override void Initialize()
{
this.md5.Initialize();
this.sha.Initialize();
this.initializePad();
this.hashing = false;
}
protected override byte[] HashFinal()
{
if (!this.hashing)
{
this.hashing = true;
}
// Finalize the md5 hash
this.md5.TransformBlock(this.secret, 0, this.secret.Length, this.secret, 0);
this.md5.TransformFinalBlock(this.innerPadMD5, 0, this.innerPadMD5.Length);
byte[] firstResultMD5 = this.md5.Hash;
this.md5.Initialize();
this.md5.TransformBlock(this.secret, 0, this.secret.Length, this.secret, 0);
this.md5.TransformBlock(this.outerPadMD5, 0, this.outerPadMD5.Length, this.outerPadMD5, 0);
this.md5.TransformFinalBlock(firstResultMD5, 0, firstResultMD5.Length);
// Finalize the sha1 hash
this.sha.TransformBlock(this.secret, 0, this.secret.Length, this.secret, 0);
this.sha.TransformFinalBlock(this.innerPadSHA, 0, this.innerPadSHA.Length);
byte[] firstResultSHA = this.sha.Hash;
this.sha.Initialize();
this.sha.TransformBlock(this.secret, 0, this.secret.Length, this.secret, 0);
this.sha.TransformBlock(this.outerPadSHA, 0, this.outerPadSHA.Length, this.outerPadSHA, 0);
this.sha.TransformFinalBlock(firstResultSHA, 0, firstResultSHA.Length);
this.Initialize();
byte[] result = new byte[36];
Buffer.BlockCopy(this.md5.Hash, 0, result, 0, 16);
Buffer.BlockCopy(this.sha.Hash, 0, result, 16, 20);
return result;
}
protected override void HashCore(byte[] array, int ibStart, int cbSize)
{
if (!this.hashing)
{
this.hashing = true;
}
this.md5.TransformBlock(array, ibStart, cbSize, array, ibStart);
this.sha.TransformBlock(array, ibStart, cbSize, array, ibStart);
}
public byte[] CreateSignature(RSA rsa)
{
if (rsa == null)
{
throw new CryptographicUnexpectedOperationException ("missing key");
}
RSASslSignatureFormatter f = new RSASslSignatureFormatter(rsa);
f.SetHashAlgorithm("MD5SHA1");
return f.CreateSignature(this.Hash);
}
public bool VerifySignature(RSA rsa, byte[] rgbSignature)
{
if (rsa == null)
{
throw new CryptographicUnexpectedOperationException ("missing key");
}
if (rgbSignature == null)
{
throw new ArgumentNullException ("rgbSignature");
}
RSASslSignatureDeformatter d = new RSASslSignatureDeformatter(rsa);
d.SetHashAlgorithm("MD5SHA1");
return d.VerifySignature(this.Hash, rgbSignature);
}
#endregion
#region Private Methods
private void initializePad()
{
// Fill md5 arrays
this.innerPadMD5 = new byte[48];
this.outerPadMD5 = new byte[48];
/* Pad the key for inner and outer digest */
for (int i = 0; i < 48; ++i)
{
this.innerPadMD5[i] = 0x36;
this.outerPadMD5[i] = 0x5C;
}
// Fill sha arrays
this.innerPadSHA = new byte[40];
this.outerPadSHA = new byte[40];
/* Pad the key for inner and outer digest */
for (int i = 0; i < 40; ++i)
{
this.innerPadSHA[i] = 0x36;
this.outerPadSHA[i] = 0x5C;
}
}
#endregion
}
}
@@ -1,332 +0,0 @@
// Transport Security Layer (TLS)
// Copyright (c) 2003-2004 Carlos Guzman Alvarez
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using Mono.Security.Protocol.Tls.Handshake;
using Mono.Security.Interface;
namespace Mono.Security.Protocol.Tls
{
#if INSIDE_SYSTEM
internal
#else
public
#endif
class SslServerStream : SslStreamBase
{
#region Internal Events
internal event CertificateValidationCallback ClientCertValidation;
internal event PrivateKeySelectionCallback PrivateKeySelection;
#endregion
#region Properties
public X509Certificate ClientCertificate
{
get
{
if (this.context.HandshakeState == HandshakeState.Finished)
{
return this.context.ClientSettings.ClientCertificate;
}
return null;
}
}
#endregion
#region Callback Properties
public CertificateValidationCallback ClientCertValidationDelegate
{
get { return this.ClientCertValidation; }
set { this.ClientCertValidation = value; }
}
public PrivateKeySelectionCallback PrivateKeyCertSelectionDelegate
{
get { return this.PrivateKeySelection; }
set { this.PrivateKeySelection = value; }
}
#endregion
public event CertificateValidationCallback2 ClientCertValidation2;
#region Constructors
public SslServerStream(
Stream stream,
X509Certificate serverCertificate) : this(
stream,
serverCertificate,
false,
false,
SecurityProtocolType.Default)
{
}
public SslServerStream(
Stream stream,
X509Certificate serverCertificate,
bool clientCertificateRequired,
bool ownsStream): this(
stream,
serverCertificate,
clientCertificateRequired,
ownsStream,
SecurityProtocolType.Default)
{
}
public SslServerStream(
Stream stream,
X509Certificate serverCertificate,
bool clientCertificateRequired,
bool requestClientCertificate,
bool ownsStream)
: this (stream, serverCertificate, clientCertificateRequired, requestClientCertificate, ownsStream, SecurityProtocolType.Default)
{
}
public SslServerStream(
Stream stream,
X509Certificate serverCertificate,
bool clientCertificateRequired,
bool ownsStream,
SecurityProtocolType securityProtocolType)
: this (stream, serverCertificate, clientCertificateRequired, false, ownsStream, securityProtocolType)
{
}
public SslServerStream(
Stream stream,
X509Certificate serverCertificate,
bool clientCertificateRequired,
bool requestClientCertificate,
bool ownsStream,
SecurityProtocolType securityProtocolType)
: base(stream, ownsStream)
{
this.context = new ServerContext(
this,
securityProtocolType,
serverCertificate,
clientCertificateRequired,
requestClientCertificate);
this.protocol = new ServerRecordProtocol(innerStream, (ServerContext)this.context);
}
#endregion
#region Finalizer
~SslServerStream()
{
this.Dispose(false);
}
#endregion
#region IDisposable Methods
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if (disposing)
{
this.ClientCertValidation = null;
this.PrivateKeySelection = null;
}
}
#endregion
#region Handsake Methods
/*
Client Server
ClientHello -------->
ServerHello
Certificate*
ServerKeyExchange*
CertificateRequest*
<-------- ServerHelloDone
Certificate*
ClientKeyExchange
CertificateVerify*
[ChangeCipherSpec]
Finished -------->
[ChangeCipherSpec]
<-------- Finished
Application Data <-------> Application Data
Fig. 1 - Message flow for a full handshake
*/
internal override IAsyncResult BeginNegotiateHandshake(AsyncCallback callback, object state)
{
// Reset the context if needed
if (this.context.HandshakeState != HandshakeState.None)
{
this.context.Clear();
}
// Obtain supported cipher suites
this.context.SupportedCiphers = CipherSuiteFactory.GetSupportedCiphers (true, context.SecurityProtocol);
// Set handshake state
this.context.HandshakeState = HandshakeState.Started;
// Receive Client Hello message
return this.protocol.BeginReceiveRecord(this.innerStream, callback, state);
}
internal override void EndNegotiateHandshake(IAsyncResult asyncResult)
{
// Receive Client Hello message and ignore it
this.protocol.EndReceiveRecord(asyncResult);
// If received message is not an ClientHello send a
// Fatal Alert
if (this.context.LastHandshakeMsg != HandshakeType.ClientHello)
{
this.protocol.SendAlert(AlertDescription.UnexpectedMessage);
}
// Send ServerHello message
this.protocol.SendRecord(HandshakeType.ServerHello);
// Send ServerCertificate message
this.protocol.SendRecord(HandshakeType.Certificate);
// If the client certificate is required send the CertificateRequest message
if (((ServerContext)this.context).ClientCertificateRequired ||
((ServerContext)this.context).RequestClientCertificate)
{
this.protocol.SendRecord(HandshakeType.CertificateRequest);
}
// Send ServerHelloDone message
this.protocol.SendRecord(HandshakeType.ServerHelloDone);
// Receive client response, until the Client Finished message
// is received. IE can be interrupted at this stage and never
// complete the handshake
while (this.context.LastHandshakeMsg != HandshakeType.Finished)
{
byte[] record = this.protocol.ReceiveRecord(this.innerStream);
if ((record == null) || (record.Length == 0))
{
throw new TlsException(
AlertDescription.HandshakeFailiure,
"The client stopped the handshake.");
}
}
// Send ChangeCipherSpec and ServerFinished messages
this.protocol.SendChangeCipherSpec();
this.protocol.SendRecord (HandshakeType.Finished);
// The handshake is finished
this.context.HandshakeState = HandshakeState.Finished;
// Reset Handshake messages information
this.context.HandshakeMessages.Reset ();
// Clear Key Info
this.context.ClearKeyInfo();
}
#endregion
#region Event Methods
internal override X509Certificate OnLocalCertificateSelection(X509CertificateCollection clientCertificates, X509Certificate serverCertificate, string targetHost, X509CertificateCollection serverRequestedCertificates)
{
throw new NotSupportedException();
}
internal override bool OnRemoteCertificateValidation(X509Certificate certificate, int[] errors)
{
if (this.ClientCertValidation != null)
{
return this.ClientCertValidation(certificate, errors);
}
return (errors != null && errors.Length == 0);
}
internal override bool HaveRemoteValidation2Callback {
get { return ClientCertValidation2 != null; }
}
internal override ValidationResult OnRemoteCertificateValidation2 (Mono.Security.X509.X509CertificateCollection collection)
{
CertificateValidationCallback2 cb = ClientCertValidation2;
if (cb != null)
return cb (collection);
return null;
}
internal bool RaiseClientCertificateValidation(
X509Certificate certificate,
int[] certificateErrors)
{
return base.RaiseRemoteCertificateValidation(certificate, certificateErrors);
}
internal override AsymmetricAlgorithm OnLocalPrivateKeySelection(X509Certificate certificate, string targetHost)
{
if (this.PrivateKeySelection != null)
{
return this.PrivateKeySelection(certificate, targetHost);
}
return null;
}
internal AsymmetricAlgorithm RaisePrivateKeySelection(
X509Certificate certificate,
string targetHost)
{
return base.RaiseLocalPrivateKeySelection(certificate, targetHost);
}
#endregion
}
}
File diff suppressed because it is too large. Load diff
@@ -1,152 +0,0 @@
// Transport Security Layer (TLS)
// Copyright (c) 2003-2004 Carlos Guzman Alvarez
// Copyright (C) 2006 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.IO;
using System.Security.Cryptography;
namespace Mono.Security.Protocol.Tls
{
internal class TlsCipherSuite : CipherSuite
{
private const int MacHeaderLength = 13;
private byte[] header;
private object headerLock = new object ();
#region Constructors
public TlsCipherSuite(
short code, string name, CipherAlgorithmType cipherAlgorithmType,
HashAlgorithmType hashAlgorithmType, ExchangeAlgorithmType exchangeAlgorithmType,
bool exportable, bool blockMode, byte keyMaterialSize,
byte expandedKeyMaterialSize, short effectiveKeyBytes,
byte ivSize, byte blockSize)
:base(code, name, cipherAlgorithmType, hashAlgorithmType,
exchangeAlgorithmType, exportable, blockMode, keyMaterialSize,
expandedKeyMaterialSize, effectiveKeyBytes, ivSize, blockSize)
{
}
#endregion
#region MAC Generation Methods
public override byte[] ComputeServerRecordMAC(ContentType contentType, byte[] fragment)
{
lock (headerLock) {
if (header == null)
header = new byte [MacHeaderLength];
ulong seqnum = (Context is ClientContext) ? Context.ReadSequenceNumber : Context.WriteSequenceNumber;
Write (header, 0, seqnum);
header [8] = (byte)contentType;
Write (header, 9, this.Context.Protocol);
Write (header, 11, (short)fragment.Length);
HashAlgorithm mac = this.ServerHMAC;
mac.TransformBlock (header, 0, header.Length, header, 0);
mac.TransformBlock (fragment, 0, fragment.Length, fragment, 0);
// hack, else the method will allocate a new buffer of the same length (negative half the optimization)
mac.TransformFinalBlock (CipherSuite.EmptyArray, 0, 0);
return mac.Hash;
}
}
public override byte[] ComputeClientRecordMAC(ContentType contentType, byte[] fragment)
{
lock (headerLock) {
if (header == null)
header = new byte [MacHeaderLength];
ulong seqnum = (Context is ClientContext) ? Context.WriteSequenceNumber : Context.ReadSequenceNumber;
Write (header, 0, seqnum);
header [8] = (byte)contentType;
Write (header, 9, this.Context.Protocol);
Write (header, 11, (short)fragment.Length);
HashAlgorithm mac = this.ClientHMAC;
mac.TransformBlock (header, 0, header.Length, header, 0);
mac.TransformBlock (fragment, 0, fragment.Length, fragment, 0);
// hack, else the method will allocate a new buffer of the same length (negative half the optimization)
mac.TransformFinalBlock (CipherSuite.EmptyArray, 0, 0);
return mac.Hash;
}
}
#endregion
#region Key Generation Methods
public override void ComputeMasterSecret(byte[] preMasterSecret)
{
// Create master secret
this.Context.MasterSecret = new byte[preMasterSecret.Length];
this.Context.MasterSecret = this.PRF(
preMasterSecret, "master secret", this.Context.RandomCS, 48);
DebugHelper.WriteLine(">>>> MasterSecret", this.Context.MasterSecret);
}
public override void ComputeKeys()
{
// Create keyblock
TlsStream keyBlock = new TlsStream(
this.PRF(
this.Context.MasterSecret,
"key expansion",
this.Context.RandomSC,
this.KeyBlockSize));
this.Context.Negotiating.ClientWriteMAC = keyBlock.ReadBytes(this.HashSize);
this.Context.Negotiating.ServerWriteMAC = keyBlock.ReadBytes(this.HashSize);
this.Context.ClientWriteKey = keyBlock.ReadBytes(this.KeyMaterialSize);
this.Context.ServerWriteKey = keyBlock.ReadBytes(this.KeyMaterialSize);
if (this.IvSize != 0)
{
this.Context.ClientWriteIV = keyBlock.ReadBytes(this.IvSize);
this.Context.ServerWriteIV = keyBlock.ReadBytes(this.IvSize);
}
else
{
this.Context.ClientWriteIV = CipherSuite.EmptyArray;
this.Context.ServerWriteIV = CipherSuite.EmptyArray;
}
DebugHelper.WriteLine(">>>> KeyBlock", keyBlock.ToArray());
DebugHelper.WriteLine(">>>> ClientWriteKey", this.Context.ClientWriteKey);
DebugHelper.WriteLine(">>>> ClientWriteIV", this.Context.ClientWriteIV);
DebugHelper.WriteLine(">>>> ClientWriteMAC", this.Context.Negotiating.ClientWriteMAC);
DebugHelper.WriteLine(">>>> ServerWriteKey", this.Context.ServerWriteKey);
DebugHelper.WriteLine(">>>> ServerWriteIV", this.Context.ServerWriteIV);
DebugHelper.WriteLine(">>>> ServerWriteMAC", this.Context.Negotiating.ServerWriteMAC);
ClientSessionCache.SetContextInCache (this.Context);
// Clear no more needed data
keyBlock.Reset();
}
#endregion
}
}
@@ -1,124 +0,0 @@
// Transport Security Layer (TLS)
// Copyright (c) 2003-2004 Carlos Guzman Alvarez
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Text;
using System.Security.Cryptography.X509Certificates;
using Mono.Security.Cryptography;
using X509 = Mono.Security.X509;
namespace Mono.Security.Protocol.Tls
{
internal sealed class TlsClientSettings
{
#region Fields
private string targetHost;
private X509CertificateCollection certificates;
//private SecurityCompressionType compressionMethod;
private X509Certificate clientCertificate;
private RSAManaged certificateRSA;
#endregion
#region Properties
public string TargetHost
{
get { return this.targetHost; }
set { this.targetHost = value; }
}
public X509CertificateCollection Certificates
{
get { return this.certificates; }
set { this.certificates = value; }
}
public X509Certificate ClientCertificate
{
get { return this.clientCertificate; }
set
{
this.clientCertificate = value;
this.UpdateCertificateRSA();
}
}
public RSAManaged CertificateRSA
{
get { return this.certificateRSA; }
}
/*
public SecurityCompressionType CompressionMethod
{
get { return this.compressionMethod; }
set
{
if (value != SecurityCompressionType.None)
{
throw new NotSupportedException("Specified compression method is not supported");
}
this.compressionMethod = value;
}
}
*/
#endregion
#region Constructors
public TlsClientSettings()
{
// this.compressionMethod = SecurityCompressionType.None;
this.certificates = new X509CertificateCollection();
this.targetHost = String.Empty;
}
#endregion
#region Methods
public void UpdateCertificateRSA()
{
if (this.clientCertificate == null)
{
this.certificateRSA = null;
}
else
{
X509.X509Certificate cert = new X509.X509Certificate(this.clientCertificate.GetRawCertData());
this.certificateRSA = new RSAManaged(
cert.RSA.KeySize);
this.certificateRSA.ImportParameters(
cert.RSA.ExportParameters(false));
}
}
#endregion
}
}
@@ -1,93 +0,0 @@
// Transport Security Layer (TLS)
// Copyright (c) 2003-2004 Carlos Guzman Alvarez
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Text;
using System.Runtime.Serialization;
namespace Mono.Security.Protocol.Tls
{
[Serializable]
internal sealed class TlsException : Exception
{
#region Fields
private Alert alert;
#endregion
#region Properties
public Alert Alert
{
get { return this.alert; }
}
#endregion
#region Constructors
internal TlsException(string message) : base(message)
{
}
internal TlsException(SerializationInfo info, StreamingContext context) : base(info, context)
{
}
internal TlsException(string message, Exception ex) : base(message, ex)
{
}
internal TlsException(
AlertLevel level,
AlertDescription description)
: this (level, description, Alert.GetAlertMessage(description))
{
}
internal TlsException(
AlertLevel level,
AlertDescription description,
string message) : base (message)
{
this.alert = new Alert(level, description);
}
internal TlsException(
AlertDescription description)
: this (description, Alert.GetAlertMessage(description))
{
}
internal TlsException(
AlertDescription description,
string message) : base (message)
{
this.alert = new Alert(description);
}
#endregion
}
}
@@ -1,129 +0,0 @@
// Transport Security Layer (TLS)
// Copyright (c) 2003-2004 Carlos Guzman Alvarez
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Security.Cryptography;
using Mono.Security.Cryptography;
using Mono.Security.X509;
using Mono.Security.Protocol.Tls.Handshake;
namespace Mono.Security.Protocol.Tls
{
internal class TlsServerSettings
{
#region Fields
private X509CertificateCollection certificates;
private RSA certificateRSA;
private RSAParameters rsaParameters;
private byte[] signedParams;
private string[] distinguisedNames;
private bool serverKeyExchange;
private bool certificateRequest;
private ClientCertificateType[] certificateTypes;
#endregion
#region Properties
public bool ServerKeyExchange
{
get { return this.serverKeyExchange; }
set { this.serverKeyExchange = value; }
}
public X509CertificateCollection Certificates
{
get { return this.certificates; }
set { this.certificates = value; }
}
public RSA CertificateRSA
{
get { return this.certificateRSA; }
}
public RSAParameters RsaParameters
{
get { return this.rsaParameters; }
set { this.rsaParameters = value; }
}
public byte[] SignedParams
{
get { return this.signedParams; }
set { this.signedParams = value; }
}
public bool CertificateRequest
{
get { return this.certificateRequest; }
set { this.certificateRequest = value; }
}
public ClientCertificateType[] CertificateTypes
{
get { return this.certificateTypes; }
set { this.certificateTypes = value; }
}
public string[] DistinguisedNames
{
get { return this.distinguisedNames; }
set { this.distinguisedNames = value; }
}
#endregion
#region Constructors
public TlsServerSettings()
{
}
#endregion
#region Methods
public void UpdateCertificateRSA()
{
if (this.certificates == null ||
this.certificates.Count == 0)
{
this.certificateRSA = null;
}
else
{
this.certificateRSA = new RSAManaged(
this.certificates[0].RSA.KeySize);
this.certificateRSA.ImportParameters(
this.certificates[0].RSA.ExportParameters(false));
}
}
#endregion
}
}
@@ -1,274 +0,0 @@
// Transport Security Layer (TLS)
// Copyright (c) 2003-2004 Carlos Guzman Alvarez
// Copyright (C) 2006 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.IO;
namespace Mono.Security.Protocol.Tls
{
internal class TlsStream : Stream
{
#region Fields
private bool canRead;
private bool canWrite;
private MemoryStream buffer;
private byte[] temp;
private const int temp_size = 4;
#endregion
#region Properties
public bool EOF
{
get
{
if (this.Position < this.Length)
{
return false;
}
else
{
return true;
}
}
}
#endregion
#region Stream Properties
public override bool CanWrite
{
get { return this.canWrite; }
}
public override bool CanRead
{
get { return this.canRead; }
}
public override bool CanSeek
{
get { return this.buffer.CanSeek; }
}
public override long Position
{
get { return this.buffer.Position; }
set { this.buffer.Position = value; }
}
public override long Length
{
get { return this.buffer.Length; }
}
#endregion
#region Constructors
public TlsStream() : base()
{
this.buffer = new MemoryStream(0);
this.canRead = false;
this.canWrite = true;
}
public TlsStream(byte[] data) : base()
{
if (data != null)
this.buffer = new MemoryStream(data);
else
this.buffer = new MemoryStream ();
this.canRead = true;
this.canWrite = false;
}
#endregion
#region Specific Read Methods
// hack for reducing memory allocations
// returned value is valid only for the length asked *and*
// cannot be directly returned outside the class
// note: Mono's Stream.ReadByte does a 1 byte array allocation
private byte[] ReadSmallValue (int length)
{
if (length > temp_size)
throw new ArgumentException ("8 bytes maximum");
if (temp == null)
temp = new byte[temp_size];
if (this.Read (temp, 0, length) != length)
throw new TlsException (String.Format ("buffer underrun"));
return temp;
}
public new byte ReadByte()
{
byte[] result = ReadSmallValue (1);
return result [0];
}
public short ReadInt16()
{
byte[] result = ReadSmallValue (2);
return (short) (result[0] << 8 | result[1]);
}
public int ReadInt24()
{
byte[] result = ReadSmallValue (3);
return ((result[0] << 16) | (result[1] << 8) | result[2]);
}
public int ReadInt32()
{
byte[] result = ReadSmallValue (4);
return ((result[0] << 24) | (result[1] << 16) | (result[2] << 8) | result[3]);
}
public byte[] ReadBytes(int count)
{
byte[] bytes = new byte[count];
if (this.Read(bytes, 0, count) != count)
throw new TlsException ("buffer underrun");
return bytes;
}
#endregion
#region Specific Write Methods
// note: Mono's Stream.WriteByte does a 1 byte array allocation
public void Write(byte value)
{
if (temp == null)
temp = new byte[temp_size];
temp[0] = value;
this.Write (temp, 0, 1);
}
public void Write(short value)
{
if (temp == null)
temp = new byte[temp_size];
temp[0] = ((byte)(value >> 8));
temp[1] = ((byte)value);
this.Write (temp, 0, 2);
}
public void WriteInt24(int value)
{
if (temp == null)
temp = new byte[temp_size];
temp[0] = ((byte)(value >> 16));
temp[1] = ((byte)(value >> 8));
temp[2] = ((byte)value);
this.Write (temp, 0, 3);
}
public void Write(int value)
{
if (temp == null)
temp = new byte[temp_size];
temp[0] = ((byte)(value >> 24));
temp[1] = ((byte)(value >> 16));
temp[2] = ((byte)(value >> 8));
temp[3] = ((byte)value);
this.Write (temp, 0, 4);
}
public void Write(ulong value)
{
Write ((int)(value >> 32));
Write ((int)value);
}
public void Write(byte[] buffer)
{
this.Write(buffer, 0, buffer.Length);
}
#endregion
#region Methods
public void Reset()
{
this.buffer.SetLength(0);
this.buffer.Position = 0;
}
public byte[] ToArray()
{
return this.buffer.ToArray();
}
#endregion
#region Stream Methods
public override void Flush()
{
this.buffer.Flush();
}
public override void SetLength(long length)
{
this.buffer.SetLength(length);
}
public override long Seek(long offset, System.IO.SeekOrigin loc)
{
return this.buffer.Seek(offset, loc);
}
public override int Read(byte[] buffer, int offset, int count)
{
if (this.canRead)
{
return this.buffer.Read(buffer, offset, count);
}
throw new InvalidOperationException("Read operations are not allowed by this stream");
}
public override void Write(byte[] buffer, int offset, int count)
{
if (this.canWrite)
{
this.buffer.Write(buffer, offset, count);
}
else
{
throw new InvalidOperationException("Write operations are not allowed by this stream");
}
}
#endregion
}
}
@@ -206,65 +206,6 @@
<Compile Include="Mono.Security.Protocol.Ntlm\Type1Message.cs" />
<Compile Include="Mono.Security.Protocol.Ntlm\Type2Message.cs" />
<Compile Include="Mono.Security.Protocol.Ntlm\Type3Message.cs" />
<Compile Include="Mono.Security.Protocol.Tls.Handshake.Client\TlsClientCertificate.cs" />
<Compile Include="Mono.Security.Protocol.Tls.Handshake.Client\TlsClientCertificateVerify.cs" />
<Compile Include="Mono.Security.Protocol.Tls.Handshake.Client\TlsClientFinished.cs" />
<Compile Include="Mono.Security.Protocol.Tls.Handshake.Client\TlsClientHello.cs" />
<Compile Include="Mono.Security.Protocol.Tls.Handshake.Client\TlsClientKeyExchange.cs" />
<Compile Include="Mono.Security.Protocol.Tls.Handshake.Client\TlsServerCertificate.cs" />
<Compile Include="Mono.Security.Protocol.Tls.Handshake.Client\TlsServerCertificateRequest.cs" />
<Compile Include="Mono.Security.Protocol.Tls.Handshake.Client\TlsServerFinished.cs" />
<Compile Include="Mono.Security.Protocol.Tls.Handshake.Client\TlsServerHello.cs" />
<Compile Include="Mono.Security.Protocol.Tls.Handshake.Client\TlsServerHelloDone.cs" />
<Compile Include="Mono.Security.Protocol.Tls.Handshake.Client\TlsServerKeyExchange.cs" />
<Compile Include="Mono.Security.Protocol.Tls.Handshake.Server\TlsClientCertificate.cs" />
<Compile Include="Mono.Security.Protocol.Tls.Handshake.Server\TlsClientCertificateVerify.cs" />
<Compile Include="Mono.Security.Protocol.Tls.Handshake.Server\TlsClientFinished.cs" />
<Compile Include="Mono.Security.Protocol.Tls.Handshake.Server\TlsClientHello.cs" />
<Compile Include="Mono.Security.Protocol.Tls.Handshake.Server\TlsClientKeyExchange.cs" />
<Compile Include="Mono.Security.Protocol.Tls.Handshake.Server\TlsServerCertificate.cs" />
<Compile Include="Mono.Security.Protocol.Tls.Handshake.Server\TlsServerCertificateRequest.cs" />
<Compile Include="Mono.Security.Protocol.Tls.Handshake.Server\TlsServerFinished.cs" />
<Compile Include="Mono.Security.Protocol.Tls.Handshake.Server\TlsServerHello.cs" />
<Compile Include="Mono.Security.Protocol.Tls.Handshake.Server\TlsServerHelloDone.cs" />
<Compile Include="Mono.Security.Protocol.Tls.Handshake.Server\TlsServerKeyExchange.cs" />
<Compile Include="Mono.Security.Protocol.Tls.Handshake\ClientCertificateType.cs" />
<Compile Include="Mono.Security.Protocol.Tls.Handshake\HandshakeMessage.cs" />
<Compile Include="Mono.Security.Protocol.Tls.Handshake\HandshakeType.cs" />
<Compile Include="Mono.Security.Protocol.Tls\Alert.cs" />
<Compile Include="Mono.Security.Protocol.Tls\CipherAlgorithmType.cs" />
<Compile Include="Mono.Security.Protocol.Tls\CipherSuite.cs" />
<Compile Include="Mono.Security.Protocol.Tls\CipherSuiteCollection.cs" />
<Compile Include="Mono.Security.Protocol.Tls\CipherSuiteFactory.cs" />
<Compile Include="Mono.Security.Protocol.Tls\ClientContext.cs" />
<Compile Include="Mono.Security.Protocol.Tls\ClientRecordProtocol.cs" />
<Compile Include="Mono.Security.Protocol.Tls\ClientSessionCache.cs" />
<Compile Include="Mono.Security.Protocol.Tls\ContentType.cs" />
<Compile Include="Mono.Security.Protocol.Tls\Context.cs" />
<Compile Include="Mono.Security.Protocol.Tls\DebugHelper.cs" />
<Compile Include="Mono.Security.Protocol.Tls\ExchangeAlgorithmType.cs" />
<Compile Include="Mono.Security.Protocol.Tls\HandshakeState.cs" />
<Compile Include="Mono.Security.Protocol.Tls\HashAlgorithmType.cs" />
<Compile Include="Mono.Security.Protocol.Tls\HttpsClientStream.cs" />
<Compile Include="Mono.Security.Protocol.Tls\MD5SHA1.cs" />
<Compile Include="Mono.Security.Protocol.Tls\RSASslSignatureDeformatter.cs" />
<Compile Include="Mono.Security.Protocol.Tls\RSASslSignatureFormatter.cs" />
<Compile Include="Mono.Security.Protocol.Tls\RecordProtocol.cs" />
<Compile Include="Mono.Security.Protocol.Tls\SecurityCompressionType.cs" />
<Compile Include="Mono.Security.Protocol.Tls\SecurityParameters.cs" />
<Compile Include="Mono.Security.Protocol.Tls\SecurityProtocolType.cs" />
<Compile Include="Mono.Security.Protocol.Tls\ServerContext.cs" />
<Compile Include="Mono.Security.Protocol.Tls\ServerRecordProtocol.cs" />
<Compile Include="Mono.Security.Protocol.Tls\SslCipherSuite.cs" />
<Compile Include="Mono.Security.Protocol.Tls\SslClientStream.cs" />
<Compile Include="Mono.Security.Protocol.Tls\SslHandshakeHash.cs" />
<Compile Include="Mono.Security.Protocol.Tls\SslServerStream.cs" />
<Compile Include="Mono.Security.Protocol.Tls\SslStreamBase.cs" />
<Compile Include="Mono.Security.Protocol.Tls\TlsCipherSuite.cs" />
<Compile Include="Mono.Security.Protocol.Tls\TlsClientSettings.cs" />
<Compile Include="Mono.Security.Protocol.Tls\TlsException.cs" />
<Compile Include="Mono.Security.Protocol.Tls\TlsServerSettings.cs" />
<Compile Include="Mono.Security.Protocol.Tls\TlsStream.cs" />
<Compile Include="Mono.Security.X509.Extensions\AuthorityKeyIdentifierExtension.cs" />
<Compile Include="Mono.Security.X509.Extensions\BasicConstraintsExtension.cs" />
<Compile Include="Mono.Security.X509.Extensions\CRLDistributionPointsExtension.cs" />
@@ -74,65 +74,7 @@
./Mono.Security.Protocol.Ntlm/Type1Message.cs
./Mono.Security.Protocol.Ntlm/Type2Message.cs
./Mono.Security.Protocol.Ntlm/Type3Message.cs
./Mono.Security.Protocol.Tls/Alert.cs
./Mono.Security.Protocol.Tls/CipherAlgorithmType.cs
./Mono.Security.Protocol.Tls/CipherSuite.cs
./Mono.Security.Protocol.Tls/CipherSuiteCollection.cs
./Mono.Security.Protocol.Tls/CipherSuiteFactory.cs
./Mono.Security.Protocol.Tls/ClientContext.cs
./Mono.Security.Protocol.Tls/ClientRecordProtocol.cs
./Mono.Security.Protocol.Tls/ClientSessionCache.cs
./Mono.Security.Protocol.Tls/ContentType.cs
./Mono.Security.Protocol.Tls/Context.cs
./Mono.Security.Protocol.Tls/DebugHelper.cs
./Mono.Security.Protocol.Tls/ExchangeAlgorithmType.cs
./Mono.Security.Protocol.Tls/HandshakeState.cs
./Mono.Security.Protocol.Tls/HashAlgorithmType.cs
./Mono.Security.Protocol.Tls/MD5SHA1.cs
./Mono.Security.Protocol.Tls/HttpsClientStream.cs
./Mono.Security.Protocol.Tls/RecordProtocol.cs
./Mono.Security.Protocol.Tls/RSASslSignatureDeformatter.cs
./Mono.Security.Protocol.Tls/RSASslSignatureFormatter.cs
./Mono.Security.Protocol.Tls/SecurityCompressionType.cs
./Mono.Security.Protocol.Tls/SecurityParameters.cs
./Mono.Security.Protocol.Tls/SecurityProtocolType.cs
./Mono.Security.Protocol.Tls/ServerContext.cs
./Mono.Security.Protocol.Tls/ServerRecordProtocol.cs
./Mono.Security.Protocol.Tls/SslClientStream.cs
./Mono.Security.Protocol.Tls/SslCipherSuite.cs
./Mono.Security.Protocol.Tls/SslHandshakeHash.cs
./Mono.Security.Protocol.Tls/SslServerStream.cs
./Mono.Security.Protocol.Tls/SslStreamBase.cs
./Mono.Security.Protocol.Tls/TlsCipherSuite.cs
./Mono.Security.Protocol.Tls/TlsClientSettings.cs
./Mono.Security.Protocol.Tls/TlsException.cs
./Mono.Security.Protocol.Tls/TlsServerSettings.cs
./Mono.Security.Protocol.Tls/TlsStream.cs
./Mono.Security.Protocol.Tls.Handshake/ClientCertificateType.cs
./Mono.Security.Protocol.Tls.Handshake/HandshakeMessage.cs
./Mono.Security.Protocol.Tls.Handshake/HandshakeType.cs
./Mono.Security.Protocol.Tls.Handshake.Client/TlsClientCertificate.cs
./Mono.Security.Protocol.Tls.Handshake.Client/TlsClientCertificateVerify.cs
./Mono.Security.Protocol.Tls.Handshake.Client/TlsClientFinished.cs
./Mono.Security.Protocol.Tls.Handshake.Client/TlsClientHello.cs
./Mono.Security.Protocol.Tls.Handshake.Client/TlsClientKeyExchange.cs
./Mono.Security.Protocol.Tls.Handshake.Client/TlsServerCertificate.cs
./Mono.Security.Protocol.Tls.Handshake.Client/TlsServerCertificateRequest.cs
./Mono.Security.Protocol.Tls.Handshake.Client/TlsServerFinished.cs
./Mono.Security.Protocol.Tls.Handshake.Client/TlsServerHello.cs
./Mono.Security.Protocol.Tls.Handshake.Client/TlsServerHelloDone.cs
./Mono.Security.Protocol.Tls.Handshake.Client/TlsServerKeyExchange.cs
./Mono.Security.Protocol.Tls.Handshake.Server/TlsClientCertificate.cs
./Mono.Security.Protocol.Tls.Handshake.Server/TlsClientCertificateVerify.cs
./Mono.Security.Protocol.Tls.Handshake.Server/TlsClientFinished.cs
./Mono.Security.Protocol.Tls.Handshake.Server/TlsClientHello.cs
./Mono.Security.Protocol.Tls.Handshake.Server/TlsClientKeyExchange.cs
./Mono.Security.Protocol.Tls.Handshake.Server/TlsServerCertificate.cs
./Mono.Security.Protocol.Tls.Handshake.Server/TlsServerCertificateRequest.cs
./Mono.Security.Protocol.Tls.Handshake.Server/TlsServerFinished.cs
./Mono.Security.Protocol.Tls.Handshake.Server/TlsServerHello.cs
./Mono.Security.Protocol.Tls.Handshake.Server/TlsServerHelloDone.cs
./Mono.Security.Protocol.Tls.Handshake.Server/TlsServerKeyExchange.cs
./Mono.Xml/MiniParser.cs
./Mono.Xml/SecurityParser.cs
+25 -2
View File
@@ -5658,21 +5658,30 @@ namespace PEAPI {
char[] name;
Hashtable htable = new Hashtable();
Hashtable btable = new Hashtable (new ByteArrayHashCodeProvider (), new ByteArrayComparer ());
bool addInitByte = false;
bool initByteAdded = false;
internal MetaDataStream(char[] name, bool addInitByte) : base(new MemoryStream())
{
if (addInitByte) { Write((byte)0); size = 1; }
this.addInitByte = addInitByte;
this.name = name;
sizeOfHeader = StreamHeaderSize + (uint)name.Length;
}
internal MetaDataStream(char[] name, System.Text.Encoding enc, bool addInitByte) : base(new MemoryStream(),enc)
{
if (addInitByte) { Write((byte)0); size = 1; }
this.addInitByte = addInitByte;
this.name = name;
sizeOfHeader = StreamHeaderSize + (uint)name.Length;
}
void AddInitByte () {
if (addInitByte && !initByteAdded) {
Write((byte)0);
size += 1;
initByteAdded = true;
}
}
public uint Start {
get { return start; }
set { start = value; }
@@ -5706,6 +5715,7 @@ namespace PEAPI {
internal uint Add(string str, bool prependSize)
{
AddInitByte ();
Object val = htable[str];
uint index = 0;
if (val == null) {
@@ -5723,6 +5733,7 @@ namespace PEAPI {
}
internal uint Add (byte[] str, bool prependSize)
{
AddInitByte ();
Object val = btable [str];
uint index = 0;
if (val == null) {
@@ -5740,6 +5751,7 @@ namespace PEAPI {
internal uint Add(Guid guid, bool prependSize)
{
AddInitByte ();
byte [] b = guid.ToByteArray ();
if (prependSize) CompressNum ((uint) b.Length);
Write(guid.ToByteArray());
@@ -5749,6 +5761,7 @@ namespace PEAPI {
internal uint Add(byte[] blob)
{
AddInitByte ();
uint ix = size;
CompressNum((uint)blob.Length);
Write(blob);
@@ -5758,6 +5771,7 @@ namespace PEAPI {
internal uint Add(byte val, bool prependSize)
{
AddInitByte ();
uint ix = size;
if (prependSize) CompressNum (1);
Write(val);
@@ -5767,6 +5781,7 @@ namespace PEAPI {
internal uint Add(sbyte val, bool prependSize)
{
AddInitByte ();
uint ix = size;
if (prependSize) CompressNum (1);
Write(val);
@@ -5776,6 +5791,7 @@ namespace PEAPI {
internal uint Add(ushort val, bool prependSize)
{
AddInitByte ();
uint ix = size;
if (prependSize) CompressNum (2);
Write(val);
@@ -5785,6 +5801,7 @@ namespace PEAPI {
internal uint Add(short val, bool prependSize)
{
AddInitByte ();
uint ix = size;
if (prependSize) CompressNum (2);
Write(val);
@@ -5794,6 +5811,7 @@ namespace PEAPI {
internal uint Add(uint val, bool prependSize)
{
AddInitByte ();
uint ix = size;
if (prependSize) CompressNum (4);
Write(val);
@@ -5803,6 +5821,7 @@ namespace PEAPI {
internal uint Add(int val, bool prependSize)
{
AddInitByte ();
uint ix = size;
if (prependSize) CompressNum (4);
Write (val);
@@ -5812,6 +5831,7 @@ namespace PEAPI {
internal uint Add(ulong val, bool prependSize)
{
AddInitByte ();
uint ix = size;
if (prependSize) CompressNum (8);
Write(val);
@@ -5821,6 +5841,7 @@ namespace PEAPI {
internal uint Add(long val, bool prependSize)
{
AddInitByte ();
uint ix = size;
if (prependSize) CompressNum (8);
Write(val);
@@ -5830,6 +5851,7 @@ namespace PEAPI {
internal uint Add(float val, bool prependSize)
{
AddInitByte ();
uint ix = size;
if (prependSize) CompressNum (4);
Write(val);
@@ -5839,6 +5861,7 @@ namespace PEAPI {
internal uint Add(double val, bool prependSize)
{
AddInitByte ();
uint ix = size;
if (prependSize) CompressNum (8);
Write(val);
+2
View File
@@ -62,4 +62,6 @@ XTEST_LIB_REFS = System Facades/System.Threading.Tasks Microsoft.CSharp Facades/
XTEST_LIB_FLAGS = -unsafe -d:FEATURE_COMPILE
XTEST_RESX_RESOURCE_STRING = ../../../external/corefx/src/System.Collections.Immutable/src/Resources/Strings.resx
XTEST_SPLIT_ASSEMBLIES := $(filter monotouch%, $(PROFILE))
include ../../build/library.make
@@ -3,12 +3,10 @@
../../../external/corefx/src/CoreFx.Private.TestUtilities/src/System/AssertExtensions.cs
../../../external/corefx/src/Common/tests/System/Threading/Tasks/TaskTimeoutExtensions.cs
# System.Linq
# TODO: ../../../external/corefx/src/System.Linq/tests/*.cs
# System.Linq.Queryable
../../../external/corefx/src/System.Linq.Queryable/tests/*.cs
../../../external/corefx/src/Common/tests/System/Linq/SkipTakeData.cs
#split monotouch
#split monotouch_tv
#split monotouch_watch
# System.Linq.Expressions
../../../external/corefx/src/System.Linq.Expressions/tests/Array/*.cs:NewArrayBoundsTests.cs,ArrayAccessTests.cs,ArrayIndexTests.cs
@@ -56,7 +54,19 @@
../../../external/corefx/src/System.Linq.Expressions/tests/Unary/IncDecAssign/*.cs
../../../external/corefx/src/System.Linq.Expressions/tests/*.cs:StackSpillerTests.cs,ReadOnlyCollectionBuilderTests.cs
# System.Linq.Expressions
#split monotouch
#split monotouch_tv
#split monotouch_watch
# System.Linq
# TODO: ../../../external/corefx/src/System.Linq/tests/*.cs
# System.Linq.Queryable
../../../external/corefx/src/System.Linq.Queryable/tests/*.cs
../../../external/corefx/src/Common/tests/System/Linq/SkipTakeData.cs
# System.Linq.Parallel
../../../external/corefx/src/System.Linq.Parallel/tests/Combinatorial/*.cs
../../../external/corefx/src/System.Linq.Parallel/tests/Helpers/*.cs
../../../external/corefx/src/System.Linq.Parallel/tests/QueryOperators/*.cs:DefaultIfEmptyTests.cs,SingleSingleOrDefaultTests.cs
+1 -1
View File
@@ -99,7 +99,7 @@
<PropertyGroup Condition=" '$(Platform)' == 'wasm' ">
<OutputPath>./../../class/lib/wasm</OutputPath>
<IntermediateOutputPath>./../../class/obj/$(AssemblyName)-wasm</IntermediateOutputPath>
<DefineConstants>NET_1_1;NET_2_0;NET_2_1;NET_3_5;NET_4_0;NET_4_5;MONO;MOBILE;MOBILE_LEGACY;FULL_AOT_DESKTOP;FULL_AOT_RUNTIME;WASM;DISABLE_COM;FEATURE_NO_BSD_SOCKETS;DISABLE_REMOTING;DISABLE_SECURITY;COREFX;PLATFORM_UNIX;USEOFFSET;MONO_PARTIAL_DATA_IMPORT;NO_CODEDOM;NO_OLEDB;NO_ODBC;NO_CONFIGURATION;MONO_FEATURE_BTLS</DefineConstants>
<DefineConstants>NET_1_1;NET_2_0;NET_2_1;NET_3_5;NET_4_0;NET_4_5;MONO;MOBILE;MOBILE_LEGACY;FULL_AOT_DESKTOP;FULL_AOT_RUNTIME;WASM;DISABLE_COM;FEATURE_NO_BSD_SOCKETS;DISABLE_REMOTING;DISABLE_SECURITY;COREFX;PLATFORM_UNIX;USEOFFSET;MONO_PARTIAL_DATA_IMPORT;NO_CODEDOM;NO_OLEDB;NO_ODBC;NO_CONFIGURATION</DefineConstants>
</PropertyGroup>
<!-- @ALL_PROFILE_PROPERTIES@ -->
<PropertyGroup Condition=" '$(Configuration)' == 'Debug' ">
@@ -2,16 +2,15 @@ thisdir = class/System.Net.Http/FunctionalTests
SUBDIRS =
include ../../../build/rules.make
ASSEMBLY = System.Net.Http.FunctionalTests
LIBRARY = System.Net.Http.FunctionalTests.dll
NO_BUILD = yes
NO_INSTALL = yes
XTEST_LIB_REFS = System System.Core Facades/System.Threading.Tasks
XTEST_LIB_REFS = System System.Core Facades/System.Threading.Tasks System.Net.Http
USE_XTEST_REMOTE_EXECUTOR = YES
XTEST_LIB_FLAGS = /resource:../../System/Test/TestData/testservereku.contoso.com.pfx
the_assembly = $(topdir)/class/lib/$(PROFILE_DIRECTORY)/System.Net.Http.dll
include ../../../build/tests.make
include ../../../build/library.make
TEST_RUNTIME := MONO_URI_DOTNETRELATIVEORABSOLUTE=true $(TEST_RUNTIME)
@@ -0,0 +1,27 @@
using System.Reflection;
namespace System.Net.Http
{
partial class HttpClientHandler : HttpMessageHandler
{
static IMonoHttpClientHandler CreateDefaultHandler ()
{
string envvar = Environment.GetEnvironmentVariable ("XA_HTTP_CLIENT_HANDLER_TYPE")?.Trim ();
if (envvar?.StartsWith("System.Net.Http.MonoWebRequestHandler", StringComparison.InvariantCulture) == true)
{
Type monoWrhType = Type.GetType (envvar, false);
if (monoWrhType != null)
return (IMonoHttpClientHandler) Activator.CreateInstance (monoWrhType);
}
// Ignore other types of handlers here (e.g. AndroidHttpHandler) to keep the old behavior
// and always create SocketsHttpHandler for code like this if MonoWebRequestHandler was not specified:
//
// var handler = new HttpClientHandler { Credentials = ... };
// var httpClient = new HttpClient (handler);
//
// AndroidHttpHandler is used only when we use the parameterless ctor of HttpClient
return new SocketsHttpHandler ();
}
}
}
@@ -70,7 +70,7 @@ namespace System.Net.Http
TimeSpan? timeout;
bool disposed;
internal MonoWebRequestHandler ()
public MonoWebRequestHandler ()
{
allowAutoRedirect = true;
maxAutomaticRedirections = 50;
+388 -222
View File
@@ -124,66 +124,117 @@
<Choose>
<When Condition="'$(Platform)' == 'xammac'">
<ItemGroup>
<Compile Include="..\..\..\external\corefx\src\Common\src\System\Net\Http\HttpHandlerDefaults.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\ByteArrayContent.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\ByteArrayHelpers.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\ClientCertificateOption.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\DelegatingHandler.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\DiagnosticsHandlerLoggingStrings.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\FormUrlEncodedContent.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\AuthenticationHeaderValue.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\BaseHeaderParser.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\ByteArrayHeaderParser.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\CacheControlHeaderParser.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\CacheControlHeaderValue.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\ContentDispositionHeaderValue.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\ContentRangeHeaderValue.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\DateHeaderParser.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\EntityTagHeaderValue.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\GenericHeaderParser.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\HeaderDescriptor.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\HeaderUtilities.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\HttpContentHeaders.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\HttpGeneralHeaders.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\HttpHeaderParser.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\HttpHeaderType.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\HttpHeaderValueCollection.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\HttpHeaders.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\HttpRequestHeaders.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\HttpResponseHeaders.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\Int32NumberHeaderParser.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\Int64NumberHeaderParser.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\KnownHeader.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\KnownHeaders.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\MediaTypeHeaderParser.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\MediaTypeHeaderValue.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\MediaTypeWithQualityHeaderValue.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\NameValueHeaderValue.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\NameValueWithParametersHeaderValue.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\ObjectCollection.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\ProductHeaderValue.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\ProductInfoHeaderParser.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\ProductInfoHeaderValue.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\RangeConditionHeaderValue.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\RangeHeaderValue.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\RangeItemHeaderValue.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\RetryConditionHeaderValue.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\StringWithQualityHeaderValue.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\TimeSpanHeaderParser.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\TransferCodingHeaderParser.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\TransferCodingHeaderValue.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\TransferCodingWithQualityHeaderValue.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\UriHeaderParser.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\ViaHeaderValue.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\WarningHeaderValue.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\HttpClient.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\HttpClientHandler.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\HttpCompletionOption.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\HttpContent.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\HttpMessageHandler.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\HttpMessageInvoker.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\HttpMethod.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\HttpParseResult.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\HttpRequestException.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\HttpRequestMessage.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\HttpResponseMessage.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\HttpRuleParser.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\HttpUtilities.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\MessageProcessingHandler.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\MultipartContent.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\MultipartFormDataContent.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\ReadOnlyMemoryContent.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\SocketsHttpHandler\AuthenticationHelper.Digest.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\SocketsHttpHandler\AuthenticationHelper.NtAuth.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\SocketsHttpHandler\AuthenticationHelper.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\SocketsHttpHandler\CancellationHelper.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\SocketsHttpHandler\ChunkedEncodingReadStream.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\SocketsHttpHandler\ChunkedEncodingWriteStream.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\SocketsHttpHandler\ConnectHelper.cs" />
<Compile Include="HttpClientHandler.Legacy.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\SocketsHttpHandler\ConnectionCloseReadStream.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\SocketsHttpHandler\ContentLengthReadStream.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\SocketsHttpHandler\ContentLengthWriteStream.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\SocketsHttpHandler\CookieHelper.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\SocketsHttpHandler\DecompressionHandler.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\SocketsHttpHandler\EmptyReadStream.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\SocketsHttpHandler\HttpAuthenticatedConnectionHandler.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\SocketsHttpHandler\HttpConnection.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\SocketsHttpHandler\HttpConnectionHandler.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\SocketsHttpHandler\HttpConnectionKind.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\SocketsHttpHandler\HttpConnectionPool.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\SocketsHttpHandler\HttpConnectionPoolManager.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\SocketsHttpHandler\HttpConnectionResponseContent.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\SocketsHttpHandler\HttpConnectionSettings.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\SocketsHttpHandler\HttpContentDuplexStream.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\SocketsHttpHandler\HttpContentReadStream.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\SocketsHttpHandler\HttpContentStream.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\SocketsHttpHandler\HttpContentWriteStream.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\SocketsHttpHandler\HttpEnvironmentProxy.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\SocketsHttpHandler\RawConnectionStream.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\SocketsHttpHandler\RedirectHandler.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\SocketsHttpHandler\SocketsHttpHandler.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\SocketsHttpHandler\SystemProxyInfo.Unix.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\StreamContent.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\StreamToStreamCopy.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\StringContent.cs" />
<Compile Include="HttpClientHandler.SocketsHandler.cs" />
<Compile Include="HttpClientHandler.cs" />
<Compile Include="HttpRequestMessage.Mono.cs" />
<Compile Include="IMonoHttpClientHandler.cs" />
<Compile Include="MonoWebRequestHandler.cs" />
<Compile Include="PlatformHelper.Legacy.cs" />
<Compile Include="System.Net.Http.Headers\AuthenticationHeaderValue.cs" />
<Compile Include="System.Net.Http.Headers\CacheControlHeaderValue.cs" />
<Compile Include="System.Net.Http.Headers\CollectionExtensions.cs" />
<Compile Include="System.Net.Http.Headers\CollectionParser.cs" />
<Compile Include="System.Net.Http.Headers\ContentDispositionHeaderValue.cs" />
<Compile Include="System.Net.Http.Headers\ContentRangeHeaderValue.cs" />
<Compile Include="System.Net.Http.Headers\EntityTagHeaderValue.cs" />
<Compile Include="System.Net.Http.Headers\HashCodeCalculator.cs" />
<Compile Include="System.Net.Http.Headers\HeaderInfo.cs" />
<Compile Include="System.Net.Http.Headers\HttpContentHeaders.cs" />
<Compile Include="System.Net.Http.Headers\HttpHeaderKind.cs" />
<Compile Include="System.Net.Http.Headers\HttpHeaderValueCollection.cs" />
<Compile Include="System.Net.Http.Headers\HttpHeaders.cs" />
<Compile Include="System.Net.Http.Headers\HttpRequestHeaders.cs" />
<Compile Include="System.Net.Http.Headers\HttpResponseHeaders.cs" />
<Compile Include="System.Net.Http.Headers\Lexer.cs" />
<Compile Include="System.Net.Http.Headers\MediaTypeHeaderValue.cs" />
<Compile Include="System.Net.Http.Headers\MediaTypeWithQualityHeaderValue.cs" />
<Compile Include="System.Net.Http.Headers\NameValueHeaderValue.cs" />
<Compile Include="System.Net.Http.Headers\NameValueWithParametersHeaderValue.cs" />
<Compile Include="System.Net.Http.Headers\Parser.cs" />
<Compile Include="System.Net.Http.Headers\ProductHeaderValue.cs" />
<Compile Include="System.Net.Http.Headers\ProductInfoHeaderValue.cs" />
<Compile Include="System.Net.Http.Headers\QualityValue.cs" />
<Compile Include="System.Net.Http.Headers\RangeConditionHeaderValue.cs" />
<Compile Include="System.Net.Http.Headers\RangeHeaderValue.cs" />
<Compile Include="System.Net.Http.Headers\RangeItemHeaderValue.cs" />
<Compile Include="System.Net.Http.Headers\RetryConditionHeaderValue.cs" />
<Compile Include="System.Net.Http.Headers\StringWithQualityHeaderValue.cs" />
<Compile Include="System.Net.Http.Headers\TransferCodingHeaderValue.cs" />
<Compile Include="System.Net.Http.Headers\TransferCodingWithQualityHeaderValue.cs" />
<Compile Include="System.Net.Http.Headers\ViaHeaderValue.cs" />
<Compile Include="System.Net.Http.Headers\WarningHeaderValue.cs" />
<Compile Include="System.Net.Http\ByteArrayContent.cs" />
<Compile Include="System.Net.Http\ClientCertificateOption.cs" />
<Compile Include="System.Net.Http\DelegatingHandler.cs" />
<Compile Include="System.Net.Http\FormUrlEncodedContent.cs" />
<Compile Include="System.Net.Http\HttpClient.cs" />
<Compile Include="PlatformHelper.SocketsHandler.cs" />
<Compile Include="System.Net.Http\HttpClient.macios.cs" />
<Compile Include="System.Net.Http\HttpCompletionOption.cs" />
<Compile Include="System.Net.Http\HttpContent.cs" />
<Compile Include="System.Net.Http\HttpMessageHandler.cs" />
<Compile Include="System.Net.Http\HttpMessageInvoker.cs" />
<Compile Include="System.Net.Http\HttpMethod.cs" />
<Compile Include="System.Net.Http\HttpRequestException.cs" />
<Compile Include="System.Net.Http\HttpRequestMessage.cs" />
<Compile Include="System.Net.Http\HttpResponseMessage.cs" />
<Compile Include="System.Net.Http\MessageProcessingHandler.cs" />
<Compile Include="System.Net.Http\MultipartContent.cs" />
<Compile Include="System.Net.Http\MultipartFormDataContent.cs" />
<Compile Include="System.Net.Http\StreamContent.cs" />
<Compile Include="System.Net.Http\StringContent.cs" />
<Compile Include="corefx\ReadOnlyMemoryContent.cs" />
<Compile Include="corefx\NetEventSource.Http.cs" />
<Compile Include="corefx\SocketsHttpHandler.Mono.cs" />
</ItemGroup>
</When>
<When Condition="'$(Platform)' == 'winaot'">
@@ -323,7 +374,6 @@
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\StreamContent.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\StreamToStreamCopy.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\StringContent.cs" />
<Compile Include="..\corlib\System.Diagnostics\Debug.cs" />
<Compile Include="HttpClientHandler.wasm.cs" />
<Compile Include="HttpRequestMessage.Mono.cs" />
<Compile Include="IMonoHttpClientHandler.cs" />
@@ -629,7 +679,6 @@
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\StreamContent.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\StreamToStreamCopy.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\StringContent.cs" />
<Compile Include="..\corlib\System.Diagnostics\Debug.cs" />
<Compile Include="HttpClient.DefaultHandler.cs" />
<Compile Include="HttpClientHandler.SocketsHandler.cs" />
<Compile Include="HttpClientHandler.cs" />
@@ -745,7 +794,6 @@
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\StreamContent.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\StreamToStreamCopy.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\StringContent.cs" />
<Compile Include="..\corlib\System.Diagnostics\Debug.cs" />
<Compile Include="HttpClient.DefaultHandler.cs" />
<Compile Include="HttpClientHandler.SocketsHandler.cs" />
<Compile Include="HttpClientHandler.cs" />
@@ -861,7 +909,6 @@
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\StreamContent.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\StreamToStreamCopy.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\StringContent.cs" />
<Compile Include="..\corlib\System.Diagnostics\Debug.cs" />
<Compile Include="HttpClient.DefaultHandler.cs" />
<Compile Include="HttpClientHandler.SocketsHandler.cs" />
<Compile Include="HttpClientHandler.cs" />
@@ -878,189 +925,309 @@
</When>
<When Condition="'$(Platform)' == 'monotouch_watch'">
<ItemGroup>
<Compile Include="PlatformHelper.Legacy.cs" />
<Compile Include="System.Net.Http.Headers\AuthenticationHeaderValue.cs" />
<Compile Include="System.Net.Http.Headers\CacheControlHeaderValue.cs" />
<Compile Include="System.Net.Http.Headers\CollectionExtensions.cs" />
<Compile Include="System.Net.Http.Headers\CollectionParser.cs" />
<Compile Include="System.Net.Http.Headers\ContentDispositionHeaderValue.cs" />
<Compile Include="System.Net.Http.Headers\ContentRangeHeaderValue.cs" />
<Compile Include="System.Net.Http.Headers\EntityTagHeaderValue.cs" />
<Compile Include="System.Net.Http.Headers\HashCodeCalculator.cs" />
<Compile Include="System.Net.Http.Headers\HeaderInfo.cs" />
<Compile Include="System.Net.Http.Headers\HttpContentHeaders.cs" />
<Compile Include="System.Net.Http.Headers\HttpHeaderKind.cs" />
<Compile Include="System.Net.Http.Headers\HttpHeaderValueCollection.cs" />
<Compile Include="System.Net.Http.Headers\HttpHeaders.cs" />
<Compile Include="System.Net.Http.Headers\HttpRequestHeaders.cs" />
<Compile Include="System.Net.Http.Headers\HttpResponseHeaders.cs" />
<Compile Include="System.Net.Http.Headers\Lexer.cs" />
<Compile Include="System.Net.Http.Headers\MediaTypeHeaderValue.cs" />
<Compile Include="System.Net.Http.Headers\MediaTypeWithQualityHeaderValue.cs" />
<Compile Include="System.Net.Http.Headers\NameValueHeaderValue.cs" />
<Compile Include="System.Net.Http.Headers\NameValueWithParametersHeaderValue.cs" />
<Compile Include="System.Net.Http.Headers\Parser.cs" />
<Compile Include="System.Net.Http.Headers\ProductHeaderValue.cs" />
<Compile Include="System.Net.Http.Headers\ProductInfoHeaderValue.cs" />
<Compile Include="System.Net.Http.Headers\QualityValue.cs" />
<Compile Include="System.Net.Http.Headers\RangeConditionHeaderValue.cs" />
<Compile Include="System.Net.Http.Headers\RangeHeaderValue.cs" />
<Compile Include="System.Net.Http.Headers\RangeItemHeaderValue.cs" />
<Compile Include="System.Net.Http.Headers\RetryConditionHeaderValue.cs" />
<Compile Include="System.Net.Http.Headers\StringWithQualityHeaderValue.cs" />
<Compile Include="System.Net.Http.Headers\TransferCodingHeaderValue.cs" />
<Compile Include="System.Net.Http.Headers\TransferCodingWithQualityHeaderValue.cs" />
<Compile Include="System.Net.Http.Headers\ViaHeaderValue.cs" />
<Compile Include="System.Net.Http.Headers\WarningHeaderValue.cs" />
<Compile Include="System.Net.Http\ByteArrayContent.cs" />
<Compile Include="System.Net.Http\ClientCertificateOption.cs" />
<Compile Include="System.Net.Http\DelegatingHandler.cs" />
<Compile Include="System.Net.Http\FormUrlEncodedContent.cs" />
<Compile Include="System.Net.Http\HttpClient.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\ByteArrayContent.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\ByteArrayHelpers.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\ClientCertificateOption.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\DelegatingHandler.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\FormUrlEncodedContent.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\AuthenticationHeaderValue.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\BaseHeaderParser.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\ByteArrayHeaderParser.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\CacheControlHeaderParser.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\CacheControlHeaderValue.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\ContentDispositionHeaderValue.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\ContentRangeHeaderValue.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\DateHeaderParser.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\EntityTagHeaderValue.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\GenericHeaderParser.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\HeaderDescriptor.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\HeaderUtilities.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\HttpContentHeaders.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\HttpGeneralHeaders.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\HttpHeaderParser.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\HttpHeaderType.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\HttpHeaderValueCollection.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\HttpHeaders.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\HttpRequestHeaders.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\HttpResponseHeaders.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\Int32NumberHeaderParser.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\Int64NumberHeaderParser.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\KnownHeader.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\KnownHeaders.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\MediaTypeHeaderParser.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\MediaTypeHeaderValue.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\MediaTypeWithQualityHeaderValue.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\NameValueHeaderValue.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\NameValueWithParametersHeaderValue.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\ObjectCollection.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\ProductHeaderValue.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\ProductInfoHeaderParser.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\ProductInfoHeaderValue.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\RangeConditionHeaderValue.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\RangeHeaderValue.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\RangeItemHeaderValue.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\RetryConditionHeaderValue.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\StringWithQualityHeaderValue.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\TimeSpanHeaderParser.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\TransferCodingHeaderParser.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\TransferCodingHeaderValue.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\TransferCodingWithQualityHeaderValue.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\UriHeaderParser.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\ViaHeaderValue.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\WarningHeaderValue.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\HttpClient.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\HttpCompletionOption.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\HttpContent.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\HttpMessageHandler.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\HttpMessageInvoker.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\HttpMethod.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\HttpParseResult.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\HttpRequestException.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\HttpRequestMessage.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\HttpResponseMessage.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\HttpRuleParser.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\HttpUtilities.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\MessageProcessingHandler.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\MultipartContent.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\MultipartFormDataContent.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\ReadOnlyMemoryContent.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\StreamContent.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\StreamToStreamCopy.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\StringContent.cs" />
<Compile Include="HttpRequestMessage.Mono.cs" />
<Compile Include="System.Net.Http\HttpClient.macios.cs" />
<Compile Include="System.Net.Http\HttpClientHandler.platformnotsupported.cs" />
<Compile Include="System.Net.Http\HttpCompletionOption.cs" />
<Compile Include="System.Net.Http\HttpContent.cs" />
<Compile Include="System.Net.Http\HttpMessageHandler.cs" />
<Compile Include="System.Net.Http\HttpMessageInvoker.cs" />
<Compile Include="System.Net.Http\HttpMethod.cs" />
<Compile Include="System.Net.Http\HttpRequestException.cs" />
<Compile Include="System.Net.Http\HttpRequestMessage.cs" />
<Compile Include="System.Net.Http\HttpResponseMessage.cs" />
<Compile Include="System.Net.Http\MessageProcessingHandler.cs" />
<Compile Include="System.Net.Http\MultipartContent.cs" />
<Compile Include="System.Net.Http\MultipartFormDataContent.cs" />
<Compile Include="System.Net.Http\StreamContent.cs" />
<Compile Include="System.Net.Http\StringContent.cs" />
<Compile Include="corefx\ReadOnlyMemoryContent.cs" />
<Compile Include="System.Net.Http\HttpClientHandler.xi.cs" />
<Compile Include="corefx\NetEventSource.Http.cs" />
</ItemGroup>
</When>
<When Condition="'$(Platform)' == 'monotouch_tv'">
<ItemGroup>
<Compile Include="..\..\..\external\corefx\src\Common\src\System\Net\Http\HttpHandlerDefaults.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\ByteArrayContent.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\ByteArrayHelpers.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\ClientCertificateOption.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\DelegatingHandler.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\DiagnosticsHandlerLoggingStrings.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\FormUrlEncodedContent.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\AuthenticationHeaderValue.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\BaseHeaderParser.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\ByteArrayHeaderParser.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\CacheControlHeaderParser.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\CacheControlHeaderValue.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\ContentDispositionHeaderValue.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\ContentRangeHeaderValue.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\DateHeaderParser.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\EntityTagHeaderValue.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\GenericHeaderParser.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\HeaderDescriptor.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\HeaderUtilities.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\HttpContentHeaders.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\HttpGeneralHeaders.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\HttpHeaderParser.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\HttpHeaderType.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\HttpHeaderValueCollection.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\HttpHeaders.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\HttpRequestHeaders.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\HttpResponseHeaders.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\Int32NumberHeaderParser.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\Int64NumberHeaderParser.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\KnownHeader.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\KnownHeaders.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\MediaTypeHeaderParser.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\MediaTypeHeaderValue.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\MediaTypeWithQualityHeaderValue.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\NameValueHeaderValue.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\NameValueWithParametersHeaderValue.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\ObjectCollection.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\ProductHeaderValue.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\ProductInfoHeaderParser.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\ProductInfoHeaderValue.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\RangeConditionHeaderValue.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\RangeHeaderValue.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\RangeItemHeaderValue.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\RetryConditionHeaderValue.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\StringWithQualityHeaderValue.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\TimeSpanHeaderParser.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\TransferCodingHeaderParser.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\TransferCodingHeaderValue.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\TransferCodingWithQualityHeaderValue.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\UriHeaderParser.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\ViaHeaderValue.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\WarningHeaderValue.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\HttpClient.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\HttpClientHandler.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\HttpCompletionOption.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\HttpContent.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\HttpMessageHandler.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\HttpMessageInvoker.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\HttpMethod.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\HttpParseResult.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\HttpRequestException.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\HttpRequestMessage.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\HttpResponseMessage.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\HttpRuleParser.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\HttpUtilities.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\MessageProcessingHandler.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\MultipartContent.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\MultipartFormDataContent.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\ReadOnlyMemoryContent.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\SocketsHttpHandler\AuthenticationHelper.Digest.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\SocketsHttpHandler\AuthenticationHelper.NtAuth.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\SocketsHttpHandler\AuthenticationHelper.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\SocketsHttpHandler\CancellationHelper.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\SocketsHttpHandler\ChunkedEncodingReadStream.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\SocketsHttpHandler\ChunkedEncodingWriteStream.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\SocketsHttpHandler\ConnectHelper.cs" />
<Compile Include="HttpClientHandler.Legacy.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\SocketsHttpHandler\ConnectionCloseReadStream.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\SocketsHttpHandler\ContentLengthReadStream.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\SocketsHttpHandler\ContentLengthWriteStream.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\SocketsHttpHandler\CookieHelper.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\SocketsHttpHandler\DecompressionHandler.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\SocketsHttpHandler\EmptyReadStream.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\SocketsHttpHandler\HttpAuthenticatedConnectionHandler.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\SocketsHttpHandler\HttpConnection.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\SocketsHttpHandler\HttpConnectionHandler.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\SocketsHttpHandler\HttpConnectionKind.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\SocketsHttpHandler\HttpConnectionPool.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\SocketsHttpHandler\HttpConnectionPoolManager.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\SocketsHttpHandler\HttpConnectionResponseContent.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\SocketsHttpHandler\HttpConnectionSettings.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\SocketsHttpHandler\HttpContentDuplexStream.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\SocketsHttpHandler\HttpContentReadStream.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\SocketsHttpHandler\HttpContentStream.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\SocketsHttpHandler\HttpContentWriteStream.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\SocketsHttpHandler\HttpEnvironmentProxy.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\SocketsHttpHandler\RawConnectionStream.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\SocketsHttpHandler\RedirectHandler.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\SocketsHttpHandler\SocketsHttpHandler.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\SocketsHttpHandler\SystemProxyInfo.Unix.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\StreamContent.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\StreamToStreamCopy.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\StringContent.cs" />
<Compile Include="HttpClientHandler.SocketsHandler.cs" />
<Compile Include="HttpClientHandler.cs" />
<Compile Include="HttpRequestMessage.Mono.cs" />
<Compile Include="IMonoHttpClientHandler.cs" />
<Compile Include="MonoWebRequestHandler.cs" />
<Compile Include="PlatformHelper.Legacy.cs" />
<Compile Include="System.Net.Http.Headers\AuthenticationHeaderValue.cs" />
<Compile Include="System.Net.Http.Headers\CacheControlHeaderValue.cs" />
<Compile Include="System.Net.Http.Headers\CollectionExtensions.cs" />
<Compile Include="System.Net.Http.Headers\CollectionParser.cs" />
<Compile Include="System.Net.Http.Headers\ContentDispositionHeaderValue.cs" />
<Compile Include="System.Net.Http.Headers\ContentRangeHeaderValue.cs" />
<Compile Include="System.Net.Http.Headers\EntityTagHeaderValue.cs" />
<Compile Include="System.Net.Http.Headers\HashCodeCalculator.cs" />
<Compile Include="System.Net.Http.Headers\HeaderInfo.cs" />
<Compile Include="System.Net.Http.Headers\HttpContentHeaders.cs" />
<Compile Include="System.Net.Http.Headers\HttpHeaderKind.cs" />
<Compile Include="System.Net.Http.Headers\HttpHeaderValueCollection.cs" />
<Compile Include="System.Net.Http.Headers\HttpHeaders.cs" />
<Compile Include="System.Net.Http.Headers\HttpRequestHeaders.cs" />
<Compile Include="System.Net.Http.Headers\HttpResponseHeaders.cs" />
<Compile Include="System.Net.Http.Headers\Lexer.cs" />
<Compile Include="System.Net.Http.Headers\MediaTypeHeaderValue.cs" />
<Compile Include="System.Net.Http.Headers\MediaTypeWithQualityHeaderValue.cs" />
<Compile Include="System.Net.Http.Headers\NameValueHeaderValue.cs" />
<Compile Include="System.Net.Http.Headers\NameValueWithParametersHeaderValue.cs" />
<Compile Include="System.Net.Http.Headers\Parser.cs" />
<Compile Include="System.Net.Http.Headers\ProductHeaderValue.cs" />
<Compile Include="System.Net.Http.Headers\ProductInfoHeaderValue.cs" />
<Compile Include="System.Net.Http.Headers\QualityValue.cs" />
<Compile Include="System.Net.Http.Headers\RangeConditionHeaderValue.cs" />
<Compile Include="System.Net.Http.Headers\RangeHeaderValue.cs" />
<Compile Include="System.Net.Http.Headers\RangeItemHeaderValue.cs" />
<Compile Include="System.Net.Http.Headers\RetryConditionHeaderValue.cs" />
<Compile Include="System.Net.Http.Headers\StringWithQualityHeaderValue.cs" />
<Compile Include="System.Net.Http.Headers\TransferCodingHeaderValue.cs" />
<Compile Include="System.Net.Http.Headers\TransferCodingWithQualityHeaderValue.cs" />
<Compile Include="System.Net.Http.Headers\ViaHeaderValue.cs" />
<Compile Include="System.Net.Http.Headers\WarningHeaderValue.cs" />
<Compile Include="System.Net.Http\ByteArrayContent.cs" />
<Compile Include="System.Net.Http\ClientCertificateOption.cs" />
<Compile Include="System.Net.Http\DelegatingHandler.cs" />
<Compile Include="System.Net.Http\FormUrlEncodedContent.cs" />
<Compile Include="System.Net.Http\HttpClient.cs" />
<Compile Include="PlatformHelper.SocketsHandler.cs" />
<Compile Include="System.Net.Http\HttpClient.macios.cs" />
<Compile Include="System.Net.Http\HttpCompletionOption.cs" />
<Compile Include="System.Net.Http\HttpContent.cs" />
<Compile Include="System.Net.Http\HttpMessageHandler.cs" />
<Compile Include="System.Net.Http\HttpMessageInvoker.cs" />
<Compile Include="System.Net.Http\HttpMethod.cs" />
<Compile Include="System.Net.Http\HttpRequestException.cs" />
<Compile Include="System.Net.Http\HttpRequestMessage.cs" />
<Compile Include="System.Net.Http\HttpResponseMessage.cs" />
<Compile Include="System.Net.Http\MessageProcessingHandler.cs" />
<Compile Include="System.Net.Http\MultipartContent.cs" />
<Compile Include="System.Net.Http\MultipartFormDataContent.cs" />
<Compile Include="System.Net.Http\StreamContent.cs" />
<Compile Include="System.Net.Http\StringContent.cs" />
<Compile Include="corefx\ReadOnlyMemoryContent.cs" />
<Compile Include="corefx\NetEventSource.Http.cs" />
<Compile Include="corefx\SocketsHttpHandler.Mono.cs" />
</ItemGroup>
</When>
<When Condition="'$(Platform)' == 'monotouch'">
<ItemGroup>
<Compile Include="..\..\..\external\corefx\src\Common\src\System\Net\Http\HttpHandlerDefaults.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\ByteArrayContent.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\ByteArrayHelpers.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\ClientCertificateOption.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\DelegatingHandler.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\DiagnosticsHandlerLoggingStrings.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\FormUrlEncodedContent.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\AuthenticationHeaderValue.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\BaseHeaderParser.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\ByteArrayHeaderParser.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\CacheControlHeaderParser.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\CacheControlHeaderValue.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\ContentDispositionHeaderValue.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\ContentRangeHeaderValue.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\DateHeaderParser.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\EntityTagHeaderValue.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\GenericHeaderParser.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\HeaderDescriptor.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\HeaderUtilities.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\HttpContentHeaders.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\HttpGeneralHeaders.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\HttpHeaderParser.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\HttpHeaderType.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\HttpHeaderValueCollection.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\HttpHeaders.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\HttpRequestHeaders.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\HttpResponseHeaders.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\Int32NumberHeaderParser.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\Int64NumberHeaderParser.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\KnownHeader.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\KnownHeaders.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\MediaTypeHeaderParser.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\MediaTypeHeaderValue.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\MediaTypeWithQualityHeaderValue.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\NameValueHeaderValue.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\NameValueWithParametersHeaderValue.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\ObjectCollection.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\ProductHeaderValue.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\ProductInfoHeaderParser.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\ProductInfoHeaderValue.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\RangeConditionHeaderValue.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\RangeHeaderValue.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\RangeItemHeaderValue.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\RetryConditionHeaderValue.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\StringWithQualityHeaderValue.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\TimeSpanHeaderParser.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\TransferCodingHeaderParser.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\TransferCodingHeaderValue.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\TransferCodingWithQualityHeaderValue.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\UriHeaderParser.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\ViaHeaderValue.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\Headers\WarningHeaderValue.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\HttpClient.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\HttpClientHandler.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\HttpCompletionOption.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\HttpContent.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\HttpMessageHandler.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\HttpMessageInvoker.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\HttpMethod.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\HttpParseResult.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\HttpRequestException.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\HttpRequestMessage.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\HttpResponseMessage.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\HttpRuleParser.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\HttpUtilities.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\MessageProcessingHandler.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\MultipartContent.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\MultipartFormDataContent.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\ReadOnlyMemoryContent.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\SocketsHttpHandler\AuthenticationHelper.Digest.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\SocketsHttpHandler\AuthenticationHelper.NtAuth.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\SocketsHttpHandler\AuthenticationHelper.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\SocketsHttpHandler\CancellationHelper.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\SocketsHttpHandler\ChunkedEncodingReadStream.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\SocketsHttpHandler\ChunkedEncodingWriteStream.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\SocketsHttpHandler\ConnectHelper.cs" />
<Compile Include="HttpClientHandler.Legacy.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\SocketsHttpHandler\ConnectionCloseReadStream.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\SocketsHttpHandler\ContentLengthReadStream.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\SocketsHttpHandler\ContentLengthWriteStream.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\SocketsHttpHandler\CookieHelper.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\SocketsHttpHandler\DecompressionHandler.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\SocketsHttpHandler\EmptyReadStream.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\SocketsHttpHandler\HttpAuthenticatedConnectionHandler.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\SocketsHttpHandler\HttpConnection.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\SocketsHttpHandler\HttpConnectionHandler.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\SocketsHttpHandler\HttpConnectionKind.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\SocketsHttpHandler\HttpConnectionPool.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\SocketsHttpHandler\HttpConnectionPoolManager.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\SocketsHttpHandler\HttpConnectionResponseContent.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\SocketsHttpHandler\HttpConnectionSettings.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\SocketsHttpHandler\HttpContentDuplexStream.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\SocketsHttpHandler\HttpContentReadStream.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\SocketsHttpHandler\HttpContentStream.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\SocketsHttpHandler\HttpContentWriteStream.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\SocketsHttpHandler\HttpEnvironmentProxy.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\SocketsHttpHandler\RawConnectionStream.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\SocketsHttpHandler\RedirectHandler.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\SocketsHttpHandler\SocketsHttpHandler.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\SocketsHttpHandler\SystemProxyInfo.Unix.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\StreamContent.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\StreamToStreamCopy.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\StringContent.cs" />
<Compile Include="HttpClientHandler.SocketsHandler.cs" />
<Compile Include="HttpClientHandler.cs" />
<Compile Include="HttpRequestMessage.Mono.cs" />
<Compile Include="IMonoHttpClientHandler.cs" />
<Compile Include="MonoWebRequestHandler.cs" />
<Compile Include="PlatformHelper.Legacy.cs" />
<Compile Include="System.Net.Http.Headers\AuthenticationHeaderValue.cs" />
<Compile Include="System.Net.Http.Headers\CacheControlHeaderValue.cs" />
<Compile Include="System.Net.Http.Headers\CollectionExtensions.cs" />
<Compile Include="System.Net.Http.Headers\CollectionParser.cs" />
<Compile Include="System.Net.Http.Headers\ContentDispositionHeaderValue.cs" />
<Compile Include="System.Net.Http.Headers\ContentRangeHeaderValue.cs" />
<Compile Include="System.Net.Http.Headers\EntityTagHeaderValue.cs" />
<Compile Include="System.Net.Http.Headers\HashCodeCalculator.cs" />
<Compile Include="System.Net.Http.Headers\HeaderInfo.cs" />
<Compile Include="System.Net.Http.Headers\HttpContentHeaders.cs" />
<Compile Include="System.Net.Http.Headers\HttpHeaderKind.cs" />
<Compile Include="System.Net.Http.Headers\HttpHeaderValueCollection.cs" />
<Compile Include="System.Net.Http.Headers\HttpHeaders.cs" />
<Compile Include="System.Net.Http.Headers\HttpRequestHeaders.cs" />
<Compile Include="System.Net.Http.Headers\HttpResponseHeaders.cs" />
<Compile Include="System.Net.Http.Headers\Lexer.cs" />
<Compile Include="System.Net.Http.Headers\MediaTypeHeaderValue.cs" />
<Compile Include="System.Net.Http.Headers\MediaTypeWithQualityHeaderValue.cs" />
<Compile Include="System.Net.Http.Headers\NameValueHeaderValue.cs" />
<Compile Include="System.Net.Http.Headers\NameValueWithParametersHeaderValue.cs" />
<Compile Include="System.Net.Http.Headers\Parser.cs" />
<Compile Include="System.Net.Http.Headers\ProductHeaderValue.cs" />
<Compile Include="System.Net.Http.Headers\ProductInfoHeaderValue.cs" />
<Compile Include="System.Net.Http.Headers\QualityValue.cs" />
<Compile Include="System.Net.Http.Headers\RangeConditionHeaderValue.cs" />
<Compile Include="System.Net.Http.Headers\RangeHeaderValue.cs" />
<Compile Include="System.Net.Http.Headers\RangeItemHeaderValue.cs" />
<Compile Include="System.Net.Http.Headers\RetryConditionHeaderValue.cs" />
<Compile Include="System.Net.Http.Headers\StringWithQualityHeaderValue.cs" />
<Compile Include="System.Net.Http.Headers\TransferCodingHeaderValue.cs" />
<Compile Include="System.Net.Http.Headers\TransferCodingWithQualityHeaderValue.cs" />
<Compile Include="System.Net.Http.Headers\ViaHeaderValue.cs" />
<Compile Include="System.Net.Http.Headers\WarningHeaderValue.cs" />
<Compile Include="System.Net.Http\ByteArrayContent.cs" />
<Compile Include="System.Net.Http\ClientCertificateOption.cs" />
<Compile Include="System.Net.Http\DelegatingHandler.cs" />
<Compile Include="System.Net.Http\FormUrlEncodedContent.cs" />
<Compile Include="System.Net.Http\HttpClient.cs" />
<Compile Include="PlatformHelper.SocketsHandler.cs" />
<Compile Include="System.Net.Http\HttpClient.macios.cs" />
<Compile Include="System.Net.Http\HttpCompletionOption.cs" />
<Compile Include="System.Net.Http\HttpContent.cs" />
<Compile Include="System.Net.Http\HttpMessageHandler.cs" />
<Compile Include="System.Net.Http\HttpMessageInvoker.cs" />
<Compile Include="System.Net.Http\HttpMethod.cs" />
<Compile Include="System.Net.Http\HttpRequestException.cs" />
<Compile Include="System.Net.Http\HttpRequestMessage.cs" />
<Compile Include="System.Net.Http\HttpResponseMessage.cs" />
<Compile Include="System.Net.Http\MessageProcessingHandler.cs" />
<Compile Include="System.Net.Http\MultipartContent.cs" />
<Compile Include="System.Net.Http\MultipartFormDataContent.cs" />
<Compile Include="System.Net.Http\StreamContent.cs" />
<Compile Include="System.Net.Http\StringContent.cs" />
<Compile Include="corefx\ReadOnlyMemoryContent.cs" />
<Compile Include="corefx\NetEventSource.Http.cs" />
<Compile Include="corefx\SocketsHttpHandler.Mono.cs" />
</ItemGroup>
</When>
<When Condition="'$(Platform)' == 'monodroid'">
@@ -1167,8 +1334,7 @@
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\StreamContent.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\StreamToStreamCopy.cs" />
<Compile Include="..\..\..\external\corefx\src\System.Net.Http\src\System\Net\Http\StringContent.cs" />
<Compile Include="..\corlib\System.Diagnostics\Debug.cs" />
<Compile Include="HttpClientHandler.SocketsHandler.cs" />
<Compile Include="HttpClientHandler.SocketsHandler.Android.cs" />
<Compile Include="HttpClientHandler.cs" />
<Compile Include="HttpRequestMessage.Mono.cs" />
<Compile Include="IMonoHttpClientHandler.cs" />
@@ -63,7 +63,7 @@ namespace System.Net.Http
return Task.FromResult<Stream> (new MemoryStream (content, offset, count));
}
protected internal override Task SerializeToStreamAsync (Stream stream, TransportContext context)
protected override Task SerializeToStreamAsync (Stream stream, TransportContext context)
{
return stream.WriteAsync (content, offset, count);
}
@@ -8,27 +8,34 @@ namespace System.Net.Http {
static HttpMessageHandler CreateDefaultHandler ()
{
Type type = Type.GetType("Android.Runtime.AndroidEnvironment, Mono.Android");
if (type == null)
return GetFallback ("Invalid Mono.Android assembly? Cannot find Android.Runtime.AndroidEnvironment");
string envvar = Environment.GetEnvironmentVariable ("XA_HTTP_CLIENT_HANDLER_TYPE")?.Trim ();
MethodInfo method = type.GetMethod ("GetHttpMessageHandler", BindingFlags.Static | BindingFlags.NonPublic);
if (method == null)
return GetFallback ("Your Xamarin.Android version does not support obtaining of the custom HttpClientHandler");
if (string.IsNullOrEmpty (envvar))
return new HttpClientHandler ();
object ret = method.Invoke (null, null);
if (ret == null)
return GetFallback ("Xamarin.Android returned no custom HttpClientHandler");
if (envvar?.StartsWith ("System.Net.Http.MonoWebRequestHandler", StringComparison.InvariantCulture) == true)
{
Type monoWrhType = Type.GetType (envvar, false);
if (monoWrhType != null)
return new HttpClientHandler ((IMonoHttpClientHandler) Activator.CreateInstance (monoWrhType));
var handler = ret as HttpMessageHandler;
if (handler == null)
return GetFallback ($"{ret?.GetType()} is not a valid HttpMessageHandler");
return handler;
}
return new HttpClientHandler ();
}
Type handlerType = Type.GetType (envvar, false);
if (handlerType == null && !envvar.Contains (", "))
{
// if assembly was not specified - look for it in Mono.Android too
// (e.g. AndroidHttpHandler is there)
handlerType = Type.GetType (envvar + ", Mono.Android", false);
}
if (handlerType == null)
return new HttpClientHandler ();
if (Activator.CreateInstance (handlerType) is HttpMessageHandler msgHandler)
return msgHandler;
static HttpMessageHandler GetFallback (string message)
{
Console.WriteLine (message + ". Defaulting to System.Net.Http.HttpClientHandler");
return new HttpClientHandler ();
}
}
@@ -44,7 +44,12 @@ namespace System.Net.Http
long buffer_size;
TimeSpan timeout;
#if !XAMARIN_MODERN && !WASM
#if XAMARIN_MODERN
public HttpClient ()
: this (CreateDefaultHandler (), true)
{
}
#elif !WASM
public HttpClient ()
: this (new HttpClientHandler (), true)
{
@@ -3,12 +3,6 @@ using System.Reflection;
namespace System.Net.Http {
public partial class HttpClient {
public HttpClient ()
: this (CreateDefaultHandler ())
{
}
static HttpMessageHandler CreateDefaultHandler ()
{
return ObjCRuntime.RuntimeOptions.GetHttpMessageHandler ();
@@ -0,0 +1,148 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Net.Security;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
using System.Threading.Tasks;
namespace System.Net.Http
{
public class HttpClientHandler : HttpMessageHandler
{
HttpMessageHandler platformHandler;
public HttpClientHandler ()
{
// Ensure GetHttpMessageHandler does not recursively call new HttpClientHandler ()
platformHandler = ObjCRuntime.RuntimeOptions.GetHttpMessageHandler ();
}
protected override void Dispose (bool disposing)
{
if (disposing) {
if (platformHandler != null) {
platformHandler.Dispose ();
platformHandler = null;
}
}
base.Dispose (disposing);
}
public virtual bool SupportsAutomaticDecompression => false;
public virtual bool SupportsProxy => false;
public virtual bool SupportsRedirectConfiguration => false;
public bool UseCookies {
get => throw new PlatformNotSupportedException ();
set => throw new PlatformNotSupportedException ();
}
public CookieContainer CookieContainer {
get => throw new PlatformNotSupportedException ();
set => throw new PlatformNotSupportedException ();
}
public ClientCertificateOption ClientCertificateOptions {
get => throw new PlatformNotSupportedException ();
set => throw new PlatformNotSupportedException ();
}
public X509CertificateCollection ClientCertificates {
get => throw new PlatformNotSupportedException ();
set => throw new PlatformNotSupportedException ();
}
public Func<HttpRequestMessage, X509Certificate2, X509Chain, SslPolicyErrors, bool> ServerCertificateCustomValidationCallback {
get => throw new PlatformNotSupportedException ();
set => throw new PlatformNotSupportedException ();
}
public bool CheckCertificateRevocationList {
get => throw new PlatformNotSupportedException ();
set => throw new PlatformNotSupportedException ();
}
public SslProtocols SslProtocols {
get => throw new PlatformNotSupportedException ();
set => throw new PlatformNotSupportedException ();
}
public DecompressionMethods AutomaticDecompression {
get => throw new PlatformNotSupportedException ();
set => throw new PlatformNotSupportedException ();
}
public bool UseProxy {
get => throw new PlatformNotSupportedException ();
set => throw new PlatformNotSupportedException ();
}
public IWebProxy Proxy {
get => throw new PlatformNotSupportedException ();
set => throw new PlatformNotSupportedException ();
}
public ICredentials DefaultProxyCredentials {
get => throw new PlatformNotSupportedException ();
set => throw new PlatformNotSupportedException ();
}
public bool PreAuthenticate {
get => throw new PlatformNotSupportedException ();
set => throw new PlatformNotSupportedException ();
}
public bool UseDefaultCredentials {
get => throw new PlatformNotSupportedException ();
set => throw new PlatformNotSupportedException ();
}
public ICredentials Credentials {
get => throw new PlatformNotSupportedException ();
set => throw new PlatformNotSupportedException ();
}
public bool AllowAutoRedirect {
get => throw new PlatformNotSupportedException ();
set => throw new PlatformNotSupportedException ();
}
public int MaxAutomaticRedirections {
get => throw new PlatformNotSupportedException ();
set => throw new PlatformNotSupportedException ();
}
public int MaxConnectionsPerServer {
get => throw new PlatformNotSupportedException ();
set => throw new PlatformNotSupportedException ();
}
public int MaxResponseHeadersLength {
get => throw new PlatformNotSupportedException ();
set => throw new PlatformNotSupportedException ();
}
public long MaxRequestContentBufferSize {
get => throw new PlatformNotSupportedException ();
set => throw new PlatformNotSupportedException ();
}
public IDictionary<string, object> Properties => throw new PlatformNotSupportedException ();
public static Func<HttpRequestMessage, X509Certificate2, X509Chain, SslPolicyErrors, bool> DangerousAcceptAnyServerCertificateValidator { get; } = delegate { return true; };
protected internal override Task<HttpResponseMessage> SendAsync (HttpRequestMessage request, CancellationToken cancellationToken)
{
if (platformHandler == null)
throw new ObjectDisposedException (GetType().ToString());
return platformHandler.SendAsync (request, cancellationToken);
}
}
}
@@ -212,7 +212,12 @@ namespace System.Net.Http
return value.Length;
}
protected internal abstract Task SerializeToStreamAsync (Stream stream, TransportContext context);
internal Task SerializeToStreamAsync_internal (Stream stream, TransportContext context)
{
return SerializeToStreamAsync (stream, context);
}
protected abstract Task SerializeToStreamAsync (Stream stream, TransportContext context);
protected internal abstract bool TryComputeLength (out long length);
}
}
Loaded 100 of 331 files, more files were not shown because too many files have changed in this diff. Show more