Clicky

20180327

Bulk encryption with asymetric keys

This post will explain a method encrypt bulk data with a public (known to everyone) password where the encrypted data only can be decrypted with a secret password.

But let's first explain a simpler encryption method using one password only for encryption and decryption. For example 7-Zip can compress files and also encrypt them. Alice want to send a message to Bob via email. But she does not want that Eve is able to read the message. Alice uses 7-Zip to encrypt the message with a password ("P@ssw0rd"). The encrypted message contains garbled data and as long as Eve does not know the password, the message can travel safely over the Internet and once Bob has received the message he can reverse the encryption by using his decryption password.
Symmetric encryption

Alice must tell Bob the password by a "covert channel", e.g. An SMS or WhatsApp message. Sending the password via email is not a good idea because that allows Eve to find out the password and decrypt the message. This encryption method is called "symmetric" encryption because the encryption and decryption password are the same. The advantage of this method is simplicity, speed and it is suited for the encryption of bulk data. The disadvantages are that Alice must know Bob and use a secure method to convey the password.

It would be better if the encryption password differs from the decryption password. E.g. Alice uses "pA55w0rd1" to encrypt the message and Bob is using "Th1sI5maiDecrpti0nP@ssword" to decrypt the message. This method has several advantages. The encryption password can be published anywhere, anyone might know this password. Also, Alice does not need to know Bob in advance because Bob only knows the decryption password. If the encrypted message is seen by Eve, she still cannot decrypt the message even if she has the encryption password.

Asymmetric encryption
Asymmetric encryption has a couple of disadvantages too. Without going into nitty-gritty details, asymmetric encryption is slow and not suited for bulk encryption. So when we combine symmetric and asymmetric encryption, we can overcome the disadvantages of both methods and encrypt bulk data with a public password.

To combine asymmetric (OpenSSL) and symmetric (7-Zip) encryption another password is used: a "Session Password". This password is used only once, can be long and complex, and can be automatically generated.

Let's now tie it all together. These are the steps to encrypt:
  1. Generate a Session Password
  2. ZIP and encrypt the bulk data with the Session Password (7-Zip)
  3. Encrypt the Session Password with the public password, creating a small file with the encrypted Session Password (OpenSSL).
  4. Send both the encrypted bulk data ZIP file and the encrypted Session Password file to Bob
Once Bob receives the two files he does:
  1. Decrypt the Session Password with his private password
  2. Unzip and unencrypt the bulk data with the Session Password

Preparations:
  1. Download and install OpenSSL. Check the "bin" folder.
  2. Install 7-Zip. Check the installation folder.
One time only: Create the public password and Bob's decryption password:

set OpenSSLdir=c:\Scripts\OpenSSL-Win32\bin
set OpenSSL="%OpenSSLdir%\openssl.exe"
%openssl% genrsa -out BobsPasswords.pem 4096
%openssl% rsa -in BobsPasswords.pem -out BobsPublicPassword.pem -outform PEM -pubout


Now you will have two files:
 
BobsPasswords.pem
BobsPublicPassword.pem

IMPORTANT: move the file BobsPasswords.pem to a memory stick and delete it from the hard disk.

This is a script to compress and encrypt a folder (and its subfolders). Save as "ZipEncrypt.bat":

    @echo off
    cls
   
    if %1.==. (
        echo.
        echo *** Use: ZipEncrypt {folder}
        goto :EOF
    )   
   
    if not exist %1\ (
        echo.
        echo *** Folder %1\ not found.
        goto :EOF
    )   
   
::--- Create SessionPassword...
    echo.
    echo *** Create SessionPassword...
    set OpenSSLdir=c:\OpenSSL-Win32\bin
    set OpenSSL=%OpenSSLdir%\openssl.exe  
    for /f "usebackq tokens=* delims=" %%I IN (`%OpenSSL% rand -hex 32 2^>nul`) DO set SessionPassword=%%I  

::--- Filename randomization...
    set RND=%RANDOM%
    echo.
    echo *** Filename randomization number: %RND%

::--- Compress and Encrypt folder...
    echo.
    echo *** Compressing and Encrypting the backup...
    "C:\Program Files\7-Zip\7z.exe" a -bb1 -mx=3 -v100m -r -bd -p%SessionPassword% "%TEMP%\AsymmetricBackup%RND%_data.7z" "%1\*" 
   
::--- Encrypt SessionPassword with     BobsPublicPassword.pem...
    echo.
    echo *** Encrypting the SessionKey...
    <nul set /p=%SessionPassword%|"%OpenSSLdir%\openssl.exe " rsautl -encrypt -inkey "c:\scripts\BobsPublicPassword.pem" -pubin -out "%TEMP%\EncryptedSession-%RND%.Key"
   
::--- List result...
    echo.
    echo *** These are all the files of this backup:
    dir "%TEMP%\*%RND%*.*" | findstr %RND%



This is an example output of the script:

(TBD)

Note that the backup is split in chunks of 100MB (104,857,600 = 2^20 * 100).

When a Bulk ZIP file and encrypted SessionPassword are received by Bob, he has to:

1. Unencrypt the SessionPassword with his decryption password. I assume that the memorystick, with Bob's decryption password, is drive H:

"c:\Scripts\OpenSSL-Win32\bin\openssl.exe" rsautl -decrypt -inkey H:\BobsPasswords.pem -in 12345-EncryptedSession.Key -out SessionPassword.key

2. Unzip and unencrypt the Bulk ZIPfile with the SessionPassword







20180302

{hier de naam van uw .nl domein}.be domein kopen voordat deze gekaapt wordt? (Deel 2)


Zie hier deel 1.

NU.NL bericht er over. Merk op dat Trademark Office niet enige is met dit soort praktijken.

Het .NET domein met dezelfde naam als mijn .COM domein kwam vrij nadat de vorige eigenaar de domeinnaam opgegeven had. Ik kreeg een email van een (andere) domain registrar dat het .NET domein vrij zou komen (hierdoor werd ik wakker!) en dat ik het domein van hen kon kopen voor $90 (ik wist, da's veel te duur). Bovendien kreeg ik niet eens de garantie dat ze het domein konden leveren! Geen slapende honden wakker maken dus verder niet gereageerd.

Ik heb de domein expiratie methode opgezocht en rustig gewacht totdat het domein geheel vrij was. Daarna het .NET domein online (!) bij mijn eigen domein provider geregistreerd voor EUR10/jaar.

Algemeen advies: aan alle email met een zekere urgentie is het altijd goed om de context uit te zoeken en voordat je tot handelen overgaat, eerst een nachtje te slapen.

20180126

Capacitor plague, deel 2

Lees hier deel 1.

Ik kocht op Marktplaats weer een paar managed ethernet switches en een was zo dood als een pier. Opengeschroefd en even naar mwo (meest waarschijnlijke oorzaak), de power supply, gekeken. Er zit een eenvoudige PWM powersupply in. De hoogspannings ELCO (100µF/400V) vertoonde electroliet lekkage.

Lekkage aan de hoogspannings ELCO

Na het vervangen van de ELCO: nog steeds geen licht of geluid. Even gemeten en de nieuwe ELCO werkte goed (300VDC) echter op de trafo (in de gele isolatie) geen wisselspanning. Conclusie: oscillator doet niet. Er zit een eenvoudige oscillator in met eigen ELCO (47µ/25V) die na demontage ook lekkage vertoonde.

Oscillator ELCO (hoogspannings ELCO is al verwijderd)


Na het vervangen van deze ELCO: succes!

Twee defecte ELCOs
Meteen even een weerstandje in de voeding van de ventilator geplaatst zodat 'ie niet zoveel lawaai maakt.

Het resultaat
De hoogspannings ELCO is rood en dus steekt 'ie ook weer mooi af bij de rest...

Naschrift: Het betreft hier een Dell PowerConnect 2724 switch. Deze voeding (Delta ADP-40VP) wordt in de PowerConnect 27xx en 28xx series gebruikt. In de 28xx is er een ander type hoogspannings ELCO gebruikt die geen last lijkt te hebben van Capacitor Plague.

20171210

Detect public IP address change and send email

I really, really should stop scripting in VBscript. It is boo, boo and is already 10+ years replaced by Powershell. Having said that, I needed a simple method to detect a change on a dynamic assigned public IP address. 

Note: for the SendMail function check this post.

This is the script:

    on error resume next

    dim fso, wsh
    set fso = Createobject("scripting.filesystemobject")
    set wsh = CreateObject("wscript.shell")

    const key = "HKEY_CURRENT_USER\SOFTWARE\getPublicIP\publicIPaddress"
    if isnull(wsh.regRead(key)) then wsh.Regwrite key,"0.0.0.0", "REG_SZ"
    Err.Clear
  
    '--- Get public IP address...
    Set objHTTP = CreateObject("Msxml2.XMLHTTP")
    objHTTP.open "GET", "http://ipinfo.io/json", False
    objHTTP.send
    t = split(Cstr(objHTTP.responseText),chr(34))
    currentIPaddress = t(3)

    '--- Read previous IP address...
    previousIPaddress = wsh.regRead(key)

    '--- Compare and when changed, send email with new IP address...
    if currentIPaddress <> previousIPaddress then

        s = "Public IP address has changed." & vbCrLF
        s = s  & "Previous IP address: " & previousIPaddress & vbCrLf
        s = s  & "Current IP address : " & currentIPaddress & vbCrLf
        wscript.echo "Sending email:" &vbCrLf & s
      
        if sendmail(s) = 0 then
            wscript.echo "*** Succesfully sent email."
            wsh.Regwrite key, currentIPaddress, "REG_SZ"
            wsh.LogEvent 0,s
        else
            wscript.echo "*** Error sending email"
        end if  
      
    else
        wscript.echo "*** Public IP address not changed: " & currentIPaddress
    end if



20171116

Month calendar with vertical outlined weeks

VBscript is still boo, boo but some things are really simple to build in VBscript. Here is a calendar program with vertical outlined weeks, week numbers and even consideration for leap years (until the year 2100).

Use:

 C:\Scripts\> cscript //nologo calendar.vbs MM-YYYY

--- 8< ---------------------------------------------

Function Print(s)
    if len(s)=1 then wscript.stdout.write " "
    wscript.stdout.write s & "  "
end Function

Datum           = wscript.arguments(0)
dayOfTheWeek    = DatePart("w",datum)
weekNumber      = DatePart("ww",datum, vbSunday ,vbFirstFourDays)
ArrayStart      = dayOfTheWeek - ((dayOfTheWeek -1) * 2)
monthNumber     = Month(Datum)
WeekDays        = Array("Su","Mo","Tu","We","Th","Fr","Sa")
DaysInMonth     = Array(31,28,31,30,31,30,31,31,30,31,30,31)
monthNames      = Array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec")

'--- Adjust values...
if DaysInMonth(monthNumber-1) + (dayOfTheWeek-1) > 35 then NuOfWeeks = 6 else NuOfWeeks = 5
if Year(Datum) mod 4=0 then DaysInMonth(1)=27

wscript.echo vbCrLf & "Calendar of: " & monthNames(monthNumber-1) & "-" & year(Datum) & vbCrLf
'--- Print weeknumbers
Print " "
for w = 0 to (NuOfWeeks-1) : Print (weekNumber + w) : next
wscript.echo ""
for w = 0 to (NuOfWeeks) : Print "--" : next
wscript.echo ""

'--- Print calendar...
Column = 0
for i = ArrayStart to ArrayStart + 6
    Print Weekdays(Column)
    Column = Column + 1
    for j = 0 to 5
        dayNumber = i + (j * 7)
        if (dayNumber >= 1) and (dayNumber <= DaysInMonth(monthNumber-1)) then
            Print DayNumber
        else
            Print " "
        end if
    next
    wscript.echo ""
next
 

20171110

Automatic emailing of your scanned documents


Some document scanners have the capability to send an email with the scanned document attached. Maybe your scanner can only store scanned files on a NAS, network share or in a folder on your computer. In that case, the next script will detect new scans and email them to you.

Yes, it is VBscript and that is boo, boo, as I mentioned before. However, the email method here, although deprecated, is also used by PowerShell users since it can deal with implicit SSL.

This post consists of two parts:
1. The script
2. A method to start the script automatically if the user is not logged on

The script


Copy & paste all the lines between the markers to Notepad or so and save the script as "MailScan.vbs". Then modify the Recipient with your email address. Modify the SMTP parameters. You might want to create a Gmail address specifically for sending scans. Finally, configure the folder where your scanner stores the scans.

--- 8< -------------------------------------
on error resume next

sub SendMail(Recipient, PDFfile)
 
    Dim objEmail
    Set objEmail        = CreateObject("CDO.Message")

    objEmail.From         = "scannername@yourdomain.com"
    objEmail.To         = Recipient
    objEmail.Subject     = "Scanned document from scanner {scannername/location}"
    objEmail.Textbody     = now() & ", this email contains a scanned document from scanner {scannername/location}: " & PDFfile

'--- When you host your own mailserver, use this:   
    objEmail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendusing")             = 2
    objEmail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver")         = "192.168.1.13" ' IP address of your emailserver
    objEmail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpusessl")         = 0
    objEmail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate")     = 1
    objEmail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendusername")        ="smtpaccount@yourdomain.com"
    objEmail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendpassword")        ="{Password}"
    objEmail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport")     = 25
   
'--- Or you can use Google's SMTP service:   
    REM objEmail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendusername")        = aGoogleAccount
    REM objEmail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendpassword")        = theGooglePassword
    REM objEmail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver")         = "smtp.gmail.com"
    REM objEmail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpusessl")         = 1
    REM objEmail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate")     = 1
    REM objEmail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendusing")             = 2
    REM objEmail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport")     = 465

    objEmail.AddAttachment PDFfile
    objEmail.Configuration.Fields.Update
   
    objEmail.Send

    SendMail = Err
   
end sub

'--- Main ----------------------------------------------------------------------------------------------------

const emailReceipient = "your@email_addre.ss"
const intInterval = "5" 'check every 'intInterval' seconds for new file(s)...

dim fso
set fso=CreateObject("scripting.FileSystemObject")

'--- Split up the drive and the scan folder. Needed for WMI...
strDrive     = "M:"
strFolder    = "\\ProgramData\\MailScan\\"

wscript.echo "Scanning folder for files to arrive: " & replace(strDrive,"\\","\") & replace(strFolder,"\\","\")

'--- Set up event WMI handler...
Set objWMIService = GetObject( "winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2" )
strQuery =  _
    "Select * From __InstanceOperationEvent"                             _
    & " Within "                                     & intInterval         _
    & " Where Targetinstance Isa 'CIM_DataFile'"                         _
    & " And TargetInstance.Drive='"                 & strDrive &  "'"    _
    & " And TargetInstance.Path='"                     & strFolder & "'"
Set colEvents = objWMIService. ExecNotificationQuery (strQuery)

'--- Loop endless with an interval of 'intInterval'...
Do    
    Set objEvent = colEvents.NextEvent()
    Set objTargetInst = objEvent.TargetInstance

    Select Case objEvent.Path_.Class
        Case "__InstanceCreationEvent"
            f=objTargetInst.Name
            WScript.Echo "*** New file received: " & f
           
            wscript.echo "*** emailReceipient : " & emailReceipient
            wscript.echo "*** Filename: " & f
           
            '--- Check for PDF file and email that...
            if Instr(lcase(f),".pdf") > 0 then
                call SendMail(emailReceipient,f)
                wscript.echo "*** Emailing of PDF file done"
                if Err <> 0 then wscript.echo "*** Error sending mail. Errormessage: 0x" & hex(Err) & " - " & Err.Description
            end if   
           
            '--- You can delete the PDF file after emailing. Uncomment the next lines...
            'fso.DeleteFile f,true
            'wscript.echo "File deleted: " & f
    End Select
Loop

--- 8< -------------------------------------

Testing the script

To test if everything works fine we manually start the script:

  c:\Scripts> cscript //nologo MailScan.vbs

Make a scan, or just copy a PDF file in the scanfolder, and check the output on the screen. If all goes well you see:

Scanning folder for files to arrive: M:\ProgramData\MailScan\
*** New file received: m:\programdata\mailscan\manual_en - copy (2) - copy - copy - copy.pdf
*** emailTo : your@email_addre.ss
*** Filename: m:\programdata\mailscan\manual_en - copy (2) - copy - copy - copy.pdf
*** Emailing of PDF file ready


If there is an error sending the PDF you will see:

Scanning folder for files to arrive: M:\ProgramData\MailScan\
*** New file received: m:\programdata\mailscan\manual_en - copy (5).pdf
*** emailTo : your@email_addre.ss
*** Filename: m:\programdata\mailscan\manual_en - copy (5).pdf
*** Emailing of PDF file done
*** Error sending mail. Errormessage: 80040211 - The message could not be sent to the SMTP server. The transport error code was 0x80040217. The server response
was not available


The Windows Service

 

You want to have this service 24x7 available, even when you are not logged on to your computer. When we use script in a Windows Service we can run the script automatically in the background. We need a utility to configure this for you: the Non-Sucking Service Manager. Download NSSM here.

Start NSSM and configure the scan service:

  C:\Scripts> nssm install MailScan

Configure the next two tabs. Configure in "Arguments" the folder where the script is stored.


When all is entered correctly press the "Install Service" button. We can start the service:

  C:\Scripts> net start MailScan

Now make a scan and check your mailbox!
Real Time Web Analytics