HOW TO encrypt all incoming email

This section contains user-submitted tutorials.
Post Reply
jacko
Normal user
Normal user
Posts: 35
Joined: 2017-10-25 22:24

HOW TO encrypt all incoming email

Post by jacko » 2017-11-04 22:20

I wanted to achieve this : All incoming email are encrypted. you can then use a smartcard with Gnupg to view the email. Thanks to thunderbird and enigmail this process is invisible ; To the user the mails look as if regular mails with few differences.
In a word, catch all email receive everything and after spam checks and so on, the mail is send encrypted to the account secure@mydomain while removing the original mail.
The system is based on the script gpgit , this script in perl has been made for exim on linux.
Here : https://www.grepular.com/Automatically_ ... ming_Email
and here : https://gitlab.com/mikecardwell/gpgit .
Thankfully cygwin is able to compile all the necessary dependencies and it requires a lot. Using strawberry or activeperl failed. You need to install perl with devel packages in cygwin. https://www.cygwin.com/
then compile the 2 modules:

Code: Select all

cpan install MIME::Tools
cpan install Mail::GnuPG
generate your key for email secure@domain.com under the cygwin terminal

Code: Select all

gpg --gen-key
place gpgit in your /bin directory.
Because of the eventhandler " OnDeliverMessage(oMessage)" we can intercept the .eml file ready to be put in the INBOX of the user . On the forum there is a thread about pipping made by the dev of hmailserver : viewtopic.php?f=14&t=2960&p=186708 At that point I had troubles with permissions (as someone in that thread) , I was unable to run a command from the eventhandler script. Because I'm reckless I decided to run the hmailserver service as an admin user and the batch file can be run.
Here is the code in evenhandlers:
At the beginning of the script we check if email is to be delivered to secure@domain.com it will then NOT be encrypted. you should give to people some catchall email not this private mail account.

Code: Select all

Const g_sPHPPath     = "C:\cygwin\bin\perl.exe"
Const g_sScriptPath  = "C:\cygwin\bin\gpgit"
Const g_sPipeAddress = "secure@mydomain.com"
Const bash = "c:\cygwin\bin\bash -l -c "
Const dossiercrypt = "c:\cygwin\home\ted\crypt\"
const g_sDQ          = """"
   Sub OnDeliverMessage(oMessage)
   If g_sPipeAddress = "" Then
      bPipeMessage = True
   Else
      bPipeMessage = False
      Set obRecipients = oMessage.Recipients
      For i = 0 to obRecipients.Count - 1
         Set obRecipient = obRecipients.Item(i)
         If LCase(obRecipient.Address) = LCase(g_sPipeAddress) Then
            bPipeMessage = False
			Else bPipeMessage = True
         End If
      Next
   End If 
   If bPipeMessage Then
   dim oApp
   Set oApp = CreateObject("hMailServer.Application")
Call oApp.Authenticate("Administrator", "--yourpassword--")
dim openPos 
dim closePos 
dim midBit 
openPos = instr (oMessage.Filename, "{")
closePos = instr (oMessage.Filename, "}")
midBit = mid (oMessage.Filename, openPos+1, closePos - openPos - 1)
	EventLog.Write(midBit)
	Dim objFichier, outFile
	Set objFichier = CreateObject("Scripting.FileSystemObject")
Set outFile = objFichier.CreateTextFile("C:\cygwin\home\ted\cryptage.bat", True)
	outFile.WriteLine "@echo off"
	outFile.WriteLine "CALL c:\cygwin\bin\bash -l -c " & g_sDQ & "cat " & g_sDQ & g_sDQ & g_sDQ & g_sDQ & "c:\\\\Program\ Files\ \(x86\)\\\\hMailServer\\\\Data\\\\{" &  midBit & "}.eml" & g_sDQ &  g_sDQ & g_sDQ & g_sDQ &" | perl /bin/gpgit secure@mydomain.com >  c:\\\\cygwin\\\\home\\\\ted\\\\crypt\\\\{"& midBit &"}.eml"""
	outFile.WriteLine "timeout /t 10"
outFile.Close
set outFile = Nothing
Set truc = CreateObject("WScript.Shell")
 EventLog.Write(sCommandLine)
  Call truc.Run("C:\cygwin\home\ted\cryptage.bat", 0, TRUE)
 Set truc = Nothing
Dim withoutParts 
withoutParts = Replace(oMessage.From, """", "")
Dim sujet 
'sujet = Replace(oMessage.Subject, "%", "%%")
sujet = oMessage.Subject
Dim objFichierrenvoi, outFilerenvoi
	Set objFichierrenvoi = CreateObject("Scripting.FileSystemObject")
	'Open write stream
	Set outFilerenvoi = objFichierrenvoi.CreateTextFile("C:\cygwin\home\ted\renvoi.bat", True)
outFilerenvoi.WriteLine "@echo off"
outFilerenvoi.WriteLine "chcp 28591 > nul"
outFilerenvoi.WriteLine "SET to=" & g_sPipeAddress
outFilerenvoi.WriteLine "SET fichier=" & dossiercrypt & "{" & midBit & "}.eml"
outFilerenvoi.WriteLine "SET subject=" & sujet
outFilerenvoi.WriteLine "SET from=" & oMessage.Subject
outFilerenvoi.WriteLine g_sDQ  & "c:\cygwin\home\ted\blat.exe" & g_sDQ & " %fichier% -raw -to %to% -s " & g_sDQ & "%subject%"& g_sDQ & " -from " & g_sDQ & withoutParts & g_sDQ
outFilerenvoi.Close
set outFilerenvoi = Nothing
 Set renvoi = CreateObject("WScript.Shell")
  Call renvoi.Run("C:\cygwin\home\ted\renvoi.bat", 0, TRUE)
 Set renvoi = Nothing
 Dim objFichiererase, outFileerase
	Set objFichiererase = CreateObject("Scripting.FileSystemObject")
	'Open write stream
	Set outFileerase = objFichiererase.CreateTextFile("C:\cygwin\home\ted\erase.bat", True)
outFileerase.WriteLine "@echo off"
outFileerase.WriteLine "SET fichier=" & dossiercrypt & "{" & midBit & "}.eml"
outFileerase.WriteLine "del %fichier%"
outFileerase.Close
Set outFileerase = Nothing
Set deletefile = CreateObject("WScript.Shell")
  Call deletefile.Run("C:\cygwin\home\ted\erase.bat", 0, TRUE)
 Set deletefile = Nothing
Dim dteWait
dteWait = DateAdd("s", 20, Now())
Do Until (Now() > dteWait)
Loop
Result.Value = 1 
End if
End sub
Once the email has been piped to gpgit which check what key we are using and dont double crypt the file the new eml is put in a directory. A pickup folder would be nice and some people did it via special built of hmailserver but didnt share it. Instead we get the subject then use blat http://www.blat.net/ in a command to add the subject.

Code: Select all

blat -install 127.0.0.1 secure@domain.com - 1010 - secure@domain.com *yourpassword*
Blat requires Stunnel https://www.stunnel.org/index.html as it cant use TLS auth. I use required argument for TLS in hmailserver therefore is needed. Just add under TCP/IP a new port like 1025 with required TLS. Stunnel is setup as a service, its conf file only needs this :

Code: Select all

[ssmtp]
client = yes
accept  = 127.0.0.1:1010
connect = 127.0.0.1:1025
cert = stunnel.pem
Blat sends back the new email in mime format to the secure account , the remaining .eml file is erased and the event "ondeliver" goes on and dont deliver the original mail
( Result= 1 )
This is made for one account but could be arranged for multiple users with case statements.
known bug : if "%" is used in subject it will not show as % is used in batch file for variable it would need to be escaped though if done it messed up the UTF-8 coding. on your client side you need thunderbird (Warning Outlook have trouble with mime type and creates2 attached files at least on my version outlook 2010 it is a known bug maybe corrected in later version), the addon enigmail and to install the windows version of gnupg https://www.gpg4win.org/
Now I hope this give you ideas , it's not bug free it's just for reference.

jacko
Normal user
Normal user
Posts: 35
Joined: 2017-10-25 22:24

Re: HOW TO encrypt all incoming email

Post by jacko » 2017-11-06 12:21

UPDATE

Because email sent with emojis were stopping the CreateObject("Scripting.FileSystemObject") method I had to modify the script accordingly. Now accents and emojis are passed.
After

Code: Select all

 Dim withoutParts 
withoutParts = Replace(oMessage.From, """", "")
the new code is :

Code: Select all

Dim objStream
Set objStream = CreateObject("ADODB.Stream")
objStream.CharSet = "utf-16"
objStream.Open
objStream.WriteText "@echo off" & Chr(13) & Chr(10)
objStream.WriteText "chcp 28591 > nul" & Chr(13) & Chr(10)
objStream.WriteText "SET to=" & g_sPipeAddress & Chr(13) & Chr(10)
objStream.WriteText "SET fichier=" & dossiercrypt & "{" & midBit & "}.eml" & Chr(13) & Chr(10)
objStream.WriteText g_sDQ  & "c:\cygwin\home\ted\blat.exe" & g_sDQ & " %fichier% -raw -to %to% -s " & g_sDQ & oMessage.Subject & g_sDQ & " -from " & g_sDQ & withoutParts  & g_sDQ

objStream.SaveToFile "C:\cygwin\home\ted\renvoi.bat", 2

Dim objFichierrecode, outFilerecode
	Set objFichierrecode = CreateObject("Scripting.FileSystemObject")
Set outFilerecode = objFichierrecode.CreateTextFile("C:\cygwin\home\ted\recode.bat", True)
	outFilerecode.WriteLine "@echo off"
	outFilerecode.WriteLine "chcp 28591 > nul"
	outFilerecode.WriteLine "SET utf=UTF16..UTF8"
	outFilerecode.WriteLine "SET renvoi=C:\cygwin\home\ted\renvoi.bat"
	outFilerecode.WriteLine g_sDQ  & "C:\cygwin\bin\recode.exe"& g_sDQ  & " %utf% %renvoi%"
	outFilerecode.WriteLine "cmd /c "& g_sDQ &"C:\cygwin\home\ted\renvoi.bat" & g_sDQ
	outFilerecode.Close
	set outFilerecode = Nothing
	
	
	Set renvoi = CreateObject("WScript.Shell")
  Call renvoi.Run("C:\cygwin\home\ted\recode.bat", 0, TRUE)
 Set renvoi = Nothing
 
 Dim objFichiererase, outFileerase
   Set objFichiererase = CreateObject("Scripting.FileSystemObject")
   'Open write stream
   Set outFileerase = objFichiererase.CreateTextFile("C:\cygwin\home\ted\erase.bat", True)
outFileerase.WriteLine "@echo off"
outFileerase.WriteLine "SET fichier=" & dossiercrypt & "{" & midBit & "}.eml"
outFileerase.WriteLine "del %fichier%"
outFileerase.Close
Set outFileerase = Nothing
Set deletefile = CreateObject("WScript.Shell")
  Call deletefile.Run("C:\cygwin\home\ted\erase.bat", 0, TRUE)
 Set deletefile = Nothing
 
 Dim dteWait
dteWait = DateAdd("s", 20, Now())
Do Until (Now() > dteWait)
Loop
Result.Value = 1 
End if
End Sub
It requires " recode.exe" which is found in your /bin cygwin install.

User avatar
Dravion
Senior user
Senior user
Posts: 1486
Joined: 2015-09-26 11:50
Location: Germany
Contact:

Re: HOW TO encrypt all incoming email

Post by Dravion » 2017-11-06 13:02

Sorry, this Solution is complete crap and doesnt have anything to do with Unix Kiss approach and has many
showstopper points of failure.

hMailServer is a userfriendly Windows Package. If you want some Unix/Linux MTA like Exim4 you can install
Cygwin32/64 and get what you want but its not the intention of the project making things as crappy and complex
like on Linux. Thats why many people using hMailServer. Ease of use, GUI and beginner friendly.

jacko
Normal user
Normal user
Posts: 35
Joined: 2017-10-25 22:24

Re: HOW TO encrypt all incoming email

Post by jacko » 2017-11-06 13:30

I am a total beginner hence I use hmailserver.
I just wanted to share what I did this week as there arent any windows" encrypt all incoming email solution" out there ( at least to my knowledge and free) and I used only script events and the pipping script Martin made.
this is for reference only I hard coded some paths which of course is not ideal. this is not a release thing. I just thought some people might have a look at it and decide for their own. I know I would have been interested.
but thanks for the kind words.

User avatar
Dravion
Senior user
Senior user
Posts: 1486
Joined: 2015-09-26 11:50
Location: Germany
Contact:

Re: HOW TO encrypt all incoming email

Post by Dravion » 2017-11-06 13:41

Ok.This shouldnt sound to rude :)
Keep allways in mind if you publish a User-submitted tutorial there is a chance someone will try to implement it
on its Operating System. A tutorial should allways carefully crafted and verified so it has some value to the reader.
If you want to exchange ideas, please goto the general or offtopic section. If you have a little script, even a untested
or errorprone one, goto the scripting section.

jacko
Normal user
Normal user
Posts: 35
Joined: 2017-10-25 22:24

Re: HOW TO encrypt all incoming email

Post by jacko » 2017-11-06 13:58

okay my bad then if I put that in the wrong section.

User avatar
mattg
Moderator
Moderator
Posts: 20275
Joined: 2007-06-14 05:12
Location: 'The Outback' Australia

Re: HOW TO encrypt all incoming email

Post by mattg » 2017-11-07 00:01

And I still maintain that this concept (encrypting email after they arrive at your hmailserver) is flawed.

To me it is like a second-hand car yard not caring how cars get to them (No checking, no security), and then locking them in a caged area with the keys to the cage clearly visibly hanging from a post in the centre of the yard.

I'm really not sure what is intended to be achieved, but make no mistake this is NOT security in any way shape or form.
Just 'cause I link to a page and say little else doesn't mean I am not being nice.
https://www.hmailserver.com/documentation

prisma
Senior user
Senior user
Posts: 310
Joined: 2010-07-09 13:16

Re: HOW TO encrypt all incoming email

Post by prisma » 2017-11-08 12:57

Hi,

I agree. The way jacko wants to achieve security does not make many sense. From what I understood from the script, the mailserver has knowledge about the private gnupg key of the user. Or am I wrong? This would break security.
If a mail user want to have end-to-end security, he should handle his encryption without annoying the server administrator.

The idea of storing mails *generally* encrypted is definitely a good idea. The security increase is immense.
I'm not sure if it fits to jacjo's needs, but here is a little digression about storing encrypted mails:

Protect data to be stolen by taking HDD or SSD from storage cases: Bitlocker

Protect data from the ability to be viewed by many administrators in the company: EFS
The simple way:
  • Let run hmailserver service with an own service principal
  • The service principal gets an EFS certificate
  • Encrypt datafolder with this EFS certificate
Approach: Only people with access to the service principal credentials, and noboy else, no other administrator, backup agent etc., is able to read the mails. This circle of people is definitely much smaller. Administrators are able to do everything with the mailserver, beside reading mails.

Post Reply