EvanBlack EvanBlack - 1 year ago 99
Vb.net Question

How to check if system date is correct? (to prevent abuse) vb .NET

I am working on a business related program, so I need to know if system date is correct -synced- with remote server. How do you do that in vb .NET winforms?

P.S: In addition, is there any way to raise some event when system clock changed to prevent hacks? I don't want users to change local date after logging in their account.

Thanks in advance.

Answer Source

You will need to verify the clock with an external server and accept it if it is within a certain tolerance. All clocks are wrong by some degree. Usually a webservice on a server somewhere is enough, but there are many free NTP-services. Note however it would take me 5 minutes to bypass that, so for more security you need to use SSL (HTTPS) (makes man-in-the-middle attacks impossible).

Note however:

  • You need to compensate correctly for timezones as server and users could have different timezones. Timezone info is sent in ISO 8601 formatted DateTime string, so thats easy enough.
  • What is preventing user from disconnecting internet? Do you really want to require internet access to start the app? Someone with a laptop would quickly discover that offline mode makes the app work.
  • One technique used by some is to say that if a time in the future (after product has expired) has been spotted by the app then you need to reactivate it. Reactivation requires communication with internet server which can verify the license against a trusted clock.

If you want to know when a user changes the clock simply set up a thread to loop with a 60 second Thread.Sleep(60000). Then check current DateTime against the one 60 seconds ago. It should always be 60 seconds -/+ 1 seconds since last check. (+/- 1 second is to compensate for delays like app hanging slightly as timer is executing, etc)

I threw together a quick example:
EDIT: Sorry, first sample was in C#. Redone it in VB.Net.

Imports System.Threading

Public Class Form1
    Private TimeMonitorThread As Thread

    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        TimeMonitorThread = New Thread(TimeMonitorThreadLoop)
        TimeMonitorThread.Name = "TimeMonitorThread"
        TimeMonitorThread.IsBackground = True

    End Sub

    Private Sub TimeMonitorThreadLoop()

        Dim sleepSeconds As Integer = 60
        Dim tolerance As Integer = 1

        While (True)
            Dim before As DateTime = DateTime.Now
            Thread.Sleep(sleepSeconds * 1000)
            Dim after As DateTime = DateTime.Now
            If (Math.Abs(CInt(after.Subtract(before).TotalSeconds) - sleepSeconds) > tolerance) Then
                ' Time has changed!
            End If
        End While
    End Sub

End Class