mirror of
https://github.com/BepInEx/mono.git
synced 2026-11-16 01:41:18 -10:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4a50a2eb04 | ||
|
|
e0217d6371 | ||
|
|
75eaefcff7 | ||
|
|
a7db40a813 | ||
|
|
05f0f319f5 | ||
|
|
48a6994de5 | ||
|
|
d3292aa3cf | ||
|
|
345c823407 | ||
|
|
31dd8c2ee3 | ||
|
|
2b0cc9644a | ||
|
|
08253d307f | ||
|
|
6b354998f9 | ||
|
|
a60df8f914 | ||
|
|
2ace29070d | ||
|
|
d31389ecd7 | ||
|
|
9e912609b6 | ||
|
|
ed278e541c | ||
|
|
97281d6f84 | ||
|
|
2736860b21 | ||
|
|
06ae29dfe0 | ||
|
|
9ebe96f923 | ||
|
|
466440920b | ||
|
|
72efb8ad49 | ||
|
|
e0229d06aa | ||
|
|
37f8d4e654 | ||
|
|
e98e13652f | ||
|
|
e887042951 | ||
|
|
7914e0cc6b | ||
|
|
893c7c7caa | ||
|
|
f1ce89d63f | ||
|
|
8a915e5f3a | ||
|
|
9e27c03294 | ||
|
|
34504f021d | ||
|
|
8195519607 | ||
|
|
7625234438 | ||
|
|
1e8e357831 | ||
|
|
aa506ca1bb | ||
|
|
104abd7fe7 | ||
|
|
f477bce548 | ||
|
|
3d4f44d85c | ||
|
|
93b97d5582 | ||
|
|
6f73c2dab8 | ||
|
|
44e6226c31 | ||
|
|
95743afa80 | ||
|
|
fdc6495a54 | ||
|
|
ebb4598096 | ||
|
|
b3b9960ed1 | ||
|
|
db49be3cbb | ||
|
|
cf8495e2f7 | ||
|
|
07fa0bd3b4 | ||
|
|
929a8a7fd8 | ||
|
|
237f210ea2 | ||
|
|
49d5c4d14d | ||
|
|
6630bcc67f | ||
|
|
f3e30a0ad0 | ||
|
|
deb3115b15 | ||
|
|
6ecf9e87ba | ||
|
|
c0e237b734 | ||
|
|
137ffe8b7c | ||
|
|
8131518bb1 | ||
|
|
8700c04b02 | ||
|
|
4888c49c26 | ||
|
|
40c1cd3576 | ||
|
|
d89b96a298 | ||
|
|
ad385f98b3 | ||
|
|
62ee01b36b | ||
|
|
803c657b24 | ||
|
|
36539ed67f | ||
|
|
4b9dc08ac1 | ||
|
|
e9d68e9485 | ||
|
|
b9f185b74a | ||
|
|
16d1a2e6f1 | ||
|
|
a4790c892d | ||
|
|
cc28706e58 | ||
|
|
166fdf60b0 | ||
|
|
170d33c35b | ||
|
|
8aa3654de5 | ||
|
|
dc8d55d446 | ||
|
|
9566027142 | ||
|
|
8b86349c2c | ||
|
|
0be756d609 | ||
|
|
b484979aa9 | ||
|
|
3648cb087b | ||
|
|
dff84a2464 | ||
|
|
ca72deed17 | ||
|
|
c9b7f767a8 | ||
|
|
1d043a31e7 | ||
|
|
6b3aa3a05b | ||
|
|
a27aa7afd0 | ||
|
|
6ae3360342 | ||
|
|
a94dda5b5a | ||
|
|
dc76a95aa9 | ||
|
|
5811404e55 | ||
|
|
578e0df42f | ||
|
|
27921fbbd0 | ||
|
|
fffb1201bd | ||
|
|
feca5e042d | ||
|
|
744d77ea7f | ||
|
|
c6f71167a1 | ||
|
|
95cad24526 | ||
|
|
e4c0b50dec | ||
|
|
c9b88b45fe | ||
|
|
10ac2750e2 | ||
|
|
79f5e6c288 | ||
|
|
3d397805d4 | ||
|
|
2823ac5d95 | ||
|
|
3695d8704e | ||
|
|
9adce0b632 | ||
|
|
d49d3efd5d | ||
|
|
67ff64a381 | ||
|
|
8a03f60897 | ||
|
|
17cef4c4f9 | ||
|
|
249522036d | ||
|
|
447cb03399 | ||
|
|
9aeef958c6 | ||
|
|
db02ebc88b | ||
|
|
f26e73b49b | ||
|
|
d274cfbacd | ||
|
|
1340095581 | ||
|
|
b0d966bd7a | ||
|
|
7f91972ded | ||
|
|
cddf90dda4 | ||
|
|
e4cc70f4b5 | ||
|
|
c5edcd1ed4 | ||
|
|
450d474684 | ||
|
|
fb7b075e49 | ||
|
|
6f04054541 | ||
|
|
db568c6fe0 | ||
|
|
0e3caf00df | ||
|
|
2da4e54a7f | ||
|
|
5f3446bd12 | ||
|
|
c5e3ca90de | ||
|
|
fec907397d | ||
|
|
1801bdad6a | ||
|
|
4ec9bd03e5 | ||
|
|
1bd76c6069 | ||
|
|
f1a3f3c58d | ||
|
|
893486638c | ||
|
|
84d64d314b | ||
|
|
d6ee245c94 | ||
|
|
768fefbad1 | ||
|
|
dc4a7f5ed7 | ||
|
|
6ac749ed20 | ||
|
|
9d781eb78c | ||
|
|
8800bfdf9c | ||
|
|
4ef7c566af | ||
|
|
fc390a5f24 | ||
|
|
ec81a868a1 | ||
|
|
aea7214eb4 | ||
|
|
a7287bdae5 | ||
|
|
25b53a642b | ||
|
|
0595c0e6d7 | ||
|
|
81a4a19f0a | ||
|
|
1553889bc5 | ||
|
|
638e2c6a86 | ||
|
|
b7ef736338 | ||
|
|
6fd07e4745 | ||
|
|
7952e73780 | ||
|
|
861812252a | ||
|
|
2c8e0f68c1 | ||
|
|
951769b279 | ||
|
|
fe7654f745 | ||
|
|
7a15b71873 | ||
|
|
2dfd682ac9 | ||
|
|
1b5658d590 | ||
|
|
e5d88dbd04 | ||
|
|
43a938fefb | ||
|
|
8fda1738f7 | ||
|
|
4d7adf4d2a | ||
|
|
df30c7228c | ||
|
|
31b475e25a | ||
|
|
8b8b8b5010 | ||
|
|
e29f8e32b7 | ||
|
|
e73aa17e23 | ||
|
|
bed1b39c6e | ||
|
|
bc769e7376 | ||
|
|
cdf8b839ae | ||
|
|
479d2dff36 | ||
|
|
4419dc919f | ||
|
|
92c08fab4d | ||
|
|
6159407846 | ||
|
|
a2cd8b2495 | ||
|
|
b99a3e9514 | ||
|
|
1e60703a19 | ||
|
|
11dca2a3b8 | ||
|
|
745e5ba3c3 | ||
|
|
d08713198f | ||
|
|
433d7c5004 | ||
|
|
15d61d3f47 | ||
|
|
69407517bc | ||
|
|
fdca1630dc | ||
|
|
b98911d4f8 | ||
|
|
0663433389 | ||
|
|
fb5b2c949d | ||
|
|
bc9b64b807 | ||
|
|
ebb5846e0d | ||
|
|
f34fd20fbf | ||
|
|
cf1a9e0033 | ||
|
|
64c3405594 | ||
|
|
d4a2f01064 | ||
|
|
8ea0426488 | ||
|
|
113d855adb | ||
|
|
d5b182c6d8 | ||
|
|
274db87e60 | ||
|
|
0e02fa55af | ||
|
|
5fdea0b84b | ||
|
|
d34ba480f9 | ||
|
|
296b8d40cf | ||
|
|
cd2388fd6f | ||
|
|
858fc11900 | ||
|
|
565b81e26f | ||
|
|
f731db32dd | ||
|
|
b96260e603 | ||
|
|
20752df324 | ||
|
|
c1461e4a2d | ||
|
|
fd82c6036e | ||
|
|
7e522ef179 | ||
|
|
21d7d41bfe | ||
|
|
2cea0a89d1 | ||
|
|
0d357c1347 | ||
|
|
f07e93da2f | ||
|
|
3ff90ac0c2 | ||
|
|
9f50bdb2d9 | ||
|
|
4b9226619c | ||
|
|
32ab6bcf00 | ||
|
|
67c8d0d812 | ||
|
|
5fcd00669c | ||
|
|
b19d9aa658 | ||
|
|
1d44139d01 | ||
|
|
bc678a2c10 | ||
|
|
91f10aeee4 | ||
|
|
91413f78f3 | ||
|
|
84f4e1dcbf | ||
|
|
105ead8707 | ||
|
|
d8ae32a9ee | ||
|
|
a2992d634b | ||
|
|
fffad7e3a8 | ||
|
|
8836231459 | ||
|
|
d44e0e80d7 | ||
|
|
a0c7d73d6f | ||
|
|
37f628750a | ||
|
|
958b9b2658 | ||
|
|
4908d1f19a | ||
|
|
7c7d406fc0 |
No files matched your search
+1
-1
@@ -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
|
||||
|
||||
@@ -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
@@ -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
|
||||
|
||||
@@ -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
@@ -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
@@ -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
@@ -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.
|
||||
|
||||
@@ -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
@@ -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
@@ -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
@@ -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
|
||||
|
||||
|
||||
@@ -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
@@ -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
|
||||
Vendored
+4
-2
@@ -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 $_
|
||||
|
||||
Vendored
+41
-2
@@ -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
@@ -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
@@ -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
|
||||
|
||||
Vendored
+1
-1
Submodule external/api-snapshot updated: 698b653491...3f261a6c67.
Vendored
+1
-1
Submodule external/bockbuild updated: ec63a2da8b...c9d4ecdba4.
Vendored
+1
-1
Submodule external/cecil updated: cb6c1ca9aa...a6a7f5c0f4.
+1
Submodule external/coreclr added at b1f16cf71f.
Vendored
+1
-1
Submodule external/corefx updated: 8e3b279377...6e65509a17.
+2
-2
@@ -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"
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
@@ -23,3 +23,7 @@ ifeq ($(HOST_PLATFORM),macos)
|
||||
MONO_FEATURE_APPLETLS=1
|
||||
ENABLE_GSS=1
|
||||
endif
|
||||
|
||||
ifeq ($(HOST_PLATFORM),linux)
|
||||
ENABLE_GSS=1
|
||||
endif
|
||||
@@ -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 {
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
-149
@@ -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
|
||||
}
|
||||
}
|
||||
-220
@@ -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
|
||||
}
|
||||
}
|
||||
-87
@@ -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
|
||||
}
|
||||
}
|
||||
-139
@@ -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
|
||||
}
|
||||
}
|
||||
-98
@@ -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
|
||||
}
|
||||
}
|
||||
-450
@@ -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
|
||||
}
|
||||
}
|
||||
-111
@@ -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
|
||||
}
|
||||
}
|
||||
-102
@@ -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
|
||||
}
|
||||
}
|
||||
-150
@@ -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
|
||||
}
|
||||
}
|
||||
-52
@@ -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
|
||||
}
|
||||
}
|
||||
-121
@@ -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
|
||||
}
|
||||
}
|
||||
-276
@@ -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
|
||||
}
|
||||
}
|
||||
-86
@@ -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
|
||||
}
|
||||
}
|
||||
-88
@@ -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
|
||||
}
|
||||
}
|
||||
-152
@@ -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
|
||||
}
|
||||
}
|
||||
-116
@@ -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
|
||||
}
|
||||
}
|
||||
-74
@@ -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
|
||||
}
|
||||
}
|
||||
-107
@@ -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
|
||||
}
|
||||
}
|
||||
-75
@@ -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
|
||||
}
|
||||
}
|
||||
-122
@@ -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
|
||||
}
|
||||
}
|
||||
-52
@@ -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
|
||||
}
|
||||
}
|
||||
-110
@@ -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
Reference in new issue
Block a user