Example #1
0
 public static Mic ValueOf(String receivedContentMic)
 {
     String[] s = receivedContentMic.Split(',');
     if (s.Length != 2)
     {
         throw new ArgumentException("Invalid mic: '" + receivedContentMic + "'. Required syntax: encoded-message-digest \",\" (sha1|md5)");
     }
     return(new Mic(s[0].Trim(), SMimeDigestMethod.FindByIdentifier(s[1].Trim())));
 }
Example #2
0
        protected HttpPost PrepareHttpRequest()
        {
            Trace span = this.root.Child();

            span.Record(Annotations.ServiceName("request"));
            span.Record(Annotations.ClientSend());
            try
            {
                HttpPost httpPost;

                // Create the body part of the MIME message containing our content to be transmitted.
                MimeEntity mimeBodyPart = MimeMessageHelper.CreateMimeBodyPart(
                    this.transmissionRequest.GetPayload(),
                    "application/xml");

                // Digest method to use.
                SMimeDigestMethod digestMethod =
                    SMimeDigestMethod.FindByTransportProfile(
                        this.transmissionRequest.GetEndpoint().TransportProfile);



                // Create a complete S/MIME message using the body part containing our content as the
                // signed part of the S/MIME message.
                MimeMessage signedMimeMessage =
                    this.sMimeMessageFactory.CreateSignedMimeMessage(mimeBodyPart, digestMethod);

                var signedMultipart = (signedMimeMessage.Body as MultipartSigned);
                Debug.Assert(signedMultipart != null, nameof(signedMultipart) + " != null");
                this.outboundMic = MimeMessageHelper.CalculateMic(signedMultipart[0], digestMethod);
                span.Record(Annotations.Tag("mic", this.outboundMic.ToString()));
                span.Record(Annotations.Tag("endpoint url", this.transmissionRequest.GetEndpoint().Address.ToString()));

                // Initiate POST request
                httpPost = new HttpPost(this.transmissionRequest.GetEndpoint().Address);

                foreach (var header in signedMimeMessage.Headers)
                {
                    span.Record(Annotations.Tag(header.Field, header.Value));
                    httpPost.AddHeader(header.Field, header.Value.Replace("\r\n\t", string.Empty));
                }
                signedMimeMessage.Headers.Clear();

                this.transmissionIdentifier = TransmissionIdentifier.FromHeader(httpPost.Headers[As2Header.MessageId]);

                // Write content to OutputStream without headers.
                using (var m = new MemoryStream())
                {
                    signedMultipart.WriteTo(m);
                    httpPost.Entity = m.ToBuffer();
                }

                var contentType = signedMultipart.Headers[HeaderId.ContentType];

                // Set all headers specific to AS2 (not MIME).
                httpPost.Host = "skynet.sediva.it";
                httpPost.Headers.Add("Content-Type", this.NormalizeHeaderValue(contentType));
                httpPost.Headers.Add(As2Header.As2From, this.fromIdentifier);
                httpPost.Headers.Add(
                    As2Header.As2To,
                    CertificateUtils.ExtractCommonName(this.transmissionRequest.GetEndpoint().Certificate));
                httpPost.Headers.Add(As2Header.DispositionNotificationTo, "*****@*****.**");
                httpPost.Headers.Add(
                    As2Header.DispositionNotificationOptions,
                    As2DispositionNotificationOptions.GetDefault(digestMethod).ToString());
                httpPost.Headers.Add(As2Header.As2Version, As2Header.Version);
                httpPost.Headers.Add(As2Header.Subject, "AS2 message from HYPERWAY");
                httpPost.Headers.Add(As2Header.Date, As2DateUtil.Rfc822.GetFormat(DateTime.Now));
                return(httpPost);
            }
            catch (Exception)
            {
                throw new HyperwayTransmissionException(
                          "Unable to stream S/MIME message into byte array output stream");
            }
            finally
            {
                span.Record(Annotations.ClientRecv());
            }
        }
Example #3
0
 public Mic(String digestAsString, SMimeDigestMethod algorithm)
 {
     this.digestAsString = digestAsString;
     this.algorithm      = algorithm;
 }
Example #4
0
 public Mic(Digest digest) : this(new Base64Encoding().ToString(digest.Value),
                                  SMimeDigestMethod.FindByDigestMethod(digest.Method))
 {
 }
Example #5
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);
            }
        }
 public static As2DispositionNotificationOptions GetDefault(SMimeDigestMethod digestMethod)
 {
     return(ValueOf(
                "signed-receipt-protocol=required,pkcs7-signature; signed-receipt-micalg=required,"
                + digestMethod.GetIdentifier()));
 }