Compare commits

...
244 Commits
Author SHA1 Message Date
Vlad Brezae 4a50a2eb04 Fix jit regression 2019-11-18 18:13:13 +02:00
Vlad Brezae e0217d6371 Bump coreclr to include layout / gcdescr changes 2019-11-18 15:07:03 +02:00
Vlad Brezae 75eaefcff7 No critical regions on coregc
Should add them later
2019-11-18 14:49:37 +02:00
Vlad Brezae a7db40a813 Pin internal thread object
It is used in start_wrapper_internal which doesn't register its stack end. Not sure yet where sgen pins this from.
2019-11-18 14:46:35 +02:00
Vlad Brezae 05f0f319f5 Add scanning of roots 2019-11-18 14:46:35 +02:00
Vlad Brezae 48a6994de5 Add gc descriptors for objects
We store them before the imt tables, which currently always wastes imt space and is not optimized for gc access since it is far away from vtable pointer. CoreGC doesn't yet know how to scan value arrays, but it is enough for simple tests.
2019-11-18 14:46:31 +02:00
Vlad Brezae d3292aa3cf Implement api for triggering manual collections 2019-11-17 16:07:23 +02:00
Vlad Brezae 345c823407 Enable running of empty application 2019-11-17 15:55:28 +02:00
Vlad Brezae 31dd8c2ee3 Add some missing api 2019-11-15 14:51:22 +01:00
Vlad Brezae 2b0cc9644a Another fix for object allocation size
We might need to have the minimal object size represented also in the vtable base size for normal objects in the future.
2019-11-15 14:30:36 +01:00
Vlad Brezae 08253d307f Add support for gchandles 2019-11-15 00:09:27 +01:00
Vlad Brezae 6b354998f9 Switch runtime to ptr sizes gchandles
In order to align to CoreGC handles. Breaks embedding api and products.
2019-11-14 23:28:23 +01:00
Vlad Brezae a60df8f914 I'm stupid 2019-11-14 21:35:44 +01:00
Vlad Brezae 2ace29070d Add missing vtable storing 2019-11-14 20:06:00 +01:00
Vlad Brezae d31389ecd7 Finish write barriers 2019-11-14 20:02:28 +01:00
Vlad Brezae 9e912609b6 Header is not included in object sizes
Except for free object apparently ?
2019-11-14 19:17:15 +01:00
Vlad Brezae ed278e541c Add allocation 2019-11-14 18:33:38 +01:00
Vlad Brezae 97281d6f84 Make sure we have handle stack allocated
This allocation should be done outside of sgen
2019-11-14 18:33:07 +01:00
Vlad Brezae 2736860b21 Add root registering mechanism 2019-11-14 17:41:37 +01:00
Vlad Brezae 06ae29dfe0 Add encoding for root descriptors
Same as sgen. We don't need SgenArrayList since all root scanning should happen with the world stopped, so no complex descriptors can be allocated.
2019-11-14 12:21:22 +01:00
Vlad Brezae 9ebe96f923 Remove fields that are not used and don't look like they will 2019-11-14 10:26:31 +01:00
Vlad Brezae 466440920b Add support for mono object size computation, and various flags
This information is accessed through the vtable->gc_descr field. The vtable will need a new, larger real gcdescr to be used by the gc to find object references.
2019-11-13 16:53:29 +01:00
Imran Hameed 72efb8ad49 Draft STW implementation for CoreCLR GC. 2019-11-12 09:05:01 -08:00
Bernhard Urban-Forster e0229d06aa [coregc] implement mono_gc_wbarrier_object_copy_internal 2019-11-12 17:43:04 +01:00
Bernhard Urban 37f8d4e654 [configure] require CXX linker when coregc is enabled 2019-11-09 04:27:07 -08:00
Vlad Brezae e98e13652f Revert "[coregc] implement GCToEEInterface::GetFreeObjectMethodTable"
This reverts commit 893c7c7caa.
2019-11-09 14:03:40 +02:00
Vlad Brezae e887042951 Add missing api which is used on linux 2019-11-09 14:03:24 +02:00
Vlad Brezae 7914e0cc6b Add some needed configure checks for coregc on ubuntu 2019-11-09 13:22:17 +02:00
Bernhard Urban-Forster 893c7c7caa [coregc] implement GCToEEInterface::GetFreeObjectMethodTable 2019-11-09 12:05:39 +01:00
Vlad Brezae f1ce89d63f Add initial glue
Mono will invoke gc functionality through the standard mono_gc api. The glue should implement this API and invoke GC functionality through pGCHeap and pGCHandleManager. The GC will ask for runtime information through the registered GCToEEInterface.
2019-11-08 19:05:34 +02:00
Vlad Brezae 8a915e5f3a bump coreclr 2019-11-08 17:42:13 +02:00
Vlad Brezae 9e27c03294 Make coregc-mono c++ so we can interact with coregc interface
Removed HAVE_CORE_GC from coregc-mono.cpp since I'm too stupid to pass this flag to the c++ compiler.
2019-11-07 17:48:48 +02:00
Bernhard Urban-Forster 34504f021d bump coreclr 2019-11-06 21:58:51 +01:00
Bernhard Urban-Forster 8195519607 initial build support for coreclr gc 2019-11-06 21:58:51 +01:00
Bernhard Urban-Forster 7625234438 add mono/coreclr submodule with mono-coregc branch 2019-11-06 09:09:58 +01:00
Jay Krell 1e8e357831 Handles reduction -- 4 MERP functions. (#17711)
Handles reduction -- 4 MERP functions.
2019-11-06 03:56:10 +01:00
Jay Krell aa506ca1bb error_init reduction. (#17712) 2019-11-05 16:38:40 -05:00
JesperTreetopandStephen Toub 104abd7fe7 Prevent DivideByZeroException in EventCounter.ToString() (#27581)
* Prevent DivideByZeroException in EventCounter.ToString()

Maybe it should print something other than 0. Maybe "Mean" should be excluded. But at least with this it doesn't divide by zero. Ternary operator in interpolated string is not super readable; didn't know if making the code more descriptive would have performance implications.

* Update src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/EventCounter.cs

Co-Authored-By: Stephen Toub <[email protected]>

Signed-off-by: dotnet-bot <[email protected]>
2019-11-05 21:18:22 +01:00
Ryan Lucia f477bce548 [loader] Skip the full pinvoke resolution process for __Internal (#17701) 2019-11-05 14:35:00 -05:00
Tanner Gooding 3d4f44d85c Fixing the return type of the ArmBase.ReverseElementBits methods in the PlatformNotSupported file (#27672)
Signed-off-by: dotnet-bot <[email protected]>
2019-11-05 20:20:17 +01:00
Bernhard Urban-Forster 93b97d5582 [mini] Fix Coverity CID 1455161 & 1455162 (#17615)
* [mini] Fix Coverity CID 1455161 & 1455162

> Null-checking "ji" suggests that it may be null, but it has already been dereferenced on all paths leading to the check.

* do not rely on assert to guard ji-nullness.  refactor a bit
2019-11-05 19:09:32 +01:00
Johan Lorensson 6f73c2dab8 Fix MSVC intellisense for LLVM sources. (#17706) 2019-11-05 13:16:32 +01:00
Johan Lorensson 44e6226c31 Fix correct accumulated time for parallelized jobs in SGEN. (#17518)
* Fix correct accumulated time for parallelized jobs in SGEN.

Current implementation incorrectly accumulate time for scan jobs for
the follow metrics when running parallel minor GC:

time_minor_scan_major_blocks,
time_minor_scan_los,
time_major_scan_mod_union_blocks,
time_major_scan_mod_union_los

Commit fix so updates are atomic making sure values are correct in cases
where parallel minor GC is used.

* Implement 64-bit atommic add fallback in SGEN.
2019-11-05 01:57:06 -05:00
Nikolay Sivov 95743afa80 [mono] Fix ProcessExit handler argument. (#17680)
Problem was spotted with mono tracing hitting ProcessExit handler,
and crashing on first argument.
2019-11-05 01:56:43 -05:00
Egor Bogatov fdc6495a54 [netcore] Intrinsify Buffer.IsPrimitiveTypeArray (#17438)
* Improve IsPrimitive intrinsic

* Implement it for interpreter

* clean up

* clean up
2019-11-05 01:50:37 -05:00
Zoltan Varga ebb4598096 [wasm] Build the tests with --no-native-strip. (#17698) 2019-11-04 17:46:52 -05:00
Vlad Brezae b3b9960ed1 [interp] Use GetType instrinsic also on net4x (#17654)
We didn't do this because it had some issues when GetType was invoked through reflection. This issue would also be present with jit but, because jit doesn't use direct wrappers, the GetType call can't be intrinsified in that scenario. See https://github.com/mono/mono/pull/5350 for the context of the issue.
2019-11-04 12:58:38 -05:00
Dotnet-GitSync-Bot db49be3cbb Update only S.P.CoreLib for ReverseElementBits (dotnet/coreclr#27582) (#17695)
Signed-off-by: dotnet-bot <[email protected]>
2019-11-04 12:55:57 -05:00
Egor Bogatov cf8495e2f7 [netcore] Copy Array.Clear impl from CoreCLR (#17411)
* Address feedback

* fix build error

* Fix has_reference usage in object.c

* Fix fallback impl

* Rename to ArrayHasReferences

* Rename to ObjectHasReferences

* Rollback to ArrayHasReferences

* Rename to ObjectHasReference

* remove redundant is_array variable

* ObjectHasReferences can accept any object

* undo changes in Program.cs

* undo changes in Program.cs
2019-11-04 12:48:04 -05:00
Filip Navara 07fa0bd3b4 Intrinsify Activator.CreateInstance<T> for value types with no ctor (#17688)
* Intrinsify Activator.CreateInstance<T> for value types with no ctor

* Fix failed test, address feedback
2019-11-04 12:40:13 -05:00
Zoltan Varga 929a8a7fd8 [jit] Allow Unsafe.As<TFrom, TTo> on gsharedvt types. (#17692) 2019-11-04 18:14:59 +01:00
Bernhard Urban-Forster 237f210ea2 [interp] use mask instead of bool expression (#17683)
Discovered by Coverity:
```
>>>     CID 1455205:    (CONSTANT_EXPRESSION_RESULT)
>>>     The expression "flag && 2" is suspicious because it performs a
        Boolean operation on a constant other than 0 or 1.
```
2019-11-04 15:56:46 +01:00
Alexander Köplinger 49d5c4d14d [sdks] Use Xcode 11.2 stable version for iOS/Mac SDKs
As requested by the xamarin-macios team.
2019-11-04 15:27:42 +01:00
Tarek Mahmoud Sayed 6630bcc67f Fix Buggy code in TimeZoneInfo (dotnet/coreclr#27591)
Although couldn’t reach the corner case cause executing the buggy code, the fix here is done according to the similar code in TimeZoneInfo which show the intention of the change

https://github.com/dotnet/coreclr/blob/97c582975eed3260ef21e0bcc55c8c86d1e3bec8/src/System.Private.CoreLib/shared/System/TimeZoneInfo.cs#L1638
https://github.com/dotnet/coreclr/blob/97c582975eed3260ef21e0bcc55c8c86d1e3bec8/src/System.Private.CoreLib/shared/System/TimeZoneInfo.cs#L1568

Signed-off-by: dotnet-bot <[email protected]>
2019-11-04 09:59:54 +01:00
Jan Kotas f3e30a0ad0 Delete two more FCalls (dotnet/coreclr#27640)
Signed-off-by: dotnet-bot <[email protected]>
2019-11-04 08:57:17 +01:00
Jan Kotas deb3115b15 Use simple Array.Copy overload where possible (dotnet/coreclr#27641)
The simple Array.Copy overload does not come with a performance penalty anymore.

Signed-off-by: dotnet-bot <[email protected]>
2019-11-04 08:57:17 +01:00
Jan Kotas 6ecf9e87ba Consolidate *.Fast.cs (dotnet/coreclr#27644)
System.Memory OOB package that this split was originally done for does not exist anymore.

Signed-off-by: dotnet-bot <[email protected]>
2019-11-04 08:57:17 +01:00
Johan Lorensson c0e237b734 Mono NetCore Windows only build/test. (#17646)
Support for Windows Mono NetCore build/test wihtout any need for
cygwin/wsl/automake just MSBuild and MSVC. Windows build support mirror
technologies used by coreclr/aracade builds msbuild + powershell.

Windows only Mono NetCore build, makes a port of existing build.sh and
Makefile, implementing a build.ps1 and build.targets. So far full build
support + execution of corefx test suite is implemented. Other make file
rules can be added when needed.

MSVC build runtime seems to hits a couple of additional test failures
in corefx test suite that needs to be investigated further.

Building NetCore Mono on Windows can now be done without cygwin or wsl.
Build depends on regular VS install (or build tools), if xunit summary
is requested, python needs to be installed.
2019-11-04 08:55:36 +01:00
Egor Bogatov 137ffe8b7c [netcore] Improve Array.CreateInstance (#17673)
* Rewrite Array.CreateInstance

* Rewrite Array.CreateInstance

* Address feedback

* Convert the icall to NOHANDLES

* fix build errors, remove NOHANDLES

* Fix GC.KeepAlive usage

* Remove icall definition for GC.KeepAlive (it's no an icall)

* Fix failing tests (expect details in the AOORE)
2019-11-03 22:39:19 -05:00
Filip Navara 8131518bb1 [netcore] Improve default constructor lookup, (#17666)
* [netcore] Improve default constructor lookup, cache when no default constructor is found (common for struct)

* Address PR feedback
2019-11-03 18:28:32 +01:00
Levi Broderick 8700c04b02 Fix typo in Tuple.cs (dotnet/coreclr#27637)
Reported by https://github.com/dotnet/corefx/issues/42321

Signed-off-by: dotnet-bot <[email protected]>
2019-11-03 18:17:23 +01:00
Alexander Köplinger 4888c49c26 [netcore] Disable shared compilation for System.Private.CoreLib
There's a dotnet process hanging around which seems to lock the build when called from the SDKs Makefiles.
2019-11-03 15:43:40 +01:00
Alexander Köplinger 40c1cd3576 [netcore] Fix strong name key for System.Private.CoreLib
It's using the silverlight key: https://github.com/dotnet/coreclr/blob/34fe045a27e150bde7ee54e0d5f0df635922519d/src/System.Private.CoreLib/System.Private.CoreLib.csproj#L112
2019-11-03 15:43:40 +01:00
Alexander Köplinger d89b96a298 [netcore] Fix out of tree build for netcore/ folder 2019-11-03 15:43:40 +01:00
Jan Kotas ad385f98b3 Normalize trailing whitespaces (dotnet/coreclr#27626)
Normalize trailing whitespaces in frequently changing files (docs and sources)

Signed-off-by: dotnet-bot <[email protected]>
2019-11-02 16:51:03 +01:00
Bernhard Urban-Forster 62ee01b36b [interp] s/MONO_API_ERROR_INIT/error_init_reuse/g (#17650)
[interp] s/MONO_API_ERROR_INIT/error_init_reuse/g
2019-11-02 16:45:36 +01:00
Zoltan Varga 803c657b24 [jit] Call mono_class_setup_fields () before accessing field->offset. (#17667)
Fixes https://github.com/mono/mono/issues/17665.
2019-11-02 03:57:25 -04:00
Manuel de la Pena 36539ed67f [iOS] Match changes done in xamarin-macios in the SDK runtime. (#17664)
* [iOS] Match changes done in xamarin-maciosn in the SDK runtime.

* Address reviews.
2019-11-02 01:40:40 -04:00
Jay Krell 4b9dc08ac1 Move MonoError from managed wrappers to native wrappers. (#15894)
Move MonoError from managed wrappers to native wrappers.

Move MonoError from managed wrappers (ilgen) to native wrappers (C preprocessor).

Alternative to https://github.com/mono/mono/pull/15869.
Which says: Previously, we would emit a call to memset
since the struct is large (> 100 bytes). Only the error code
field needs to be initialized.
Which that PR and this PR both fix, in different ways.

In the past:
- This did not work due to a possible dependency on precise GC,
  interacting with what gets zeroed or not here.
  That is why I put it on the managed side.
  We'll see if that reproduces.
  (https://github.com/mono/mono/pull/11294/files#diff-efe0070415f3f0c0f24ed0221aa1962aR339
  external/coreclr/tests/src/CoreMangLib/cti/system/weakreference/weakreferenceisaliveb.exe.)

- Some indication that embedding API should expose MonoError
  and not set_pending_exception. This does not seem relevant
  presently, and the code seems better structured and
  more efficient this way. It can revisited if/when new public API
  is the dominant concern, or do it this way for these functions,
  and another way for actual public functions.
  (https://github.com/mono/mono/pull/11294#issuecomment-432443485)
2019-11-01 22:36:06 +01:00
Zoltan Varga e9d68e9485 [netcore] Cleanups. (#17661)
* [netcore] Remove the type_info field from RuntimeType, extend the TypeCache structure instead.

* [netcore] Remove some linker exclusions which are not needed.
2019-11-01 12:52:45 -04:00
Steve Pfister b9f185b74a Bump mono/corefx@6e65509 (#17631)
Pulls in PR https://github.com/mono/corefx/pull/368
2019-11-01 11:04:27 -04:00
Jo Shields 16d1a2e6f1 [System.Net.Http]: Bring HttpClient from CoreFX on monotouch and xammac. (#17628) 2019-11-01 10:26:08 -04:00
monojenkins a4790c892d [csproj] Update project files 2019-11-01 14:25:26 +00:00
monojenkins cc28706e58 Bump API snapshot submodule 2019-11-01 14:24:11 +00:00
Vlad Brezae 166fdf60b0 [interp] Handle remoting field access same as jit (#17641)
Doing this we avoid using slow ldrmfld in the common case of loading fields from instance methods, when we execute on the real object. We could do this also for strmfld but we need to track on the stack if the instance object is this, which is not worth the trouble.
2019-11-01 14:55:58 +02:00
Vlad Brezae 170d33c35b [interp] Optimize call path (#17623)
* [interp] Optimize void calls

By avoiding setting of retval

* [interp] Avoid computing param count for every call

* [interp] Remove wrong profiler check

From the times when interp had its own EH mechanism. We raise this event from mono_handle_exception_internal for interp.

* [interp] Remove profiling check code from method exit

We emit MINT_PROF_EXIT opcode when under profiler. Unify profiling enter/exit with tracing enter/exit since they are very similar.
2019-11-01 14:55:27 +02:00
Filip Navara 8aa3654de5 Lower min/max SSE operations on x64 (#17536)
Follow up on #17511.
2019-11-01 13:30:41 +01:00
Zoltan Varga dc8d55d446 [llvm] Fix a case where we treated the dreg of a store_membase instruction as a dreg, its actually the base reg. (#17648) 2019-11-01 03:43:42 -04:00
Steve Pfister 9566027142 Modify run-jenkins.sh to adapt wasm build for the OSX CI lane (#16785)
* Modify run-jenkins.sh to adapt wasm build for the OSX CI lane

* Round 2... Go

* Make ENABLE_WASM_DYNAMIC_RUNTIME conditional on non-OSX

* Add runtime-threads target

* Ignore 'multiple rules generate' on osx

* Fix typo

* Remove blank line

* Exclude CoreXml.Test.XLinq.FunctionalTests.EventsTests.EventsReplaceNodes.XElementReplaceNodes

* Revert "Ignore 'multiple rules generate' on osx"

This reverts commit 5010721bd710d6955aaee47aa7f49ad7845763fc.

* Check if OSX lane can follow general build flow
2019-11-01 01:44:50 -04:00
Stephen Toub 8b86349c2c Disable another static analysis rule (dotnet/corefx#42265)
Signed-off-by: dotnet-bot <[email protected]>
2019-10-31 22:23:35 +01:00
Bernhard Urban-Forster 0be756d609 [threadpool] cache processor count (#17642)
On top of https://github.com/mono/corefx/pull/369 this improves the execution time of `System.Core-xunit` on Linux/ARM64 by 2x, so from:

```console
$ make -C mcs/class/System.Core run-xunit-test
[...]
=== TEST EXECUTION SUMMARY ===
   net_4_x_System.Core_xunit-test  Total: 48774, Errors: 0, Failed: 0, Skipped: 6, Time: 131.143s
```
to
```console
$ make -C mcs/class/System.Core run-xunit-test
[...]
=== TEST EXECUTION SUMMARY ===
   net_4_x_System.Core_xunit-test  Total: 48774, Errors: 0, Failed: 0, Skipped: 6, Time: 74.636s
```

This is only relevant for non-netcore. The CoreCLR folks just recently fixed something similar (thanks to Marek sharing this link): https://github.com/dotnet/coreclr/pull/27543
2019-10-31 22:08:14 +01:00
Vlad Brezae b484979aa9 [interp] Avoid emitting MINT_SAFEPOINT for every single call (#17625) 2019-10-31 16:49:16 +01:00
Jonathan Chambers 3648cb087b Avoid caching of System.dll image and types as they may be unloaded with appdomain. (#17602) 2019-10-31 10:13:01 -04:00
Zoltan Varga dff84a2464 [wasm] Fix xunit test ninja errors. (#17639)
* [wasm] Error out on duplicate assemblies in the packager.

* [wasm] Switch search path order to avoid duplicate references to assemblies.

* Copy all xunit binaries to test_lib_dir.

* Revert "Copy all xunit binaries to test_lib_dir."

This reverts commit b15b03c16b508c04dc6121196fddca0e6d949e2f.
2019-10-31 10:10:51 -04:00
Alexander Köplinger ca72deed17 Fix build 2019-10-31 14:36:53 +01:00
Ben Adams c9b7f767a8 Don't needlessly refresh proc count (dotnet/coreclr#27543)
Signed-off-by: dotnet-bot <[email protected]>
2019-10-31 14:36:53 +01:00
Vlad Brezae 1d043a31e7 [interp] Fix interp logging (#17636)
* [interp] Don't print NOPs during cprop

They can become numerous and distracting.

* [interp] Fix mono_interp_print_code

Regressed after code_size was changed to byte count instead of short count.
2019-10-31 15:32:50 +02:00
abrevet-dev 6b3aa3a05b [WinForms] Change HotkeyPrefix default value in TabControlPainter.cs (#17579)
The default behavior on .NET Framework is _HotkeyPrefix.None_ when creating a _TabControl_ element (ampersands not escaped). 
If an user wants to override this behavior, he has to declare a _DrawItemEventHandler_ (with _DrawMode = OwnerDrawFixed_).

Fixes #16206
2019-10-31 13:48:12 +01:00
Stephen Toub a27aa7afd0 Update analyzer versions (dotnet/corefx#42249)
* Update analyzer packages to latest NuGet versions

* Fix new warnings

Signed-off-by: dotnet-bot <[email protected]>
2019-10-31 11:09:58 +01:00
Stephen Toub 6ae3360342 Clean up Uri.UnescapeDataString (dotnet/corefx#42225)
- Use string.IndexOf rather than an open-coded, unsafe loop.
- Avoid an unnecessary SequenceEquals at the end: we're only at this point if a `%` was found highlighting that something escaped was found.
- Use stack memory for smaller inputs if possible, to avoid unnecessary ArrayPool interaction
- Remove an unnecessary argument to a helper function.
- Fix ValueStringBuilder.Grow to only copy the contained data.

Signed-off-by: dotnet-bot <[email protected]>
2019-10-31 11:09:58 +01:00
Egor Chesakov a94dda5b5a Add BitwiseSelect (dotnet/coreclr#27430)
Signed-off-by: dotnet-bot <[email protected]>
2019-10-31 08:51:46 +01:00
Zoltan Varga dc76a95aa9 [runtime] Add a --enable-minimal=threads configure option to disable threading support. Use it on wasm. (#17611) 2019-10-31 01:33:50 -04:00
Zoltan Varga 5811404e55 [eglib] Assert in g_strlcpy () if src/dest is NULL, instead of printing a warning. (#17507)
Related to https://github.com/mono/mono/issues/17283.
2019-10-30 16:07:44 -04:00
Martin Baulig 578e0df42f [System.Net.Http]: Bring HttpClient from CoreFX on monotouch and xammac. 2019-10-30 15:37:25 -04:00
Jo Shields 27921fbbd0 Rearrange System.Private.CoreLib for easier monorepo integration (#17517)
* [netcore] Move corlib around to match CoreCLR directory layout better

This is a prerequisite to making a sane migration of this whole
directory from mono.git to coreclr.git
2019-10-30 15:09:06 -04:00
Thays Grazia fffb1201bd [dim][regression] Explicit interface override (#17583)
* Precedence order:
-> Override interface method in class
-> Method in class
-> DIM
2019-10-30 14:47:15 -03:00
Egor Chesakov feca5e042d Add ComputeCrc32, ComputeCrc32C (dotnet/coreclr#27421)
Signed-off-by: dotnet-bot <[email protected]>
2019-10-30 18:06:03 +01:00
Egor Chesakov 744d77ea7f Remove unsigned overloads of LeadingSignCount (dotnet/coreclr#27533)
Signed-off-by: dotnet-bot <[email protected]>
2019-10-30 18:06:03 +01:00
Martin Baulig c6f71167a1 Bump CoreFX to pickup corefx PR #367 to fix #17133. (#17590) 2019-10-30 12:32:21 -04:00
Bernhard Urban-Forster 95cad24526 [interp] fix signature mismatch between jit<>interp for string constructor (#17595)
[interp] fix signature mismatch between jit<>interp for string constructor
2019-10-30 16:36:04 +01:00
Marek Safar e4c0b50dec [System.Private.CoreLib] Remove NativeRuntimeEventSource 2019-10-30 16:07:43 +01:00
Jan Kotas c9b88b45fe Move runtime specific methods out of the runtime partition
Signed-off-by: dotnet-bot <[email protected]>
2019-10-30 16:07:43 +01:00
Jay Krell 10ac2750e2 Inline TLS access. (#17119)
Inline TLS access.

This attempt differs from the previous in that the TLS accessor functions are presented to far less code, i.e. not to main.c, so their data references do not need to be resolved so much.

See https://github.com/mono/mono/commit/bffd4c6b99213a0b154d7efac9b0581df67775e8 etc.
2019-10-30 16:06:24 +01:00
Zoltan Varga 79f5e6c288 Remove some unused icalls. (#17612) 2019-10-30 10:08:50 -04:00
Filip Navara 3d397805d4 [netcore] Report errors on Windows CI (#17616)
* [netcore] Report errors on Windows CI

* Fix Windows build
2019-10-30 14:39:47 +01:00
Zoltan Varga 2823ac5d95 [wasm] Print a useful error message instead of a signature mismatch error on missing icalls. (#17600) 2019-10-30 00:04:15 -04:00
Dotnet-GitSync-Bot 3695d8704e Mirror changes from mono/coreclr,corefx (#17609)
* Revert removal of SuppressGCTransition from SystemNative_GetTimestamp() (#27473)

* Revert removal of SuppressGCTransition from SystemNative_GetTimestamp()

* Insert GC_POLL before statement with unmanaged call.

* JIT test for insertion of GCPoll

Signed-off-by: dotnet-bot <[email protected]>

* Add file creation method that takes an ACL (dotnet/corefx#42099)

Approved API Proposal: #41614
Related change for directory creation method that takes an ACL: #41834 -merged and ported to 3.1 Prev2

Description
We have extension methods in System.IO.FileSystem.AclExtensions that let the user get and set ACLs for existing files, but we do not have methods that create files with predefined ACLs.
.NET ACL (Access Control List) support is Windows specific. This change will reside inside the System.IO.FileSystem.AccessControl assembly.

Customer impact
Before this change, customers had to create a file or filestream, then set its ACLs. This presents a few problems:

Potential security hole as files can be accessed between creation and modification.
Porting difficulties as there isn't a 1-1 API replacement
Stability issues with background processes (file filters) can prevent modifying ACLs right after creation (typically surfaces as a security exception).
This change addresses those problems by adding a new extension method that allows creating a file and ensuring the provided ACLs are set during creation.
This change is expected to be backported to 3.1.

Signed-off-by: dotnet-bot <[email protected]>
2019-10-30 00:03:47 -04:00
Zoltan Varga 9adce0b632 [wasm] Fix build problems. (#17596)
* [runtime] Add a stub for MacOsIPInterfaceProperties::ParseRouteInfo icall on non-osx platforms to fix the wasm aot build.

* [wasm] Avoid generating invalid ninja build files if an assembly is specified on the command line and its also an implicit reference.

* Put back and ifdef.

* Fix the windows build.
2019-10-30 00:03:08 -04:00
Filip Navara d49d3efd5d Temporary build fix 2019-10-29 23:34:11 +01:00
Noah Falk 67ff64a381 Support large EventSource filter args (dotnet/coreclr#27500)
1. Fix NullReferenceException. When the filter args exceeded the
hard-coded size limit GetDataFromController would return data = null.
The code previously asserted that data was not null and triggered NRE
when it was. The fix correctly null checks the value instead of
asserting and uses an empty args dictionary in this case, the same as if
filter args had been empty to begin with.

2. ETW has always limited filter args to 1024 bytes but EventPipe has no
such restriction. When using DiagnosticSourceEventSource it can be
useful to specify a larger filter arg blob. I can't do anything about
ETW's restriction but there is no need for the runtime to force
EventPipe to be equally limited. The larger size also reduces the chance
that we need to hit the fallback path above causing filter args to be
ignored.

Signed-off-by: dotnet-bot <[email protected]>
2019-10-29 23:34:11 +01:00
Jan Kotas 8a03f60897 Cleanup (dotnet/coreclr#27502)
* Delete empty FireCustomerDebugProbe FCall

* Delete duplicate C++ compiler command line options

Signed-off-by: dotnet-bot <[email protected]>
2019-10-29 23:34:11 +01:00
Elinor Fung 17cef4c4f9 Basic infrastructure for binder tracing (dotnet/coreclr#27383)
Signed-off-by: dotnet-bot <[email protected]>
2019-10-29 23:34:11 +01:00
Stephen Toub 249522036d Fix StreamReader to pass cancellation token into ReadBufferAsync (#27464)
ReadAsyncInternal is correctly passing its token into the two call sites where it delegates directly to the underlying stream, but in one place it calls through ReadBufferAsync, which is currently not defined to take a token.  Fix that, and pass the token through.

Signed-off-by: dotnet-bot <[email protected]>
2019-10-29 23:34:11 +01:00
Jan Kotas 447cb03399 Delete unnecessary abstraction from stubbed out SecurityElement (#27474)
The stubbed out SecurityElement implementation does not support extensibility that ISecurityElementFactory was designed for.

Signed-off-by: dotnet-bot <[email protected]>
2019-10-29 23:34:11 +01:00
Dan Moseley 9aeef958c6 Add path to not-absolute-path exception (dotnet/coreclr#27470)
Signed-off-by: dotnet-bot <[email protected]>
2019-10-29 23:34:11 +01:00
Filip Navara db02ebc88b Fix building portable thread pool on Windows (dotnet/corert#7849)
Signed-off-by: dotnet-bot <[email protected]>
2019-10-29 23:34:11 +01:00
Stephen Toub f26e73b49b Move PreserveDependencyAttribute to shared (dotnet/corefx#42174)
We need to use it in corelib, too.

Signed-off-by: dotnet-bot <[email protected]>
2019-10-29 23:34:11 +01:00
Bernhard Urban-Forster d274cfbacd [mini] Initial tiered compilation work (#17551)
[mini] Initial tiered compilation work

Enable it with `./autogen.sh --enable-experiment=tiered`.

Let's consider `Simple.cs`:
```csharp
using System.Runtime.CompilerServices;
using System;

public class Simple {
    public static void Main (string []args) {
        HotMethod ();
        Console.WriteLine ("cnt: " + cnt);
        HotMethod ();
        Console.WriteLine ("cnt: " + cnt);
    }

    static int cnt = 0;

    [MethodImplAttribute (MethodImplOptions.NoInlining)]
    public static void HotMethod () {
        for (int i = 0; i <= 1000; i++)
            cnt += i;
    }
}
```

```console
$ csc Simple.cs
$ MONO_LOG_LEVEL=debug MONO_LOG_MASK=tiered ./mono/mini/mono-sgen --trace=M:Simple:HotMethod --interp=-all Simple.exe
[0x10ec275c0: 0.00000 0] ENTER:i Simple:HotMethod ()()
Mono: tiered: queued Simple:HotMethod ()
[0x10ec275c0: 0.00010 0] LEAVE:i Simple:HotMethod ()(
Mono: tiered: patching 0x7fe855803224 with patch_kind=INTERP @ tier_level=0
Mono:   -> caller= Simple:Main (string[]) [{0x7fe85420df88} + 0x34 interp]  (0x7fe8558031f0 0x7fe855803258) [0x7fe85420c880 - Simple.exe]
Mono:   -> callee=Simple:HotMethod ()
Mono: tiered: patching 0x7fe8558031f2 with patch_kind=INTERP @ tier_level=0
Mono:   -> caller= Simple:Main (string[]) [{0x7fe85420df88} + 0x2 interp]  (0x7fe8558031f0 0x7fe855803258) [0x7fe85420c880 - Simple.exe]
Mono:   -> callee=Simple:HotMethod ()
cnt: 500500
[0x10ec275c0: 0.04093 0] ENTER:c Simple:HotMethod ()()
[0x10ec275c0: 0.04095 0] LEAVE:c Simple:HotMethod ()(
cnt: 1001000
```
Note the suffix after `ENTER:`
* `i` indicates it's executed by the interpreter
* `c` indicates it's a compiled method (JIT)

Another example:
```console
$ make -C mono/mini gshared.exe
$ ./mono/mini/mono-sgen --interp=-all --stats ./mono/mini/gshared.exe
Regression tests: 84 ran, 0 failed in Tests
[...]
Tiered statistics
Methods promoted                    : 68
```

It's a basic proof-of-concept for now. An incomplete list of future work items:

* Right now it only works for direct calls, need to expand it to virtual/interface calls.
* Calls of the JIT leading into the interpreter again can't be patched yet.
* Kind of related, no concept of versioning compiled methods does exist yet. The interpreter maintains its own table of "transformed" methods, however, when doing the transition from JIT->interpreter, the wrapper+interpmethod will end up in the JIT table. We need a way to have multiple JIT compilation results for the same MonoMethod exist.
* Investigate actual performance. We might have to optimize the interp<>JIT transition.
* Patching is racy. Need to make that atomic.
* All the FIXMEs in this PR



<!--
Thank you for your Pull Request!

If you are new to contributing to Mono, please try to do your best at conforming to our coding guidelines http://www.mono-project.com/community/contributing/coding-guidelines/ but don't worry if you get something wrong. One of the project members will help you to get things landed.

Does your pull request fix any of the existing issues? Please use the following format: Fixes #issue-number
-->
2019-10-29 22:36:01 +01:00
Alexander Köplinger 1340095581 [acceptance-tests] Bump mono/roslyn to get build fix
See https://github.com/mono/roslyn/commit/6bfcd4e770609a38b8523e83ce1ec943162f30bb
2019-10-29 20:27:09 +01:00
Zoltan Varga b0d966bd7a [eglib] Handle dli.dli_sname being NULL in g_module_address (). (#17592)
Should fix the warnings/assertions in g_strlcpy ().
2019-10-29 09:21:23 -04:00
Aniruddha Shastri 7f91972ded Support platform-independent newlines in line wrapping in Mono… (#17431)
* Add newLine parameter to StringCoda methods

* Update Options.cs to handle both kinds of newlines

* Add test to OptionSetTest

* Directly handle \r\n instead of using the TextWriter.NewLine
2019-10-29 13:53:41 +01:00
dotnet-maestro[bot] cddf90dda4 [master] Update dependencies from dotnet/arcade dotnet/core-setup dotnet/corefx (#17577)
* Update dependencies from https://github.com/dotnet/arcade build 20191027.3

- Microsoft.DotNet.Arcade.Sdk - 5.0.0-beta.19527.3
- Microsoft.DotNet.Helix.Sdk - 5.0.0-beta.19527.3

* Update dependencies from https://github.com/dotnet/core-setup build 20191027.2

- Microsoft.NETCore.App - 5.0.0-alpha1.19527.2

* Update dependencies from https://github.com/dotnet/corefx build 20191027.5

- Microsoft.Private.CoreFx.NETCoreApp - 5.0.0-alpha.1.19527.5

* Update CoreFX.issues.rsp

GetGCMemoryInfo was moved to GCExtendedTests in https://github.com/dotnet/corefx/commit/d6dac9e6a7875862b91139334c8ec620f599cd4d.

GetTotalAllocatedBytes and GetAllocatedBytesForCurrentThread seem to pass now.
2019-10-29 12:51:33 +01:00
Zoltan Varga e4cc70f4b5 [runtime] Implement support for SuppressGCTransitionAttribute. (#17534)
Fixes https://github.com/mono/mono/issues/17367.
2019-10-28 10:59:52 -04:00
Johan Lorensson c5edcd1ed4 Additional and adjusted logging for parallel minor GC. (#17522)
* Additional and adjusted logging for parallel minor GC.

When running parallel minor GC we currently get incorrect timing
on several loggings and counters due to work being put on thread pool
and accumulated. This commit fix so that the logging is accurate
when running with and without parallelization. In parallel mode a new
logging is also added to show the accumulated split between major and los
remset scan jobs.

The counters time_minor_scan_remsets and time_minor_scan_roots are only
updated when not running parallel GC since they are not correct when
running parallel GC.

* Fix WASM build error.
2019-10-28 15:34:42 +01:00
Alexander Köplinger 450d474684 [netcore] Fix offsets generation when cross compiling
The offsets-tool.py uses some magic to map `typename` to `<underscore>typename` for looking up runtime types.
This caused issues on netcore because we aliased it to a different name.

To fix this let's keep the `_MonoInternalThread` name instead and just fix the one location where `_MonoThread` is used.
2019-10-28 13:57:17 +01:00
Alexander Köplinger fb7b075e49 [netcore] Don't load types in aot-compiler.c that don't exist in corefx
Fixes https://github.com/mono/mono/issues/16026
2019-10-28 13:57:17 +01:00
dotnet-maestro[bot] 6f04054541 Update dependencies from dotnet/corefx (dotnet/coreclr#27431)
* Update dependencies from https://github.com/dotnet/corefx build 20191024.13

- Microsoft.NETCore.Platforms - 5.0.0-alpha.1.19524.13
- Microsoft.Private.CoreFx.NETCoreApp - 5.0.0-alpha.1.19524.13

* Update dependencies from https://github.com/dotnet/corefx build 20191024.14

- Microsoft.NETCore.Platforms - 5.0.0-alpha.1.19524.14
- Microsoft.Private.CoreFx.NETCoreApp - 5.0.0-alpha.1.19524.14

* Update dependencies from https://github.com/dotnet/corefx build 20191025.6

- Microsoft.NETCore.Platforms - 5.0.0-alpha.1.19525.6
- Microsoft.Private.CoreFx.NETCoreApp - 5.0.0-alpha.1.19525.6

* Workaround https://github.com/dotnet/coreclr/issues/27465

Signed-off-by: dotnet-bot <[email protected]>
2019-10-27 17:54:12 +01:00
Alexis Christoforides db568c6fe0 [merp] Introduce a new 'dump mode' that allows different signal behavior when dumping (#17537)
* dump_native_stacktrace should always register the sigterm handler.

Cherry picked from the https://github.com/mono/mono/pull/17310

* [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:48:40 -04:00
Aleksey Kliger (λgeek) 0e3caf00df [runtime] Unbalanced GC Unsafe transitions before shutdown (#17566)
When embedders call mono_runtime_quit or mono_jit_cleanup, we need to do unbalanced transitions to GC Unsafe, because after mini_cleanup runs we don't have GC thread states anymore and MONO_EXIT_GC_UNSAFE will assert.

* [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-26 18:45:35 -04:00
Ben Adams 2da4e54a7f Avoid mod operator when fast alternative available (dotnet/coreclr#27299)
Signed-off-by: dotnet-bot <[email protected]>
2019-10-26 19:07:15 +02:00
Jay Krell 5f3446bd12 [cxx][x86] int/ptr casts (#17570)
[cxx][x86] int/ptr casts
2019-10-26 18:26:15 +02:00
Dotnet-GitSync-Bot c5e3ca90de Mirror changes from mono/coreclr (#17571)
* Use ValueStringBuilder instead of StringBuidler{Cache} in multiple places

Signed-off-by: dotnet-bot <[email protected]>

* Avoid unnecessary allocations in Exception.ToString

Signed-off-by: dotnet-bot <[email protected]>
2019-10-26 07:48:46 -04:00
Dotnet-GitSync-Bot fec907397d Mirror changes from mono/coreclr,corert,corefx (#17565)
* Update Corelib to include Stopwatch (dotnet/coreclr#27417)

* Update Corelib to include Stopwatch

* Delete HighPerformanceCounter

Signed-off-by: dotnet-bot <[email protected]>

* Share completed Task between Task and AsyncTaskMethodBuilder (#27437)

Signed-off-by: dotnet-bot <[email protected]>
2019-10-25 21:23:46 -04:00
Caleb Cornett 1801bdad6a Add --preload-file packager option 2019-10-25 14:53:15 -05:00
Leonard 4ec9bd03e5 Fixes #17190: SerializationException on ListViewItemCount (#17195)
* Fix issue #17190: SerializationException on ListViewItemCount

ListViewGroup doesn't (always) have a serialized member "ListViewItemCount".

This patch accounts for that and also adds support for the "ItemsCount"
property that upstream [1] seems to use.

Also items should be initialized regardless of the count, otherwise we get a NPE.

[1] https://github.com/dotnet/winforms/blob/master/src/System.Windows.Forms/src/System/Windows/Forms/ListViewGroup.cs#L144
2019-10-25 19:30:08 +02:00
Kenneth Pouncey 1bd76c6069 Spacing 2019-10-25 12:19:54 -05:00
Kenneth Pouncey f1a3f3c58d Add CompileFunction to Runtime that returns a WebAssembly.Core.Function
- The code passed to `CompileFunction` is not a function definition. Instead it must create and return a function instance.
- Solves the problem of accessing `Node.js` functionality as defining a JavaScript function executes in the global space and does not get `Node.js` access.
- Returning a function instance allows the function to initialize and maintain encapsulated state.
2019-10-25 12:19:54 -05:00
Jay Krell 893486638c [cxx] Compile mini-llvm.c as C++ if configure -enable-cxx. (#17558)
[cxx] Compile mini-llvm.c as C++ if configure -enable-cxx.

This is presently catastrophic, because of `MonoJitICallId` varying between C and C++, and therefore the layout of `MonoCallInst`.

Related to:
https://github.com/mono/mono/pull/17557

https://github.com/mono/mono/pull/17445#issuecomment-546175352
2019-10-25 17:46:01 +02:00
Jay Krell 84d64d314b [jit][x86][cxx] int/ptr casts (#17382) 2019-10-25 11:34:50 -04:00
Aleksey Kliger (λgeek) d6ee245c94 [runtime] Make mono_thread_manage external only (#17554)
* [runtime] Make mono_thread_manage external only

runtime should use mono_thread_manage_internal
2019-10-25 11:28:18 -04:00
Vlad Brezae 768fefbad1 [interp] Optimize stelem (#17519)
* [interp] Optimize stelem instructions

* [intepr] Optimize stelem_ref and slowpath casts

mono_object_isinst_checked uses coop handles and is very slow. Attempt to use the straightforward mono_class_is_assignable_from_checked.

Makes stelem_ref 5x faster.
2019-10-25 16:25:08 +02:00
Egor Bogatov dc4a7f5ed7 [llvm] Use -place-safepoints in JIT mode too (#17116)
* always use -place-safepoints pass in JIT mode

* ignore loaded llvm

* remove gc.safepoint_poll after optimizations

* fix typo

* cleanup

* cleanup

* cleanup

* cleanup

* Do not emit safepoints on entry thus simple functions (without calls and loops) won't have them at all

* Undo  -spp-no-entry=true

* fix failing tests

* do not emit sp in Allocators
2019-10-25 16:10:57 +02:00
Kenneth Pouncey 6ac749ed20 [wasm][bcl] Fix System.Diagnostics.Trace.TraceError crash. (#17509)
* Fix `System.Diagnostics.Trace.TraceError` crash.

- WASM does not have access to the command line arguments through the browser so the length is 0 causing index out of range error.
- The zero index of the command line arguments is what decides the `AppName` so under WASM the AppName will be blanks.

* Address review comments

* Remove #ifdef for WASM only.

- Addresses review note.
- As per channel discussion some embedding scenarios might be the same.
2019-10-25 11:17:00 +02:00
Zoltan Varga 9d781eb78c [wasm] Propagate exit code from Main in the test runner. (#17559)
* [wasm] Propagate exit code from Main in the test runner.

* Disable some System tests as they currently fail.
2019-10-25 04:59:30 -04:00
Dotnet-GitSync-Bot 8800bfdf9c Fix build break (#17553)
Signed-off-by: dotnet-bot <[email protected]>
2019-10-24 18:30:09 -04:00
Jay Krell 4ef7c566af [cxx] externC for some icalls, for wasm and ios. (#17444)
Maybe all JIT icalls?
2019-10-24 17:59:11 -04:00
Jay Krell fc390a5f24 Include signal.h unconditionally. (#17430)
Some of the includes already were unconditional, including both on Win32 and Unix.
It is part of ANSI C 89, albeit in a reduced form compared to typical Unix (no sigaction).

Remove configuration of MSG_NOSIGNAL which has no other uses.

Preserve configuration of signal.h temporarily due to other uses of ifdef HAVE_SIGNAL_H.
 i.e. LLVM?
2019-10-24 17:44:57 -04:00
Jay Krell ec81a868a1 [cxx][x86] int/ptr casts. (#17441)
* [cxx][x86] Another int/ptr cast.

* More casts. Notice these are under
`#if defined (MONO_ARCH_USE_SIGACTION) && !defined (MONO_CROSS_COMPILE)`
which would explain them not showing up.
2019-10-24 17:37:12 -04:00
Dotnet-GitSync-Bot aea7214eb4 Optimize GC.AllocateUninitializedArray and use it in StringBuilder (#27364) (#17550)
* use GC.AllocateUninitializedArray for allocating internal char buffers

* force inlining of AllocateUninitializedArray to have no perf hit on the small buffers hot path

* insrease the threshold from 256 to 2048 bytes

* use Unsafe.As instead of a cast

* remove the size precondition from AllocateNewArray method, the called AllocateSzArray is responsible for handling negative size

Signed-off-by: dotnet-bot <[email protected]>
2019-10-24 16:02:11 -04:00
dotnet-maestro[bot] a7287bdae5 [master] Update dependencies from dotnet/arcade dotnet/core-setup dotnet/corefx (#17458)
* Update dependencies from https://github.com/dotnet/arcade build 20191018.2

- Microsoft.DotNet.Arcade.Sdk - 5.0.0-beta.19518.2
- Microsoft.DotNet.Helix.Sdk - 5.0.0-beta.19518.2

* Update dependencies from https://github.com/dotnet/core-setup build 20191021.2

- Microsoft.NETCore.App - 5.0.0-alpha1.19521.2

* Update dependencies from https://github.com/dotnet/corefx build 20191020.7

- Microsoft.Private.CoreFx.NETCoreApp - 5.0.0-alpha1.19520.7

* Update dependencies from https://github.com/dotnet/arcade build 20191023.3

- Microsoft.DotNet.Arcade.Sdk - 5.0.0-beta.19523.3
- Microsoft.DotNet.Helix.Sdk - 5.0.0-beta.19523.3

* Update dependencies from https://github.com/dotnet/core-setup build 20191023.10

- Microsoft.NETCore.App - 5.0.0-alpha1.19523.10

* Update dependencies from https://github.com/dotnet/corefx build 20191023.8

- Microsoft.Private.CoreFx.NETCoreApp - 5.0.0-alpha1.19523.8

* Disable a file system watcher test on mac

See https://github.com/mono/mono/issues/17547

* Reenable tests that were fixed
2019-10-24 21:06:46 +02:00
Bernhard Urban-Forster 25b53a642b [interp] fix code length for JitInfo (#17538)
* [interp] fix code length for JitInfo

* fix c++ build
2019-10-24 20:13:27 +02:00
Tanner Gooding 0595c0e6d7 Move down S.N.Vector APIs and expose new conversion support (#27401)
* Updating S.P.Corelib to start building Vector2/3/4 and supporting types

* Removing HAS_INTRINSICS usages from Matrix4x4

Signed-off-by: dotnet-bot <[email protected]>
2019-10-24 14:10:07 -04:00
Marek Safar 81a4a19f0a [netcore] Fix corerun build deps 2019-10-24 14:09:14 -04:00
Martin Baulig 1553889bc5 Cleaning up SslStream, MobileAuthenticatedStream and TaskToApm. (#17393)
### 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.


* Bump API snapshot submodule

* [csproj] Update project files
2019-10-24 19:42:54 +02:00
Calvin Buckley 638e2c6a86 Fix eglib on AIX/PASE (#17476)
* fix eglib on AIX/PASE

	* Work around access(2) syscall bug on PASE
	  On PASE, X_OK will always returns true. This is contrary to
	  how AIX behaves (though corresponds to documentation!). This
	  is probably because it's an upcall to the ILE version of
	  access, and that seemingly always returns true.

	* Always export the dummy function in the test suite
	  The AIX linker didn't export this properly, without using the
	  giant sledgehammer of -bexpall. Write an export file and use
	  it. This required some build system changes to expose an
	  AIX-only automake conditional.

	* Use a file that exists on PASE for tests
	  PASE doesn't use Unix-style DNS resolution, so /etc/hosts is
	  missing. Use /etc/magic, since that seems to be present.

	* Don't use /bin on AIX/PASE for tests
	  This is a symlink to /usr/bin, and it seems chdir/getcwd
	  follows links. Use /usr instead, that is unlikely to be a
	  symlink.

	* Make a note what directory we're in if we fail test_cwd

* Change manual executable access check change per Jay

* Change test on POSIXy platforms to always use root directory
2019-10-24 18:04:20 +02:00
Vlad Brezae b7ef736338 [interp] Add super instructions for field storing (#17525)
* [interp] Add also floating versions for stloc.np

* [interp] Add super instructions for stfld

When storing into a field of a local or an argument (ldloc/ldarg -> random instructions that end up pushing one value -> stfld). We add this instruction to the cprop pass because the instructions that are optimized together are not consecutive and we need the stack information to be able to access the instruction that loaded the argument / local and to make sure that the local wasn't dirtied. Alternatively we could make the super instruction pass stack aware, which we should probably do if more super instruction candidates turn out to require stack state information.

* [interp] Enable cprop for methods without locals

We do some optimizations here that don't apply to locals.

* [interp] Fix result stack type of CEE_CONV_OVF_I_UN
2019-10-24 18:05:04 +03:00
Vladimir Sadov 6fd07e4745 Moving StopWatch to src\Common\src\Corelib (dotnet/corefx#42072)
Signed-off-by: dotnet-bot <[email protected]>
2019-10-24 16:54:28 +02:00
Egor Bogatov 7952e73780 Bump to mono/corefx@fb41040
Includes upstream corefx changes that makes NTLM auth work for more scenarios.
2019-10-24 10:04:24 -04:00
Bernhard Urban-Forster 861812252a [lldb] another fix for handling interp frames (#17535)
[lldb] another fix for handling interp frames

And improved error message in case it breaks again.
2019-10-24 14:07:22 +02:00
Dotnet-GitSync-Bot 2c8e0f68c1 Add AdvSimd (LeadingZeroCount, LeadingSignCount, PopCount) (#27382) (#17532)
* AdvSimd.LeadingSignCount

* AdvSimd.LeadingZeroCount

* AdvSimd.PopCount

Signed-off-by: dotnet-bot <[email protected]>
2019-10-24 07:16:49 -04:00
Zoltan Varga 951769b279 [netcore] Add a few more missing SSE intrinsics. (#17511)
* [netcore] Add a few more missing SSE intrinsics.

* Disable some intrinsics for non-llvm.
2019-10-24 06:57:13 -04:00
Johan Lorensson fe7654f745 Adjust restart world logging level to match start major/nursery logging. (#17520)
With this change we will get the following logging on level 1:

2019-10-22 15:46:59 Start nursery collection 38898 00000205A0000000-00000205A1000000, size: 16777216
2019-10-22 15:46:59 restarted (pause time: 2728 usec, max: 689233 usec)

showing the pause time and when runtime was restared, before this fix
we will only see the start log message on level 1.
2019-10-24 04:57:55 -04:00
Filip Navara 7a15b71873 [netcore] Managed ThreadPool implementation (#17387)
* Wire up the managed side of the portable thread pool

* Remove old native thread pool code

* Fix non-netcore build

* Fix Thread.IsThreadPoolThread

* Fix MSVC builds

* Code style fix

* Make the locking primitives uninterruptible

* Revert icall changes for non-netcore

* Implement Thread.ResetThreadPoolThread

* Compile out more thread pool code for netcore

* Remove ThreadPoolBoundHandle, it is shared now

* Address PR feedback on code style
2019-10-24 04:56:25 -04:00
Dotnet-GitSync-Bot 2dfd682ac9 Enable pooling for async ValueTask/ValueTask<T> methods (#26310) (#17531)
Today `async ValueTask/ValueTask<T>` methods use builders that special-case the synchronously completing case (to just return a `default(ValueTask)` or `new ValueTask<T>(result))` but defer to the equivalent of `async Task/Task<T>` for when the operation completes asynchronously. This, however, doesn't take advantage of the fact that value tasks can wrap arbitrary `IValueTaskSource/IValueTaskSource<T>` implementations.

This commit gives `AsyncValueTaskMethodBuilder` and `AsyncValueTaskMethodBuilder<T>` the ability to use pooled `IValueTaskSource/IValueTaskSource<T>` instances, such that calls to an `async ValueTask/ValueTask<T>` method incur 0 allocations (ammortized) as long as there's a cached object available.

Currently the pooling is behind a feature flag, requiring opt-in via the DOTNET_SYSTEM_THREADING_POOLASYNCVALUETASKS environment variable (setting it to "true" or "1").  This is done for a few reasons:
- There's a breaking change here, in that while we say/document that `ValueTask/ValueTask<T>`s are more limited in what they can be used for, nothing in the implementation actually stops a `ValueTask` that was wrapping a `Task` from being used as permissively as `Task`, e.g. if you were to `await` such a `ValueTask` multiple times, it would happen to work, even though we say "never do that". This change means that anyone who was relying on such undocumented behaviors will now be broken. I think this is a reasonable thing to do in a major release, but I also want feedback and a lot of runway on it.
- Policy around pooling. Pooling is always a difficult thing to tune. Right now I've chosen a policy that limits the number of pooled objects per state machine type to an arbitrary multiple of the processor count, and that tries to strike a balance between contention and garbage by using a spin lock and if there's any contention while trying to get or return a pooled object, the cache is ignored. We will need to think hard about what policy to use here. It's also possible it could be tuned per state machine, e.g. by having an attribute that's looked up via reflection when creating the cache for a state machine, but that'll add a lot of first-access overhead to any `async ValueTask/ValueTask<T>` method.  For now, it's tunable via the `DOTNET_SYSTEM_THREADING_POOLASYNCVALUETASKSLIMIT` environment variable, which may be set to the maximum number of pooled objects desired per state machine.
- Performance validation.  Preliminary numbers show that this accomplishes its goal, having on-par throughput with the current implementation but with significantly less allocation.  That needs to be validated at scale and across a variety of workloads.
- Diagnostics.  There are several diagnostics-related abilities available for `async Task/Task<T>` methods that are not included here when using `async ValueTask/ValueTask<T>` when pooling.  We need to evaluate these (e.g. tracing) and determine which pieces need to be enabled and which we're fine omitting.

Before shipping .NET 5, we could choose to flip the polarity of the switch (making it opt-out rather than opt-in), remove the fallback altogether and just have it be always on, or revert this change, all based on experimentation and data we receive between now and then.

Signed-off-by: dotnet-bot <[email protected]>
2019-10-24 03:09:50 -04:00
Kenneth Pouncey 1b5658d590 [wasm][sdk] Bump SDK version to 0.2.2 (#17516)
* [wasm][sdk] Bump SDK version to 2.2

* Update SDK version for browser tests
2019-10-24 07:37:28 +02:00
Dotnet-GitSync-Bot e5d88dbd04 Mirror changes from mono/coreclr,corefx,corert (#17526)
* Apply SuppressGCAttribute to some SPCL functions. (dotnet/coreclr#27369)

Apply SuppressGCAttribute to some SPCL functions.

Only insert GC_POLL in first morph call.

Signed-off-by: dotnet-bot <[email protected]>

* Remove unused methods (dotnet/coreclr#27370)

Signed-off-by: dotnet-bot <[email protected]>

* Move Matrix3x2/4x4, Plan, and Quaternion to the shared CoreLib partition (#42021)

Signed-off-by: dotnet-bot <[email protected]>

* Remove Socket.InnerSafeCloseSocket (dotnet/corefx#41888)

* Remove Socket.InnerSafeCloseSocket

* Move IsInvalid checks in SetHandle function

* PR feedback

* Remove unnecessary 'SocketPal.'

* Remove SafeSocketHandle.SetHandle

Signed-off-by: dotnet-bot <[email protected]>
2019-10-23 23:01:00 -04:00
Maxim Lipnin 43a938fefb [wasm][xunit tests] Exclude some System.Data tests (#17527) 2019-10-23 22:55:56 -04:00
Thays Grazia 8fda1738f7 [debugger] Changing how debugger handles exception when hybrid suspend is enabled (#17478)
* 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-23 17:56:58 -03:00
Jay Krell 4d7adf4d2a [cxx] Put extern "C" in MONO_LLVM_INTERNAL. (#17443) 2019-10-23 15:36:35 -04:00
Johan Lorensson df30c7228c Optimize LOS for better parallelization. (#17173)
Scanning LOS list as part of minor GC didn't parallelize well since
all scan jobs needed to walk the complete LOS list. This led to touching
a lot of memory walking the list, increasing minor GC pause times
when the number of items in the LOS list increased. As an example,
stressing LOS data structure using ~600 MB's of random sized byte arrays
caused minor GC pause times between ~20ms without parallelization and ~19ms
with parallelization. NOTE, the more work each job gets (more memory to scan)
we will get a better parallelization, but still a lot of room for improvement.

Changing from a normal linked list to a SgenArrayList makes it more effective
to parallelize the scan jobs and since the list is using sequential
memory, this will also reduce cache misses for each thread iterating LOS
objects. Tagging objects in SgenArrayList with reference information reduce
cache misses dramatically in cases where objects not including references
exists on the list, since scanning jobs can skip these items without any
need to touch object memory causing cache misses.

Same scenario running with fix gives us minor GC pause times, without
parallelization in ~7ms (down from 20~ms) and with parallelization,
< 5ms (down from 19ms). NOTE, the more work each job gets (more memory to scan)
we will get a better result using parallelization, so the delta will increase
between using and not using parallelization, this scenario primarily stress
the extreme case where most LOS objects doesn't have references.

In total, this optimization reduce minor GC pause time 4x, from ~19ms when
using parallelization down to < 5ms.
2019-10-23 14:58:04 -04:00
Zoltan Varga 31b475e25a [wasm] Avoid adding an extra arg to native-to-managed wrappers. (#17508)
[wasm] Avoid adding an extra arg to native-to-managed wrappers.

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




<!--
Thank you for your Pull Request!

If you are new to contributing to Mono, please try to do your best at conforming to our coding guidelines http://www.mono-project.com/community/contributing/coding-guidelines/ but don't worry if you get something wrong. One of the project members will help you to get things landed.

Does your pull request fix any of the existing issues? Please use the following format: Fixes #issue-number
-->
2019-10-23 17:06:18 +02:00
Jay Krell 8b8b8b5010 [coop] Fix big endian problem in MonoThradStateMachine and cleanup. (#17502) 2019-10-23 10:21:54 -04:00
Filip Navara e29f8e32b7 [netcore] Add Unsafe.SkipInit intrinsic 2019-10-23 09:26:09 -04:00
Tanner Gooding e73aa17e23 Adding SkipInit to Internal.Runtime.CompilerServices.Unsafe (#27377)
* Adding SkipInit to Internal.Runtime.CompilerServices.Unsafe

* Updating the runtime to handle Unsafe.SkipInit

* Updating Decimal.DecCalc to use Unsafe.SkipInit

* Removing 'workaround for CS0165' comments

Signed-off-by: dotnet-bot <[email protected]>
2019-10-23 09:26:09 -04:00
Marius Ungureanu bed1b39c6e 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:36:46 +02:00
Kenneth Pouncey bc769e7376 [wasm] move jsvu repo back after fixes for v8 (#17514) 2019-10-23 13:34:36 +02:00
Kenneth Pouncey cdf8b839ae [wasm][binding] Add bindings for calling the entry point of an '.exe' (#17510)
- Add `mono_bind_assembly_entry_point`
- Add `mono_call_assembly_entry_point`
   - Module.mono_call_assembly_entry_point("WasmHttpStreamSync", []);

Example:

```
   Module.mono_call_assembly_entry_point("WasmHttpStreamSync", []);
```

```
   var main = Module.mono_bind_assembly_entry_point("WasmHttpStreamSync", []);
   main();
```
2019-10-23 12:43:16 +02:00
Vlad Brezae 479d2dff36 [interp] Add a new super instructions pass (#17489)
Together with a few very simple super instructions. We replace common instruction patterns to avoid indirection via interp stack, instruction dispatch overhead and to allow the compiler to generate better code for the instruction.
2019-10-23 11:57:07 +03:00
Vlad Brezae 4419dc919f [interp] Retry cprop pass if killing stloc (#17491)
When replacing a stloc with a pop, we should retry the pass, since it is very likely that we will be able to kill the instruction that pushed that value on the stack.
2019-10-23 10:39:27 +03:00
Jay Krell 92c08fab4d SetLastError slightly later, in case last error not preserved, and it is just as good. (#17483)
SetLastError slightly later, in case last error not preserved, and it is just as good.
2019-10-23 09:36:15 +02:00
Vlad Brezae 6159407846 [interp] Optimize ldelem instructions (#17494)
Remove the switch and have each instruction have its own code. Seems to improve speed on a benchmark that heavily uses ldelem by about 10-20%.
2019-10-23 10:23:49 +03:00
Zoltan Varga a2cd8b2495 [wasm] Enable threads again on CI, it seems to work again. (#17503) 2019-10-23 02:41:46 -04:00
Dotnet-GitSync-Bot b99a3e9514 Move Vector2/3/4 to the shared CoreLib partition (dotnet/corefx#42005) (#17505)
Signed-off-by: dotnet-bot <[email protected]>
2019-10-23 00:36:20 -04:00
Filip Navara 1e60703a19 [netcore] Disable debugging code in lookup_intrins (#17464) 2019-10-23 00:01:51 -04:00
Aaron Robinson 11dca2a3b8 Add documentation for SuppressGCTransition (dotnet/coreclr#27368)
Signed-off-by: dotnet-bot <[email protected]>
2019-10-22 21:30:52 -04:00
Zoltan Varga 745e5ba3c3 [wasm] Bump emscripten to 1.39.0. (#17484)
* [wasm] Bump emscripten to 1.39.0.

* [wasm] Fix threads build.
2019-10-22 20:09:07 -04:00
Larry Ewing d08713198f [wasm] fix package target 2019-10-22 18:19:19 -05:00
Larry Ewing 433d7c5004 [wasm] Bump DebugProxy to netstandard 2.1 / netcore 3.0.0 2019-10-22 18:19:19 -05:00
Larry Ewing 15d61d3f47 [wasm] work around jsvu / v8 changes 2019-10-22 15:50:18 -05:00
Tanner Gooding 69407517bc Adding back more arm intrinsics that existing before refactoring (#27153)
* Adding AdvSimd.And

* Adding AdvSimd.AndNot

* Adding AdvSimd.Or

* Adding AdvSimd.OrNot

* Adding AdvSimd.Xor

* Adding AdvSimd.Not

* Removing a trailing whitespace from AdvSimd.PlatformNotSupported.cs

* Adding AdvSimd.Subtract

Signed-off-by: dotnet-bot <[email protected]>
2019-10-22 14:48:34 -04:00
Filip Navara fdca1630dc Fix nullability error in portable thread pool (dotnet/coreclr#27366)
Signed-off-by: dotnet-bot <[email protected]>
2019-10-22 14:48:34 -04:00
Jan Kotas b98911d4f8 Delete Uap quirks from CoreLib (dotnet/coreclr#27356)
This matches cleanup done in CoreFX.

Signed-off-by: dotnet-bot <[email protected]>
2019-10-22 14:48:34 -04:00
Adam Sitnik 0663433389 remove double bound check from StringBuilder.Append(char) (#27340)
Signed-off-by: dotnet-bot <[email protected]>
2019-10-22 14:48:34 -04:00
Aleksey Kliger (λgeek) fb5b2c949d [reflection] mono_method_get_base_method on a GTD should use canonical ginst (#17475)
* [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-22 14:07:44 -04:00
Maxim Lipnin bc9b64b807 Get resource string 2019-10-22 12:13:38 -05:00
Aleksey Kliger (λgeek) ebb5846e0d [coop] Use bitfields for coop state machine state representation (#17298)
* [checked] Mask the thread state in GC thread state assertions

Because we have extra bits (like suspend count and the no_checkpoints bit) on
the thread state, we have to mask it to get the actual thread state enum value

* [coop] Use bitfields to represent coop thread state

Instead of using a 32-bit int, use bitfields and type-punning through a union
type.  We need to type pun because we need to access the entire state as a 32-bit int so that we can do atomic CAS.

* use atomic load of thread state in unwrap_thread_state.

Saw one stack trace on CI on the full coop lane where check_thread_state saw STATE_RUNNING
but with a positive suspend count.  Another thread was starting a GC a
the time.  Seems like we saw the state as runnning, but the suspend
count as if we were already in async_suspend_requested.

Thread 22 (Thread 0x7f43c03ff700 (LWP 39860)):
2019-10-22 12:14:05 -04:00
Marek Safar f34fd20fbf [System.Private.CoreLib] Remove unused methods 2019-10-22 11:28:22 -04:00
Filip Navara cf1a9e0033 Update Mono for changes in shared CoreLib partition 2019-10-22 09:46:29 -04:00
Jan Kotas 64c3405594 Cleanup memory copy helpers (dotnet/coreclr#27307)
- Merge RuntimeImports that has just a few FCalls into Buffer.
- Delete assembly implementation of memcpy for ARM. The implementation was outdated and it was used only on Windows ARM and only for fraction of memcpy callsites.
- Delete unnecessary PInvoke into SysStringLen. We have a managed equivalent on System.Runtime.InteropServices.Marshal.
- Delete large amount of redundant code between SecureString.Windows.cs and SecureString.Unix.cs, and switch SecureString to use Spans
- Fold null check into IsWin32Atom

Signed-off-by: dotnet-bot <[email protected]>
2019-10-22 09:46:29 -04:00
Jan Kotas d4a2f01064 Rewrite Buffer.BlockCopy in C# (dotnet/coreclr#27216)
* Rewrite Buffer.BlockCopy in C#

Fixes #27106

* Workaround to enable type check optimizations for BlockCopy only

Signed-off-by: dotnet-bot <[email protected]>
2019-10-22 09:46:29 -04:00
Tanner Gooding 8ea0426488 Improve codegen for IsNan (dotnet/coreclr#27272)
* Updating double.IsNaN and float.IsNaN to just `return x != x`

* Updating x86 codegen to optimize `x != x` for floating-point

* Changing the isnan optimization to only check the operand assigned registers

Signed-off-by: dotnet-bot <[email protected]>
2019-10-22 09:46:29 -04:00
Jan Kotas 113d855adb Delete ENABLE_WINRT define (dotnet/coreclr#27240)
.NET Native specific code not needed anymore

Signed-off-by: dotnet-bot <[email protected]>
2019-10-22 09:46:29 -04:00
Ben Adams d5b182c6d8 Improve Dictionary TryGetValue size/perfomance (dotnet/coreclr#27195)
* Dictionary avoid second bounds check in Get methods

* Add NullRef methods to Unsafe

Signed-off-by: dotnet-bot <[email protected]>
2019-10-22 09:46:29 -04:00
Levi Broderick 274db87e60 Fix DecoderNLS.Convert to out the correct value for 'completed' (#27210)
This is a complementary fix to https://github.com/dotnet/coreclr/issues/23020

Signed-off-by: dotnet-bot <[email protected]>
2019-10-22 09:46:29 -04:00
Del Myers 0e02fa55af Enable ETW/EventSource logging of task IDs for boxed state machines (#27115)
* Wrap MoveNext Action for TPL event tracing

Wraps the MoveNext action of the AsyncStateMachineBox in a
continuation wrapper when async causality tracing is on so that the
TPL event source can find the task that is associated with a
continuation. Does not wrap otherwise.

* Clarifying comment

* removing trailing whitespace

* code review feedback.

Makes AsyncMethodBuilderCore.TryFindContinuationTask check to
whether the target of a continuation is itself a task, as a fall-back
to checking to see if the continuation is a ContinuationWrapper

* Got rid of unnecessary null checks

Signed-off-by: dotnet-bot <[email protected]>
2019-10-22 09:46:29 -04:00
Levi Broderick 5fdea0b84b Update Utf8String to match latest prototype (dotnet/coreclr#27046)
Signed-off-by: dotnet-bot <[email protected]>
2019-10-22 09:46:29 -04:00
Stephen Toub d34ba480f9 Use stackalloc expressions with builder ctors (dotnet/coreclr#27194)
Signed-off-by: dotnet-bot <[email protected]>
2019-10-22 09:46:29 -04:00
Aaron Robinson 296b8d40cf Conditionally remove the GC transition from a P/Invoke (#26458)
* Provide mechanism to remove the GC transition from a P/Invoke.
  New Attribute: 'System.Runtime.InteropServices.SuppressGCTransitionAttribute'

Signed-off-by: dotnet-bot <[email protected]>
2019-10-22 09:46:29 -04:00
Jan Kotas cd2388fd6f Replace primitive Array fcalls with managed implementations (#27123)
Prep-work for #27106

Signed-off-by: dotnet-bot <[email protected]>
2019-10-22 09:46:29 -04:00
Filip Navara 858fc11900 Move portable thread pool to shared partition (dotnet/corert#7828)
* Move portable thread pool to shared partition

* Rename ClrThreadPool to PortableThreadPool

Signed-off-by: dotnet-bot <[email protected]>
2019-10-22 09:46:29 -04:00
Dan Moseley 565b81e26f Annotate System.Resources.ResourceWriter for nullable ref types (#41880)
* Annotate System.Resources.ResourceWriter for nullable ref types

* ref

* Mark common as nullable enable explicitly

* _resourceList

Signed-off-by: dotnet-bot <[email protected]>
2019-10-22 09:46:29 -04:00
Eriawan Kusumawardhono f731db32dd Replace tfm based constants with SDK ones (dotnet/corefx#41601)
* replace DefineConstants with SDK ones

Signed-off-by: dotnet-bot <[email protected]>
2019-10-22 09:46:29 -04:00
Zoltan Varga b96260e603 [jit] Avoid running mono_handle_native_crash () on the altstack, it can't produce a backtrace. AMD64 only for now. (#17466)
* [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 06:31:23 -04:00
Larry Ewing 20752df324 [debugger][wasm] Check the length of the vars array. Fixes #17473 2019-10-21 18:45:57 -05:00
Vlad Brezae c1461e4a2d [interp] Replace loading of static readonly fields with LDC (#17420)
LDC is faster and also allows for constant propagation. Cleanup code a little bit.
2019-10-21 23:42:24 +03:00
Jay Krell fd82c6036e No type_traits on Android.
In file included from /Users/builder/jenkins/workspace/test-mono-pull-request-amd64-osx-products-sdks-android/mono/metadata/icall.c:42:
/Users/builder/jenkins/workspace/test-mono-pull-request-amd64-osx-products-sdks-android/mono/metadata/icall-internals.h:89:10: fatal error: 'type_traits' file not found
2019-10-21 11:15:16 -05:00
Kenneth Pouncey 7e522ef179 Modify the check for streaming to also check that the browser Response object exists. 2019-10-21 10:27:05 -05:00
Jay Krell 21d7d41bfe [cxx][debug-interp] Cast once from void* to non-void*. 2019-10-21 10:22:43 -05:00
Kenneth Pouncey 2cea0a89d1 Fix host object existence check.
- The checking for the existence of the object is incorrect: Missing parens around undefined.
- Modify error description returned back to managed code.
- Fix capitalization in global object check error.
2019-10-21 10:21:16 -05:00
Thays Grazia 0d357c1347 [tests] Replace __WATCHOS__ with MONOTOUCH_WATCH (#17459)
Fixes the conditional from mono/mono#17423, we don't define __WATCHOS__ in the Mono BCL builds. We use MONOTOUCH_WATCH instead.
2019-10-21 16:20:12 +02:00
Kenneth Pouncey f07e93da2f [wasm] Make sure message pump is working when executing via NODEJS (#17453)
- Tests if we are running in ENVIRONMENT_IS_NODE
   - run message pump if we are.

- This also fixes GC not running.

- Clean up some messages.
2019-10-21 14:29:18 +02:00
Kenneth Pouncey 3ff90ac0c2 Export mono_load_runtime_and_bcl so that is available in nodejs. (#17456) 2019-10-21 13:50:57 +02:00
Jay Krell 9f50bdb2d9 [Coop] Unconvert Microsoft.Win32.NativeMethods. (#16992)
* [Coop] Unconvert ves_icall_Microsoft_Win32_NativeMethods_CloseProcess.

* [Coop] Unconvert ves_icall_Microsoft_Win32_NativeMethods_GetCurrentProcess.

* [Coop] Unconvert ves_icall_Microsoft_Win32_NativeMethods_GetCurrentProcessId.

* [Coop] Unconvert ves_icall_Microsoft_Win32_NativeMethods_GetExitCodeProcess.

* [Coop] Unconvert ves_icall_Microsoft_Win32_NativeMethods_GetPriorityClass.

* [Coop] Unconvert ves_icall_Microsoft_Win32_NativeMethods_GetProcessTimes.

* [Coop] Unconvert ves_icall_Microsoft_Win32_NativeMethods_GetProcessWorkingSetSize.

* [Coop] Unconvert ves_icall_Microsoft_Win32_NativeMethods_SetPriorityClass.

* [Coop] Unconvert ves_icall_Microsoft_Win32_NativeMethods_SetProcessWorkingSetSize.

* [Coop] Unconvert ves_icall_Microsoft_Win32_NativeMethods_TerminateProcess.

* [Coop] Unconvert ves_icall_Microsoft_Win32_NativeMethods_WaitForInputIdle.
2019-10-21 10:29:39 +02:00
Zoltan Varga 4b9226619c [interp] Small fixes. (#17442)
* [interp] Really abort in ves_real_abort ().

* [interp] Fix stack usage in TRACE_EXIT.

* [interp] Add a callback to free ThreadContext.

* Fix warnings.

* Remove an empty statement.

* Fix a double free.
2019-10-20 23:28:25 -04:00
Filip Navara 32ab6bcf00 [netcore] Implement Array.GetElementSize as intrinsic (#17437)
* [netcore] Implement Array.GetElementSize as intrinsic

* Remove unnecessary icall

* alloc_preg -> alloc_ireg

* Implement Array.GetElementSize as intrinsic in interpreter

* Address PR feedback
2019-10-20 18:39:39 -04:00
Filip Navara 67c8d0d812 [netcore] Remove unused code for Array.Unsafe[Mov/Load/Store] intrinsics 2019-10-20 12:44:52 +02:00
monojenkins 5fcd00669c [csproj] Update project files 2019-10-20 12:43:59 +02:00
monojenkins b19d9aa658 Bump API snapshot submodule 2019-10-20 12:43:59 +02:00
Zoltan Varga 1d44139d01 Bump cecil. 2019-10-20 12:43:59 +02:00
Filip Navara bc678a2c10 Use correct variable in mini_get_cpu_features (#17436)
* Use correct variable in mini_get_cpu_features

* Address PR feedback
2019-10-20 01:26:44 -04:00
Filip Navara 91f10aeee4 Remove dead code left out in #17341 (#17433) 2019-10-20 01:23:05 -04:00
Jay Krell 91413f78f3 [jit][x86][cxx] int/ptr casts in mini-x86.c (#17380) 2019-10-19 19:20:56 +02:00
Jay Krell 84f4e1dcbf Replace ICALL_DECL_EXPORT with ICALL_EXPORT. They are always the same, and it is only used once. (#17429)
Replace ICALL_DECL_EXPORT with ICALL_EXPORT. They are always the same and it is only used once.
2019-10-19 13:25:54 +02:00
Thays Grazia 105ead8707 Changing behavior of some tests in WatchOs
Needs this ifdefs because of this https://github.com/mono/mono/pull/17260. (#17423)
2019-10-18 21:23:44 -04:00
Aleksey Kliger (λgeek) d8ae32a9ee [bcl] Add null reference checks to Interlocked.Exchange<T> (#17400)
* [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
2019-10-18 19:11:22 -04:00
Jay Krell a2992d634b [cxx] [wasm] int/ptr casts esp. m2n-gen. (#17379) 2019-10-19 00:03:00 +02:00
Martin Baulig fffad7e3a8 Remove the Legacy TLS Provider. (#17391)
* `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.
2019-10-19 00:02:48 +02:00
imhameed 8836231459 Merge pull request #17279 from imhameed/bug-gh-16935-netcore-equalsall-codegen
Generate LLVM IR for OP_XEQUAL that is recognized by LLVM's vector pattern recognizers.
2019-10-18 12:47:41 -07:00
Alex Rønne Petersen d44e0e80d7 Some updates to make RISC-V buildable again. (#17408)
Some updates to make RISC-V buildable again.

Also some updates to the toolchain setup documentation.
2019-10-18 20:16:14 +02:00
Kenneth Pouncey a0c7d73d6f [sdks] add .gitignore python __pycache__ (#17414)
This will ignore the __pycache__ files generated after the tools offset build.
2019-10-18 18:08:57 +02:00
Vlad Brezae 37f628750a [profiler] Fix coverage profiler on macos (#17396)
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.
2019-10-18 16:31:47 +02:00
Jay Krell 958b9b2658 [interp][wasm] Remove more varargs to conserve stack. (#17388) 2019-10-18 10:39:05 +03:00
Egor Bogatov 4908d1f19a Enable GSS on Linux and Android (#17223) 2019-10-17 19:01:44 -04:00
Imran Hameed 7c7d406fc0 Generate LLVM IR for OP_XEQUAL that is recognized by LLVM's vector pattern recognizers. 2019-10-10 16:05:34 -07:00
723 changed files with 24715 additions and 19781 deletions

No files matched your search

+1 -1
View File
@@ -140,7 +140,7 @@ sdks/builds/llvm-*/
sdks/builds/android-*/
mcs/build/compiler-server.log
tools/offsets-tool-py/offtool/
tools/offsets-tool-py/clang/__pycache__
##############################################################################
# Arcade output directories
+4
View File
@@ -68,3 +68,7 @@
[submodule "external/illinker-test-assets"]
path = external/illinker-test-assets
url = git://github.com/mono/illinker-test-assets.git
[submodule "coreclr"]
path = external/coreclr
url = git://github.com/mono/coreclr.git
branch = mono-coregc
+1 -1
View File
@@ -21,7 +21,7 @@ endif
if ENABLE_NETCORE
update_submodules =
SUBDIRS = mk llvm mono runtime netcore netcore/corerun
SUBDIRS = mk llvm mono runtime netcore
else
update_submodules = update_submodules
SUBDIRS = $(build_with_msvc) mk po $(libgc_dir) llvm mono $(ikvm_native_dir) support data runtime scripts man samples $(tools_dir) $(build_without_msvc) $(docs_dir) acceptance-tests
+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"
+70 -21
View File
@@ -63,7 +63,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=811DFDEB-0230-4C72-91AD-A1AC9CFDA823
MONO_CORLIB_VERSION=4e2d4257-1f2b-418c-9829-dd006fe09df5
#
# Put a quoted #define in config.h.
@@ -473,6 +473,8 @@ case "$host" in
mono_cv_clang=no
;;
*-*-aix*|*-*-os400*)
AC_DEFINE(HOST_AIX,1,[Targeting the AIX and PASE platforms])
host_aix=yes
dnl IMPORTANT: For svr4 sonames on AIX, you should set
dnl `OBJECT_MODE=64` when configuring.
dnl libtool cannot generate functioning svr4 sonames on
@@ -576,6 +578,7 @@ AM_CONDITIONAL(HOST_ANDROID, test x$platform_android = xyes)
AM_CONDITIONAL(HOST_TIZEN, test x$platform_tizen = xyes)
AM_CONDITIONAL(HOST_IOS, test x$platform_ios = xyes)
AM_CONDITIONAL(HOST_WASM, test x$platform_wasm = xyes)
AM_CONDITIONAL(HOST_AIX, test x$host_aix = xyes)
if test -z "$HOST_DARWIN_TRUE"; then :
PLATFORM_AOT_SUFFIX=.dylib
@@ -702,6 +705,11 @@ case "$host" in
have_sys_zlib=no
zlib_msg="bundled zlib"
;;
# Use bundled zlib on RISC-V for now to make cross-compiling easier.
riscv*)
have_sys_zlib=no
zlib_msg="bundled zlib"
;;
*)
AC_CHECK_HEADER(zlib.h, [have_sys_zlib=yes], [have_sys_zlib=no])
if test x$have_sys_zlib = xyes; then
@@ -1352,6 +1360,7 @@ MONO_LLVM_PATH_OPTION=llvm-path="`pwd`/llvm/usr/bin"
if test x$cross_compiling = xyes -o x$enable_mcs_build = xno; then
DISABLE_MCS_DOCS_default=yes
elif test x$with_runtime_preset = xnetcore; then
# Keep in sync with winconfig.h netcore configuration.
DISABLE_MCS_DOCS_default=yes
BTLS_SUPPORTED=no
enable_mcs_build=no
@@ -1744,7 +1753,7 @@ AM_CONDITIONAL(ENABLE_STATIC_GCC_LIBS, test "x$enable_static_gcc_libs" = "xyes")
AC_ARG_ENABLE(minimal, [ --enable-minimal=LIST drop support for LIST subsystems.
LIST is a comma-separated list from: aot, profiler, decimal, pinvoke, debug, appdomains, verifier, dllmap,
reflection_emit, reflection_emit_save, large_code, logging, com, ssa, generics, attach, jit, interpreter, simd, soft_debug, perfcounters, normalization, desktop_loader, shared_perfcounters, remoting,
security, lldb, mdb, assert_messages, cleanup, sgen_marksweep_conc, sgen_split_nursery, sgen_gc_bridge, sgen_debug_helpers, sockets, gac.],
security, lldb, mdb, assert_messages, cleanup, sgen_marksweep_conc, sgen_split_nursery, sgen_gc_bridge, sgen_debug_helpers, sockets, gac, threads.],
[
for feature in `echo "$enable_minimal" | sed -e "s/,/ /g"`; do
eval "mono_feature_disable_$feature='yes'"
@@ -1961,6 +1970,11 @@ if test "x$mono_feature_disable_dllmap" = "xyes"; then
AC_MSG_NOTICE([Disabled DllMap in the loader.])
fi
if test "x$mono_feature_disable_threads" = "xyes"; then
AC_DEFINE(DISABLE_THREADS, 1, [Disable Threads])
AC_MSG_NOTICE([Disabled threading support])
fi
AC_ARG_ENABLE(executables, [ --disable-executables disable the build of the runtime executables], enable_executables=$enableval, enable_executables=yes)
AM_CONDITIONAL(DISABLE_EXECUTABLES, test x$enable_executables = xno)
@@ -2165,6 +2179,25 @@ if test x$host_win32 = xno; then
AC_SEARCH_LIBS(clock_gettime, rt)
AC_CHECK_FUNCS(clock_nanosleep)
AC_MSG_CHECKING(for _SC_AVPHYS_PAGES)
AC_TRY_COMPILE([#include <unistd.h>], [
const int foo = _SC_AVPHYS_PAGES;
],[
AC_MSG_RESULT(yes)
AC_DEFINE(HAVE__SC_AVPHYS_PAGES, 1, [_SC_AVPHYS_PAGES])
], [
AC_MSG_RESULT(no)
])
AC_MSG_CHECKING(for _SC_PHYS_PAGES)
AC_TRY_COMPILE([#include <unistd.h>], [
const int foo = _SC_PHYS_PAGES;
],[
AC_MSG_RESULT(yes)
AC_DEFINE(HAVE__SC_PHYS_PAGES, 1, [_SC_PHYS_PAGES])
], [
AC_MSG_RESULT(no)
])
dnl dynamic loader support
AC_CHECK_FUNC(dlopen, DL_LIB="",
AC_CHECK_LIB(dl, dlopen, DL_LIB="-ldl", dl_support=no)
@@ -2353,21 +2386,6 @@ if test x$host_win32 = xno; then
AC_CHECK_LIB(inotify, inotify_init, LIBS="$LIBS -linotify")
esac
dnl *******************************
dnl *** Checks for MSG_NOSIGNAL ***
dnl *******************************
AC_MSG_CHECKING(for MSG_NOSIGNAL)
AC_TRY_COMPILE([#include <sys/socket.h>], [
int f = MSG_NOSIGNAL;
], [
# Yes, we have it...
AC_MSG_RESULT(yes)
AC_DEFINE(HAVE_MSG_NOSIGNAL, 1, [Have MSG_NOSIGNAL])
], [
# We'll have to use signals
AC_MSG_RESULT(no)
])
dnl *****************************
dnl *** Checks for IPPROTO_IP ***
dnl *****************************
@@ -2776,6 +2794,7 @@ if test x$host_win32 = xno; then
AC_CHECK_FUNCS(pthread_attr_setstacksize)
AC_CHECK_FUNCS(pthread_attr_getstack pthread_attr_getstacksize)
AC_CHECK_FUNCS(pthread_get_stacksize_np pthread_get_stackaddr_np)
AC_CHECK_FUNCS(pthread_condattr_setclock)
dnl check that pthread_mutexattr_setprotocol is declared
AC_CHECK_DECLS([pthread_mutexattr_setprotocol], [], [], [[#include <pthread.h>]])
AC_CHECK_FUNCS(mincore mlock munlock)
@@ -3797,6 +3816,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)
])
@@ -3808,6 +3828,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)
])
@@ -4939,6 +4960,23 @@ fi
AC_SUBST(SGEN_DEFINES)
AM_CONDITIONAL(SUPPORT_SGEN, test x$buildsgen = xyes)
dnl
dnl CoreCLR GC checks (coregc)
dnl
COREGC_DEFINES=
AC_ARG_WITH(coregc, [ --with-coregc=yes,no CoreCLR GC, default=yes],[buildcoregc=$with_coregc],[buildcoregc=yes])
if test x$buildcoregc = xyes; then
AC_DEFINE(HAVE_MOVING_COLLECTOR, 1, [Moving collector])
COREGC_DEFINES="-DHAVE_CORE_GC --std=gnu++11"
if test "x$gc_msg" = "x"; then
gc_msg="coregc"
else
gc_msg="coregc and $gc_msg"
fi
fi
AC_SUBST(COREGC_DEFINES)
AM_CONDITIONAL(SUPPORT_COREGC, test x$buildcoregc = xyes)
jit_status="Building and using the JIT"
libsuffix=".so"
@@ -5696,7 +5734,7 @@ dnl *** feature experiments ***
dnl ***************************
dnl When adding experiments, also add to mono/utils/mono-experiments.def
AC_ARG_ENABLE(experiment, [ --enable-experiment=LIST Enable experimental fatures from the comma-separate LIST. Available experiments: null],[
AC_ARG_ENABLE(experiment, [ --enable-experiment=LIST Enable experimental fatures from the comma-separate LIST. Available experiments: null,tiered],[
if test x$enable_experiment != x ; then
AC_DEFINE(ENABLE_EXPERIMENTS,1,[Enable feature experiments])
@@ -5707,14 +5745,20 @@ AC_ARG_ENABLE(experiment, [ --enable-experiment=LIST Enable experimental f
if test "x$mono_experiment_test_enable_all" = "xyes"; then
eval "mono_experiment_test_enable_null='yes'"
eval "mono_experiment_test_enable_tiered='yes'"
true
fi
if test "x$mono_experiment_test_enable_null" = "xyes"; then
AC_DEFINE(ENABLE_EXPERIMENT_null, 1, [Enable experiment 'null'])
fi
if test "x$mono_experiment_test_enable_tiered" = "xyes"; then
AC_DEFINE(ENABLE_EXPERIMENT_TIERED, 1, [Enable experiment 'Tiered Compilation'])
fi
],[])
AM_CONDITIONAL(ENABLE_EXPERIMENT_TIERED, test x$mono_experiment_test_enable_tiered = xyes)
dnl **********************
dnl *** checked builds ***
dnl **********************
@@ -6421,7 +6465,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
@@ -6618,7 +6666,7 @@ AC_SUBST(MONO_NATIVE_PLATFORM_TYPE_UNIFIED)
# mono/mini/Makefile.am.in we have CCLD=$MONO_CXXLD and CXXLD=$MONO_CXXLD which bypasses
# automake's autodetection and lets us use the linker that we want.
#
if test "x$enable_llvm_runtime" = "xyes"; then
if test "x$enable_llvm_runtime" = "xyes" || test "x$buildcoregc" = "xyes"; then
AC_SUBST(MONO_CXXLD, [$CXX])
else
AC_SUBST(MONO_CXXLD, [$CC])
@@ -6709,6 +6757,7 @@ mono/arch/arm64/Makefile
mono/arch/mips/Makefile
mono/arch/riscv/Makefile
mono/sgen/Makefile
mono/coregc/Makefile
mono/native/platform-type.c
mono/native/platform-type-compat.c
mono/native/platform-type-unified.c
@@ -6988,7 +7037,7 @@ if test x$buildsgen = xyes; then
fi
if test "x$with_core" = "xonly"; then
if test ! -d netcore; then
if test ! -e netcore/Makefile; then
# Out of tree builds
mkdir -p netcore
echo "all:" > netcore/Makefile
+4 -3
View File
@@ -1,4 +1,5 @@
import lldb
import traceback
def print_frames(thread, num_frames, current_thread):
# TODO: Make output header similar to bt.
@@ -19,11 +20,11 @@ def print_frames(thread, num_frames, current_thread):
ipoffset = frame.EvaluateExpression('ip').GetValueAsUnsigned()
insn = ''
if ipoffset != 0:
ipoffset -= frame.EvaluateExpression('imethod->code').GetValueAsUnsigned()
insn = "\"" + frame.EvaluateExpression('mono_interp_opname [*ip]').summary[1:-1] + "\""
ipoffset -= frame.EvaluateExpression('frame->imethod->code').GetValueAsUnsigned()
insn = "\"" + frame.EvaluateExpression('mono_interp_opname (*ip)').summary[1:-1] + "\""
var = '%s @ %d %s || %s' % (methoddesc, ipoffset, insn, frame)
except Exception as e:
print("DBG: execfail:" + str(e))
traceback.print_exc()
elif function_name == "mono_interp_transform_method":
try:
s = 'runtime_method->method'
+61 -39
View File
@@ -2,36 +2,58 @@
These are some useful links and notes pertaining to the RISC-V port of Mono.
## Useful RISC-V documents
## Useful RISC-V documentation
* [RISC-V User-Level ISA Specification](https://riscv.org/specifications/)
* [RISC-V Privileged ISA Specification](https://riscv.org/specifications/privileged-isa/)
* [RISC-V Debug Specification Standard](https://github.com/riscv/riscv-debug-spec/blob/master/riscv-debug-spec.pdf)
* [RISC-V Assembly Programmer's Manual](https://github.com/riscv/riscv-asm-manual/blob/master/riscv-asm.md)
* [RISC-V ELF psABI Specification](https://github.com/riscv/riscv-elf-psabi-doc/blob/master/riscv-elf.md)
* [RISC-V User-Level ISA Specification](https://riscv.org/specifications)
* [RISC-V Privileged ISA Specification](https://riscv.org/specifications/privileged-isa)
* [RISC-V Debug Specification](https://riscv.org/specifications/debug-specification)
* [RISC-V ELF psABI Specification](https://github.com/riscv/riscv-elf-psabi-doc)
* [RISC-V C API Specification](https://github.com/riscv/riscv-c-api-doc)
* [RISC-V Toolchain Conventions](https://github.com/riscv/riscv-toolchain-conventions)
* [RISC-V Assembly Programmer's Manual](https://github.com/riscv/riscv-asm-manual)
## Useful RISC-V repositories
* [RISC-V Organization](https://github.com/riscv)
* [RISC-V Linux](https://github.com/riscv/riscv-linux)
* [RISC-V LLD](https://github.com/riscv/riscv-lld)
* [RISC-V GNU Toolchain](https://github.com/riscv/riscv-gnu-toolchain)
* [RISC-V Binutils](https://github.com/riscv/riscv-binutils-gdb)
* [RISC-V GCC](https://github.com/riscv/riscv-gcc)
* [RISC-V Glibc](https://github.com/riscv/riscv-glibc)
* [RISC-V Newlib](https://github.com/riscv/riscv-newlib)
* [RISC-V Tools](https://github.com/riscv/riscv-tools)
* [RISC-V GNU Toolchain](https://github.com/riscv/riscv-gnu-toolchain)
* [RISC-V Binutils](https://github.com/riscv/riscv-binutils-gdb)
* [RISC-V GCC](https://github.com/riscv/riscv-gcc)
* [RISC-V Glibc](https://github.com/riscv/riscv-glibc)
* [RISC-V Newlib](https://github.com/riscv/riscv-newlib)
* [RISC-V QEMU](https://github.com/riscv/riscv-qemu)
* [RISC-V Opcodes](https://github.com/riscv/riscv-opcodes)
* [RISC-V Tests](https://github.com/riscv/riscv-tests)
* [lowRISC Organization](https://github.com/lowrisc)
* [RISC-V LLVM](https://github.com/lowrisc/riscv-llvm)
## Setting up a cross environment
Setting up a cross environment with a Linux toolchain and QEMU is quite easy.
### Debian/Ubuntu packages
First, add these to your `.bashrc` (or some other script that you run):
This is the most painless way of getting a functional toolchain installed. Note
that these packages may not be available on older distributions; this is tested
on Ubuntu 19.04.
First, add this to your `$HOME/.bashrc` (or some other script that you run):
```bash
export RISCV=$HOME/riscv
export PATH=$RISCV/bin:$PATH
export QEMU_LD_PREFIX=/usr/riscv64-linux-gnu
```
Next, install the toolchain packages like so:
```bash
# apt install autoconf automake binutils-riscv64-linux-gnu build-essential gcc-riscv64-linux-gnu gdb-multiarch g++-riscv64-linux-gnu libtool qemu qemu-system-misc qemu-user qemu-user-static
```
You will now have all the toolchain binaries in `/usr/bin`.
### Building manually
This approach may be somewhat unstable since you will be using the latest
versions of the various parts of the toolchain.
First, add this to your `$HOME/.bashrc` (or some other script that you run):
```bash
export RISCV=$HOME/riscv
@@ -39,47 +61,42 @@ export PATH=$RISCV/bin:$PATH
export QEMU_LD_PREFIX=$RISCV/sysroot
```
Install some dependencies needed to build the toolchain:
Next, install some dependencies needed to build the toolchain:
```console
# apt install autoconf automake autotools-dev curl libmpc-dev libmpfr-dev libgmp-dev libusb-1.0-0-dev gawk build-essential bison flex texinfo gperf libtool patchutils bc zlib1g-dev device-tree-compiler pkg-config libexpat-dev libglib2.0-dev libpixman-1-dev
# apt install autoconf automake autotools-dev curl libmpc-dev libmpfr-dev libgmp-dev gawk build-essential bison flex texinfo gperf libtool patchutils bc zlib1g-dev libexpat-dev
```
Now you can build the toolchain:
Finally, build the toolchain:
```console
$ git clone --recursive [email protected]:riscv/riscv-tools.git
$ cd riscv-tools
$ ./build.sh
$ git clone --recursive [email protected]:riscv/riscv-gnu-toolchain.git
$ cd riscv-gnu-toolchain
$ ./configure --prefix=$RISCV --enable-multilib
$ ./configure --prefix=$RISCV --enable-linux --enable-multilib --with-arch=rv64imafdc --with-abi=lp64d
$ make linux
$ cd ../..
$ git clone --recursive [email protected]:riscv/riscv-qemu.git
$ cd riscv-qemu
$ mkdir build
$ cd build
$ ../configure --prefix=$RISCV --disable-werror
$ make
$ make install
```
This will install the built toolchain binaries in `$RISCV/bin`.
## Building Mono with a cross toolchain
Building Mono is quite straightforward:
```console
$ ./autogen.sh --prefix=$RISCV/sysroot --host=riscv64-unknown-linux-gnu
$ ./autogen.sh --prefix=$RISCV/sysroot --host=riscv64-linux-gnu
$ make
$ make install
```
(Note: You may need to use `--host=riscv64-unknown-linux-gnu` instead if you
built the toolchain manually.)
You can set `CFLAGS` as appropriate to change the RISC-V options, such as which
standard extensions and ABI to use. For example, to use the 64-bit soft float
ABI:
```console
$ CFLAGS="-mabi=lp64" ./autogen.sh --prefix=$RISCV/sysroot --host=riscv64-unknown-linux-gnu
$ CFLAGS="-mabi=lp64" ./autogen.sh --prefix=$RISCV/sysroot --host=riscv64-linux-gnu
```
Note that, since this is a cross build, the `mcs` directory won't be built. You
@@ -89,19 +106,24 @@ Mono and copy them into `$RISCV/sysroot`.
You can run Mono with QEMU like this:
```console
$ qemu-riscv64 $RISCV/sysroot/bin/mono hello.exe
$ qemu-riscv64 ./mono/mini/mono hello.exe
```
## Debugging
Debugging with GDB currently requires a manually built toolchain.
It can be done like so:
```console
$ qemu-riscv64 -g 12345 ./mono/mini/mono-sgen --interp basic.exe &
$ riscv64-unknown-elf-gdb -ex 'target remote localhost:12345' -ex 'b main' -ex 'c' ./mono/mini/mono-sgen
$ qemu-riscv64 -g 12345 ./mono/mini/mono --interp basic.exe &
$ riscv64-unknown-elf-gdb -ex 'target remote localhost:12345' -ex 'b main' -ex 'c' ./mono/mini/mono
```
## Things to be done
In no particular order:
Things that need to be done beyond the basic 64-bit port, in no particular
order:
* Complete the soft float port.
* Complete the 32-bit port.
+8 -8
View File
@@ -1,13 +1,13 @@
<?xml version="1.0" encoding="utf-8"?>
<Dependencies>
<ProductDependencies>
<Dependency Name="Microsoft.Private.CoreFx.NETCoreApp" Version="5.0.0-alpha1.19515.14">
<Dependency Name="Microsoft.Private.CoreFx.NETCoreApp" Version="5.0.0-alpha.1.19527.5">
<Uri>https://github.com/dotnet/corefx</Uri>
<Sha>b50bd0a1d3f0326fc717706cb5c5950ab41cf437</Sha>
<Sha>17c14aa2b50cfb5920d03ea8835c9a4932b5359c</Sha>
</Dependency>
<Dependency Name="Microsoft.NETCore.App" Version="5.0.0-alpha1.19515.17">
<Dependency Name="Microsoft.NETCore.App" Version="5.0.0-alpha1.19527.2">
<Uri>https://github.com/dotnet/core-setup</Uri>
<Sha>0ceceab994c8e965bf50b11fc230dc2ea67aa1ec</Sha>
<Sha>b3749864f47f38599a94070497225c665124fe82</Sha>
</Dependency>
<Dependency Name="Microsoft.Net.Compilers" Version="3.3.1-beta4-19476-06">
<Uri>https://github.com/dotnet/roslyn</Uri>
@@ -15,13 +15,13 @@
</Dependency>
</ProductDependencies>
<ToolsetDependencies>
<Dependency Name="Microsoft.DotNet.Arcade.Sdk" Version="5.0.0-beta.19511.1">
<Dependency Name="Microsoft.DotNet.Arcade.Sdk" Version="5.0.0-beta.19527.3">
<Uri>https://github.com/dotnet/arcade</Uri>
<Sha>64a027b8d8b3a8e8e214bb00da02148335e3bd92</Sha>
<Sha>5ce0aaed2f8df9cd2fe0221a426c021efe37f655</Sha>
</Dependency>
<Dependency Name="Microsoft.DotNet.Helix.Sdk" Version="5.0.0-beta.19511.1">
<Dependency Name="Microsoft.DotNet.Helix.Sdk" Version="5.0.0-beta.19527.3">
<Uri>https://github.com/dotnet/arcade</Uri>
<Sha>64a027b8d8b3a8e8e214bb00da02148335e3bd92</Sha>
<Sha>5ce0aaed2f8df9cd2fe0221a426c021efe37f655</Sha>
</Dependency>
</ToolsetDependencies>
</Dependencies>
+2 -2
View File
@@ -5,9 +5,9 @@
<PreReleaseVersionLabel>prerelease</PreReleaseVersionLabel>
<!-- Package versions -->
<!-- corefx -->
<MicrosoftPrivateCoreFxNETCoreAppVersion>5.0.0-alpha1.19515.14</MicrosoftPrivateCoreFxNETCoreAppVersion>
<MicrosoftPrivateCoreFxNETCoreAppVersion>5.0.0-alpha.1.19527.5</MicrosoftPrivateCoreFxNETCoreAppVersion>
<!-- core-setup -->
<MicrosoftNETCoreAppVersion>5.0.0-alpha1.19515.17</MicrosoftNETCoreAppVersion>
<MicrosoftNETCoreAppVersion>5.0.0-alpha1.19527.2</MicrosoftNETCoreAppVersion>
<!-- roslyn -->
<MicrosoftNetCompilersVersion>3.3.1-beta4-19476-06</MicrosoftNetCompilersVersion>
</PropertyGroup>
+11 -1
View File
@@ -18,6 +18,7 @@ Param(
[switch] $sign,
[switch] $pack,
[switch] $publish,
[switch] $clean,
[switch][Alias('bl')]$binaryLog,
[switch] $ci,
[switch] $prepareMachine,
@@ -48,6 +49,7 @@ function Print-Usage() {
Write-Host " -pack Package build outputs into NuGet packages and Willow components"
Write-Host " -sign Sign build outputs"
Write-Host " -publish Publish artifacts (e.g. symbols)"
Write-Host " -clean Clean the solution"
Write-Host ""
Write-Host "Advanced settings:"
@@ -112,6 +114,14 @@ function Build {
@properties
}
if ($clean) {
if(Test-Path $ArtifactsDir) {
Remove-Item -Recurse -Force $ArtifactsDir
Write-Host "Artifacts directory deleted."
}
exit 0
}
try {
if ($help -or (($null -ne $properties) -and ($properties.Contains("/help") -or $properties.Contains("/?")))) {
Print-Usage
@@ -123,7 +133,7 @@ try {
$nodeReuse = $false
}
if (($restore) -and ($null -eq $env:DisableNativeToolsetInstalls)) {
if ($restore) {
InitializeNativeTools
}
+14 -1
View File
@@ -26,6 +26,7 @@ usage()
echo " --pack Package build outputs into NuGet packages and Willow components"
echo " --sign Sign build outputs"
echo " --publish Publish artifacts (e.g. symbols)"
echo " --clean Clean the solution"
echo ""
echo "Advanced settings:"
@@ -62,6 +63,7 @@ publish=false
sign=false
public=false
ci=false
clean=false
warn_as_error=true
node_reuse=true
@@ -82,6 +84,9 @@ while [[ $# > 0 ]]; do
usage
exit 0
;;
-clean)
clean=true
;;
-configuration|-c)
configuration=$2
shift
@@ -196,7 +201,15 @@ function Build {
ExitWithExitCode 0
}
if [[ "$restore" == true && -z ${DisableNativeToolsetInstalls:-} ]]; then
if [[ "$clean" == true ]]; then
if [ -d "$artifacts_dir" ]; then
rm -rf $artifacts_dir
echo "Artifacts directory deleted."
fi
exit 0
fi
if [[ "$restore" == true ]]; then
InitializeNativeTools
fi
+7 -2
View File
@@ -1,7 +1,8 @@
param (
$darcVersion = $null,
$versionEndpoint = "https://maestro-prod.westus2.cloudapp.azure.com/api/assets/darc-version?api-version=2019-01-16",
$verbosity = "m"
$verbosity = "m",
$toolpath = $null
)
. $PSScriptRoot\tools.ps1
@@ -27,7 +28,11 @@ function InstallDarcCli ($darcVersion) {
Write-Host "Installing Darc CLI version $darcVersion..."
Write-Host "You may need to restart your command window if this is the first dotnet tool you have installed."
& "$dotnet" tool install $darcCliPackageName --version $darcVersion --add-source "$arcadeServicesSource" -v $verbosity -g
if (-not $toolpath) {
& "$dotnet" tool install $darcCliPackageName --version $darcVersion --add-source "$arcadeServicesSource" -v $verbosity -g
}else {
& "$dotnet" tool install $darcCliPackageName --version $darcVersion --add-source "$arcadeServicesSource" -v $verbosity --tool-path "$toolpath"
}
}
InstallDarcCli $darcVersion
+19 -5
View File
@@ -20,6 +20,10 @@ while [[ $# > 0 ]]; do
verbosity=$2
shift
;;
--toolpath)
toolpath=$2
shift
;;
*)
echo "Invalid argument: $1"
usage
@@ -52,17 +56,27 @@ function InstallDarcCli {
InitializeDotNetCli
local dotnet_root=$_InitializeDotNetCli
local uninstall_command=`$dotnet_root/dotnet tool uninstall $darc_cli_package_name -g`
local tool_list=$($dotnet_root/dotnet tool list -g)
if [[ $tool_list = *$darc_cli_package_name* ]]; then
echo $($dotnet_root/dotnet tool uninstall $darc_cli_package_name -g)
if [ -z "$toolpath" ]; then
local tool_list=$($dotnet_root/dotnet tool list -g)
if [[ $tool_list = *$darc_cli_package_name* ]]; then
echo $($dotnet_root/dotnet tool uninstall $darc_cli_package_name -g)
fi
else
local tool_list=$($dotnet_root/dotnet tool list --tool-path "$toolpath")
if [[ $tool_list = *$darc_cli_package_name* ]]; then
echo $($dotnet_root/dotnet tool uninstall $darc_cli_package_name --tool-path "$toolpath")
fi
fi
local arcadeServicesSource="https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-tools/nuget/v3/index.json"
echo "Installing Darc CLI version $darcVersion..."
echo "You may need to restart your command shell if this is the first dotnet tool you have installed."
echo $($dotnet_root/dotnet tool install $darc_cli_package_name --version $darcVersion --add-source "$arcadeServicesSource" -v $verbosity -g)
if [ -z "$toolpath" ]; then
echo $($dotnet_root/dotnet tool install $darc_cli_package_name --version $darcVersion --add-source "$arcadeServicesSource" -v $verbosity -g)
else
echo $($dotnet_root/dotnet tool install $darc_cli_package_name --version $darcVersion --add-source "$arcadeServicesSource" -v $verbosity --tool-path "$toolpath")
fi
}
InstallDarcCli
+4 -2
View File
@@ -3,7 +3,9 @@ Param(
[string] $verbosity = "minimal",
[string] $architecture = "",
[string] $version = "Latest",
[string] $runtime = "dotnet"
[string] $runtime = "dotnet",
[string] $RuntimeSourceFeed = "",
[string] $RuntimeSourceFeedKey = ""
)
. $PSScriptRoot\tools.ps1
@@ -15,7 +17,7 @@ try {
if ($architecture -and $architecture.Trim() -eq "x86") {
$installdir = Join-Path $installdir "x86"
}
InstallDotNet $installdir $version $architecture $runtime $true
InstallDotNet $installdir $version $architecture $runtime $true -RuntimeSourceFeed $RuntimeSourceFeed -RuntimeSourceFeedKey $RuntimeSourceFeedKey
}
catch {
Write-Host $_
+41 -2
View File
@@ -14,6 +14,8 @@ scriptroot="$( cd -P "$( dirname "$source" )" && pwd )"
version='Latest'
architecture=''
runtime='dotnet'
runtimeSourceFeed=''
runtimeSourceFeedKey=''
while [[ $# > 0 ]]; do
opt="$(echo "$1" | awk '{print tolower($0)}')"
case "$opt" in
@@ -29,18 +31,55 @@ while [[ $# > 0 ]]; do
shift
runtime="$1"
;;
-runtimesourcefeed)
shift
runtimeSourceFeed="$1"
;;
-runtimesourcefeedkey)
shift
runtimeSourceFeedKey="$1"
;;
*)
echo "Invalid argument: $1"
usage
exit 1
;;
esac
shift
done
# Use uname to determine what the CPU is.
cpuname=$(uname -p)
# Some Linux platforms report unknown for platform, but the arch for machine.
if [[ "$cpuname" == "unknown" ]]; then
cpuname=$(uname -m)
fi
case $cpuname in
aarch64)
buildarch=arm64
;;
amd64|x86_64)
buildarch=x64
;;
armv7l)
buildarch=arm
;;
i686)
buildarch=x86
;;
*)
echo "Unknown CPU $cpuname detected, treating it as x64"
buildarch=x64
;;
esac
. "$scriptroot/tools.sh"
dotnetRoot="$repo_root/.dotnet"
InstallDotNet $dotnetRoot $version "$architecture" $runtime true || {
if [[ $architecture != "" ]] && [[ $architecture != $buildarch ]]; then
dotnetRoot="$dotnetRoot/$architecture"
fi
InstallDotNet $dotnetRoot $version "$architecture" $runtime true $runtimeSourceFeed $runtimeSourceFeedKey || {
local exit_code=$?
echo "dotnet-install.sh failed (exit code '$exit_code')." >&2
ExitWithExitCode $exit_code
@@ -8,6 +8,7 @@ Set-StrictMode -Version 2.0
# scripts don't necessarily execute in the same agent that run the
# build.ps1/sh script this variable isn't automatically set.
$ci = $true
$disableConfigureToolsetImport = "true"
. $PSScriptRoot\..\tools.ps1
function Create-MaestroApiRequestHeaders([string]$ContentType = "application/json") {
@@ -1,26 +0,0 @@
param(
[Parameter(Mandatory=$true)][string] $ReleaseConfigsPath # Full path to ReleaseConfigs.txt asset
)
. $PSScriptRoot\post-build-utils.ps1
try {
$Content = Get-Content $ReleaseConfigsPath
$BarId = $Content | Select -Index 0
$Channels = ""
$Content | Select -Index 1 | ForEach-Object { $Channels += "$_ ," }
$IsStableBuild = $Content | Select -Index 2
Write-PipelineSetVariable -Name 'BARBuildId' -Value $BarId
Write-PipelineSetVariable -Name 'InitialChannels' -Value "$Channels"
Write-PipelineSetVariable -Name 'IsStableBuild' -Value $IsStableBuild
}
catch {
Write-Host $_
Write-Host $_.Exception
Write-Host $_.ScriptStackTrace
ExitWithExitCode 1
}
@@ -10,6 +10,7 @@ Set-StrictMode -Version 2.0
# scripts don't necessarily execute in the same agent that run the
# build.ps1/sh script this variable isn't automatically set.
$ci = $true
$disableConfigureToolsetImport = "true"
. $PSScriptRoot\..\tools.ps1
$ExtractPackage = {
@@ -83,7 +83,6 @@ stages:
/p:InstallersAzureAccountKey=$(dotnetcli-storage-key)
/p:ChecksumsTargetStaticFeed=$(ChecksumsBlobFeedUrl)
/p:ChecksumsAzureAccountKey=$(dotnetclichecksums-storage-key)
/p:PublishToAzureDevOpsNuGetFeeds=true
/p:AzureDevOpsStaticShippingFeed='https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-tools/nuget/v3/index.json'
/p:AzureDevOpsStaticShippingFeedKey='$(dn-bot-dnceng-artifact-feeds-rw)'
/p:AzureDevOpsStaticTransportFeed='https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-tools/nuget/v3/index.json'
@@ -118,7 +118,6 @@ stages:
/p:InstallersAzureAccountKey=$(dotnetcli-storage-key)
/p:ChecksumsTargetStaticFeed=$(ChecksumsBlobFeedUrl)
/p:ChecksumsAzureAccountKey=$(dotnetclichecksums-storage-key)
/p:PublishToAzureDevOpsNuGetFeeds=true
/p:AzureDevOpsStaticShippingFeed='https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-tools/nuget/v3/index.json'
/p:AzureDevOpsStaticShippingFeedKey='$(dn-bot-dnceng-artifact-feeds-rw)'
/p:AzureDevOpsStaticTransportFeed='https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-tools/nuget/v3/index.json'
@@ -118,7 +118,6 @@ stages:
/p:InstallersAzureAccountKey=$(dotnetcli-storage-key)
/p:ChecksumsTargetStaticFeed=$(ChecksumsBlobFeedUrl)
/p:ChecksumsAzureAccountKey=$(dotnetclichecksums-storage-key)
/p:PublishToAzureDevOpsNuGetFeeds=true
/p:AzureDevOpsStaticShippingFeed='https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet3.1/nuget/v3/index.json'
/p:AzureDevOpsStaticShippingFeedKey='$(dn-bot-dnceng-artifact-feeds-rw)'
/p:AzureDevOpsStaticTransportFeed='https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet3.1-transport/nuget/v3/index.json'
@@ -118,7 +118,6 @@ stages:
/p:InstallersAzureAccountKey=$(dotnetcli-storage-key)
/p:ChecksumsTargetStaticFeed=$(ChecksumsBlobFeedUrl)
/p:ChecksumsAzureAccountKey=$(dotnetclichecksums-storage-key)
/p:PublishToAzureDevOpsNuGetFeeds=true
/p:AzureDevOpsStaticShippingFeed='https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet5/nuget/v3/index.json'
/p:AzureDevOpsStaticShippingFeedKey='$(dn-bot-dnceng-artifact-feeds-rw)'
/p:AzureDevOpsStaticTransportFeed='https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet5-transport/nuget/v3/index.json'
@@ -128,7 +128,6 @@ stages:
/p:ChecksumsAzureAccountKey=$(InternalChecksumsBlobFeedKey)
/p:InstallersTargetStaticFeed=$(InternalInstallersBlobFeedUrl)
/p:InstallersAzureAccountKey=$(InternalInstallersBlobFeedKey)
/p:PublishToAzureDevOpsNuGetFeeds=true
/p:AzureDevOpsStaticShippingFeed='https://pkgs.dev.azure.com/dnceng/_packaging/dotnet3-internal/nuget/v3/index.json'
/p:AzureDevOpsStaticShippingFeedKey='$(dn-bot-dnceng-artifact-feeds-rw)'
/p:AzureDevOpsStaticTransportFeed='https://pkgs.dev.azure.com/dnceng/_packaging/dotnet3-internal-transport/nuget/v3/index.json'
@@ -118,7 +118,6 @@ stages:
/p:InstallersAzureAccountKey=$(dotnetcli-storage-key)
/p:ChecksumsTargetStaticFeed=$(ChecksumsBlobFeedUrl)
/p:ChecksumsAzureAccountKey=$(dotnetclichecksums-storage-key)
/p:PublishToAzureDevOpsNuGetFeeds=true
/p:AzureDevOpsStaticShippingFeed='https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet3/nuget/v3/index.json'
/p:AzureDevOpsStaticShippingFeedKey='$(dn-bot-dnceng-artifact-feeds-rw)'
/p:AzureDevOpsStaticTransportFeed='https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet3-transport/nuget/v3/index.json'
@@ -118,7 +118,6 @@ stages:
/p:InstallersAzureAccountKey=$(dotnetcli-storage-key)
/p:ChecksumsTargetStaticFeed=$(ChecksumsBlobFeedUrl)
/p:ChecksumsAzureAccountKey=$(dotnetclichecksums-storage-key)
/p:PublishToAzureDevOpsNuGetFeeds=true
/p:AzureDevOpsStaticShippingFeed='https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet3.1/nuget/v3/index.json'
/p:AzureDevOpsStaticShippingFeedKey='$(dn-bot-dnceng-artifact-feeds-rw)'
/p:AzureDevOpsStaticTransportFeed='https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet3.1-transport/nuget/v3/index.json'
@@ -118,7 +118,6 @@ stages:
/p:InstallersAzureAccountKey=$(dotnetcli-storage-key)
/p:ChecksumsTargetStaticFeed=$(ChecksumsBlobFeedUrl)
/p:ChecksumsAzureAccountKey=$(dotnetclichecksums-storage-key)
/p:PublishToAzureDevOpsNuGetFeeds=true
/p:AzureDevOpsStaticShippingFeed='https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-tools/nuget/v3/index.json'
/p:AzureDevOpsStaticShippingFeedKey='$(dn-bot-dnceng-artifact-feeds-rw)'
/p:AzureDevOpsStaticTransportFeed='https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-tools/nuget/v3/index.json'
@@ -83,7 +83,6 @@ stages:
/p:InstallersAzureAccountKey=$(dotnetcli-storage-key)
/p:ChecksumsTargetStaticFeed=$(ChecksumsBlobFeedUrl)
/p:ChecksumsAzureAccountKey=$(dotnetclichecksums-storage-key)
/p:PublishToAzureDevOpsNuGetFeeds=true
/p:AzureDevOpsStaticShippingFeed='https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-tools/nuget/v3/index.json'
/p:AzureDevOpsStaticShippingFeedKey='$(dn-bot-dnceng-artifact-feeds-rw)'
/p:AzureDevOpsStaticTransportFeed='https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-tools/nuget/v3/index.json'
@@ -4,6 +4,8 @@ jobs:
pool:
vmImage: 'windows-2019'
steps:
- checkout: none
- task: DownloadBuildArtifacts@0
displayName: Download Release Configs
inputs:
@@ -14,5 +16,25 @@ jobs:
name: setReleaseVars
displayName: Set Release Configs Vars
inputs:
filePath: $(Build.SourcesDirectory)/eng/common/post-build/setup-maestro-vars.ps1
arguments: -ReleaseConfigsPath '$(Build.StagingDirectory)/ReleaseConfigs/ReleaseConfigs.txt'
targetType: inline
script: |
try {
$Content = Get-Content $(Build.StagingDirectory)/ReleaseConfigs/ReleaseConfigs.txt
$BarId = $Content | Select -Index 0
$Channels = ""
$Content | Select -Index 1 | ForEach-Object { $Channels += "$_ ," }
$IsStableBuild = $Content | Select -Index 2
Write-Host "##vso[task.setvariable variable=BARBuildId;isOutput=true]$BarId"
Write-Host "##vso[task.setvariable variable=InitialChannels;isOutput=true]$Channels"
Write-Host "##vso[task.setvariable variable=IsStableBuild;isOutput=true]$IsStableBuild"
}
catch {
Write-Host $_
Write-Host $_.Exception
Write-Host $_.ScriptStackTrace
exit 1
}
@@ -23,6 +23,7 @@ parameters:
EnableXUnitReporter: false # optional -- true enables XUnit result reporting to Mission Control
WaitForWorkItemCompletion: true # optional -- true will make the task wait until work items have been completed and fail the build if work items fail. False is "fire and forget."
IsExternal: false # [DEPRECATED] -- doesn't do anything, jobs are external if HelixAccessToken is empty and Creator is set
HelixBaseUri: 'https://helix.dot.net/' # optional -- sets the Helix API base URI (allows targeting int)
Creator: '' # optional -- if the build is external, use this to specify who is sending the job
DisplayNamePrefix: 'Run Tests' # optional -- rename the beginning of the displayName of the steps in AzDO
condition: succeeded() # optional -- condition for step to execute; defaults to succeeded()
@@ -55,6 +56,7 @@ steps:
DotNetCliVersion: ${{ parameters.DotNetCliVersion }}
EnableXUnitReporter: ${{ parameters.EnableXUnitReporter }}
WaitForWorkItemCompletion: ${{ parameters.WaitForWorkItemCompletion }}
HelixBaseUri: ${{ parameters.HelixBaseUri }}
Creator: ${{ parameters.Creator }}
SYSTEM_ACCESSTOKEN: $(System.AccessToken)
condition: and(${{ parameters.condition }}, eq(variables['Agent.Os'], 'Windows_NT'))
@@ -85,6 +87,7 @@ steps:
DotNetCliVersion: ${{ parameters.DotNetCliVersion }}
EnableXUnitReporter: ${{ parameters.EnableXUnitReporter }}
WaitForWorkItemCompletion: ${{ parameters.WaitForWorkItemCompletion }}
HelixBaseUri: ${{ parameters.HelixBaseUri }}
Creator: ${{ parameters.Creator }}
SYSTEM_ACCESSTOKEN: $(System.AccessToken)
condition: and(${{ parameters.condition }}, ne(variables['Agent.Os'], 'Windows_NT'))
+41 -8
View File
@@ -49,6 +49,8 @@
# An array of names of processes to stop on script exit if prepareMachine is true.
$processesToStopOnExit = if (Test-Path variable:processesToStopOnExit) { $processesToStopOnExit } else { @("msbuild", "dotnet", "vbcscompiler") }
$disableConfigureToolsetImport = if (Test-Path variable:disableConfigureToolsetImport) { $disableConfigureToolsetImport } else { $null }
set-strictmode -version 2.0
$ErrorActionPreference = "Stop"
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
@@ -175,7 +177,14 @@ function InstallDotNetSdk([string] $dotnetRoot, [string] $version, [string] $arc
InstallDotNet $dotnetRoot $version $architecture
}
function InstallDotNet([string] $dotnetRoot, [string] $version, [string] $architecture = "", [string] $runtime = "", [bool] $skipNonVersionedFiles = $false) {
function InstallDotNet([string] $dotnetRoot,
[string] $version,
[string] $architecture = "",
[string] $runtime = "",
[bool] $skipNonVersionedFiles = $false,
[string] $runtimeSourceFeed = "",
[string] $runtimeSourceFeedKey = "") {
$installScript = GetDotNetInstallScript $dotnetRoot
$installParameters = @{
Version = $version
@@ -186,10 +195,29 @@ function InstallDotNet([string] $dotnetRoot, [string] $version, [string] $archit
if ($runtime) { $installParameters.Runtime = $runtime }
if ($skipNonVersionedFiles) { $installParameters.SkipNonVersionedFiles = $skipNonVersionedFiles }
& $installScript @installParameters
if ($lastExitCode -ne 0) {
Write-PipelineTelemetryError -Category "InitializeToolset" -Message "Failed to install dotnet cli (exit code '$lastExitCode')."
ExitWithExitCode $lastExitCode
try {
& $installScript @installParameters
}
catch {
Write-PipelineTelemetryError -Category "InitializeToolset" -Message "Failed to install dotnet runtime '$runtime' from public location."
# Only the runtime can be installed from a custom [private] location.
if ($runtime -and ($runtimeSourceFeed -or $runtimeSourceFeedKey)) {
if ($runtimeSourceFeed) { $installParameters.AzureFeed = $runtimeSourceFeed }
if ($runtimeSourceFeedKey) {
$decodedBytes = [System.Convert]::FromBase64String($runtimeSourceFeedKey)
$decodedString = [System.Text.Encoding]::UTF8.GetString($decodedBytes)
$installParameters.FeedCredential = $decodedString
}
try {
& $installScript @installParameters
}
catch {
Write-PipelineTelemetryError -Category "InitializeToolset" -Message "Failed to install dotnet runtime '$runtime' from custom location '$runtimeSourceFeed'."
}
}
}
}
@@ -418,6 +446,9 @@ function GetSdkTaskProject([string]$taskName) {
}
function InitializeNativeTools() {
if ($env:DisableNativeToolsetInstalls) {
return
}
if (Get-Member -InputObject $GlobalJson -Name "native-tools") {
$nativeArgs= @{}
if ($ci) {
@@ -602,7 +633,9 @@ Write-PipelineSetVariable -Name 'TMP' -Value $TempDir
# Import custom tools configuration, if present in the repo.
# Note: Import in global scope so that the script set top-level variables without qualification.
$configureToolsetScript = Join-Path $EngRoot "configure-toolset.ps1"
if (Test-Path $configureToolsetScript) {
. $configureToolsetScript
if (!$disableConfigureToolsetImport) {
$configureToolsetScript = Join-Path $EngRoot "configure-toolset.ps1"
if (Test-Path $configureToolsetScript) {
. $configureToolsetScript
}
}
+31 -5
View File
@@ -4,6 +4,7 @@
# CI mode - set to true on CI server for PR validation build or official build.
ci=${ci:-false}
disable_configure_toolset_import=${disable_configure_toolset_import:-null}
# Set to true to use the pipelines logger which will enable Azure logging output.
# https://github.com/Microsoft/azure-pipelines-tasks/blob/master/docs/authoring/commands.md
@@ -191,8 +192,28 @@ function InstallDotNet {
fi
bash "$install_script" --version $version --install-dir "$root" $archArg $runtimeArg $skipNonVersionedFilesArg || {
local exit_code=$?
Write-PipelineTelemetryError -category 'InitializeToolset' "Failed to install dotnet SDK (exit code '$exit_code')."
ExitWithExitCode $exit_code
Write-PipelineTelemetryError -category 'InitializeToolset' "Failed to install dotnet SDK from public location (exit code '$exit_code')."
if [[ -n "$runtimeArg" ]]; then
local runtimeSourceFeed=''
if [[ -n "${6:-}" ]]; then
runtimeSourceFeed="--azure-feed $6"
fi
local runtimeSourceFeedKey=''
if [[ -n "${7:-}" ]]; then
decodedFeedKey=`echo $7 | base64 --decode`
runtimeSourceFeedKey="--feed-credential $decodedFeedKey"
fi
if [[ -n "$runtimeSourceFeed" || -n "$runtimeSourceFeedKey" ]]; then
bash "$install_script" --version $version --install-dir "$root" $archArg $runtimeArg $skipNonVersionedFilesArg $runtimeSourceFeed $runtimeSourceFeedKey || {
local exit_code=$?
Write-PipelineTelemetryError -category 'InitializeToolset' "Failed to install dotnet SDK from custom location '$runtimeSourceFeed' (exit code '$exit_code')."
ExitWithExitCode $exit_code
}
fi
fi
}
}
@@ -252,6 +273,9 @@ function GetNuGetPackageCachePath {
}
function InitializeNativeTools() {
if [[ -z "${DisableNativeToolsetInstalls:-}" ]]; then
return
fi
if grep -Fq "native-tools" $global_json_file
then
local nativeArgs=""
@@ -413,9 +437,11 @@ Write-PipelineSetVariable -name "Temp" -value "$temp_dir"
Write-PipelineSetVariable -name "TMP" -value "$temp_dir"
# Import custom tools configuration, if present in the repo.
configure_toolset_script="$eng_root/configure-toolset.sh"
if [[ -a "$configure_toolset_script" ]]; then
. "$configure_toolset_script"
if [[ "$disable_configure_toolset_import" != null ]]; then
configure_toolset_script="$eng_root/configure-toolset.sh"
if [[ -a "$configure_toolset_script" ]]; then
. "$configure_toolset_script"
fi
fi
# TODO: https://github.com/dotnet/arcade/issues/1468
+1 -1
Vendored Submodule
+1
Submodule external/coreclr added at b1f16cf71f.
+1 -1
+2 -2
View File
@@ -3,7 +3,7 @@
"dotnet": "5.0.100-alpha1-014854"
},
"msbuild-sdks": {
"Microsoft.DotNet.Arcade.Sdk": "5.0.0-beta.19511.1",
"Microsoft.DotNet.Helix.Sdk": "5.0.0-beta.19511.1"
"Microsoft.DotNet.Arcade.Sdk": "5.0.0-beta.19527.3",
"Microsoft.DotNet.Helix.Sdk": "5.0.0-beta.19527.3"
}
}
+2
View File
@@ -37,6 +37,8 @@ NO_CONSOLE = yes
ifeq ($(HOST_PLATFORM),win32)
PROFILE_MCS_FLAGS += -d:MOBILE_DESKTOP_HOST -d:WIN_PLATFORM
else
ENABLE_GSS=1
endif
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
@@ -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 ();
@@ -2191,6 +2206,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 {
+13 -1
View File
@@ -5139,7 +5139,19 @@ 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;
}
#endif
} // class DebuggerTests
} // namespace
@@ -218,9 +218,13 @@ namespace Mono.Options
int start = 0, end;
do {
end = GetLineEnd (start, width, self);
char c = self [end-1];
// endCorrection is 1 if the line end is '\n', and might be 2 if the line end is '\r\n'.
int endCorrection = 1;
if (end >= 2 && self.Substring (end - 2, 2).Equals ("\r\n"))
endCorrection = 2;
char c = self [end - endCorrection];
if (char.IsWhiteSpace (c))
--end;
end -= endCorrection;
bool needContinuation = end != self.Length && !IsEolChar (c);
string continuation = "";
if (needContinuation) {
@@ -231,7 +235,7 @@ namespace Mono.Options
yield return line;
start = end;
if (char.IsWhiteSpace (c))
++start;
start += endCorrection;
width = GetNextWidth (ewidths, width, ref hw);
} while (start < self.Length);
}
@@ -262,6 +266,8 @@ namespace Mono.Options
int end = System.Math.Min (start + length, description.Length);
int sep = -1;
for (int i = start; i < end; ++i) {
if (i + 2 <= description.Length && description.Substring (i, 2).Equals ("\r\n"))
return i+2;
if (description [i] == '\n')
return i+1;
if (IsEolChar (description [i]))
@@ -497,6 +497,25 @@ namespace MonoTests.Mono.Options
Assert.AreEqual (expected.ToString (), actual.ToString ());
}
[Test]
public void NewLines ()
{
var p = new OptionSet () {
"What is interesting about this is that we are going to use a newli\r\nne that is windows style"
};
StringWriter expected = new StringWriter ();
expected.NewLine = "\r\n";
expected.WriteLine ("What is interesting about this is that we are going to use a newli");
expected.WriteLine ("ne that is windows style");
StringWriter actual = new StringWriter ();
actual.NewLine = "\r\n";
p.WriteOptionDescriptions (actual);
Assert.AreEqual (expected.ToString (), actual.ToString ());
}
[Test]
public void OptionBundling ()
{
@@ -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
}
}
Loaded 100 of 723 files, more files were not shown because too many files have changed in this diff. Show more