Top-Themen

AppleEntwicklungHardwareInternetLinuxMicrosoftMultimediaNetzwerkeOff TopicSicherheitSonstige SystemeVirtualisierungWeiterbildungZusammenarbeit

Aktuelle Themen

Administrator.de FeedbackApache ServerAppleAssemblerAudioAusbildungAuslandBackupBasicBatch & ShellBenchmarksBibliotheken & ToolkitsBlogsCloud-DiensteClusterCMSCPU, RAM, MainboardsCSSC und C++DatenbankenDatenschutzDebianDigitiales FernsehenDNSDrucker und ScannerDSL, VDSLE-BooksE-BusinessE-MailEntwicklungErkennung und -AbwehrExchange ServerFestplatten, SSD, RaidFirewallFlatratesGoogle AndroidGrafikGrafikkarten & MonitoreGroupwareHardwareHosting & HousingHTMLHumor (lol)Hyper-VIconsIDE & EditorenInformationsdiensteInstallationInstant MessagingInternetInternet DomäneniOSISDN & AnaloganschlüsseiTunesJavaJavaScriptKiXtartKVMLAN, WAN, WirelessLinuxLinux DesktopLinux NetzwerkLinux ToolsLinux UserverwaltungLizenzierungMac OS XMicrosoftMicrosoft OfficeMikroTik RouterOSMonitoringMultimediaMultimedia & ZubehörNetzwerkeNetzwerkgrundlagenNetzwerkmanagementNetzwerkprotokolleNotebook & ZubehörNovell NetwareOff TopicOpenOffice, LibreOfficeOutlook & MailPapierkorbPascal und DelphiPeripheriegerätePerlPHPPythonRechtliche FragenRedHat, CentOS, FedoraRouter & RoutingSambaSAN, NAS, DASSchriftartenSchulung & TrainingSEOServerServer-HardwareSicherheitSicherheits-ToolsSicherheitsgrundlagenSolarisSonstige SystemeSoziale NetzwerkeSpeicherkartenStudentenjobs & PraktikumSuche ProjektpartnerSuseSwitche und HubsTipps & TricksTK-Netze & GeräteUbuntuUMTS, EDGE & GPRSUtilitiesVB for ApplicationsVerschlüsselung & ZertifikateVideo & StreamingViren und TrojanerVirtualisierungVisual StudioVmwareVoice over IPWebbrowserWebentwicklungWeiterbildungWindows 7Windows 8Windows 10Windows InstallationWindows MobileWindows NetzwerkWindows ServerWindows SystemdateienWindows ToolsWindows UpdateWindows UserverwaltungWindows VistaWindows XPXenserverXMLZusammenarbeit

Powershell: Send a mime encrypted email with excel file attachment

Frage Sicherheit Verschlüsselung & Zertifikate

Mitglied: Thomminger

Thomminger (Level 1) - Jetzt verbinden

16.06.2014, aktualisiert 13:11 Uhr, 2464 Aufrufe, 3 Kommentare, 1 Danke

Hi guys!

I've a tricky challenge.
I try to send mime encrypted mails.
Therefore I search in AD by using "cn" to get the certificate and mail address.
so far so good....

The native email without attachment run fine. email was sent encrypted:

$RecipientCN = $null
$RootDSE = $null
$Certificate = $null
$UserCertificate = $null
$ExcelFile = "C:\Temp\123.xlsx"

$RecipientCN='<cn>'
$SearchForestForPerson = New-Object DirectoryServices.DirectorySearcher([ADSI]"LDAP://DC=domain,DC=com")
$SearchForestForPerson.SearchScope = "subtree"
$SearchForestForPerson.PropertiesToLoad.Add("mail") | Out-Null
$SearchForestForPerson.PropertiesToLoad.Add("usercertificate") | Out-Null
$SearchForestForPerson.Filter = ("(&(objectClass=person)(CN=$RecipientCN))")
$Recipient = $SearchForestForPerson.FindOne()

$ChosenCertificate = $null
$Now = Get-Date
If ($Recipient.Properties.usercertificate -ne $null) {
ForEach ($UserCertificate in $Recipient.Properties.usercertificate) {
$ValidForSecureEmail = $false
$Certificate = [System.Security.Cryptography.X509Certificates.X509Certificate2]$UserCertificate
$Extensions = $Certificate.Extensions
ForEach ($Extension in $Extensions) {
If ($Extension.EnhancedKeyUsages -ne $null) {
ForEach ($EnhancedKeyUsage in $Extension.EnhancedKeyUsages) {
If ($EnhancedKeyUsage.FriendlyName -ine "Secure Email") {
$ValidForSecureEmail = $true
break
}
}
If ($ValidForSecureEmail) {
break
}
}
}
If ($ValidForSecureEmail) {
If ($Now -gt $Certificate.NotBefore.AddMinutes(-5) -and $Now -lt $Certificate.NotAfter.AddMinutes(5)) {
$ChosenCertificate = $Certificate
}
}
If ($ChosenCertificate -ne $null) {
break

}
}
}


Add-Type -assemblyName "System.Security"
$MailClient = New-Object System.Net.Mail.SmtpClient "<smtp server>"
$Message = New-Object System.Net.Mail.MailMessage

$Message.To.Add($Recipient.properties.mail.item(0))
$Message.From = "<sender address>"
$Message.Subject = "Unencrypted subject of the message"
$Body = "This is the mail body"
$MIMEMessage = New-Object system.Text.StringBuilder
$MIMEMessage.AppendLine('Content-Type: text/plain; charset="UTF-8"') | Out-Null
$MIMEMessage.AppendLine('Content-Transfer-Encoding: 7bit') | Out-Null
$MIMEMessage.AppendLine() | Out-Null
$MIMEMessage.AppendLine($Body) | Out-Null

[Byte[]] $BodyBytes = [System.Text.Encoding]::ASCII.GetBytes($MIMEMessage.ToString())

$ContentInfo = New-Object System.Security.Cryptography.Pkcs.ContentInfo (,$BodyBytes)
$CMSRecipient = New-Object System.Security.Cryptography.Pkcs.CmsRecipient $ChosenCertificate
$EnvelopedCMS = New-Object System.Security.Cryptography.Pkcs.EnvelopedCms $ContentInfo
$EnvelopedCMS.Encrypt($CMSRecipient)
[Byte[]] $EncryptedBytes = $EnvelopedCMS.Encode()
$MemoryStream = New-Object System.IO.MemoryStream @(,$EncryptedBytes)
$AlternateView = New-Object System.Net.Mail.AlternateView($MemoryStream, "application/pkcs7-mime; smime-type=enveloped-data;name=smime.p7m")
$Message.AlternateViews.Add($AlternateView)
$MailClient.Send($Message)


...but I've no success with an encrypted email with attached excel file ($ExcelFile).

Do anyone have an idea or better a script code which I can use to send an encrypted email with an attachment?

Thanks!

Thomminger
Mitglied: colinardo
16.06.2014, aktualisiert um 17:00 Uhr
Hello Thomminger, welcome to administrator.de!
As far as i know, encrypted MIME attachments are not supported with System.Net.Mail. You may consider to implement your
own security mecanism (embed your mail as an encrypted attachment, ... like a scrambled *.zip file for example). Or use a third party programming-library for composing your messages.

A solution could be this library: http://www.codeproject.com/Articles/41727/An-S-MIME-Library-for-Sending ... which also supports attachments. You can compile this code an use the corresponding *.dll in your powershell-project by loading it via add-type.

Here is an example with this library and Powershell:

This sends an encrypted and signed message with an included attachment:
01.
# load managed code library 
02.
add-type -Path "D:\Cpi.Net.SecureMail.dll" 
03.
 
04.
# load cryptocertificate by defining path and password 
05.
$mycert = new-object System.Security.Cryptography.X509Certificates.X509Certificate2("D:\yourcryptocert.p12","PASSWORD_OF_CERTIFICATE") 
06.
 
07.
# load recipient public certificate 
08.
$recipientCert = new-object System.Security.Cryptography.X509Certificates.X509Certificate2("D:\recipient.cer") 
09.
 
10.
# create secure mail message 
11.
$mail = new-object Cpi.Net.SecureMail.SecureMailMessage 
12.
 
13.
# add sender and recipient 
14.
$mail.From = new-object Cpi.Net.SecureMail.SecureMailAddress("sender@domain.com","SENDERNAME",$mycert,$mycert) 
15.
$mail.To.Add((new-object Cpi.Net.SecureMail.SecureMailAddress("recipient@domain.com","RECIPIENTNAME",$recipientCert))) 
16.
 
17.
$mail.Body = "This is a secure message with Attachment" 
18.
 
19.
# add secure attachment to mail message 
20.
$mail.Attachments.Add((new-object Cpi.Net.SecureMail.SecureAttachment("d:\yourattachment.txt"))) 
21.
 
22.
# set mail properties (encrypted and signed) 
23.
$mail.IsSigned = $true 
24.
$mail.IsEncrypted = $true 
25.
 
26.
# create smtp-client to send mail message 
27.
$smtp = new-object System.Net.Mail.SmtpClient("smtp.yourdomain.com", 25) 
28.
$smtp.Credentials = new-object System.Net.NetworkCredential("SMTPUSERNAME","SMTPPASSWORD") 
29.
 
30.
# finally send mail 
31.
$smtp.Send($mail)
For simplicity i have compiled the library for you, download it here: Cpi.Net.SecureMail.dll (Compiled against .NET Framework 3.5)

Regards
@colinardo
Bitte warten ..
Mitglied: Thomminger
16.06.2014 um 15:57 Uhr
Hi colinardo!

Thanks a lot for your fast reply!

As well for your support by creating and compiling this *.dll.

But...I hoped for a regular/standardized - in best case powershell or .net integrated solution.

Your provided solution with this compiled *.dll is not usable for my szenario. I've no doubt of your competence, but I've to fulfill different security standards and as you know - *.dll imply a lot of risks inside of them.

Thanks for your support. Maybe you or other wise guys in this community find additional solutions for this topic.

You're very welcome!

nice time!

regards
Thomminger
Bitte warten ..
Mitglied: colinardo
16.06.2014, aktualisiert um 17:12 Uhr
you can compile the dll out of the code yourself if you have security concerns... or look in the public available .net code of the library and implement this directly in powershell with the standard net objects... with that you can be sure there is nothing dangerous inside!
Bitte warten ..
Ähnliche Inhalte
Batch & Shell
gelöst Powershell excel (6)

Frage von Crank69 zum Thema Batch & Shell ...

Batch & Shell
Excel mit Powershell formatieren (13)

Frage von Tastuser zum Thema Batch & Shell ...

Entwicklung
gelöst Powershell File durchsuchen (1)

Frage von easy4breezy zum Thema Entwicklung ...

Microsoft Office
Excel File - an einer Stelle nur Lesen und an anderer Bearbeiten (2)

Frage von LenzDan zum Thema Microsoft Office ...

Neue Wissensbeiträge
Entwicklung

Exploit Development

Anleitung von burhanudinn123 zum Thema Entwicklung ...

Windows Update

Microsoft Update KB4034664 verursacht Probleme mit Multimonitor-Systemen

(1)

Tipp von beidermachtvongreyscull zum Thema Windows Update ...

Viren und Trojaner

CNC-Fräsen von MECANUMERIC werden (ggf.) mit Viren, Trojanern, Würmern ausgeliefert

(4)

Erfahrungsbericht von anteNope zum Thema Viren und Trojaner ...

Heiß diskutierte Inhalte
Netzwerkprotokolle
Leiten "dumme" Switches VLAN-Tags mit durch? (17)

Frage von coltseavers zum Thema Netzwerkprotokolle ...

E-Business
Wo tragt ihr eure privaten Termine ein? (14)

Frage von honeybee zum Thema E-Business ...

Batch & Shell
Batch zum suchen und verschieben von Verknüpfungen (12)

Frage von zeroblue2005 zum Thema Batch & Shell ...

Windows Server
Terminalserver starten willkürlich neu (12)

Frage von thaefliger zum Thema Windows Server ...