/// <summary>
		/// Initializes a new instance of the <see cref="MimeKit.Cryptography.PrivateKeyNotFoundException"/> class.
		/// </summary>
		/// <remarks>
		/// Creates a new <see cref="PrivateKeyNotFoundException"/>.
		/// </remarks>
		/// <param name="mailbox">The mailbox that could not be resolved to a valid private key.</param>
		/// <param name="message">A message explaining the error.</param>
		/// <exception cref="System.ArgumentNullException">
		/// <paramref name="mailbox"/> is <c>null</c>.
		/// </exception>
		public PrivateKeyNotFoundException (MailboxAddress mailbox, string message) : base (message)
		{
			if (mailbox == null)
				throw new ArgumentNullException ("mailbox");

			KeyId = mailbox.Address;
		}
 /// <summary>
 /// Initializes a new instance of the <see cref="MimeKit.Cryptography.CertificateNotFoundException"/> class.
 /// </summary>
 /// <remarks>
 /// Creates a new <see cref="CertificateNotFoundException"/>.
 /// </remarks>
 /// <param name="mailbox">The mailbox that could not be resolved to a valid certificate.</param>
 /// <param name="message">A message explaining the error.</param>
 public CertificateNotFoundException(MailboxAddress mailbox, string message) : base(message)
 {
     Mailbox = mailbox;
 }
        /// <summary>
        /// Sign the content using the specified signer.
        /// </summary>
        /// <returns>A new <see cref="MimeKit.MimePart"/> instance
        /// containing the detached signature data.</returns>
        /// <param name="signer">The signer.</param>
        /// <param name="digestAlgo">The digest algorithm to use for signing.</param>
        /// <param name="content">The content.</param>
        /// <exception cref="System.ArgumentNullException">
        /// <para><paramref name="signer"/> is <c>null</c>.</para>
        /// <para>-or-</para>
        /// <para><paramref name="content"/> is <c>null</c>.</para>
        /// </exception>
        /// <exception cref="System.ArgumentOutOfRangeException">
        /// <paramref name="digestAlgo"/> is out of range.
        /// </exception>
        /// <exception cref="System.NotSupportedException">
        /// The specified <see cref="DigestAlgorithm"/> is not supported by this context.
        /// </exception>
        /// <exception cref="CertificateNotFoundException">
        /// A signing certificate could not be found for <paramref name="signer"/>.
        /// </exception>
        /// <exception cref="Org.BouncyCastle.Cms.CmsException">
        /// An error occurred in the cryptographic message syntax subsystem.
        /// </exception>
        public override MimePart Sign(MailboxAddress signer, DigestAlgorithm digestAlgo, Stream content)
        {
            if (signer == null)
                throw new ArgumentNullException ("signer");

            if (content == null)
                throw new ArgumentNullException ("content");

            var cmsSigner = GetCmsSigner (signer, digestAlgo);

            return Sign (cmsSigner, content);
        }
		/// <summary>
		/// Finds the certificate records for the specified mailbox.
		/// </summary>
		/// <remarks>
		/// Searches the database for certificates matching the specified mailbox that are valid
		/// for the date and time specified, returning all matching records populated with the
		/// desired fields.
		/// </remarks>
		/// <returns>The matching certificate records populated with the desired fields.</returns>
		/// <param name="mailbox">The mailbox.</param>
		/// <param name="now">The date and time.</param>
		/// <param name="requirePrivateKey"><c>true</c> if a private key is required.</param>
		/// <param name="fields">The desired fields.</param>
		/// <exception cref="System.ArgumentNullException">
		/// <paramref name="mailbox"/> is <c>null</c>.
		/// </exception>
		public IEnumerable<X509CertificateRecord> Find (MailboxAddress mailbox, DateTime now, bool requirePrivateKey, X509CertificateRecordFields fields)
		{
			if (mailbox == null)
				throw new ArgumentNullException ("mailbox");

			using (var command = GetSelectCommand (mailbox, now, requirePrivateKey, fields)) {
				var reader = command.ExecuteReader ();

				try {
					var parser = new X509CertificateParser ();
					var buffer = new byte[4096];

					while (reader.Read ()) {
						yield return LoadCertificateRecord (reader, parser, ref buffer);
					}
				} finally {
					reader.Close ();
				}
			}

			yield break;
		}
		/// <summary>
		/// Gets the cms signer for the specified <see cref="MimeKit.MailboxAddress"/>.
		/// </summary>
		/// <remarks>
		/// Gets the cms signer for the specified <see cref="MimeKit.MailboxAddress"/>.
		/// </remarks>
		/// <returns>The cms signer.</returns>
		/// <param name="mailbox">The mailbox.</param>
		/// <param name="digestAlgo">The preferred digest algorithm.</param>
		/// <exception cref="CertificateNotFoundException">
		/// A certificate for the specified <paramref name="mailbox"/> could not be found.
		/// </exception>
		protected override CmsSigner GetCmsSigner (MailboxAddress mailbox, DigestAlgorithm digestAlgo)
		{
			var certificate = GetCmsSignerCertificate (mailbox);
			var pair = DotNetUtilities.GetKeyPair (certificate.PrivateKey);
			var cert = DotNetUtilities.FromX509Certificate (certificate);
			var signer = new CmsSigner (cert, pair.Private);
			signer.DigestAlgorithm = digestAlgo;
			return signer;
		}
        X509Certificate2 GetCmsRecipientCertificate(MailboxAddress mailbox)
        {
            var store = new X509Store (StoreName.My, StoreLocation);
            var now = DateTime.Now;

            store.Open (OpenFlags.ReadOnly);

            try {
                foreach (var certificate in store.Certificates) {
                    if (certificate.NotBefore > now || certificate.NotAfter < now)
                        continue;

                    var usage = certificate.Extensions[X509Extensions.KeyUsage.Id] as X509KeyUsageExtension;
                    if (usage != null && (usage.KeyUsages & RealX509KeyUsageFlags.DataEncipherment) == 0)
                        continue;

                    if (certificate.GetNameInfo (X509NameType.EmailName, false) != mailbox.Address)
                        continue;

                    return certificate;
                }
            } finally {
                store.Close ();
            }

            throw new CertificateNotFoundException (mailbox, "A valid certificate could not be found.");
        }
		/// <summary>
		/// Gets the signing key associated with the mailbox address.
		/// </summary>
		/// <remarks>
		/// Gets the signing key associated with the mailbox address.
		/// </remarks>
		/// <returns>The signing key.</returns>
		/// <param name="mailbox">The mailbox.</param>
		/// <exception cref="System.ArgumentNullException">
		/// <paramref name="mailbox"/> is <c>null</c>.
		/// </exception>
		/// <exception cref="PrivateKeyNotFoundException">
		/// A private key for the specified <paramref name="mailbox"/> could not be found.
		/// </exception>
		protected virtual PgpSecretKey GetSigningKey (MailboxAddress mailbox)
		{
			if (mailbox == null)
				throw new ArgumentNullException ("mailbox");

			foreach (PgpSecretKeyRing keyring in SecretKeyRingBundle.GetKeyRings ()) {
				foreach (PgpSecretKey key in keyring.GetSecretKeys ()) {
					if (!PgpSecretKeyMatches (keyring.GetSecretKey (), mailbox))
						continue;

					if (!key.IsSigningKey)
						continue;

					var pubkey = key.PublicKey;
					if (pubkey.IsRevoked ())
						continue;

					long seconds = pubkey.GetValidSeconds ();
					if (seconds != 0) {
						var expires = pubkey.CreationTime.AddSeconds ((double) seconds);
						if (DateTime.Now >= expires)
							continue;
					}

					return key;
				}
			}

			throw new PrivateKeyNotFoundException (mailbox, "The private key could not be found.");
		}
Exemple #8
0
        public IActionResult Index([Bind] Contacto contacto)
        {
            string sRet;


            try
            {
                if (ModelState.IsValid)
                {
                    // Por ahora hardcodeo la marca hasta que esté en el frontend
                    //registro.marca_id = 1;

                    sRet = Validar(contacto);

                    if (sRet != "")
                    {
                        ViewBag.Message = sRet;


                        ViewBag.ListOfProvincias = Datos.ObtenerProvincias();

                        return(View(contacto));
                    }

                    if (Datos.InsertarConsulta(contacto) > 0)
                    {
                        IConfigurationBuilder builder = new ConfigurationBuilder()
                                                        .SetBasePath(Directory.GetCurrentDirectory())
                                                        .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);

                        IConfigurationRoot    configuration = builder.Build();
                        IConfigurationSection SmtpServer    = configuration.GetSection("Smtp").GetSection("Server");
                        IConfigurationSection SmtpFrom      = configuration.GetSection("Smtp").GetSection("FromAddress");
                        IConfigurationSection SmtpAdmin     = configuration.GetSection("Smtp").GetSection("AdminAddress");
                        IConfigurationSection SmtpUser      = configuration.GetSection("Smtp").GetSection("User");
                        IConfigurationSection SmtpPassword  = configuration.GetSection("Smtp").GetSection("Password");
                        IConfigurationSection SmtpPort      = configuration.GetSection("Smtp").GetSection("Port");
                        IConfigurationSection UseSSL        = configuration.GetSection("Smtp").GetSection("UseSSL");


                        MimeMessage    message = new MimeMessage();
                        MailboxAddress from    = new MailboxAddress("Admin", SmtpFrom.Value);
                        //MailboxAddress to = new MailboxAddress(contacto.Nombre + ", " + contacto.Apellido, contacto.Email);

                        MailboxAddress to = new MailboxAddress("Arcor", SmtpAdmin.Value);
                        message.Subject = "Consulta desde el Sitio Promo A Todo Bagley 2021";
                        message.To.Add(to);
                        message.From.Add(from);

                        string nl  = "<br/>";
                        string nl2 = System.Environment.NewLine;

                        String sHtmlBody = "";
                        String sTextBody = "";

                        sHtmlBody = sHtmlBody + "*************************************************************************" + nl;
                        sHtmlBody = sHtmlBody + "Email de consulta desde el Sitio Promo A Todo Bagley 2021" + nl;
                        sHtmlBody = sHtmlBody + "*************************************************************************" + nl + nl;
                        sHtmlBody = sHtmlBody + "Datos de la consulta:" + nl;
                        sHtmlBody = sHtmlBody + "Nombre y Apellido: " + contacto.Nombre.Trim() + " " + contacto.Apellido.Trim() + nl;
                        sHtmlBody = sHtmlBody + "Dni: " + contacto.Dni + nl;
                        sHtmlBody = sHtmlBody + "Direccion: " + contacto.Direccion + nl;
                        sHtmlBody = sHtmlBody + "Email: " + contacto.Email + nl;
                        sHtmlBody = sHtmlBody + "Ciudad: " + contacto.Localidad + nl;
                        sHtmlBody = sHtmlBody + "Provincia: " + contacto.Provincia + nl;
                        sHtmlBody = sHtmlBody + "Telefono: " + contacto.Area + "-" + contacto.Telefono + nl;
                        sHtmlBody = sHtmlBody + "Movil: " + contacto.AreaMovil + "-" + contacto.Movil + nl;
                        sHtmlBody = sHtmlBody + "Comentarios: " + contacto.Consulta + nl;

                        sTextBody = sTextBody + "*************************************************************************" + nl2;
                        sTextBody = sTextBody + "Email de consulta desde el Sitio Promo A Todo Bagley 2021" + nl2;
                        sTextBody = sTextBody + "*************************************************************************" + nl2 + nl2;
                        sTextBody = sTextBody + "Datos de la consulta:" + nl2;
                        sTextBody = sTextBody + "Nombre y Apellido: " + contacto.Nombre.Trim() + " " + contacto.Apellido.Trim() + nl2;
                        sTextBody = sTextBody + "Dni: " + contacto.Dni + nl2;
                        sTextBody = sTextBody + "Direccion: " + contacto.Direccion + nl2;
                        sTextBody = sTextBody + "Email: " + contacto.Email + nl2;
                        sTextBody = sTextBody + "Ciudad: " + contacto.Localidad + nl2;
                        sTextBody = sTextBody + "Provincia: " + contacto.Provincia + nl2;
                        sTextBody = sTextBody + "Telefono: " + contacto.Area + "-" + contacto.Telefono + nl2;
                        sTextBody = sTextBody + "Movil: " + contacto.AreaMovil + "-" + contacto.Movil + nl2;
                        sTextBody = sTextBody + "Comentarios: " + contacto.Consulta + nl2;


                        BodyBuilder bodyBuilder = new BodyBuilder();
                        bodyBuilder.HtmlBody = sHtmlBody;
                        bodyBuilder.TextBody = sTextBody;
                        message.Body         = bodyBuilder.ToMessageBody();

                        SmtpClient client = new SmtpClient();
                        //client.Connect(SmtpServer.Value, 25, false);
                        client.Connect(SmtpServer.Value, Int32.Parse(SmtpPort.Value), bool.Parse(UseSSL.Value));
                        client.Authenticate(SmtpUser.Value, SmtpPassword.Value);

                        client.Send(message);
                        client.Disconnect(true);
                        client.Dispose();



                        return(RedirectToAction("Gracias", "Contacto"));
                    }

                    else
                    {
                        ViewBag.Message = "Algunos campos estan incompletos.";
                    }
                }


                //ME FIJO SI EL PROBLEMA ES EL CAPTCHA
                var state = ViewData.ModelState.FirstOrDefault(x => x.Key.Equals("Recaptcha"));
                if (state.Value != null && state.Value.Errors.Any(x => !string.IsNullOrEmpty(x.ErrorMessage)))
                {
                    ViewBag.Message = "Revise el CAPTCHA.";
                }
                else
                {
                    ViewBag.Message = "Hubo un problema con el formulario, por favor revise los campos.";
                }
            }
            catch (Exception)
            {
                ViewBag.Message = "Ha ocurrido un error en el sitio. Inténtelo nuevamente.";
                // return RedirectToAction("Index", "Home");
            }


            ViewBag.ListOfProvincias = Datos.ObtenerProvincias();

            return(View(contacto));
        }
 /// <summary>
 /// Gets the <see cref="CmsRecipient"/> for the specified mailbox.
 /// </summary>
 /// <returns>A <see cref="CmsRecipient"/>.</returns>
 /// <param name="mailbox">The mailbox.</param>
 /// <exception cref="CertificateNotFoundException">
 /// A certificate for the specified <paramref name="mailbox"/> could not be found.
 /// </exception>
 protected abstract CmsRecipient GetCmsRecipient(MailboxAddress mailbox);
        public async Task <IActionResult> Privacy()
        {
            var a = new List <string>();

            a.Add("*****@*****.**");

            var mimeMessage = new MimeMessage();

            mimeMessage.From.Add(MailboxAddress.Parse("*****@*****.**"));

            foreach (var item in a)
            {
                mimeMessage.To.Add(MailboxAddress.Parse(item));
            }
            mimeMessage.Subject = "EMAIL_Subject";

            var builder = new BodyBuilder();

            builder.TextBody = "<html><head><meta http-equiv='Content-Type' content='text/html; charset=utf-8' /></head><body leftmargin='0' topmargin='0' marginwidth='0' marginheight='0' width='700' ><table width='650px' border='0' cellpadding='0' cellspacing='0'><tr></tr></table><table width='650px' border='0' cellpadding='0' cellspacing='0' class='Context_tb' ><tr><td class='Context_td01' align='left'>親愛的顧客,您好:<br><br>您於網路郵局終止約定帳戶之申請已完成,該約定帳戶已失效。請詳閱附檔,檢視終止帳戶之資料。<br><br></td></tr><tr><td class='Context_td01' align='left'>提醒您,附檔已設定為加密文件,<font color='red'>開啟密碼為您的身分證字號(大寫英文字母+9位數字;外籍人士為居留證號碼:兩個大寫英文字母+8位數字)。</font><br><br></td></tr><tr><td class='Context_td01' align='left'>若您無法看到電子郵件通知單內容,請至Adobe Acrobat官網下載Adobe Reader軟體並安裝。<br><br></td></tr><tr><td class='Context_td01' align='left'>如需任何協助,請隨時致電本公司24小時客戶服務中心0800-700-365,手機請改撥付費電話(04)23542030。<br><br>本信件由系統發出,請勿直接回覆此信。</td></tr></td></tr></table></body></html>";
            var attachmentPath = @"D:\Yong-Wen Huang_CV(English).pdf";

            // We may also want to attach a calendar event for Monica's party...
            if (!System.IO.File.Exists(attachmentPath))
            {
                var aa = @"D:\Yong-Wen Huang_CV(English).pdf";
                return(View());
            }
            builder.Attachments.Add(attachmentPath);

            // Now we just need to set the message body and we're done
            mimeMessage.Body = builder.ToMessageBody();

            try
            {
                using (SmtpClient smtpClient = new SmtpClient())
                {
                    await smtpClient.ConnectAsync("smtp.gmail.com", 465, true);

                    await smtpClient.AuthenticateAsync("*****@*****.**", "rqnaqrtjjyygujyg");

                    await smtpClient.SendAsync(mimeMessage);

                    await smtpClient.DisconnectAsync(true);
                }
            }
            catch (SmtpCommandException ex)
            {
                switch (ex.ErrorCode)
                {
                case SmtpErrorCode.RecipientNotAccepted:
                    _logger.LogError(ex, $"\tRecipient not accepted: {ex.Mailbox}");
                    break;

                case SmtpErrorCode.SenderNotAccepted:
                    _logger.LogError(ex, $"\tSender not accepted: {ex.Mailbox}");
                    break;

                case SmtpErrorCode.MessageNotAccepted:
                    _logger.LogError(ex, $"\tMessage not accepted.");
                    break;
                }
                var b = await SendMailThread(mimeMessage, 0).ConfigureAwait(false);
            }
            catch (SmtpProtocolException ex)
            {
                _logger.LogError(ex, $"Protocol error while sending message: {ex.Message}");
                var b = await SendMailThread(mimeMessage, 0).ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"Protocol error while sending message: {ex.Message}");
                var b = await SendMailThread(mimeMessage, 0).ConfigureAwait(false);

                var adfs = 0;
            }

            return(View());
        }
Exemple #11
0
        public void Send(string subject, string content, MessagePriority priority)
        {
            if (Enabled)
            {
                try
                {
                    using var client = new SmtpClient();
                    var options = SecureSocketOptions.None;
                    if (_secure)
                    {
                        if (_secureMode.HasValue)
                        {
                            switch (_secureMode.Value)
                            {
                            case 1:
                                options = SecureSocketOptions.Auto;
                                break;

                            case 2:
                                options = SecureSocketOptions.SslOnConnect;
                                break;

                            case 3:
                                options = SecureSocketOptions.StartTls;
                                break;

                            case 4:
                                options = SecureSocketOptions.StartTlsWhenAvailable;
                                break;
                            }
                        }
                        else
                        {
                            options = SecureSocketOptions.StartTls;
                        }
                    }
                    client.Connect(_server, _port, options);
                    if (!string.IsNullOrEmpty(_user))
                    {
                        client.Authenticate(new NetworkCredential(_user, _password));
                    }
                    foreach (var receiverAddress in _receiverAddresses)
                    {
                        _log.Information("Sending e-mail with subject {subject} to {_receiverAddress}", subject, receiverAddress);
                        var sender   = new MailboxAddress(_senderName, _senderAddress);
                        var receiver = new MailboxAddress(receiverAddress);
                        var message  = new MimeMessage()
                        {
                            Sender   = sender,
                            Priority = priority,
                            Subject  = subject
                        };
                        message.Subject = subject;
                        message.From.Add(sender);
                        message.To.Add(receiver);
                        var bodyBuilder = new BodyBuilder();
                        bodyBuilder.HtmlBody = content + $"<p>Sent by win-acme version {Assembly.GetEntryAssembly().GetName().Version} from {Environment.MachineName}</p>";
                        message.Body         = bodyBuilder.ToMessageBody();
                        client.Send(message);
                    }
                }
                catch (Exception ex)
                {
                    _log.Error(ex, "Problem sending e-mail");
                }
            }
        }
Exemple #12
0
        private MimeMessage BuildMailMessage(NotifyMessage m)
        {
            var mimeMessage = new MimeMessage
            {
                Subject = m.Subject
            };

            var fromAddress = MailboxAddress.Parse(ParserOptions.Default, m.From);

            mimeMessage.From.Add(fromAddress);

            foreach (var to in m.To.Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries))
            {
                mimeMessage.To.Add(MailboxAddress.Parse(ParserOptions.Default, to));
            }

            if (m.ContentType == Pattern.HTMLContentType)
            {
                var textPart = new TextPart("plain")
                {
                    Text = HtmlUtil.GetText(m.Content),
                    ContentTransferEncoding = ContentEncoding.QuotedPrintable
                };

                var multipartAlternative = new MultipartAlternative {
                    textPart
                };

                var htmlPart = new TextPart("html")
                {
                    Text = GetHtmlView(m.Content),
                    ContentTransferEncoding = ContentEncoding.QuotedPrintable
                };

                if (m.EmbeddedAttachments != null && m.EmbeddedAttachments.Count > 0)
                {
                    var multipartRelated = new MultipartRelated
                    {
                        Root = htmlPart
                    };

                    foreach (var attachment in m.EmbeddedAttachments)
                    {
                        var mimeEntity = ConvertAttachmentToMimePart(attachment);
                        if (mimeEntity != null)
                        {
                            multipartRelated.Add(mimeEntity);
                        }
                    }

                    multipartAlternative.Add(multipartRelated);
                }
                else
                {
                    multipartAlternative.Add(htmlPart);
                }

                mimeMessage.Body = multipartAlternative;
            }
            else
            {
                mimeMessage.Body = new TextPart("plain")
                {
                    Text = m.Content,
                    ContentTransferEncoding = ContentEncoding.QuotedPrintable
                };
            }

            if (!string.IsNullOrEmpty(m.ReplyTo))
            {
                mimeMessage.ReplyTo.Add(MailboxAddress.Parse(ParserOptions.Default, m.ReplyTo));
            }

            mimeMessage.Headers.Add("Auto-Submitted", string.IsNullOrEmpty(m.AutoSubmitted) ? "auto-generated" : m.AutoSubmitted);

            return(mimeMessage);
        }
Exemple #13
0
        private static string ExtractEmail(string emailString)
        {
            var mailboxAddress = new MailboxAddress(emailString);

            return(mailboxAddress.Address);
        }
Exemple #14
0
 public void MailBoxAddress_ShouldParseEmail(string text, string name, string address)
 {
     Assert.True(MailboxAddress.TryParse(text, out var mailboxAddress));
     Assert.Equal(name, mailboxAddress.Name);
     Assert.Equal(address, mailboxAddress.Address);
 }
		/// <summary>
		/// Cryptographically signs the specified entity.
		/// </summary>
		/// <remarks>
		/// <para>Signs the entity using the supplied signer, digest algorithm and the default
		/// <see cref="SecureMimeContext"/>.</para>
		/// <para>For better interoperability with other mail clients, you should use
		/// <see cref="MultipartSigned.Create(SecureMimeContext, CmsSigner, MimeEntity)"/>
		/// instead as the multipart/signed format is supported among a much larger
		/// subset of mail client software.</para>
		/// </remarks>
		/// <returns>The signed entity.</returns>
		/// <param name="signer">The signer.</param>
		/// <param name="digestAlgo">The digest algorithm to use for signing.</param>
		/// <param name="entity">The entity.</param>
		/// <exception cref="System.ArgumentNullException">
		/// <para><paramref name="signer"/> is <c>null</c>.</para>
		/// <para>-or-</para>
		/// <para><paramref name="entity"/> is <c>null</c>.</para>
		/// </exception>
		/// <exception cref="CertificateNotFoundException">
		/// A signing certificate could not be found for <paramref name="signer"/>.
		/// </exception>
		/// <exception cref="Org.BouncyCastle.Cms.CmsException">
		/// An error occurred in the cryptographic message syntax subsystem.
		/// </exception>
		public static ApplicationPkcs7Mime Sign (MailboxAddress signer, DigestAlgorithm digestAlgo, MimeEntity entity)
		{
			if (signer == null)
				throw new ArgumentNullException (nameof (signer));

			if (entity == null)
				throw new ArgumentNullException (nameof (entity));

			using (var ctx = (SecureMimeContext) CryptographyContext.Create ("application/pkcs7-mime")) {
				return Sign (ctx, signer, digestAlgo, entity);
			}
		}
Exemple #16
0
 /// <summary>
 /// Gets the <see cref="CmsSigner"/> for the specified mailbox.
 /// </summary>
 /// <returns>A <see cref="CmsSigner"/>.</returns>
 /// <param name="mailbox">The mailbox.</param>
 /// <param name="digestAlgo">The preferred digest algorithm.</param>
 /// <exception cref="CertificateNotFoundException">
 /// A certificate for the specified <paramref name="mailbox"/> could not be found.
 /// </exception>
 protected abstract CmsSigner GetCmsSigner(MailboxAddress mailbox, DigestAlgorithm digestAlgo);
		/// <summary>
		/// Cryptographically signs and encrypts the specified entity.
		/// </summary>
		/// <remarks>
		/// Cryptographically signs entity using the supplied signer and then
		/// encrypts the result to the specified recipients.
		/// </remarks>
		/// <returns>The signed and encrypted entity.</returns>
		/// <param name="ctx">The S/MIME context to use for signing and encrypting.</param>
		/// <param name="signer">The signer.</param>
		/// <param name="digestAlgo">The digest algorithm to use for signing.</param>
		/// <param name="recipients">The recipients.</param>
		/// <param name="entity">The entity.</param>
		/// <exception cref="System.ArgumentNullException">
		/// <para><paramref name="ctx"/> is <c>null</c>.</para>
		/// <para>-or-</para>
		/// <para><paramref name="signer"/> is <c>null</c>.</para>
		/// <para>-or-</para>
		/// <para><paramref name="recipients"/> is <c>null</c>.</para>
		/// <para>-or-</para>
		/// <para><paramref name="entity"/> is <c>null</c>.</para>
		/// </exception>
		/// <exception cref="CertificateNotFoundException">
		/// <para>A signing certificate could not be found for <paramref name="signer"/>.</para>
		/// <para>-or-</para>
		/// <para>A certificate could not be found for one or more of the <paramref name="recipients"/>.</para>
		/// </exception>
		/// <exception cref="Org.BouncyCastle.Cms.CmsException">
		/// An error occurred in the cryptographic message syntax subsystem.
		/// </exception>
		public static ApplicationPkcs7Mime SignAndEncrypt (SecureMimeContext ctx, MailboxAddress signer, DigestAlgorithm digestAlgo, IEnumerable<MailboxAddress> recipients, MimeEntity entity)
		{
			if (ctx == null)
				throw new ArgumentNullException ("ctx");

			if (signer == null)
				throw new ArgumentNullException ("signer");

			if (recipients == null)
				throw new ArgumentNullException ("recipients");

			if (entity == null)
				throw new ArgumentNullException ("entity");

			return Encrypt (ctx, recipients, MultipartSigned.Create (ctx, signer, digestAlgo, entity));
		}
Exemple #18
0
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl      = returnUrl ?? Url.Content("~/");
            ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
            if (ModelState.IsValid)
            {
                SwishUser user = new SwishUser
                {
                    UserName = Input.UserName,
                    FName    = Input.FName,
                    LName    = Input.LName,
                    DOB      = Input.DOB,
                    PPicPath = "ProfilePlaceholder.png",
                    Gender   = Input.Gender,
                    Email    = Input.Email
                };
                try
                {
                    if (_userManager.FindByEmailAsync(Input.Email).Result.Email == Input.Email)
                    {
                        ViewData["Error"] = "User with given E-Mail already exists.";
                        return(Page());
                    }
                }
                catch { }

                try
                {
                    if (_userManager.FindByNameAsync(Input.UserName).Result.UserName == Input.UserName)
                    {
                        ViewData["Error"] = "User with given Username already exists.";
                        return(Page());
                    }
                }
                catch { }

                IdentityResult result = await _userManager.CreateAsync(user, Input.Password);

                if (result.Succeeded)
                {
                    _logger.LogInformation("User created a new account with password.");

                    string code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                    code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
                    string callbackUrl = Url.Page(
                        "/Account/ConfirmEmail",
                        pageHandler: null,
                        values: new { area = "Identity", userId = user.Id, code = code },
                        protocol: Request.Scheme);

                    MimeMessage    message     = new MimeMessage();
                    MailboxAddress from        = new MailboxAddress("No-Reply", "*****@*****.**");
                    BodyBuilder    bodyBuilder = new BodyBuilder();
                    MailboxAddress to          = new MailboxAddress(Input.UserName, Input.Email);
                    SmtpClient     client      = new SmtpClient();

                    bodyBuilder.HtmlBody = $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.";

                    message.From.Add(from);
                    message.To.Add(to);
                    message.Subject = "Account E-Mail confirmation";
                    message.Body    = bodyBuilder.ToMessageBody();

                    client.Connect("mail.deepseagt.com", 465, true);
                    client.Authenticate("*****@*****.**", "M^TQ*b#5Hfgb");
                    client.Send(message);
                    client.Disconnect(true);
                    client.Dispose();

                    if (_userManager.Options.SignIn.RequireConfirmedAccount)
                    {
                        return(RedirectToPage("RegisterConfirmation", new { email = Input.Email }));
                    }
                    else
                    {
                        await _signInManager.SignInAsync(user, isPersistent : false);

                        return(LocalRedirect(returnUrl));
                    }
                }
                foreach (IdentityError error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }

            // If we got this far, something failed, redisplay form
            ViewData["Error"] = "There was an error in registering";
            return(Page());
        }
		/// <summary>
		/// Gets the public key associated with the mailbox address.
		/// </summary>
		/// <remarks>
		/// Gets the public key associated with the mailbox address.
		/// </remarks>
		/// <returns>The encryption key.</returns>
		/// <param name="mailbox">The mailbox.</param>
		/// <exception cref="System.ArgumentNullException">
		/// <paramref name="mailbox"/> is <c>null</c>.
		/// </exception>
		/// <exception cref="PublicKeyNotFoundException">
		/// The public key for the specified <paramref name="mailbox"/> could not be found.
		/// </exception>
		protected virtual PgpPublicKey GetPublicKey (MailboxAddress mailbox)
		{
			if (mailbox == null)
				throw new ArgumentNullException ("mailbox");

			foreach (PgpPublicKeyRing keyring in PublicKeyRingBundle.GetKeyRings ()) {
				foreach (PgpPublicKey key in keyring.GetPublicKeys ()) {
					if (!PgpPublicKeyMatches (keyring.GetPublicKey (), mailbox))
						continue;

					if (!key.IsEncryptionKey || key.IsRevoked ())
						continue;

					long seconds = key.GetValidSeconds ();
					if (seconds != 0) {
						var expires = key.CreationTime.AddSeconds ((double) seconds);
						if (expires >= DateTime.Now)
							continue;
					}

					return key;
				}
			}

			throw new PublicKeyNotFoundException (mailbox, "The public key could not be found.");
		}
Exemple #20
0
 /// <summary>
 /// Initializes a new instance of the <see cref="MimeKit.Cryptography.PublicKeyNotFoundException"/> class.
 /// </summary>
 /// <remarks>
 /// Creates a new <see cref="PublicKeyNotFoundException"/>.
 /// </remarks>
 /// <param name="mailbox">The mailbox that could not be resolved to a valid private key.</param>
 /// <param name="message">A message explaining the error.</param>
 public PublicKeyNotFoundException(MailboxAddress mailbox, string message) : base(message)
 {
     Mailbox = mailbox;
 }
		/// <summary>
		/// Creates a new <see cref="MultipartEncrypted"/>.
		/// </summary>
		/// <remarks>
		/// Signs the entity using the supplied signer and digest algorithm and then encrypts to
		/// the specified recipients, encapsulating the result in a new multipart/encrypted part.
		/// </remarks>
		/// <returns>A new <see cref="MimeKit.Cryptography.MultipartEncrypted"/> instance containing
		/// the signed and encrypted version of the specified entity.</returns>
		/// <param name="signer">The signer to use to sign the entity.</param>
		/// <param name="digestAlgo">The digest algorithm to use for signing.</param>
		/// <param name="recipients">The recipients for the encrypted entity.</param>
		/// <param name="entity">The entity to sign and encrypt.</param>
		/// <exception cref="System.ArgumentNullException">
		/// <para><paramref name="signer"/> is <c>null</c>.</para>
		/// <para>-or-</para>
		/// <para><paramref name="recipients"/> is <c>null</c>.</para>
		/// <para>-or-</para>
		/// <para><paramref name="entity"/> is <c>null</c>.</para>
		/// </exception>
		/// <exception cref="System.NotSupportedException">
		/// A default <see cref="OpenPgpContext"/> has not been registered.
		/// </exception>
		/// <exception cref="PrivateKeyNotFoundException">
		/// The private key for <paramref name="signer"/> could not be found.
		/// </exception>
		/// <exception cref="PublicKeyNotFoundException">
		/// A public key for one or more of the <paramref name="recipients"/> could not be found.
		/// </exception>
		/// <exception cref="System.OperationCanceledException">
		/// The user chose to cancel the password prompt.
		/// </exception>
		/// <exception cref="System.UnauthorizedAccessException">
		/// 3 bad attempts were made to unlock the secret key.
		/// </exception>
		public static MultipartEncrypted Create (MailboxAddress signer, DigestAlgorithm digestAlgo, IEnumerable<MailboxAddress> recipients, MimeEntity entity)
		{
			if (signer == null)
				throw new ArgumentNullException ("signer");

			if (recipients == null)
				throw new ArgumentNullException ("recipients");

			if (entity == null)
				throw new ArgumentNullException ("entity");

			using (var ctx = (OpenPgpContext) CryptographyContext.Create ("application/pgp-encrypted")) {
				return Create (ctx, signer, digestAlgo, recipients, entity);
			}
		}
        public virtual void TestSecureMimeEncapsulatedSigning()
        {
            var self = new MailboxAddress("MimeKit UnitTests", "*****@*****.**");

            var cleartext = new TextPart("plain");

            cleartext.Text = "This is some text that we'll end up signing...";

            using (var ctx = CreateContext()) {
                var        signed = ApplicationPkcs7Mime.Sign(ctx, self, DigestAlgorithm.Sha1, cleartext);
                MimeEntity extracted;

                Assert.AreEqual(SecureMimeType.SignedData, signed.SecureMimeType, "S/MIME type did not match.");

                var signatures = signed.Verify(ctx, out extracted);

                Assert.IsInstanceOf <TextPart> (extracted, "Extracted part is not the expected type.");
                Assert.AreEqual(cleartext.Text, ((TextPart)extracted).Text, "Extracted content is not the same as the original.");

                Assert.AreEqual(1, signatures.Count, "Verify returned an unexpected number of signatures.");
                foreach (var signature in signatures)
                {
                    try {
                        bool valid = signature.Verify();

                        Assert.IsTrue(valid, "Bad signature from {0}", signature.SignerCertificate.Email);
                    } catch (DigitalSignatureVerifyException ex) {
                        Assert.Fail("Failed to verify signature: {0}", ex);
                    }

                    var algorithms = ((SecureMimeDigitalSignature)signature).EncryptionAlgorithms;
                    int i          = 0;

                    if (ctx.IsEnabled(EncryptionAlgorithm.Camellia256))
                    {
                        Assert.AreEqual(EncryptionAlgorithm.Camellia256, algorithms[i++], "Expected Camellia-256 capability");
                    }
                    Assert.AreEqual(EncryptionAlgorithm.Aes256, algorithms[i++], "Expected AES-256 capability");
                    if (ctx.IsEnabled(EncryptionAlgorithm.Camellia192))
                    {
                        Assert.AreEqual(EncryptionAlgorithm.Camellia192, algorithms[i++], "Expected Camellia-192 capability");
                    }
                    Assert.AreEqual(EncryptionAlgorithm.Aes192, algorithms[i++], "Expected AES-192 capability");
                    if (ctx.IsEnabled(EncryptionAlgorithm.Camellia128))
                    {
                        Assert.AreEqual(EncryptionAlgorithm.Camellia128, algorithms[i++], "Expected Camellia-128 capability");
                    }
                    Assert.AreEqual(EncryptionAlgorithm.Aes128, algorithms[i++], "Expected AES-128 capability");
                    if (ctx.IsEnabled(EncryptionAlgorithm.Idea))
                    {
                        Assert.AreEqual(EncryptionAlgorithm.Idea, algorithms[i++], "Expected IDEA capability");
                    }
                    if (ctx.IsEnabled(EncryptionAlgorithm.Cast5))
                    {
                        Assert.AreEqual(EncryptionAlgorithm.Cast5, algorithms[i++], "Expected Cast5 capability");
                    }
                    Assert.AreEqual(EncryptionAlgorithm.TripleDes, algorithms[i++], "Expected Triple-DES capability");
                    //Assert.AreEqual (EncryptionAlgorithm.RC2128, algorithms[i++], "Expected RC2-128 capability");
                    //Assert.AreEqual (EncryptionAlgorithm.RC264, algorithms[i++], "Expected RC2-64 capability");
                    //Assert.AreEqual (EncryptionAlgorithm.Des, algorithms[i++], "Expected DES capability");
                    //Assert.AreEqual (EncryptionAlgorithm.RC240, algorithms[i++], "Expected RC2-40 capability");
                }
            }
        }
		RealCmsRecipient GetRealCmsRecipient (MailboxAddress mailbox)
		{
			return new RealCmsRecipient (GetCmsRecipientCertificate (mailbox));
		}
        public virtual void TestSecureMimeSigning()
        {
            var body = new TextPart("plain")
            {
                Text = "This is some cleartext that we'll end up signing..."
            };
            var self    = new MailboxAddress("MimeKit UnitTests", "*****@*****.**");
            var message = new MimeMessage {
                Subject = "Test of signing with S/MIME"
            };

            message.From.Add(self);
            message.Body = body;

            using (var ctx = CreateContext()) {
                message.Sign(ctx);

                Assert.IsInstanceOf <MultipartSigned> (message.Body, "The message body should be a multipart/signed.");

                var multipart = (MultipartSigned)message.Body;

                Assert.AreEqual(2, multipart.Count, "The multipart/signed has an unexpected number of children.");

                var protocol = multipart.ContentType.Parameters["protocol"];
                Assert.AreEqual(ctx.SignatureProtocol, protocol, "The multipart/signed protocol does not match.");

                Assert.IsInstanceOf <TextPart> (multipart[0], "The first child is not a text part.");
                Assert.IsInstanceOf <ApplicationPkcs7Signature> (multipart[1], "The second child is not a detached signature.");

                var signatures = multipart.Verify(ctx);
                Assert.AreEqual(1, signatures.Count, "Verify returned an unexpected number of signatures.");
                foreach (var signature in signatures)
                {
                    try {
                        bool valid = signature.Verify();

                        Assert.IsTrue(valid, "Bad signature from {0}", signature.SignerCertificate.Email);
                    } catch (DigitalSignatureVerifyException ex) {
                        Assert.Fail("Failed to verify signature: {0}", ex);
                    }

                    var algorithms = ((SecureMimeDigitalSignature)signature).EncryptionAlgorithms;
                    int i          = 0;

                    if (ctx.IsEnabled(EncryptionAlgorithm.Camellia256))
                    {
                        Assert.AreEqual(EncryptionAlgorithm.Camellia256, algorithms[i++], "Expected Camellia-256 capability");
                    }
                    Assert.AreEqual(EncryptionAlgorithm.Aes256, algorithms[i++], "Expected AES-256 capability");
                    if (ctx.IsEnabled(EncryptionAlgorithm.Camellia192))
                    {
                        Assert.AreEqual(EncryptionAlgorithm.Camellia192, algorithms[i++], "Expected Camellia-192 capability");
                    }
                    Assert.AreEqual(EncryptionAlgorithm.Aes192, algorithms[i++], "Expected AES-192 capability");
                    if (ctx.IsEnabled(EncryptionAlgorithm.Camellia128))
                    {
                        Assert.AreEqual(EncryptionAlgorithm.Camellia128, algorithms[i++], "Expected Camellia-128 capability");
                    }
                    Assert.AreEqual(EncryptionAlgorithm.Aes128, algorithms[i++], "Expected AES-128 capability");
                    if (ctx.IsEnabled(EncryptionAlgorithm.Idea))
                    {
                        Assert.AreEqual(EncryptionAlgorithm.Idea, algorithms[i++], "Expected IDEA capability");
                    }
                    if (ctx.IsEnabled(EncryptionAlgorithm.Cast5))
                    {
                        Assert.AreEqual(EncryptionAlgorithm.Cast5, algorithms[i++], "Expected Cast5 capability");
                    }
                    Assert.AreEqual(EncryptionAlgorithm.TripleDes, algorithms[i++], "Expected Triple-DES capability");
                    //Assert.AreEqual (EncryptionAlgorithm.RC2128, algorithms[i++], "Expected RC2-128 capability");
                    //Assert.AreEqual (EncryptionAlgorithm.RC264, algorithms[i++], "Expected RC2-64 capability");
                    //Assert.AreEqual (EncryptionAlgorithm.Des, algorithms[i++], "Expected DES capability");
                    //Assert.AreEqual (EncryptionAlgorithm.RC240, algorithms[i++], "Expected RC2-40 capability");
                }
            }
        }
		/// <summary>
		/// Sign the content using the specified signer.
		/// </summary>
		/// <remarks>
		/// Sign the content using the specified signer.
		/// </remarks>
		/// <returns>A new <see cref="MimeKit.MimePart"/> instance
		/// containing the detached signature data.</returns>
		/// <param name="signer">The signer.</param>
		/// <param name="digestAlgo">The digest algorithm to use for signing.</param>
		/// <param name="content">The content.</param>
		/// <exception cref="System.ArgumentNullException">
		/// <para><paramref name="signer"/> is <c>null</c>.</para>
		/// <para>-or-</para>
		/// <para><paramref name="content"/> is <c>null</c>.</para>
		/// </exception>
		/// <exception cref="System.ArgumentOutOfRangeException">
		/// <paramref name="digestAlgo"/> is out of range.
		/// </exception>
		/// <exception cref="System.NotSupportedException">
		/// The specified <see cref="DigestAlgorithm"/> is not supported by this context.
		/// </exception>
		/// <exception cref="CertificateNotFoundException">
		/// A signing certificate could not be found for <paramref name="signer"/>.
		/// </exception>
		/// <exception cref="System.Security.Cryptography.CryptographicException">
		/// An error occurred in the cryptographic message syntax subsystem.
		/// </exception>
		public override MimePart Sign (MailboxAddress signer, DigestAlgorithm digestAlgo, Stream content)
		{
			if (signer == null)
				throw new ArgumentNullException ("signer");

			if (content == null)
				throw new ArgumentNullException ("content");

			var contentInfo = new ContentInfo (ReadAllBytes (content));
			var cmsSigner = GetRealCmsSigner (signer, digestAlgo);
			var signed = new SignedCms (contentInfo, true);
			signed.ComputeSignature (cmsSigner);
			var signedData = signed.Encode ();

			return new ApplicationPkcs7Signature (new MemoryStream (signedData, false));
		}
        public void RunJob(DistributedTask _, CancellationToken cancellationToken)
        {
            try
            {
                CancellationToken = cancellationToken;

                SetProgress(5, "Setup tenant");

                TenantManager.SetCurrentTenant(CurrentTenant);

                SetProgress(10, "Setup user");

                SecurityContext.AuthenticateMe(CurrentUser); //Core.Configuration.Constants.CoreSystem);

                SetProgress(15, "Find user data");

                var currentUser = UserManager.GetUsers(SecurityContext.CurrentAccount.ID);

                SetProgress(20, "Create mime message");

                var toAddress = new MailboxAddress(currentUser.UserName, currentUser.Email);

                var fromAddress = new MailboxAddress(SmtpSettings.SenderDisplayName, SmtpSettings.SenderAddress);

                var mimeMessage = new MimeMessage
                {
                    Subject = messageSubject
                };

                mimeMessage.From.Add(fromAddress);

                mimeMessage.To.Add(toAddress);

                var bodyBuilder = new BodyBuilder
                {
                    TextBody = messageBody
                };

                mimeMessage.Body = bodyBuilder.ToMessageBody();

                mimeMessage.Headers.Add("Auto-Submitted", "auto-generated");

                using var client = GetSmtpClient();
                SetProgress(40, "Connect to host");

                client.Connect(SmtpSettings.Host, SmtpSettings.Port.GetValueOrDefault(25),
                               SmtpSettings.EnableSSL ? SecureSocketOptions.Auto : SecureSocketOptions.None, cancellationToken);

                if (SmtpSettings.EnableAuth)
                {
                    SetProgress(60, "Authenticate");

                    client.Authenticate(SmtpSettings.CredentialsUserName,
                                        SmtpSettings.CredentialsUserPassword, cancellationToken);
                }

                SetProgress(80, "Send test message");

                client.Send(FormatOptions.Default, mimeMessage, cancellationToken);
            }
            catch (AuthorizingException authError)
            {
                Error = Resource.ErrorAccessDenied; // "No permissions to perform this action";
                Logger.Error(Error, new SecurityException(Error, authError));
            }
            catch (AggregateException ae)
            {
                ae.Flatten().Handle(e => e is TaskCanceledException || e is OperationCanceledException);
            }
            catch (SocketException ex)
            {
                Error = ex.Message; //TODO: Add translates of ordinary cases
                Logger.Error(ex.ToString());
            }
            catch (AuthenticationException ex)
            {
                Error = ex.Message; //TODO: Add translates of ordinary cases
                Logger.Error(ex.ToString());
            }
            catch (Exception ex)
            {
                Error = ex.Message; //TODO: Add translates of ordinary cases
                Logger.Error(ex.ToString());
            }
            finally
            {
                try
                {
                    TaskInfo.SetProperty(FINISHED, true);
                    PublishTaskInfo();

                    SecurityContext.Logout();
                }
                catch (Exception ex)
                {
                    Logger.ErrorFormat("LdapOperation finalization problem. {0}", ex);
                }
            }
        }
		/// <summary>
		/// Initializes a new instance of the <see cref="MimeKit.Cryptography.PublicKeyNotFoundException"/> class.
		/// </summary>
		/// <remarks>
		/// Creates a new <see cref="PublicKeyNotFoundException"/>.
		/// </remarks>
		/// <param name="mailbox">The mailbox that could not be resolved to a valid private key.</param>
		/// <param name="message">A message explaining the error.</param>
		public PublicKeyNotFoundException (MailboxAddress mailbox, string message) : base (message)
		{
			Mailbox = mailbox;
		}
Exemple #28
0
 /// <summary>
 /// Asynchronously send the specified message using the supplied sender and recipients.
 /// </summary>
 /// <remarks>
 /// Asynchronously sends the specified message using the supplied sender and recipients.
 /// </remarks>
 /// <returns>An asynchronous task context.</returns>
 /// <param name="message">The message.</param>
 /// <param name="sender">The mailbox address to use for sending the message.</param>
 /// <param name="recipients">The mailbox addresses that should receive the message.</param>
 /// <param name="cancellationToken">The cancellation token.</param>
 /// <param name="progress">The progress reporting mechanism.</param>
 /// <exception cref="System.ArgumentNullException">
 /// <para><paramref name="message"/> is <c>null</c>.</para>
 /// <para>-or-</para>
 /// <para><paramref name="sender"/> is <c>null</c>.</para>
 /// <para>-or-</para>
 /// <para><paramref name="recipients"/> is <c>null</c>.</para>
 /// </exception>
 /// <exception cref="System.ObjectDisposedException">
 /// The <see cref="MailTransport"/> has been disposed.
 /// </exception>
 /// <exception cref="ServiceNotConnectedException">
 /// The <see cref="MailTransport"/> is not connected.
 /// </exception>
 /// <exception cref="ServiceNotAuthenticatedException">
 /// Authentication is required before sending a message.
 /// </exception>
 /// <exception cref="System.InvalidOperationException">
 /// <para>A sender has not been specified.</para>
 /// <para>-or-</para>
 /// <para>No recipients have been specified.</para>
 /// </exception>
 /// <exception cref="System.OperationCanceledException">
 /// The operation has been canceled.
 /// </exception>
 /// <exception cref="System.IO.IOException">
 /// An I/O error occurred.
 /// </exception>
 /// <exception cref="CommandException">
 /// The send command failed.
 /// </exception>
 /// <exception cref="ProtocolException">
 /// A protocol exception occurred.
 /// </exception>
 public virtual Task SendAsync(MimeMessage message, MailboxAddress sender, IEnumerable <MailboxAddress> recipients, CancellationToken cancellationToken = default(CancellationToken), ITransferProgress progress = null)
 {
     return(SendAsync(DefaultOptions, message, sender, recipients, cancellationToken, progress));
 }
 /// <summary>
 /// Gets the <see cref="CmsSigner"/> for the specified mailbox.
 /// </summary>
 /// <returns>A <see cref="CmsSigner"/>.</returns>
 /// <param name="mailbox">The mailbox.</param>
 /// <param name="digestAlgo">The preferred digest algorithm.</param>
 /// <exception cref="CertificateNotFoundException">
 /// A certificate for the specified <paramref name="mailbox"/> could not be found.
 /// </exception>
 protected abstract CmsSigner GetCmsSigner(MailboxAddress mailbox, DigestAlgorithm digestAlgo);
Exemple #30
0
 /// <summary>
 /// Asynchronously send the specified message using the supplied sender and recipients.
 /// </summary>
 /// <remarks>
 /// Asynchronously sends the specified message using the supplied sender and recipients.
 /// </remarks>
 /// <returns>An asynchronous task context.</returns>
 /// <param name="options">The formatting options.</param>
 /// <param name="message">The message.</param>
 /// <param name="sender">The mailbox address to use for sending the message.</param>
 /// <param name="recipients">The mailbox addresses that should receive the message.</param>
 /// <param name="cancellationToken">The cancellation token.</param>
 /// <param name="progress">The progress reporting mechanism.</param>
 /// <exception cref="System.ArgumentNullException">
 /// <para><paramref name="options"/> is <c>null</c>.</para>
 /// <para>-or-</para>
 /// <para><paramref name="message"/> is <c>null</c>.</para>
 /// <para>-or-</para>
 /// <para><paramref name="sender"/> is <c>null</c>.</para>
 /// <para>-or-</para>
 /// <para><paramref name="recipients"/> is <c>null</c>.</para>
 /// </exception>
 /// <exception cref="System.ObjectDisposedException">
 /// The <see cref="MailTransport"/> has been disposed.
 /// </exception>
 /// <exception cref="ServiceNotConnectedException">
 /// The <see cref="MailTransport"/> is not connected.
 /// </exception>
 /// <exception cref="ServiceNotAuthenticatedException">
 /// Authentication is required before sending a message.
 /// </exception>
 /// <exception cref="System.InvalidOperationException">
 /// <para>A sender has not been specified.</para>
 /// <para>-or-</para>
 /// <para>No recipients have been specified.</para>
 /// </exception>
 /// <exception cref="System.OperationCanceledException">
 /// The operation has been canceled.
 /// </exception>
 /// <exception cref="System.NotSupportedException">
 /// <para>Internationalized formatting was requested but is not supported by the transport.</para>
 /// </exception>
 /// <exception cref="System.IO.IOException">
 /// An I/O error occurred.
 /// </exception>
 /// <exception cref="CommandException">
 /// The send command failed.
 /// </exception>
 /// <exception cref="ProtocolException">
 /// A protocol exception occurred.
 /// </exception>
 public abstract Task SendAsync(FormatOptions options, MimeMessage message, MailboxAddress sender, IEnumerable <MailboxAddress> recipients, CancellationToken cancellationToken = default(CancellationToken), ITransferProgress progress = null);
		/// <summary>
		/// Cryptographically signs the content.
		/// </summary>
		/// <remarks>
		/// Cryptographically signs the content using the specified signer and digest algorithm.
		/// </remarks>
		/// <returns>A new <see cref="MimeKit.MimePart"/> instance
		/// containing the detached signature data.</returns>
		/// <param name="signer">The signer.</param>
		/// <param name="digestAlgo">The digest algorithm to use for signing.</param>
		/// <param name="content">The content.</param>
		/// <exception cref="System.ArgumentNullException">
		/// <para><paramref name="signer"/> is <c>null</c>.</para>
		/// <para>-or-</para>
		/// <para><paramref name="content"/> is <c>null</c>.</para>
		/// </exception>
		/// <exception cref="System.ArgumentOutOfRangeException">
		/// <paramref name="digestAlgo"/> is out of range.
		/// </exception>
		/// <exception cref="System.NotSupportedException">
		/// The specified <see cref="DigestAlgorithm"/> is not supported by this context.
		/// </exception>
		/// <exception cref="PrivateKeyNotFoundException">
		/// A signing key could not be found for <paramref name="signer"/>.
		/// </exception>
		/// <exception cref="System.OperationCanceledException">
		/// The user chose to cancel the password prompt.
		/// </exception>
		/// <exception cref="System.UnauthorizedAccessException">
		/// 3 bad attempts were made to unlock the secret key.
		/// </exception>
		public override MimePart Sign (MailboxAddress signer, DigestAlgorithm digestAlgo, Stream content)
		{
			if (signer == null)
				throw new ArgumentNullException (nameof (signer));

			if (content == null)
				throw new ArgumentNullException (nameof (content));

			var key = GetSigningKey (signer);

			return Sign (key, digestAlgo, content);
		}
Exemple #32
0
        public void TestSecureMimeSignAndEncrypt()
        {
            var self       = new MailboxAddress("MimeKit UnitTests", "*****@*****.**");
            var recipients = new List <MailboxAddress> ();

            // encrypt to ourselves...
            recipients.Add(self);

            var cleartext = new TextPart("plain");

            cleartext.Text = "This is some cleartext that we'll end up encrypting...";

            ApplicationPkcs7Mime encrypted;

            using (var ctx = CreateContext()) {
                encrypted = ApplicationPkcs7Mime.SignAndEncrypt(ctx, self, DigestAlgorithm.Sha1, recipients, cleartext);

                Assert.AreEqual(SecureMimeType.EnvelopedData, encrypted.SecureMimeType, "S/MIME type did not match.");
            }

            using (var ctx = CreateContext()) {
                var decrypted = encrypted.Decrypt(ctx);

                // The decrypted part should be a multipart/signed
                Assert.IsInstanceOfType(typeof(MultipartSigned), decrypted, "Expected the decrypted part to be a multipart/signed.");
                var signed = (MultipartSigned)decrypted;

                Assert.IsInstanceOfType(typeof(TextPart), signed[0], "Expected the first part of the multipart/signed to be a multipart.");
                Assert.IsInstanceOfType(typeof(ApplicationPkcs7Signature), signed[1], "Expected second part of the multipart/signed to be a pkcs7-signature.");

                var extracted = (TextPart)signed[0];
                Assert.AreEqual(cleartext.Text, extracted.Text, "The decrypted text part's text does not match the original.");

                var signatures = signed.Verify(ctx);

                Assert.AreEqual(1, signatures.Count, "Verify returned an unexpected number of signatures.");
                foreach (var signature in signatures)
                {
                    try {
                        bool valid = signature.Verify();

                        Assert.IsTrue(valid, "Bad signature from {0}", signature.SignerCertificate.Email);
                    } catch (DigitalSignatureVerifyException ex) {
                        Assert.Fail("Failed to verify signature: {0}", ex);
                    }

                    var algorithms = ((SecureMimeDigitalSignature)signature).EncryptionAlgorithms;
                    Assert.AreEqual(EncryptionAlgorithm.Camellia256, algorithms[0], "Expected Camellia-256 capability");
                    Assert.AreEqual(EncryptionAlgorithm.Aes256, algorithms[1], "Expected AES-256 capability");
                    Assert.AreEqual(EncryptionAlgorithm.Camellia192, algorithms[2], "Expected Camellia-192 capability");
                    Assert.AreEqual(EncryptionAlgorithm.Aes192, algorithms[3], "Expected AES-192 capability");
                    Assert.AreEqual(EncryptionAlgorithm.Camellia128, algorithms[4], "Expected Camellia-128 capability");
                    Assert.AreEqual(EncryptionAlgorithm.Aes128, algorithms[5], "Expected AES-128 capability");
                    Assert.AreEqual(EncryptionAlgorithm.Idea, algorithms[6], "Expected IDEA capability");
                    Assert.AreEqual(EncryptionAlgorithm.Cast5, algorithms[7], "Expected Cast5 capability");
                    Assert.AreEqual(EncryptionAlgorithm.TripleDes, algorithms[8], "Expected Triple-DES capability");
                    //Assert.AreEqual (EncryptionAlgorithm.RC2128, algorithms[9], "Expected RC2-128 capability");
                    //Assert.AreEqual (EncryptionAlgorithm.RC264, algorithms[10], "Expected RC2-64 capability");
                    //Assert.AreEqual (EncryptionAlgorithm.Des, algorithms[11], "Expected DES capability");
                    //Assert.AreEqual (EncryptionAlgorithm.RC240, algorithms[11], "Expected RC2-40 capability");
                }
            }
        }
		/// <summary>
		/// Cryptographically signs the specified entity.
		/// </summary>
		/// <remarks>
		/// <para>Signs the entity using the supplied signer, digest algorithm and <see cref="SecureMimeContext"/>.</para>
		/// <para>For better interoperability with other mail clients, you should use
		/// <see cref="MultipartSigned.Create(SecureMimeContext, CmsSigner, MimeEntity)"/>
		/// instead as the multipart/signed format is supported among a much larger
		/// subset of mail client software.</para>
		/// </remarks>
		/// <returns>The signed entity.</returns>
		/// <param name="ctx">The S/MIME context to use for signing.</param>
		/// <param name="signer">The signer.</param>
		/// <param name="digestAlgo">The digest algorithm to use for signing.</param>
		/// <param name="entity">The entity.</param>
		/// <exception cref="System.ArgumentNullException">
		/// <para><paramref name="ctx"/> is <c>null</c>.</para>
		/// <para>-or-</para>
		/// <para><paramref name="signer"/> is <c>null</c>.</para>
		/// <para>-or-</para>
		/// <para><paramref name="entity"/> is <c>null</c>.</para>
		/// </exception>
		/// <exception cref="CertificateNotFoundException">
		/// A signing certificate could not be found for <paramref name="signer"/>.
		/// </exception>
		/// <exception cref="Org.BouncyCastle.Cms.CmsException">
		/// An error occurred in the cryptographic message syntax subsystem.
		/// </exception>
		public static ApplicationPkcs7Mime Sign (SecureMimeContext ctx, MailboxAddress signer, DigestAlgorithm digestAlgo, MimeEntity entity)
		{
			if (ctx == null)
				throw new ArgumentNullException ("ctx");

			if (signer == null)
				throw new ArgumentNullException ("signer");

			if (entity == null)
				throw new ArgumentNullException ("entity");

			using (var memory = new MemoryBlockStream ()) {
				var options = FormatOptions.CloneDefault ();
				options.NewLineFormat = NewLineFormat.Dos;

				entity.WriteTo (options, memory);
				memory.Position = 0;

				return ctx.EncapsulatedSign (signer, digestAlgo, memory);
			}
		}
Exemple #34
0
        /// <inheritdoc/>
        public async Task SendEmailAsync(string email, string subject, MimeEntity message)
        {
            try
            {
                var mimeMessage = new MimeMessage();

                mimeMessage.From.Add(new MailboxAddress(_emailOption.SenderName, _emailOption.Sender));
                mimeMessage.To.Add(MailboxAddress.Parse(email));
                mimeMessage.Subject = subject;
                mimeMessage.Body    = message;

                using var client = new SmtpClient
                      {
                          // For demo-purposes, accept all SSL certificates (in case the server supports STARTTLS)
                          ServerCertificateValidationCallback = (s, c, h, e) => true
                      };

                try
                {
                    await client.ConnectAsync(_emailOption.Server, _emailOption.Port, useSsl : true);
                }
                catch (Exception ex)
                {
                    var msg = $"Не удалось установить соединение.";
                    _logger.LogError(ex, $"{msg}");
                    throw new Exception(msg, ex);
                }

                try
                {
                    await client.AuthenticateAsync(_emailOption.Sender, _emailOption.Password);
                }
                catch (Exception ex)
                {
                    var msg = $"Не удалось авторизоваться.";
                    _logger.LogError(ex, $"{msg}");
                    throw new Exception(msg, ex);
                }

                try
                {
                    await client.SendAsync(mimeMessage);
                }
                catch (Exception ex)
                {
                    var msg = $"Не удалось отправить письмо.";
                    _logger.LogError(ex, $"{msg}");
                    throw new Exception(msg, ex);
                }

                try
                {
                    await client.DisconnectAsync(true);
                }
                catch (Exception ex)
                {
                    var msg = $"Не удалось разорвать соединение.";
                    _logger.LogError(ex, $"{msg}");
                    throw new Exception(msg, ex);
                }
            }
            catch (Exception ex)
            {
                var msg = $"Ошибка при попытке отправить письмо на почту \"{email}\" по след. причине: {ex.Message}";
                _logger.LogError(ex, msg);
                throw new Exception(msg, ex);
            }
        }
		/// <summary>
		/// Cryptographically signs and encrypts the specified entity.
		/// </summary>
		/// <remarks>
		/// Cryptographically signs entity using the supplied signer and then
		/// encrypts the result to the specified recipients.
		/// </remarks>
		/// <returns>The signed and encrypted entity.</returns>
		/// <param name="signer">The signer.</param>
		/// <param name="digestAlgo">The digest algorithm to use for signing.</param>
		/// <param name="recipients">The recipients.</param>
		/// <param name="entity">The entity.</param>
		/// <exception cref="System.ArgumentNullException">
		/// <para><paramref name="signer"/> is <c>null</c>.</para>
		/// <para>-or-</para>
		/// <para><paramref name="recipients"/> is <c>null</c>.</para>
		/// <para>-or-</para>
		/// <para><paramref name="entity"/> is <c>null</c>.</para>
		/// </exception>
		/// <exception cref="CertificateNotFoundException">
		/// <para>A signing certificate could not be found for <paramref name="signer"/>.</para>
		/// <para>-or-</para>
		/// <para>A certificate could not be found for one or more of the <paramref name="recipients"/>.</para>
		/// </exception>
		/// <exception cref="Org.BouncyCastle.Cms.CmsException">
		/// An error occurred in the cryptographic message syntax subsystem.
		/// </exception>
		public static ApplicationPkcs7Mime SignAndEncrypt (MailboxAddress signer, DigestAlgorithm digestAlgo, IEnumerable<MailboxAddress> recipients, MimeEntity entity)
		{
			if (signer == null)
				throw new ArgumentNullException ("signer");

			if (recipients == null)
				throw new ArgumentNullException ("recipients");

			if (entity == null)
				throw new ArgumentNullException ("entity");

			using (var ctx = (SecureMimeContext) CryptographyContext.Create ("application/pkcs7-mime")) {
				return SignAndEncrypt (ctx, signer, digestAlgo, recipients, entity);
			}
		}
        /// <summary>
        ///
        /// </summary>
        /// <param name="mailTo"></param>
        /// <param name="mailCc"></param>
        /// <param name="mailBcc"></param>
        /// <param name="subject"></param>
        /// <param name="message"></param>
        /// <param name="encoding"></param>
        /// <param name="isHtml"></param>
        private void SendEmail(string mailTo, string mailCc, string mailBcc, string subject, string message, Encoding encoding, bool isHtml)
        {
            var _to  = new string[0];
            var _cc  = new string[0];
            var _bcc = new string[0];

            if (!string.IsNullOrEmpty(mailTo))
            {
                _to = mailTo.Split(',').Select(x => x.Trim()).ToArray();
            }
            if (!string.IsNullOrEmpty(mailCc))
            {
                _cc = mailCc.Split(',').Select(x => x.Trim()).ToArray();
            }
            if (!string.IsNullOrEmpty(mailBcc))
            {
                _bcc = mailBcc.Split(',').Select(x => x.Trim()).ToArray();
            }


            var mimeMessage = new MimeMessage();

            //add mail from
            mimeMessage.From.Add(new MailboxAddress("", SmtpOptions.User));

            //add mail to
            foreach (var to in _to)
            {
                mimeMessage.To.Add(MailboxAddress.Parse(to));
            }

            //add mail cc
            foreach (var cc in _cc)
            {
                mimeMessage.Cc.Add(MailboxAddress.Parse(cc));
            }

            //add mail bcc
            foreach (var bcc in _bcc)
            {
                mimeMessage.Bcc.Add(MailboxAddress.Parse(bcc));
            }

            //add subject
            mimeMessage.Subject = subject;

            //add email body
            TextPart body = null;

            if (isHtml)
            {
                body = new TextPart(TextFormat.Html);
            }
            else
            {
                body = new TextPart(TextFormat.Text);
            }
            //set email encoding
            body.SetText(encoding, message);

            //set email body
            mimeMessage.Body = body;

            using (var client = SmtpOptions.SmtpClient)
            {
                try
                {
                    client?.Send(mimeMessage);
                }
                catch (Exception ex)
                {
                    Logger.ErrorException("SmtpClient.SendEmail", ex);
                }
                finally
                {
                    client?.Disconnect(true);
                }
            }
        }
		/// <summary>
		/// Cryptographically signs and encrypts the specified content for the specified recipients.
		/// </summary>
		/// <remarks>
		/// Cryptographically signs and encrypts the specified content for the specified recipients.
		/// </remarks>
		/// <returns>A new <see cref="MimeKit.MimePart"/> instance
		/// containing the encrypted data.</returns>
		/// <param name="signer">The signer.</param>
		/// <param name="digestAlgo">The digest algorithm to use for signing.</param>
		/// <param name="recipients">The recipients.</param>
		/// <param name="content">The content.</param>
		/// <exception cref="System.ArgumentNullException">
		/// <para><paramref name="signer"/> is <c>null</c>.</para>
		/// <para>-or-</para>
		/// <para><paramref name="recipients"/> is <c>null</c>.</para>
		/// <para>-or-</para>
		/// <para><paramref name="content"/> is <c>null</c>.</para>
		/// </exception>
		/// <exception cref="System.ArgumentOutOfRangeException">
		/// <paramref name="digestAlgo"/> is out of range.
		/// </exception>
		/// <exception cref="System.ArgumentException">
		/// <para>One or more of the recipient keys cannot be used for encrypting.</para>
		/// <para>-or-</para>
		/// <para>No recipients were specified.</para>
		/// </exception>
		/// <exception cref="System.NotSupportedException">
		/// The specified <see cref="DigestAlgorithm"/> is not supported by this context.
		/// </exception>
		/// <exception cref="PrivateKeyNotFoundException">
		/// The private key could not be found for <paramref name="signer"/>.
		/// </exception>
		/// <exception cref="PublicKeyNotFoundException">
		/// A public key could not be found for one or more of the <paramref name="recipients"/>.
		/// </exception>
		/// <exception cref="System.OperationCanceledException">
		/// The user chose to cancel the password prompt.
		/// </exception>
		/// <exception cref="System.UnauthorizedAccessException">
		/// 3 bad attempts were made to unlock the secret key.
		/// </exception>
		public MimePart SignAndEncrypt (MailboxAddress signer, DigestAlgorithm digestAlgo, IEnumerable<MailboxAddress> recipients, Stream content)
		{
			if (signer == null)
				throw new ArgumentNullException ("signer");

			if (recipients == null)
				throw new ArgumentNullException ("recipients");

			if (content == null)
				throw new ArgumentNullException ("content");

			var key = GetSigningKey (signer);

			return SignAndEncrypt (key, digestAlgo, GetPublicKeys (recipients), content);
		}
        public async Task SendEmailAsync(Models.Mail.MailMessage message)
        {
            var mimeMessage = new MimeMessage();

            mimeMessage.From.Add(new MailboxAddress(_globalSettings.SiteName, _replyEmail));
            mimeMessage.Subject = message.Subject;
            if (!string.IsNullOrWhiteSpace(_replyDomain))
            {
                mimeMessage.MessageId = $"<{Guid.NewGuid()}@{_replyDomain}>";
            }

            foreach (var address in message.ToEmails)
            {
                var punyencoded = CoreHelpers.PunyEncode(address);
                mimeMessage.To.Add(MailboxAddress.Parse(punyencoded));
            }

            if (message.BccEmails != null)
            {
                foreach (var address in message.BccEmails)
                {
                    var punyencoded = CoreHelpers.PunyEncode(address);
                    mimeMessage.Bcc.Add(MailboxAddress.Parse(punyencoded));
                }
            }

            var builder = new BodyBuilder();

            if (!string.IsNullOrWhiteSpace(message.TextContent))
            {
                builder.TextBody = message.TextContent;
            }
            builder.HtmlBody = message.HtmlContent;
            mimeMessage.Body = builder.ToMessageBody();

            using (var client = new SmtpClient())
            {
                if (_globalSettings.Mail.Smtp.TrustServer)
                {
                    client.ServerCertificateValidationCallback = (s, c, h, e) => true;
                }

                if (!_globalSettings.Mail.Smtp.StartTls && !_globalSettings.Mail.Smtp.Ssl &&
                    _globalSettings.Mail.Smtp.Port == 25)
                {
                    await client.ConnectAsync(_globalSettings.Mail.Smtp.Host, _globalSettings.Mail.Smtp.Port,
                                              MailKit.Security.SecureSocketOptions.None);
                }
                else
                {
                    var useSsl = _globalSettings.Mail.Smtp.Port == 587 && !_globalSettings.Mail.Smtp.SslOverride ?
                                 false : _globalSettings.Mail.Smtp.Ssl;
                    await client.ConnectAsync(_globalSettings.Mail.Smtp.Host, _globalSettings.Mail.Smtp.Port, useSsl);
                }

                if (CoreHelpers.SettingHasValue(_globalSettings.Mail.Smtp.Username) &&
                    CoreHelpers.SettingHasValue(_globalSettings.Mail.Smtp.Password))
                {
                    await client.AuthenticateAsync(_globalSettings.Mail.Smtp.Username,
                                                   _globalSettings.Mail.Smtp.Password);
                }

                await client.SendAsync(mimeMessage);

                await client.DisconnectAsync(true);
            }
        }
		static bool PgpSecretKeyMatches (PgpSecretKey key, MailboxAddress mailbox)
		{
			var secure = mailbox as SecureMailboxAddress;

			if (secure != null) {
				var fingerprint = GetFingerprint (key.KeyId, secure.Fingerprint.Length);

				return secure.Fingerprint.EndsWith (fingerprint, StringComparison.OrdinalIgnoreCase);
			}

			foreach (string userId in key.UserIds) {
				MailboxAddress email;

				if (!MailboxAddress.TryParse (userId, out email))
					continue;

				if (string.Compare (mailbox.Address, email.Address, StringComparison.OrdinalIgnoreCase) == 0)
					return true;
			}

			return false;
		}
 /// <summary>
 /// Initializes a new instance of the <see cref="MailKit.Net.Smtp.SmtpCommandException"/> class.
 /// </summary>
 /// <remarks>
 /// Creates a new <see cref="SmtpCommandException"/>.
 /// </remarks>
 /// <param name="code">The error code.</param>
 /// <param name="status">The status code.</param>
 /// <param name="mailbox">The rejected mailbox.</param>
 /// <param name="message">The error message.</param>
 public SmtpCommandException(SmtpErrorCode code, SmtpStatusCode status, MailboxAddress mailbox, string message) : base(message)
 {
     StatusCode = status;
     Mailbox    = mailbox;
     ErrorCode  = code;
 }
		/// <summary>
		/// Creates a new <see cref="MultipartEncrypted"/>.
		/// </summary>
		/// <remarks>
		/// Signs the entity using the supplied signer and digest algorithm and then encrypts to
		/// the specified recipients, encapsulating the result in a new multipart/encrypted part.
		/// </remarks>
		/// <returns>A new <see cref="MultipartEncrypted"/> instance containing
		/// the signed and encrypted version of the specified entity.</returns>
		/// <param name="ctx">The OpenPGP cryptography context to use for signing and encrypting.</param>
		/// <param name="signer">The signer to use to sign the entity.</param>
		/// <param name="digestAlgo">The digest algorithm to use for signing.</param>
		/// <param name="recipients">The recipients for the encrypted entity.</param>
		/// <param name="entity">The entity to sign and encrypt.</param>
		/// <exception cref="System.ArgumentNullException">
		/// <para><paramref name="ctx"/> is <c>null</c>.</para>
		/// <para>-or-</para>
		/// <para><paramref name="signer"/> is <c>null</c>.</para>
		/// <para>-or-</para>
		/// <para><paramref name="recipients"/> is <c>null</c>.</para>
		/// <para>-or-</para>
		/// <para><paramref name="entity"/> is <c>null</c>.</para>
		/// </exception>
		/// <exception cref="PrivateKeyNotFoundException">
		/// The private key for <paramref name="signer"/> could not be found.
		/// </exception>
		/// <exception cref="PublicKeyNotFoundException">
		/// A public key for one or more of the <paramref name="recipients"/> could not be found.
		/// </exception>
		/// <exception cref="System.OperationCanceledException">
		/// The user chose to cancel the password prompt.
		/// </exception>
		/// <exception cref="System.UnauthorizedAccessException">
		/// 3 bad attempts were made to unlock the secret key.
		/// </exception>
		public static MultipartEncrypted Create (OpenPgpContext ctx, MailboxAddress signer, DigestAlgorithm digestAlgo, IEnumerable<MailboxAddress> recipients, MimeEntity entity)
		{
			if (ctx == null)
				throw new ArgumentNullException ("ctx");

			if (signer == null)
				throw new ArgumentNullException ("signer");

			if (recipients == null)
				throw new ArgumentNullException ("recipients");

			if (entity == null)
				throw new ArgumentNullException ("entity");

			using (var memory = new MemoryStream ()) {
				var options = FormatOptions.Default.Clone ();
				options.NewLineFormat = NewLineFormat.Dos;

				PrepareEntityForEncrypting (entity);
				entity.WriteTo (options, memory);
				memory.Position = 0;

				var encrypted = new MultipartEncrypted ();
				encrypted.ContentType.Parameters["protocol"] = ctx.EncryptionProtocol;

				// add the protocol version part
				encrypted.Add (new ApplicationPgpEncrypted ());

				// add the encrypted entity as the second part
				encrypted.Add (ctx.SignAndEncrypt (signer, digestAlgo, recipients, memory));

				return encrypted;
			}
		}
Exemple #42
0
 /// <summary>
 /// Cryptographically signs and encapsulates the content using the specified signer and digest algorithm.
 /// </summary>
 /// <remarks>
 /// Cryptographically signs and encapsulates the content using the specified signer and digest algorithm.
 /// </remarks>
 /// <returns>A new <see cref="MimeKit.Cryptography.ApplicationPkcs7Mime"/> instance
 /// containing the detached signature data.</returns>
 /// <param name="signer">The signer.</param>
 /// <param name="digestAlgo">The digest algorithm to use for signing.</param>
 /// <param name="content">The content.</param>
 /// <exception cref="System.ArgumentNullException">
 /// <para><paramref name="signer"/> is <c>null</c>.</para>
 /// <para>-or-</para>
 /// <para><paramref name="content"/> is <c>null</c>.</para>
 /// </exception>
 /// <exception cref="System.ArgumentOutOfRangeException">
 /// <paramref name="digestAlgo"/> is out of range.
 /// </exception>
 /// <exception cref="System.NotSupportedException">
 /// The specified <see cref="DigestAlgorithm"/> is not supported by this context.
 /// </exception>
 /// <exception cref="CertificateNotFoundException">
 /// A signing certificate could not be found for <paramref name="signer"/>.
 /// </exception>
 /// <exception cref="Org.BouncyCastle.Cms.CmsException">
 /// An error occurred in the cryptographic message syntax subsystem.
 /// </exception>
 public abstract ApplicationPkcs7Mime EncapsulatedSign(MailboxAddress signer, DigestAlgorithm digestAlgo, Stream content);
		/// <summary>
		/// Gets the database command to select the certificate records for the specified mailbox.
		/// </summary>
		/// <remarks>
		/// Gets the database command to select the certificate records for the specified mailbox.
		/// </remarks>
		/// <returns>The database command.</returns>
		/// <param name="mailbox">The mailbox.</param>
		/// <param name="now">The date and time for which the certificate should be valid.</param>
		/// <param name="requirePrivateKey">true</param>
		/// <param name="fields">The fields to return.</param>
		protected override DbCommand GetSelectCommand (MailboxAddress mailbox, DateTime now, bool requirePrivateKey, X509CertificateRecordFields fields)
		{
			var query = "SELECT " + string.Join (", ", GetColumnNames (fields)) + " FROM CERTIFICATES";
			var secure = mailbox as SecureMailboxAddress;
			var command = connection.CreateCommand ();
			var constraints = " WHERE ";

			constraints += "BASICCONSTRAINTS = @BASICCONSTRAINTS ";
			command.AddParameterWithValue ("@BASICCONSTRAINTS", -1);

			if (secure != null && !string.IsNullOrEmpty (secure.Fingerprint)) {
				if (secure.Fingerprint.Length < 40) {
					constraints += "AND FINGERPRINT LIKE @FINGERPRINT ";
					command.AddParameterWithValue ("@FINGERPRINT", secure.Fingerprint.ToLowerInvariant () + "%");
				} else {
					constraints += "AND FINGERPRINT = @FINGERPRINT ";
					command.AddParameterWithValue ("@FINGERPRINT", secure.Fingerprint.ToLowerInvariant ());
				}
			} else {
				constraints += "AND SUBJECTEMAIL = @SUBJECTEMAIL ";
				command.AddParameterWithValue ("@SUBJECTEMAIL", mailbox.Address.ToLowerInvariant ());
			}

			constraints += "AND NOTBEFORE < @NOW AND NOTAFTER > @NOW ";
			command.AddParameterWithValue ("@NOW", now);

			if (requirePrivateKey)
				constraints += "AND PRIVATEKEY IS NOT NULL";

			command.CommandText = query + constraints;
			command.CommandType = CommandType.Text;

			return command;
		}
Exemple #44
0
        private async Task <bool> ReceiveMail(Stream reader, StreamWriter writer, string line, IPEndPoint endPoint)
        {
            IPHostEntry entry = await Dns.GetHostEntryAsync(endPoint.Address);

            MailFromResult result = await ParseMailFrom(null, reader, writer, line, endPoint);

            if (result == null)
            {
                return(false);
            }
            try
            {
                string      subject;
                MimeMessage msg;
                using (Stream stream = File.OpenRead(result.BackingFile))
                {
                    msg = await MimeMessage.LoadAsync(stream, true, cancelToken);

                    subject = msg.Subject;
                }
                subject = (subject ?? string.Empty).Trim();
                if (subject.Equals("unsubscribe", StringComparison.OrdinalIgnoreCase))
                {
                    UnsubscribeHandler?.Invoke(result.From.Address, subject, msg.HtmlBody);
                    return(true);
                }

                // mail demon doesn't have an inbox yet, only forwarding, so see if any of the to addresses can be forwarded
                foreach (var kv in result.ToAddresses)
                {
                    foreach (MailboxAddress address in kv.Value)
                    {
                        MailDemonUser user = users.FirstOrDefault(u => u.MailAddress.Address.Equals(address.Address, StringComparison.OrdinalIgnoreCase));

                        // if no user or the forward address points to a user, fail
                        if (user == null || users.FirstOrDefault(u => u.MailAddress.Address.Equals(user.ForwardAddress.Address, StringComparison.Ordinal)) != null)
                        {
                            await writer.WriteLineAsync($"500 invalid command - user not found");

                            await writer.FlushAsync();
                        }

                        // setup forward headers
                        MailboxAddress forwardToAddress = (user.ForwardAddress ?? globalForwardAddress);
                        if (forwardToAddress == null)
                        {
                            await writer.WriteLineAsync($"500 invalid command - user not found 2");

                            await writer.FlushAsync();
                        }
                        else
                        {
                            string forwardDomain = forwardToAddress.Address.Substring(forwardToAddress.Address.IndexOf('@') + 1);

                            // create new object to forward on
                            MailFromResult newResult = new MailFromResult
                            {
                                BackingFile = result.BackingFile,
                                From        = user.MailAddress,
                                ToAddresses = new Dictionary <string, IEnumerable <MailboxAddress> > {
                                    { forwardDomain, new List <MailboxAddress> {
                                          forwardToAddress
                                      } }
                                }
                            };

                            // forward the message on and clear the forward headers
                            MailDemonLog.Info("Forwarding message, from: {0}, to: {1}, forward: {2}", result.From, address, forwardToAddress);
                            result.BackingFile = null; // we took ownership of the file
                            SendMail(writer, newResult, endPoint, true, (prepMsg) =>
                            {
                                prepMsg.Subject = $"FW from {result.From}: {prepMsg.Subject}";
                                prepMsg.Cc.Clear();
                                prepMsg.Bcc.Clear();
                            }).GetAwaiter();
                            return(true); // only forward to the first valid address
                        }
                    }
                }
            }
            finally
            {
                result.Dispose();
            }
            return(true);
        }
		/// <summary>
		/// Gets the X.509 certificate associated with the <see cref="MimeKit.MailboxAddress"/>.
		/// </summary>
		/// <remarks>
		/// Gets the X.509 certificate associated with the <see cref="MimeKit.MailboxAddress"/>.
		/// </remarks>
		/// <returns>The certificate.</returns>
		/// <param name="mailbox">The mailbox.</param>
		/// <exception cref="CertificateNotFoundException">
		/// A certificate for the specified <paramref name="mailbox"/> could not be found.
		/// </exception>
		protected override CmsRecipient GetCmsRecipient (MailboxAddress mailbox)
		{
			var certificate = GetCmsRecipientCertificate (mailbox);
			var cert = DotNetUtilities.FromX509Certificate (certificate);
			var recipient = new CmsRecipient (cert);

			foreach (var extension in certificate.Extensions) {
				if (extension.Oid.Value == "1.2.840.113549.1.9.15") {
					var algorithms = DecodeEncryptionAlgorithms (extension.RawData);

					if (algorithms != null)
						recipient.EncryptionAlgorithms = algorithms;

					break;
				}
			}

			return recipient;
		}
Exemple #46
0
        public void TestArgumentExceptions()
        {
            var path   = Path.Combine(TestHelper.ProjectDir, "TestData", "smime", "smime.p12");
            var entity = new TextPart("plain")
            {
                Text = "This is some text..."
            };
            var mailbox    = new MailboxAddress("MimeKit UnitTests", "*****@*****.**");
            var recipients = new CmsRecipientCollection();
            var signer     = new CmsSigner(path, "no.secret");
            var mailboxes  = new [] { mailbox };

            recipients.Add(new CmsRecipient(signer.Certificate));

            using (var ctx = new TemporarySecureMimeContext()) {
                ctx.Import(path, "no.secret");

                // Compress
                Assert.Throws <ArgumentNullException> (() => ApplicationPkcs7Mime.Compress(null, entity));
                Assert.Throws <ArgumentNullException> (() => ApplicationPkcs7Mime.Compress(ctx, null));
                Assert.Throws <ArgumentNullException> (() => ApplicationPkcs7Mime.Compress(null));

                // Encrypt
                Assert.Throws <ArgumentNullException> (() => ApplicationPkcs7Mime.Encrypt(null, mailboxes, entity));
                Assert.Throws <ArgumentNullException> (() => ApplicationPkcs7Mime.Encrypt(null, recipients, entity));
                Assert.Throws <ArgumentNullException> (() => ApplicationPkcs7Mime.Encrypt(ctx, (IEnumerable <MailboxAddress>)null, entity));
                Assert.Throws <ArgumentNullException> (() => ApplicationPkcs7Mime.Encrypt(ctx, (CmsRecipientCollection)null, entity));
                Assert.Throws <ArgumentNullException> (() => ApplicationPkcs7Mime.Encrypt(ctx, recipients, null));
                Assert.Throws <ArgumentNullException> (() => ApplicationPkcs7Mime.Encrypt(ctx, mailboxes, null));

                Assert.Throws <ArgumentNullException> (() => ApplicationPkcs7Mime.Encrypt((IEnumerable <MailboxAddress>)null, entity));
                Assert.Throws <ArgumentNullException> (() => ApplicationPkcs7Mime.Encrypt((CmsRecipientCollection)null, entity));
                Assert.Throws <ArgumentNullException> (() => ApplicationPkcs7Mime.Encrypt(recipients, null));
                Assert.Throws <ArgumentNullException> (() => ApplicationPkcs7Mime.Encrypt(mailboxes, null));

                // Sign
                Assert.Throws <ArgumentNullException> (() => ApplicationPkcs7Mime.Sign(null, mailbox, DigestAlgorithm.Sha1, entity));
                Assert.Throws <ArgumentNullException> (() => ApplicationPkcs7Mime.Sign(null, signer, entity));
                Assert.Throws <ArgumentNullException> (() => ApplicationPkcs7Mime.Sign(ctx, (MailboxAddress)null, DigestAlgorithm.Sha1, entity));
                Assert.Throws <ArgumentNullException> (() => ApplicationPkcs7Mime.Sign(ctx, (CmsSigner)null, entity));
                Assert.Throws <ArgumentNullException> (() => ApplicationPkcs7Mime.Sign(ctx, mailbox, DigestAlgorithm.Sha1, null));
                Assert.Throws <ArgumentNullException> (() => ApplicationPkcs7Mime.Sign(ctx, signer, null));

                Assert.Throws <ArgumentNullException> (() => ApplicationPkcs7Mime.Sign((MailboxAddress)null, DigestAlgorithm.Sha1, entity));
                Assert.Throws <ArgumentNullException> (() => ApplicationPkcs7Mime.Sign((CmsSigner)null, entity));
                Assert.Throws <ArgumentNullException> (() => ApplicationPkcs7Mime.Sign(mailbox, DigestAlgorithm.Sha1, null));
                Assert.Throws <ArgumentNullException> (() => ApplicationPkcs7Mime.Sign(signer, null));

                // SignAndEncrypt
                Assert.Throws <ArgumentNullException> (() => ApplicationPkcs7Mime.SignAndEncrypt(null, mailbox, DigestAlgorithm.Sha1, mailboxes, entity));
                Assert.Throws <ArgumentNullException> (() => ApplicationPkcs7Mime.SignAndEncrypt(ctx, null, DigestAlgorithm.Sha1, mailboxes, entity));
                Assert.Throws <ArgumentNullException> (() => ApplicationPkcs7Mime.SignAndEncrypt(ctx, mailbox, DigestAlgorithm.Sha1, null, entity));
                Assert.Throws <ArgumentNullException> (() => ApplicationPkcs7Mime.SignAndEncrypt(ctx, mailbox, DigestAlgorithm.Sha1, mailboxes, null));
                Assert.Throws <ArgumentNullException> (() => ApplicationPkcs7Mime.SignAndEncrypt(null, DigestAlgorithm.Sha1, mailboxes, entity));
                Assert.Throws <ArgumentNullException> (() => ApplicationPkcs7Mime.SignAndEncrypt(mailbox, DigestAlgorithm.Sha1, null, entity));
                Assert.Throws <ArgumentNullException> (() => ApplicationPkcs7Mime.SignAndEncrypt(mailbox, DigestAlgorithm.Sha1, mailboxes, null));

                Assert.Throws <ArgumentNullException> (() => ApplicationPkcs7Mime.SignAndEncrypt(null, signer, recipients, entity));
                Assert.Throws <ArgumentNullException> (() => ApplicationPkcs7Mime.SignAndEncrypt(ctx, null, recipients, entity));
                Assert.Throws <ArgumentNullException> (() => ApplicationPkcs7Mime.SignAndEncrypt(ctx, signer, null, entity));
                Assert.Throws <ArgumentNullException> (() => ApplicationPkcs7Mime.SignAndEncrypt(ctx, signer, recipients, null));
                Assert.Throws <ArgumentNullException> (() => ApplicationPkcs7Mime.SignAndEncrypt(null, recipients, entity));
                Assert.Throws <ArgumentNullException> (() => ApplicationPkcs7Mime.SignAndEncrypt(signer, null, entity));
                Assert.Throws <ArgumentNullException> (() => ApplicationPkcs7Mime.SignAndEncrypt(signer, recipients, null));

                var compressed = ApplicationPkcs7Mime.Compress(ctx, entity);
                var encrypted  = ApplicationPkcs7Mime.Encrypt(recipients, entity);
                var signed     = ApplicationPkcs7Mime.Sign(signer, entity);

                // Decompress
                Assert.Throws <ArgumentNullException> (() => compressed.Decompress(null));
                Assert.Throws <InvalidOperationException> (() => encrypted.Decompress(ctx));
                Assert.Throws <InvalidOperationException> (() => signed.Decompress(ctx));

                // Decrypt
                Assert.Throws <ArgumentNullException> (() => encrypted.Decrypt(null));
                Assert.Throws <InvalidOperationException> (() => compressed.Decrypt(ctx));
                Assert.Throws <InvalidOperationException> (() => signed.Decrypt(ctx));

                // Verify
                Assert.Throws <ArgumentNullException> (() => {
                    MimeEntity mime;

                    signed.Verify(null, out mime);
                });
                Assert.Throws <InvalidOperationException> (() => {
                    MimeEntity mime;

                    compressed.Verify(ctx, out mime);
                });
                Assert.Throws <InvalidOperationException> (() => {
                    MimeEntity mime;

                    encrypted.Verify(ctx, out mime);
                });
            }
        }
		X509Certificate2 GetCmsSignerCertificate (MailboxAddress mailbox)
		{
			var store = new X509Store (StoreName.My, StoreLocation);
			var secure = mailbox as SecureMailboxAddress;
			var now = DateTime.Now;

			store.Open (OpenFlags.ReadOnly);

			try {
				foreach (var certificate in store.Certificates) {
					if (certificate.NotBefore > now || certificate.NotAfter < now)
						continue;

					var usage = certificate.Extensions[X509Extensions.KeyUsage.Id] as X509KeyUsageExtension;
					if (usage != null && (usage.KeyUsages & (RealX509KeyUsageFlags.DigitalSignature | RealX509KeyUsageFlags.NonRepudiation)) == 0)
						continue;

					if (!certificate.HasPrivateKey)
						continue;

					if (secure != null) {
						if (certificate.Thumbprint != secure.Fingerprint)
							continue;
					} else {
						if (certificate.GetNameInfo (X509NameType.EmailName, false) != mailbox.Address)
							continue;
					}

					return certificate;
				}
			} finally {
				store.Close ();
			}

			throw new CertificateNotFoundException (mailbox, "A valid signing certificate could not be found.");
		}
Exemple #48
0
        public void TestArgumentExceptions()
        {
            using (var client = new SmtpClient()) {
                var credentials = new NetworkCredential("username", "password");
                var socket      = new Socket(SocketType.Stream, ProtocolType.Tcp);
                var message     = CreateSimpleMessage();
                var sender      = message.From.Mailboxes.FirstOrDefault();
                var recipients  = message.To.Mailboxes.ToList();
                var options     = FormatOptions.Default;
                var empty       = new MailboxAddress[0];

                // Connect
                Assert.Throws <ArgumentNullException> (() => client.Connect((Uri)null));
                Assert.Throws <ArgumentNullException> (async() => await client.ConnectAsync((Uri)null));
                Assert.Throws <ArgumentNullException> (() => client.Connect(null, 25, false));
                Assert.Throws <ArgumentNullException> (async() => await client.ConnectAsync(null, 25, false));
                Assert.Throws <ArgumentException> (() => client.Connect(string.Empty, 25, false));
                Assert.Throws <ArgumentException> (async() => await client.ConnectAsync(string.Empty, 25, false));
                Assert.Throws <ArgumentOutOfRangeException> (() => client.Connect("host", -1, false));
                Assert.Throws <ArgumentOutOfRangeException> (async() => await client.ConnectAsync("host", -1, false));
                Assert.Throws <ArgumentNullException> (() => client.Connect(null, 25, SecureSocketOptions.None));
                Assert.Throws <ArgumentNullException> (async() => await client.ConnectAsync(null, 25, SecureSocketOptions.None));
                Assert.Throws <ArgumentException> (() => client.Connect(string.Empty, 25, SecureSocketOptions.None));
                Assert.Throws <ArgumentException> (async() => await client.ConnectAsync(string.Empty, 25, SecureSocketOptions.None));
                Assert.Throws <ArgumentOutOfRangeException> (() => client.Connect("host", -1, SecureSocketOptions.None));
                Assert.Throws <ArgumentOutOfRangeException> (async() => await client.ConnectAsync("host", -1, SecureSocketOptions.None));

                Assert.Throws <ArgumentNullException> (() => client.Connect(null, "host", 25, SecureSocketOptions.None));
                Assert.Throws <ArgumentException> (() => client.Connect(socket, "host", 25, SecureSocketOptions.None));

                // Authenticate
                Assert.Throws <ArgumentNullException> (() => client.Authenticate(null));
                Assert.Throws <ArgumentNullException> (async() => await client.AuthenticateAsync(null));
                Assert.Throws <ArgumentNullException> (() => client.Authenticate(null, "password"));
                Assert.Throws <ArgumentNullException> (async() => await client.AuthenticateAsync(null, "password"));
                Assert.Throws <ArgumentNullException> (() => client.Authenticate("username", null));
                Assert.Throws <ArgumentNullException> (async() => await client.AuthenticateAsync("username", null));
                Assert.Throws <ArgumentNullException> (() => client.Authenticate(null, credentials));
                Assert.Throws <ArgumentNullException> (async() => await client.AuthenticateAsync(null, credentials));
                Assert.Throws <ArgumentNullException> (() => client.Authenticate(Encoding.UTF8, null));
                Assert.Throws <ArgumentNullException> (async() => await client.AuthenticateAsync(Encoding.UTF8, null));
                Assert.Throws <ArgumentNullException> (() => client.Authenticate(null, "username", "password"));
                Assert.Throws <ArgumentNullException> (async() => await client.AuthenticateAsync(null, "username", "password"));
                Assert.Throws <ArgumentNullException> (() => client.Authenticate(Encoding.UTF8, null, "password"));
                Assert.Throws <ArgumentNullException> (async() => await client.AuthenticateAsync(Encoding.UTF8, null, "password"));
                Assert.Throws <ArgumentNullException> (() => client.Authenticate(Encoding.UTF8, "username", null));
                Assert.Throws <ArgumentNullException> (async() => await client.AuthenticateAsync(Encoding.UTF8, "username", null));

                // Send
                Assert.Throws <ArgumentNullException> (() => client.Send(null));

                Assert.Throws <ArgumentNullException> (() => client.Send(null, message));
                Assert.Throws <ArgumentNullException> (() => client.Send(options, null));

                Assert.Throws <ArgumentNullException> (() => client.Send(message, null, recipients));
                Assert.Throws <ArgumentNullException> (() => client.Send(message, sender, null));
                Assert.Throws <InvalidOperationException> (() => client.Send(message, sender, empty));

                Assert.Throws <ArgumentNullException> (() => client.Send(null, message, sender, recipients));
                Assert.Throws <ArgumentNullException> (() => client.Send(options, message, null, recipients));
                Assert.Throws <ArgumentNullException> (() => client.Send(options, message, sender, null));
                Assert.Throws <InvalidOperationException> (() => client.Send(options, message, sender, empty));

                Assert.Throws <ArgumentNullException> (async() => await client.SendAsync(null));

                Assert.Throws <ArgumentNullException> (async() => await client.SendAsync(null, message));
                Assert.Throws <ArgumentNullException> (async() => await client.SendAsync(options, null));

                Assert.Throws <ArgumentNullException> (async() => await client.SendAsync(message, null, recipients));
                Assert.Throws <ArgumentNullException> (async() => await client.SendAsync(message, sender, null));
                Assert.Throws <InvalidOperationException> (async() => await client.SendAsync(message, sender, empty));

                Assert.Throws <ArgumentNullException> (async() => await client.SendAsync(null, message, sender, recipients));
                Assert.Throws <ArgumentNullException> (async() => await client.SendAsync(options, message, null, recipients));
                Assert.Throws <ArgumentNullException> (async() => await client.SendAsync(options, message, sender, null));
                Assert.Throws <InvalidOperationException> (async() => await client.SendAsync(options, message, sender, empty));

                // Expand
                Assert.Throws <ArgumentNullException> (() => client.Expand(null));
                Assert.Throws <ArgumentException> (() => client.Expand(string.Empty));
                Assert.Throws <ArgumentException> (() => client.Expand("line1\r\nline2"));
                Assert.Throws <ArgumentNullException> (async() => await client.ExpandAsync(null));
                Assert.Throws <ArgumentException> (async() => await client.ExpandAsync(string.Empty));
                Assert.Throws <ArgumentException> (async() => await client.ExpandAsync("line1\r\nline2"));

                // Verify
                Assert.Throws <ArgumentNullException> (() => client.Verify(null));
                Assert.Throws <ArgumentException> (() => client.Verify(string.Empty));
                Assert.Throws <ArgumentException> (() => client.Verify("line1\r\nline2"));
                Assert.Throws <ArgumentNullException> (async() => await client.VerifyAsync(null));
                Assert.Throws <ArgumentException> (async() => await client.VerifyAsync(string.Empty));
                Assert.Throws <ArgumentException> (async() => await client.VerifyAsync("line1\r\nline2"));
            }
        }
		RealCmsSigner GetRealCmsSigner (MailboxAddress mailbox, DigestAlgorithm digestAlgo)
		{
			var signer = new RealCmsSigner (GetCmsSignerCertificate (mailbox));
			signer.DigestAlgorithm = new Oid (GetDigestOid (digestAlgo));
			signer.SignedAttributes.Add (new Pkcs9SigningTime ());
			signer.IncludeOption = X509IncludeOption.ExcludeRoot;
			return signer;
		}
 /// <summary>
 /// Check whether or not a particular mailbox address can be used for signing.
 /// </summary>
 /// <remarks>
 /// Checks whether or not as particular mailbocx address can be used for signing.
 /// </remarks>
 /// <returns><c>true</c> if the mailbox address can be used for signing; otherwise, <c>false</c>.</returns>
 /// <param name="signer">The signer.</param>
 /// <exception cref="System.ArgumentNullException">
 /// <paramref name="signer"/> is <c>null</c>.
 /// </exception>
 public abstract bool CanSign(MailboxAddress signer);
		/// <summary>
		/// Gets the database command to select the certificate records for the specified mailbox.
		/// </summary>
		/// <remarks>
		/// Gets the database command to select the certificate records for the specified mailbox.
		/// </remarks>
		/// <returns>The database command.</returns>
		/// <param name="mailbox">The mailbox.</param>
		/// <param name="now">The date and time for which the certificate should be valid.</param>
		/// <param name="requirePrivateKey"><c>true</c> if the certificate must have a private key.</param>
		/// <param name="fields">The fields to return.</param>
		protected abstract IDbCommand GetSelectCommand (MailboxAddress mailbox, DateTime now, bool requirePrivateKey, X509CertificateRecordFields fields);
 /// <summary>
 /// Check whether or not the cryptography context can encrypt to a particular recipient.
 /// </summary>
 /// <remarks>
 /// Checks whether or not the cryptography context can be used to encrypt to a particular recipient.
 /// </remarks>
 /// <returns><c>true</c> if the cryptography context can be used to encrypt to the designated recipient; otherwise, <c>false</c>.</returns>
 /// <param name="mailbox">The recipient's mailbox address.</param>
 /// <exception cref="System.ArgumentNullException">
 /// <paramref name="mailbox"/> is <c>null</c>.
 /// </exception>
 public abstract bool CanEncrypt(MailboxAddress mailbox);
Exemple #53
0
		/// <summary>
		/// Creates a new <see cref="MultipartSigned"/>.
		/// </summary>
		/// <remarks>
		/// Cryptographically signs the entity using the supplied signer and digest algorithm in
		/// order to generate a detached signature and then adds the entity along with the
		/// detached signature data to a new multipart/signed part.
		/// </remarks>
		/// <returns>A new <see cref="MultipartSigned"/> instance.</returns>
		/// <param name="ctx">The cryptography context to use for signing.</param>
		/// <param name="signer">The signer.</param>
		/// <param name="digestAlgo">The digest algorithm to use for signing.</param>
		/// <param name="entity">The entity to sign.</param>
		/// <exception cref="System.ArgumentNullException">
		/// <para><paramref name="ctx"/> is <c>null</c>.</para>
		/// <para>-or-</para>
		/// <para><paramref name="signer"/> is <c>null</c>.</para>
		/// <para>-or-</para>
		/// <para><paramref name="entity"/> is <c>null</c>.</para>
		/// </exception>
		/// <exception cref="System.ArgumentOutOfRangeException">
		/// The <paramref name="digestAlgo"/> was out of range.
		/// </exception>
		/// <exception cref="System.NotSupportedException">
		/// The <paramref name="digestAlgo"/> is not supported.
		/// </exception>
		/// <exception cref="CertificateNotFoundException">
		/// A signing certificate could not be found for <paramref name="signer"/>.
		/// </exception>
		/// <exception cref="PrivateKeyNotFoundException">
		/// The private key could not be found for <paramref name="signer"/>.
		/// </exception>
		/// <exception cref="Org.BouncyCastle.Cms.CmsException">
		/// An error occurred in the cryptographic message syntax subsystem.
		/// </exception>
		public static MultipartSigned Create (CryptographyContext ctx, MailboxAddress signer, DigestAlgorithm digestAlgo, MimeEntity entity)
		{
			if (signer == null)
				throw new ArgumentNullException ("signer");

			if (entity == null)
				throw new ArgumentNullException ("entity");

			PrepareEntityForSigning (entity);

			using (var memory = new MemoryBlockStream ()) {
				using (var filtered = new FilteredStream (memory)) {
					// Note: see rfc3156, section 3 - second note
					filtered.Add (new ArmoredFromFilter ());

					// Note: see rfc3156, section 5.4 (this is the main difference between rfc2015 and rfc3156)
					filtered.Add (new TrailingWhitespaceFilter ());

					// Note: see rfc2015 or rfc3156, section 5.1
					filtered.Add (new Unix2DosFilter ());

					entity.WriteTo (filtered);
					filtered.Flush ();
				}

				memory.Position = 0;

				// Note: we need to parse the modified entity structure to preserve any modifications
				var parser = new MimeParser (memory, MimeFormat.Entity);
				var parsed = parser.ParseEntity ();
				memory.Position = 0;

				// sign the cleartext content
				var signature = ctx.Sign (signer, digestAlgo, memory);
				var micalg = ctx.GetDigestAlgorithmName (digestAlgo);
				var signed = new MultipartSigned ();

				// set the protocol and micalg Content-Type parameters
				signed.ContentType.Parameters["protocol"] = ctx.SignatureProtocol;
				signed.ContentType.Parameters["micalg"] = micalg;

				// add the modified/parsed entity as our first part
				signed.Add (parsed);

				// add the detached signature as the second part
				signed.Add (signature);

				return signed;
			}
		}
 /// <summary>
 /// Cryptographically sign the content.
 /// </summary>
 /// <remarks>
 /// Cryptographically signs the content using the specified signer and digest algorithm.
 /// </remarks>
 /// <returns>A new <see cref="MimePart"/> instance
 /// containing the detached signature data.</returns>
 /// <param name="signer">The signer.</param>
 /// <param name="digestAlgo">The digest algorithm to use for signing.</param>
 /// <param name="content">The content.</param>
 /// <exception cref="System.ArgumentNullException">
 /// <para><paramref name="signer"/> is <c>null</c>.</para>
 /// <para>-or-</para>
 /// <para><paramref name="content"/> is <c>null</c>.</para>
 /// </exception>
 /// <exception cref="System.ArgumentOutOfRangeException">
 /// <paramref name="digestAlgo"/> is out of range.
 /// </exception>
 /// <exception cref="System.NotSupportedException">
 /// The specified <see cref="DigestAlgorithm"/> is not supported by this context.
 /// </exception>
 /// <exception cref="CertificateNotFoundException">
 /// A signing certificate could not be found for <paramref name="signer"/>.
 /// </exception>
 public abstract MimePart Sign(MailboxAddress signer, DigestAlgorithm digestAlgo, Stream content);
        /// <summary>
        /// Sign and encapsulate the content using the specified signer.
        /// </summary>
        /// <returns>A new <see cref="MimeKit.Cryptography.ApplicationPkcs7Mime"/> instance
        /// containing the detached signature data.</returns>
        /// <param name="signer">The signer.</param>
        /// <param name="digestAlgo">The digest algorithm to use for signing.</param>
        /// <param name="content">The content.</param>
        /// <exception cref="System.ArgumentNullException">
        /// <para><paramref name="signer"/> is <c>null</c>.</para>
        /// <para>-or-</para>
        /// <para><paramref name="content"/> is <c>null</c>.</para>
        /// </exception>
        /// <exception cref="System.ArgumentOutOfRangeException">
        /// <paramref name="digestAlgo"/> is out of range.
        /// </exception>
        /// <exception cref="System.NotSupportedException">
        /// The specified <see cref="DigestAlgorithm"/> is not supported by this context.
        /// </exception>
        /// <exception cref="CertificateNotFoundException">
        /// A signing certificate could not be found for <paramref name="signer"/>.
        /// </exception>
        /// <exception cref="Org.BouncyCastle.Cms.CmsException">
        /// An error occurred in the cryptographic message syntax subsystem.
        /// </exception>
        public virtual ApplicationPkcs7Mime EncapsulatedSign(MailboxAddress signer, DigestAlgorithm digestAlgo, Stream content)
        {
            if (signer == null)
                throw new ArgumentNullException ("signer");

            if (content == null)
                throw new ArgumentNullException ("content");

            var cmsSigner = GetCmsSigner (signer, digestAlgo);

            return EncapsulatedSign (cmsSigner, content);
        }
Exemple #56
0
        public void RunJob()
        {
            using (var smtpClient = GetSmtpClient())
            {
                CoreContext.TenantManager.SetCurrentTenant(_tenantID);
                SecurityContext.AuthenticateMe(CoreContext.Authentication.GetAccountByID(_currUser));

                var userCulture = CoreContext.UserManager.GetUsers(_currUser).GetCulture();

                Thread.CurrentThread.CurrentCulture   = userCulture;
                Thread.CurrentThread.CurrentUICulture = userCulture;

                var contactCount = _contactID.Count;

                if (contactCount == 0)
                {
                    Complete();
                    return;
                }

                MailSenderDataCache.Insert((SendBatchEmailsOperation)Clone());

                var from      = new MailboxAddress(_smtpSetting.SenderDisplayName, _smtpSetting.SenderEmailAddress);
                var filePaths = new List <string>();
                using (var fileDao = FilesIntegration.GetFileDao())
                {
                    foreach (var fileID in _fileID)
                    {
                        var fileObj = fileDao.GetFile(fileID);
                        if (fileObj == null)
                        {
                            continue;
                        }
                        using (var fileStream = fileDao.GetFileStream(fileObj))
                        {
                            var directoryPath = Path.Combine(Path.GetTempPath(), "teamlab", _tenantID.ToString(),
                                                             "crm/files/mailsender/");
                            if (!Directory.Exists(directoryPath))
                            {
                                Directory.CreateDirectory(directoryPath);
                            }
                            var filePath = Path.Combine(directoryPath, fileObj.Title);
                            using (var newFileStream = File.Create(filePath))
                            {
                                fileStream.StreamCopyTo(newFileStream);
                            }
                            filePaths.Add(filePath);
                        }
                    }
                }

                var templateManager = new MailTemplateManager(_daoFactory);
                var deliveryCount   = 0;

                try
                {
                    Error = string.Empty;
                    foreach (var contactID in _contactID)
                    {
                        if (IsCompleted)
                        {
                            break;              // User selected cancel
                        }
                        var contactInfoDao = _daoFactory.GetContactInfoDao();
                        var startDate      = DateTime.Now;

                        var contactEmails = contactInfoDao.GetList(contactID, ContactInfoType.Email, null, true);
                        if (contactEmails.Count == 0)
                        {
                            continue;
                        }

                        var recipientEmail = contactEmails[0].Data;

                        if (!recipientEmail.TestEmailRegex())
                        {
                            Error += string.Format(CRMCommonResource.MailSender_InvalidEmail, recipientEmail) + "<br/>";
                            continue;
                        }

                        var to = new MailboxAddress(recipientEmail);

                        var mimeMessage = new MimeMessage
                        {
                            Subject = _subject
                        };

                        mimeMessage.From.Add(from);
                        mimeMessage.To.Add(to);

                        var bodyBuilder = new BodyBuilder
                        {
                            HtmlBody = templateManager.Apply(_bodyTempate, contactID)
                        };

                        foreach (var filePath in filePaths)
                        {
                            bodyBuilder.Attachments.Add(filePath);
                        }

                        mimeMessage.Body = bodyBuilder.ToMessageBody();

                        mimeMessage.Headers.Add("Auto-Submitted", "auto-generated");

                        _log.Debug(GetLoggerRow(mimeMessage));

                        var success = false;

                        try
                        {
                            smtpClient.Send(mimeMessage);

                            success = true;
                        }
                        catch (SmtpCommandException ex)
                        {
                            _log.Error(Error, ex);

                            if (ex.ErrorCode == SmtpErrorCode.RecipientNotAccepted)
                            {
                                if (ex.StatusCode == SmtpStatusCode.MailboxBusy ||
                                    ex.StatusCode == SmtpStatusCode.MailboxUnavailable)
                                {
                                    Error = string.Format(CRMCommonResource.MailSender_MailboxBusyException, 5);

                                    Thread.Sleep(TimeSpan.FromSeconds(5));

                                    smtpClient.Send(mimeMessage);

                                    success = true;
                                }
                                else
                                {
                                    Error +=
                                        string.Format(CRMCommonResource.MailSender_FailedDeliverException,
                                                      ex.Mailbox.Address) + "<br/>";
                                }
                            }
                        }

                        if (success)
                        {
                            if (_storeInHistory)
                            {
                                AddToHistory(contactID,
                                             string.Format(CRMCommonResource.MailHistoryEventTemplate, mimeMessage.Subject));
                            }

                            var endDate      = DateTime.Now;
                            var waitInterval = endDate.Subtract(startDate);

                            deliveryCount++;

                            var estimatedTime = TimeSpan.FromTicks(waitInterval.Ticks * (_contactID.Count - deliveryCount));

                            Status = new
                            {
                                RecipientCount = _contactID.Count,
                                EstimatedTime  = estimatedTime.ToString(),
                                DeliveryCount  = deliveryCount
                            };
                        }

                        _exactPercentageValue += 100.0 / contactCount;
                        Percentage             = Math.Round(_exactPercentageValue);

                        if (MailSenderDataCache.CheckCancelFlag())
                        {
                            MailSenderDataCache.ResetAll();

                            throw new OperationCanceledException();
                        }

                        MailSenderDataCache.Insert((SendBatchEmailsOperation)Clone());

                        if (Percentage > 100)
                        {
                            Percentage = 100;

                            if (MailSenderDataCache.CheckCancelFlag())
                            {
                                MailSenderDataCache.ResetAll();

                                throw new OperationCanceledException();
                            }

                            MailSenderDataCache.Insert((SendBatchEmailsOperation)Clone());
                        }
                    }
                }
                catch (OperationCanceledException)
                {
                    MailSenderDataCache.ResetAll();
                    _log.Debug("cancel mail sender");
                }
                finally
                {
                    MailSenderDataCache.ResetAll();

                    foreach (var filePath in filePaths)
                    {
                        if (File.Exists(filePath))
                        {
                            File.Delete(filePath);
                        }
                    }
                }

                Status = new
                {
                    RecipientCount = _contactID.Count,
                    EstimatedTime  = TimeSpan.Zero.ToString(),
                    DeliveryCount  = deliveryCount
                };
            }
            Complete();
        }
 /// <summary>
 /// Gets the <see cref="CmsRecipient"/> for the specified mailbox.
 /// </summary>
 /// <returns>A <see cref="CmsRecipient"/>.</returns>
 /// <param name="mailbox">The mailbox.</param>
 /// <exception cref="CertificateNotFoundException">
 /// A certificate for the specified <paramref name="mailbox"/> could not be found.
 /// </exception>
 protected abstract CmsRecipient GetCmsRecipient(MailboxAddress mailbox);
		static bool PgpSecretKeyMatches (PgpSecretKey key, MailboxAddress mailbox)
		{
			var secure = mailbox as SecureMailboxAddress;

			if (secure != null && !string.IsNullOrEmpty (secure.Fingerprint)) {
				if (secure.Fingerprint.Length > 16) {
					var fingerprint = HexEncode (key.PublicKey.GetFingerprint ());

					return secure.Fingerprint.Equals (fingerprint, StringComparison.OrdinalIgnoreCase);
				} else {
					var id = ((int) key.KeyId).ToString ("X2");

					return secure.Fingerprint.EndsWith (id, StringComparison.OrdinalIgnoreCase);
				}
			}

			foreach (string userId in key.UserIds) {
				MailboxAddress email;

				if (!MailboxAddress.TryParse (userId, out email))
					continue;

				if (mailbox.Address.Equals (email.Address, StringComparison.OrdinalIgnoreCase))
					return true;
			}

			return false;
		}
		/// <summary>
		/// Initializes a new instance of the <see cref="MimeKit.Cryptography.CertificateNotFoundException"/> class.
		/// </summary>
		/// <remarks>
		/// Creates a new <see cref="CertificateNotFoundException"/>.
		/// </remarks>
		/// <param name="mailbox">The mailbox that could not be resolved to a valid certificate.</param>
		/// <param name="message">A message explaining the error.</param>
		public CertificateNotFoundException (MailboxAddress mailbox, string message) : base (message)
		{
			Mailbox = mailbox;
		}
Exemple #60
0
        /// <summary>
        /// Parses ENVELOPE from IMAP envelope string.
        /// </summary>
        /// <param name="envelopeString">Envelope string.</param>
        public void Parse(string envelopeString)
        {
            if (envelopeString.StartsWith("("))
            {
                envelopeString = envelopeString.Substring(1);
            }
            if (envelopeString.EndsWith(")"))
            {
                envelopeString = envelopeString.Substring(0, envelopeString.Length - 1);
            }

            string       word = "";
            StringReader r    = new StringReader(envelopeString);

            #region Date

            // Date
            word = r.ReadWord();
            if (word == null)
            {
                throw new Exception("Invalid IMAP ENVELOPE structure !");
            }
            if (word.ToUpper() == "NIL")
            {
                m_Date = DateTime.MinValue;
            }
            else
            {
                try
                {
                    m_Date = MimeUtils.ParseDate(word);
                }
                catch
                {
                    // Failed to parse date, return minimum.
                    m_Date = DateTime.MinValue;
                }
            }

            #endregion

            #region Subject

            // Subject
            word = r.ReadWord();
            if (word == null)
            {
                throw new Exception("Invalid IMAP ENVELOPE structure !");
            }
            if (word.ToUpper() == "NIL")
            {
                m_Subject = null;
            }
            else
            {
                m_Subject = MIME_Encoding_EncodedWord.DecodeS(word);
            }

            #endregion

            #region From

            // From
            m_From = ParseAddresses(r);

            #endregion

            #region Sender

            // Sender
            //	NOTE: There is confusing part, according rfc 2822 Sender: is MailboxAddress and not AddressList.
            MailboxAddress[] sender = ParseAddresses(r);
            if (sender != null && sender.Length > 0)
            {
                m_Sender = sender[0];
            }
            else
            {
                m_Sender = null;
            }

            #endregion

            #region ReplyTo

            // ReplyTo
            m_ReplyTo = ParseAddresses(r);

            #endregion

            #region To

            // To
            m_To = ParseAddresses(r);

            #endregion

            #region Cc

            // Cc
            m_Cc = ParseAddresses(r);

            #endregion

            #region Bcc

            // Bcc
            m_Bcc = ParseAddresses(r);

            #endregion

            #region InReplyTo

            // InReplyTo
            r.ReadToFirstChar();
            word = r.ReadWord();
            if (word == null)
            {
                throw new Exception("Invalid IMAP ENVELOPE structure !");
            }
            if (word.ToUpper() == "NIL")
            {
                m_InReplyTo = null;
            }
            else
            {
                m_InReplyTo = word;
            }

            #endregion

            #region MessageID

            // MessageID
            r.ReadToFirstChar();
            word = r.ReadWord();
            if (word == null)
            {
                throw new Exception("Invalid IMAP ENVELOPE structure !");
            }
            if (word.ToUpper() == "NIL")
            {
                m_MessageID = null;
            }
            else
            {
                m_MessageID = word;
            }

            #endregion
        }