Code Monkey home page Code Monkey logo

openssl-net's Introduction

OpenSSL.NET (openssl-net)

Description

A managed OpenSSL wrapper written in C# for the 2.0 .NET Framework that exposes both the Crypto API and the SSL API.

This a must for .NET developers that need crypto but don't want to use Microsoft's SSPI.

This wrapper is based on version 1.0.2a of libeay32.dll and ssleay32.dll.

Wrapper Example

The following is a partial example to show the general pattern of wrapping onto the C API.

Take DSA and the following C prototypes:

DSA *  DSA_new(void);
void   DSA_free(DSA *dsa);
int    DSA_size(const DSA *dsa);
int    DSA_generate_key(DSA *dsa);
int    DSA_sign(int dummy, const unsigned char *dgst, int len,
                unsigned char *sigret, unsigned int *siglen, DSA *dsa);
int    DSA_verify(int dummy, const unsigned char *dgst, int len,
                const unsigned char *sigbuf, int siglen, DSA *dsa);

Which gets wrapped as something akin to:

public class DSA : IDisposable
{
    // calls DSA_new()
    public DSA();

    // calls DSA_free() as needed
    ~DSA();

    // calls DSA_free() as needed
    public void Dispose();

    // returns DSA_size()
    public int Size { get; }

    // calls DSA_generate_key()
    public void GenerateKeys();

    // calls DSA_sign()
    public byte[] Sign(byte[] msg);

    // returns DSA_verify()
    public bool Verify(byte[] msg, byte[] sig);
}

Installation

Make sure you have libeay32.dll and ssleay32.dll in the current working directory of your application or in your PATH.

In your .NET project, add a reference to the ManagedOpenSsl.dll assembly.

Documentation

Take a look at the low-level C API documentation.

License

The OpenSSL libraries are distributed under the terms of the OpenSSL License & SSLeay License; this library and related code are released under the BSD license, see COPYING for more details.

Team

This library is the product of many contributors, both directly, and indirectly, thanks to the great effort of the OpenSSL team. Thanks to all those that have contributed to this project - whether code, testing, support or anything else.

Maintainer:

For security issues, please contact the maintainer directly prior to opening a public ticket. Security issues will receive prompt attention and be handled as quickly as possible.

openssl-net's People

Contributors

ffleischer avatar flaub-coco avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

openssl-net's Issues

Timing issue on SSlStreamBase.cs (AsyncHandshakeCallback)

I am having a timing issue on my client application on the method AsyncHandshakeCallback of class SslStreamBase.
If I put Thread.Sleep(100) on the first line of this method, I am able to connect into the server.

However, without Thread.Sleep, I am not able to connect to the server.

The server does not use managed open SSL and I got exception thrown at following line of the client code:
class: Bio.cs,
line 258,
method : ArraySegment ReadBytes(int count)

The stack trace shows that this method is called from line 1041 of SslStreamBase.cs.

OpenSSL defaults to http1.1

I am setting up a new ssl tunnel using this library. Everything works great except for the ALPN negotiation. When I use firefox it sends h2-12, SPDY3, and HTTP1.1. I am getting a negotiation with HTTP1.1. If I use openssl with s_client and use the -alpn flag then the server will return h2-12 correctly.

What it looks like is openssl needs some way to specify what ALPN protocol should be negotiated. Using s_server there is a flag -alpn we can specify this. Is it possible to set something like that with this library?

OpenSSL.Core.Native throws an exception.

I have installed the ManagedOpenSSL32(version: 0.6.1.0) Nuget Package to my ASP.NET MVC project, now the following peace of code throws an exception.

CryptoKey d = CryptoKey.FromPrivateKey(privateKey, null);
using (var rsa = d.GetRSA())
{
byte[] byteResult = rsa.PrivateDecrypt(bin, RSA.Padding.PKCS1);
decodedString = Encoding.UTF8.GetString(byteResult);
}

More specifically the first line. I downloaded the source code locally to test with a simple console app and the error happens on the BIO constructor with this parameter signature (Byte[] buf), on this line of code OpenSSL.Core.Native.BIO_s_mem().

This the exception message

Unable to load DLL 'x86\libeay32': The specified module could not be found.

Where is ManagedOpenSsl.dll?

It says in the instructions to add a reference to ManagedOpenSsl.dll, but where can I find it?
I don't see it in the project and if I execute the release.cmd it doesn't generate it.

EDIT: I found it after checking the code of release.cmd.
You should write in the readme that it's in bin\Debug.

AccessViolationException when call Open

I get System.AccessViolationException when call OpenSSL.Crypto.CipherContext.Open(Byte[] input, Byte[] ekey, Byte[] iv, CryptoKey pkey)

application stop at

OpenSSL.Core.Native.EVP_OpenInit(IntPtr ctx, IntPtr type, Byte[] ek, Int32 ekl, Byte[] iv, IntPtr priv) 

os: win7 64bit

code:

using (CipherContext cc = new CipherContext(cipher))
{
    Envelope env = cc.Seal(new CryptoKey[] { key }, input);
    byte[] dd = cc.Open(output, env.Keys[0], env.IV, key);
}

UnitTests crash under mono

So far, these are the tests that crash (on OSX):

  • TestCipher.TestEncryptDecrypt
  • TestCipher.TestEncryptDecryptWithSalt
  • TestECDSA.test_builtin
  • TestECDSA.x9_62_tests
  • TestHMAC.TestCase
  • TestX509.TestWithoutCfg

How to merge private key into a certificate

Hello,

I've searched for how to merge a private key file into a certificate file, but I didnt't have success.
I need to create a pfx file, using in some cases "RSA Private Key" key file, and sometimes, "Private Key" key file (pkcs8), and I didn't find any usage like that on test projects.

Do you have any documentation about that? Is it possible to achieve it?

Thank you

nuget package support

This would probably make using the library a lot easier.

If possible, use the technique that System.Data.SQLite for embedding the native libraries per platform.

Add support for ALPN

I was using this project as a template https://github.com/MSOpenTech/http2-katana/ but I noticed the version of ManagedOpenSsl is older than the one here. I tried to update to this current version but there seem to be a lot of changes, especially in SslStream. For instance, AlpnSelectedProtocol is no longer in SslStream. Is there any documentation on these changes?

OpenSSL 1.0.1 support

Is OpenSSL 1.0.1 going to be supported? Would be great to have access to things like AES in GCM mode (authenticated encryption)

DNX compliance : Cannot use AppDomain.CurrentDomain.FriendlyName

Hi,

I'm trying to migrate the library to a DNX package.
One of my last issue is the use of AppDomain. It's quite simple : It's been completly removed.
I'm wondering how should I replace the following line :

File : .OpenSSL\Ssl\SslStreamServer.cs
Line 201 (last code line of the file)
sslContext.SetSessionIdContext(Encoding.GetEncoding("ASCII").GetBytes(AppDomain.CurrentDomain.FriendlyName));

What other String can we use to ensure compliance ?
I've tried to find the "Assembly name" that's running the library because this is the default value for AppDomain friendlyName.
I could not find a way either because it requires to know a type of the "ExecutingAssembly" ==> Not possible in a ThirdPart lib ==> GetExecutingAssembly() is not compliant either ^^

OpenSSL 1.0.2h - SSL_CTX_set_cipher_list:no cipher match

I built OpenSSL 1.0.2h using MSYS/MinGW and replaced the native files with it.

I had to then comment out references to the IDEA ciphers and I'm not sure if that's related to the failure.

NUnit testing results change in that one of the tests fail where it didn't before:

TestSSL -: TestSyncIntermediate -: AuthenticateAsServer

UnitTests.TestSSL.TestSyncIntermediate:
System.AggregateException : One or more errors occurred.
----> OpenSSL.Core.OpenSslException : error:1410D0B9:SSL routines:SSL_CTX_set_cipher_list:no cipher match

Entry point "EVP_PKEY_get1_EC" was not found in DLL "libeay32"

Hi,
I tried to use the latest master version.

I want to use these stuff:

using (CryptoKey key = OpenSSL.Crypto.CryptoKey.FromPrivateKey(@"
-----BEGIN EC PRIVATE KEY-----
MHcCAQEEIDcKEenA2OlhsDOjKDmhgqvsrJW3S63eXKDf2Nzoa8HdoAoGCCqGSM49
AwEHoUQDQgAELjriJr3pzALUW+W7z2sfQLgySUJTr+Fe8pQWyJzDFVNl/VBSlew1
ToQsVla7HMDXdWoS2GPqvauKVuf8Tp8RVg==
-----END EC PRIVATE KEY-----", null))
            {
                using (Key ec = key.GetEC())
                {
...
                }
            }

It crashes at key.GetEC().

Can you fix the problem?

Thanks!

exception when no server_name is sent

I am setting up a SSL server using this wrapper calling AuthenticateAsServer(cert). Using Firefox 41 I attempt to access the server using ip address. With firefox, if you try to connect using an IP address the server_name extension is not set. When I attempt I get a "server names do not match" exception. It looks like it is setting up the SNI extension attempting to match, seeing that the secure_name extension is not present and failing. Perhaps if the server_name extension is not present it should ignore it?

No Converse of MakeString

Currently, it is possible to pass protocols and ciphers to produce an OpenSSL-style string expression.
However, I cannot find a way for passing a cipher string and obtaining a list of explicit ciphers.
The CLI equivalent for this would be "openssl ciphers [cipher-string]".

EndAuthenticateAsServer(ar) throws "Failed to complete read operation"

After a successful BeginAuthenticateAsServer(), calling EndAuthenticateAsServer() throws "Failed to complete read operation" within EndRead() in SslStreamBase.cs.

It could be a timing issue, when the calling thread calls EndAuthenticateAsServer(), while AsyncHandshakeCallback() about to complete.

Note: This exception is not happening when we use openssl command line client with (s_client option)

DllNotFoundException libssl.1.0.0.dylib

OSX 10.7.3
MONO 3.0.12

Unhandled Exception:
System.TypeInitializationException: An exception was thrown by the type initializer for PtpCore.Encryption.SecurityContext ---> System.TypeInitializationException: An exception was thrown by the type initializer for OpenSSL.Crypto.Cipher ---> System.TypeInitializationException: An exception was thrown by the type initializer for OpenSSL.Core.Native ---> System.DllNotFoundException: /Library/Frameworks/Mono.framework/Versions/3.0.12/lib/libssl.1.0.0.dylib
  at (wrapper managed-to-native) OpenSSL.Core.Native:SSL_load_error_strings ()
  at OpenSSL.Core.Native..cctor () [0x00000] in <filename unknown>:0 
  --- End of inner exception stack trace ---
  at OpenSSL.Crypto.Cipher..cctor () [0x00000] in <filename unknown>:0 
  --- End of inner exception stack trace ---
  --- End of inner exception stack trace ---

Serial Number length

Hi, i saw that serialnumber of X509Certificate is an integer, but serial number could be a number greatest of integer.

SSL_get0_alpn_selected() returns NULL and throws exception - "Cant get selected protocol...

SSL_get0_alpn_selected() returns null. I’m using standard openssl console client and my own server (with ManagedOpenSsl.dll)

The exception is – "Cant get selected protocol. See if ALPN was included into client/server hello");

public static extern void SSL_get0_alpn_selected(IntPtr ssl, out IntPtr data, out int len);

Exception thrown from the following code in ssl.cs

public string AlpnSelectedProtocol
        {
            get
            {
                var ptr = new IntPtr();
                var len = 0;

                Native.SSL_get0_alpn_selected(Handle, out ptr, out len);

                if (ptr == IntPtr.Zero)
                    throw new AlpnException("Cant get selected protocol. See if ALPN was included into client/server hello");

                var buf = new byte[len];
                Marshal.Copy(ptr, buf, 0, len);
                return Encoding.ASCII.GetString(buf, 0, len);
            }
        }

Here is my client commands, that I tried.

C:\OpenSSL-Win32\bin>openssl s_client -connect 192.168.1.51:443 -alpn 'tls_1, tls1_1, tls1_2'

C:\OpenSSL-Win32\bin>openssl s_client -connect 192.168.1.51:443 -alpn 'tls1_2’

Any help would be appreciated.

-Arun

REDO THIS WHOLE THING USING C#/.NET tools and libraries

Just making a wrapper around library that has bugs and not even updating the references DLLs just cause more bugs and security issues, because someone might think that this package actually works and is secure. BUT IT'S NOT BECAUSE YOU HAVEN'T UPDATED CODE IN 10 YEARS OR THE REFERENCED DLLs. Creating more security issues and bugs. Well done.

ManagedOpenSsl in .net core throws “System.BadImageFormatException"

Guys, I have been facing multiple challenges with getting the ManagedOpenSsl to work with .Net Core. I downloaded ManagedOpenSsl.NetCore from nuget package.

My end goal is to create a .pfx file from certificate PEM and private key. In the below code, ocert.KeyPair.PrivateKey is the certificate private key and ocert.CertificatePem is the certificate PEM.

ManagedOpenSsl.NetCore.Core.BIO key_bio = new ManagedOpenSsl.NetCore.Core.BIO(ocert.KeyPair.PrivateKey);
            ManagedOpenSsl.NetCore.Core.BIO cert_bio = new ManagedOpenSsl.NetCore.Core.BIO(ocert.CertificatePem);

            ManagedOpenSsl.NetCore.Crypto.CryptoKey key = ManagedOpenSsl.NetCore.Crypto.CryptoKey.FromPrivateKey(ocert.KeyPair.PrivateKey, "xxxxx");
            ManagedOpenSsl.NetCore.X509.X509Certificate cert = new ManagedOpenSsl.NetCore.X509.X509Certificate(cert_bio);
            ManagedOpenSsl.NetCore.Core.Stack<ManagedOpenSsl.NetCore.X509.X509Certificate> hmm = new ManagedOpenSsl.NetCore.Core.Stack<ManagedOpenSsl.NetCore.X509.X509Certificate>();

            var pfx = new ManagedOpenSsl.NetCore.X509.PKCS12(password, key, cert, hmm); // <-- 
            ManagedOpenSsl.NetCore.X509.X509Certificate certpfx = pfx.Certificate;

I'm getting error {System.TypeInitializationException: The type initializer for 'ManagedOpenSsl.NetCore.Core.Native' threw an exception. ---> System.BadImageFormatException: An attempt was made to load a program with an incorrect format. (Exception from HRESULT: 0x8007000B) at ManagedOpenSsl.NetCore.Core.Native.SSLeay() at ManagedOpenSsl.NetCore.Core.Version.get_Library() at ManagedOpenSsl.NetCore.Core.Native..cctor() --- End of inner exception stack trace - in the line of code `ManagedOpenSsl.NetCore.Core.BIO key_bio = new ManagedOpenSsl.NetCore.Core.BIO(ocert.KeyPair.PrivateKey);

I have set the Platform Target to "Any CPU", still the issue occurs. Also any implementation on how to save the pfx.Certificate to a specific folder in .pfx format ? Any help will be appreciated. Been struggling with this issue for a while now.

x64 support.

Hi,

I've tried to add _WIN64 symbol and replace original x86 dlls with x64 dlls. All tests was passed successfully.

Is any other known problems with x64 version of this project?

System.TypeInitializationException: 'OpenSSL.Core.Native' HRESULT: 0x800700B6

Hi can anyone help me? He doesn't make mistakes on all computers(windows7 or windows 10).


ERROR Message: System.TypeInitializationException: The type initializer for 'OpenSSL.Core.Native' threw an exception. ---> System.DllNotFoundException: Unable to load DLL 'x86\ssleay32': 穨╰参礚猭磅︽  (Exception from HRESULT: 0x800700B6)
at OpenSSL.Core.Native.SSL_load_error_strings()
at OpenSSL.Core.Native..cctor()
--- End of inner exception stack trace ---
at OpenSSL.Core.Native.BIO_s_mem()
at OpenSSL.Core.BIO..ctor(Byte[] buf)
at OpenSSL.Crypto.CryptoKey.FromPublicKey(String pem, String password)


I can make sure that both libeay32.dll (1.0.2a) and ssleay32.dll (1.0.2a) are under my project \x86.
I tried to revise the source code to compile it, and there was another mistake.

		// Enable FIPS mode
		if (FIPS.Enabled)
		{
			if (FIPS_mode_set(1) == 0)
			{
				throw new Exception("Failed to initialize FIPS mode");
			}
		}
	    //try
	    //{
  //          ERR_load_crypto_strings();
  //          SSL_load_error_strings();
  //      }
	    //catch (Exception)
	    //{	        
	    //}
		OPENSSL_add_all_algorithms_noconf();

		// Initialize SSL library
		Native.ExpectSuccess(**SSL_library_init()**);

System.TypeInitializationException: 'OpenSSL.Core.Native' 偺僞僀僾弶婜壔巕偑椺奜傪僗儘乕偟傑偟偨丅 ---> System.DllNotFoundException: DLL 'x86\ssleay32.dll' 傪撉傒崬傔傑偣傫:偙偺僆儁儗乕僥傿儞僌 僔僗僥儉偱偼 偼幚峴偝傟傑偣傫丅 (HRESULT 偐傜偺椺奜:0x800700B6)
応強 OpenSSL.Core.Native.SSL_library_init()
応強 OpenSSL.Core.Native..cctor()
--- 撪晹椺奜僗僞僢僋 僩儗乕僗偺廔傢傝 ---
応強 OpenSSL.Core.Native.BIO_s_mem()
応強 OpenSSL.Core.BIO..ctor(Byte[] buf)
応強 OpenSSL.Crypto.CryptoKey.FromPublicKey(String pem, String password)

DTLS support

Hi,

I'm looking for a DTLS solution in .Net which:

  • supports DTLS1.2
  • allows to strictly specify a set of supported cipher suites for a server

Does the OpenSSL.NET support these features?
I'm new to SSL/TLS. As for the native openssl1.0.2a, DTLS1.2 should be supported, however I did not find it used in the SslMethod class. Moreover, I've noticed that many of the classes which wolud allow to follow a regular openssl setup are internal and the SslStream class API allows only to create a peers using the TLSv12_client_method.

Please advise if this project is the right one to start with in my project.

Regards,
Krzysztof

request to add d2i_X509

the BIO version is there (d2i_X509_bio) but the call that takes a memory buffer is not present.

System.AccessViolationException: Attempted to read or write protected memory

I use SslSteam in HTTP server , and load local cert from disk ,cache cert in static variable , process https request , some time it's ok , but some time it throw exception:

System.AccessViolationException: Attempted to read or write protected memory
at
public int UsePrivateKey(CryptoKey key)
{
return Native.ExpectSuccess(Native.SSL_CTX_use_PrivateKey(ptr, key.Handle));
}
or

error:1408F119:SSL routines:SSL3_GET_RECORD:decryption failed or bad record mac
at
SslStream.AuthenticateAsServer(X509Certificate)

Cannot complete handshake with Oracle-HTTP-Server

When calling
sslStream.AuthenticateAsClient(target, null, null, SslProtocols.Default, SslStrength.All, false);
I get the following SSL error:
error:1408F10B:SSL routines:SSL3_GET_RECORD:wrong version number

The handshake goes:
C->S TLSv1 440 Client Hello
S<-C TLSv1 124 Server Hello
S<-C TLSv1 1481 Certificate
C->S TLSv1 61 Alert (Level: Fatal, Description: Protocol Version)
S<-C TLSv1 61 Alert (Level: Fatal, Description: Close Notify)

openssl s_client connects correctly (tested on linux). The server supports only TLSv1. You can reproduce this problem by connecting to eg. www.tis-tadawul.com.sa on port 443

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.