public byte[] SerializeRequest(HttpRequestMessage request)
        {
            Validate.ArgumentNotNull(request, nameof(request));
            Validate.ArgumentNotNull(request.RequestUri, nameof(request.RequestUri));

            PreProcessRequest(request);

            var builder = new StringBuilder();

            // request-line   = method SP request-target SP HTTP-version CRLF
            builder.Append(request.Method);
            builder.Append(SP);
            builder.Append(request.RequestUri.IsAbsoluteUri ? request.RequestUri.PathAndQuery : Uri.EscapeUriString(request.RequestUri.ToString()));
            builder.Append(SP);
            builder.Append($"{Protocol}{ProtocolVersionSeparator}");
            builder.Append(new Version(1, 1).ToString(2));
            builder.Append(CR);
            builder.Append(LF);

            // Headers
            builder.Append(request.Headers);

            if (request.Content != null)
            {
                long?contentLength = request.Content.Headers.ContentLength;
                if (contentLength.HasValue)
                {
                    request.Content.Headers.ContentLength = contentLength.Value;
                }

                builder.Append(request.Content.Headers);
            }

            // Headers end
            builder.Append(CR);
            builder.Append(LF);

            return(Encoding.ASCII.GetBytes(builder.ToString()));
        }
        protected override async Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            Validate.ArgumentNotNull(request, nameof(request));

            using (Socket socket = await this.GetConnectedSocketAsync())
            {
                using (var stream = new HttpBufferedStream(new NetworkStream(socket, true)))
                {
                    var    serializer   = new HttpRequestResponseSerializer();
                    byte[] requestBytes = serializer.SerializeRequest(request);

                    await stream.WriteAsync(requestBytes, 0, requestBytes.Length, cancellationToken);

                    if (request.Content != null)
                    {
                        await request.Content.CopyToAsync(stream);
                    }

                    return(await serializer.DeserializeResponseAsync(stream, cancellationToken));
                }
            }
        }
 public HttpUdsMessageHandler(Uri providerUri)
 {
     Validate.ArgumentNotNull(providerUri, nameof(providerUri));
     this.providerUri = providerUri;
 }
예제 #4
0
        private (X509Certificate2 primaryCert, X509Certificate2[] certChain) CreateX509Certificates(CertificateResponse cr, [CallerMemberName] string callerMemberName = default)
        {
            Validate.ArgumentNotNullOrEmpty(cr.Certificate, nameof(cr.Certificate));
            Validate.ArgumentNotNull(cr.Expiration, nameof(cr.Expiration));
            Validate.ArgumentNotNull(cr.PrivateKey, nameof(cr.PrivateKey));
            Validate.ArgumentNotNull(cr.PrivateKey.Type, nameof(cr.PrivateKey.Type));
            Validate.ArgumentNotNull(cr.PrivateKey.Bytes, nameof(cr.PrivateKey.Bytes));

            string[] rawCerts = ParseCertificateResponse(cr.Certificate);
            if (rawCerts.Length == 0 ||
                string.IsNullOrWhiteSpace(rawCerts[0]))
            {
                throw new InvalidOperationException($"Failed to retrieve certificate from IoTEdge Security daemon for {callerMemberName}. Reason: Security daemon returned an empty response.");
            }

            string primaryCert = rawCerts[0];

            X509Certificate2[] certChain = ConvertToX509(rawCerts.Skip(1));

            RsaPrivateCrtKeyParameters keyParams = null;

            var         chainCertEntries = new List <X509CertificateEntry>();
            Pkcs12Store store            = new Pkcs12StoreBuilder().Build();

            // note: the seperator between the certificate and private key is added for safety to delineate the cert and key boundary
            using (var sr = new StringReader(primaryCert + "\r\n" + cr.PrivateKey.Bytes))
            {
                var    pemReader = new PemReader(sr);
                object certObject;
                while ((certObject = pemReader.ReadObject()) != null)
                {
                    if (certObject is Org.BouncyCastle.X509.X509Certificate x509Cert)
                    {
                        chainCertEntries.Add(new X509CertificateEntry(x509Cert));
                    }

                    // when processing certificates generated via openssl certObject type is of AsymmetricCipherKeyPair
                    if (certObject is AsymmetricCipherKeyPair ackp)
                    {
                        certObject = ackp.Private;
                    }

                    if (certObject is RsaPrivateCrtKeyParameters rpckp)
                    {
                        keyParams = rpckp;
                    }
                }
            }

            if (keyParams == null)
            {
                throw new InvalidOperationException($"Private key was not found for {callerMemberName}");
            }

            store.SetKeyEntry(this.ModuleId, new AsymmetricKeyEntry(keyParams), chainCertEntries.ToArray());
            using (var ms = new MemoryStream())
            {
                store.Save(ms, Array.Empty <char>(), new SecureRandom());
                var x509PrimaryCert = new X509Certificate2(ms.ToArray());
                return(x509PrimaryCert, certChain);
            }
        }