Ejemplo n.º 1
0
        protected ITransmissionResponse HandleResponse(HttpResponse httpResponse)
        {
            Trace span = this.root.Child();

            // tracer.newChild(root.context()).name("response").start();
            span.Record(Annotations.ServiceName("response"));
            span.Record(Annotations.ClientSend());

            try
            {
                HttpResponse response = httpResponse;
                span.Record(Annotations.Tag("code", response.StatusCode.ToString()));

                // span.tag("code", String.valueOf(response.getStatusLine().getStatusCode()));

                if (response.StatusCode != HttpStatusCode.OK)
                {
                    Logger.ErrorFormat(
                        "AS2 HTTP POST expected HTTP OK, but got : {0} from {1}",
                        response.StatusCode,
                        this.transmissionRequest.GetEndpoint().Address);

                    // Throws exception
                    this.HandleFailedRequest(response);
                }

                // handle normal HTTP OK response
                Logger.DebugFormat(
                    "AS2 transmission to {0} returned HTTP OK, verify MDN response",
                    this.transmissionRequest.GetEndpoint().Address);

                string contentTypeHeader = response.Headers["Content-Type"];
                if (string.IsNullOrWhiteSpace(contentTypeHeader))
                {
                    throw new HyperwayTransmissionException(
                              "No Content-Type header in response, probably a server error.");
                }

                // Read MIME Message
                MimeMessage mimeMessage;
                using (var m = new MemoryStream())
                {
                    // Add headers to MIME Message
                    foreach (var headerName in response.Headers.AllKeys)
                    {
                        var headerText = $"{headerName}: {response.Headers[headerName]}";
                        var headerData = Encoding.ASCII.GetBytes(headerText);
                        m.Write(headerData, 0, headerData.Length);
                        m.Write(new byte[] { 13, 10 }, 0, 2);
                    }
                    m.Write(new byte[] { 13, 10 }, 0, 2);

                    var messageData = response.Entity.Content;
                    m.Write(messageData, 0, messageData.Length);


                    m.Seek(0, SeekOrigin.Begin);
                    mimeMessage = MimeMessage.Load(m);
                    mimeMessage.Headers[HeaderId.ContentType] = response.Headers["Content-Type"];
                }

                SMimeReader sMimeReader = new SMimeReader(mimeMessage);

                // Timestamp of reception of MDN
                Timestamp t3 = this.timestampProvider.Generate(sMimeReader.GetSignature(), Direction.OUT);

                MultipartSigned signedMessage = mimeMessage.Body as MultipartSigned;
                using (this.secureMimeContext())
                {
                    Debug.Assert(signedMessage != null, nameof(signedMessage) + " != null");

                    var signatures      = signedMessage.Verify();
                    var signature       = signatures.First();
                    var mimeCertificate = signature.SignerCertificate as SecureMimeDigitalCertificate;


                    // Verify if the certificate used by the receiving Access Point in
                    // the response message does not match its certificate published by the SMP
                    Debug.Assert(mimeCertificate != null, nameof(mimeCertificate) + " != null");
                    X509Certificate certificate = mimeCertificate.Certificate;
                    if (!this.transmissionRequest.GetEndpoint().Certificate.Equals(certificate))
                    {
                        throw new HyperwayTransmissionException(
                                  String.Format(
                                      "Certificate in MDN ('{0}') does not match certificate from SMP ('{1}').",
                                      certificate.SubjectDN,                                          // .getSubjectX500Principal().getName(),
                                      this.transmissionRequest.GetEndpoint().Certificate.SubjectDN)); // .getSubjectX500Principal().getName()));
                    }

                    Logger.Debug("MDN signature was verified for : " + certificate.SubjectDN);
                }


                // Verifies the actual MDN
                MdnMimeMessageInspector mdnMimeMessageInspector = new MdnMimeMessageInspector(mimeMessage);
                String msg = mdnMimeMessageInspector.GetPlainTextPartAsText();

                if (!mdnMimeMessageInspector.IsOkOrWarning(new Mic(this.outboundMic)))
                {
                    Logger.ErrorFormat("AS2 transmission failed with some error message '{0}'.", msg);
                    throw new HyperwayTransmissionException(String.Format("AS2 transmission failed : {0}", msg));
                }

                // Read structured content
                MimeEntity mimeBodyPart    = mdnMimeMessageInspector.GetMessageDispositionNotificationPart();
                var        internetHeaders = mimeBodyPart.Headers;
                // InternetHeaders internetHeaders = new InternetHeaders((InputStream)mimeBodyPart.getContent());

                // Fetch timestamp if set
                DateTime date = t3.GetDate();
                if (internetHeaders.Any(x => x.Field == MdnHeader.Date))
                {
                    var dateText = internetHeaders.First(x => x.Field == MdnHeader.Date).Value;
                    date = As2DateUtil.Rfc822.Parse(dateText);
                }


                // Return TransmissionResponse
                return(new As2TransmissionResponse(
                           this.transmissionIdentifier,
                           this.transmissionRequest,
                           this.outboundMic,
                           MimeMessageHelper.ToBytes(mimeMessage),
                           t3,
                           date));
            }
            catch (TimestampException e)
            {
                throw new HyperwayTransmissionException(e.Message, e);
            }
            catch (Exception e)
            {
                throw new HyperwayTransmissionException("Unable to parse received content.", e);
            }
            finally
            {
                span.Record(Annotations.ClientRecv());
            }
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Receives an AS2 Message in the form of a map of headers together with the payload,
        /// which is made available in an input stream
        /// <p>If persisting message to the Message Repository fails, we have to return negative MDN.</p>
        /// </summary>
        /// <param name="httpHeaders">the http headers received</param>
        /// <param name="mimeMessage">supplies the MIME message</param>
        /// <returns>MDN object to signal if everything is ok or if some error occurred while receiving</returns>
        public MimeMessage Receive(IHeaderDictionary httpHeaders, MimeMessage mimeMessage)
        {
            Logger.Debug("Receiving message ..");

            SMimeReader sMimeReader = new SMimeReader(mimeMessage);

            // Get timestamp using signature as input
            Timestamp t2 = this.timestampProvider.Generate(sMimeReader.GetSignature(), Direction.IN);

            // Initiate MDN
            MdnBuilder mdnBuilder = MdnBuilder.NewInstance(mimeMessage);

            mdnBuilder.AddHeader(MdnHeader.Date, t2.GetDate());


            // Extract Message-ID
            TransmissionIdentifier transmissionIdentifier =
                TransmissionIdentifier.FromHeader(httpHeaders[As2Header.MessageId]);

            mdnBuilder.AddHeader(MdnHeader.OriginalMessageId, httpHeaders[As2Header.MessageId]);


            // Extract signed digest and digest algorithm
            SMimeDigestMethod digestMethod = sMimeReader.GetDigestMethod();

            // Extract content headers
            byte[] headerBytes = sMimeReader.GetBodyHeader();
            Stream bodyStream  = sMimeReader.GetBodyInputStream();

            byte[] bodyBytes = bodyStream.ToBuffer();

            mdnBuilder.AddHeader(MdnHeader.OriginalContentHeader, headerBytes);


            // Extract SBDH
            Mx.Peppol.Common.Model.Header header;
            bodyStream.Seek(0, SeekOrigin.Begin);
            using (var sbdReader = SbdReader.NewInstance(bodyStream))
            {
                header = sbdReader.Header;

                // Perform validation of SBDH
                this.transmissionVerifier.Verify(header, Direction.IN);

                // Extract "fresh" InputStream
                using (Stream payloadInputStream = sMimeReader.GetBodyInputStream())
                {
                    // Persist content
                    this.persisterHandler.Persist(
                        transmissionIdentifier,
                        header,
                        new UnclosableInputStream(payloadInputStream));
                }

                // Fetch calculated digest
                var    s                = SHA1.Create();
                var    hash             = s.ComputeHash(headerBytes.Concat(bodyBytes).ToArray());
                Digest calculatedDigest = Digest.Of(DigestMethod.Sha1, hash);
                mdnBuilder.AddHeader(MdnHeader.ReceivedContentMic, new Mic(calculatedDigest));

                var check = this.VerifySignature(mimeMessage.Body as MultipartSigned, out var signatures);
                if (!check || signatures.Count != 1)
                {
                    throw new NotSupportedException("Firma non valida");
                }

                var signature   = signatures[0];
                var certificate = signature.SignerCertificate as SecureMimeDigitalCertificate;
                Debug.Assert(certificate != null, nameof(certificate) + " != null");
                this.certificateValidator.Validate(Service.Ap, certificate.Certificate);

                // Create receipt (MDN)
                mdnBuilder.AddHeader(MdnHeader.Disposition, Disposition.Processed);
                MimeMessage mdn = this.sMimeMessageFactory.CreateSignedMimeMessage(mdnBuilder.Build(), digestMethod);
                mdn.Headers.Add(As2Header.As2Version, As2Header.Version);
                mdn.Headers.Add(As2Header.As2From, httpHeaders[As2Header.As2To]);
                mdn.Headers.Add(As2Header.As2To, httpHeaders[As2Header.As2From]);

                return(mdn);
            }
        }