none
Install personal certificate only for one session - is it possible? RRS feed

  • Question

  • Hello,

    Is it possible to install personal certificate (with certutil command) only for the time the user is loged in?
    So if I sign out or shutdown PC and login again there is no more personal cer. in winstore.

    Thanks..
    Erik


    • Edited by Erik Hrast Tuesday, January 8, 2019 1:05 PM
    Tuesday, January 8, 2019 1:04 PM

All replies

  • Perhaps something like this.

    Public Sub Demo()
        Dim store As New X509Store(StoreName.My, StoreLocation.CurrentUser)
        store.Open(OpenFlags.ReadWrite Or OpenFlags.IncludeArchived)
    
        ' You could also use a more specific find type such as X509FindType.FindByThumbprint
        Dim col As X509Certificate2Collection = store.Certificates.Find(X509FindType.FindBySubjectName, "yoursubjectname", False)
    
        For Each cert In col
            Console.Out.WriteLine(cert.SubjectName.Name)
    
            ' Remove the certificate
            store.Remove(cert)
        Next
        store.Close()
    End Sub


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites

    Tuesday, January 8, 2019 1:21 PM
    Moderator
  • Hello,

    but this work without user to click on something for removing cert?
    It has to be automated procedure at log off or shutdown.

    Tuesday, January 8, 2019 1:33 PM
  • Hello,

    but this work without user to click on something for removing cert?
    It has to be automated procedure at log off or shutdown.

    You can call it were you want too e.g. in a Windows Service for example, in a Windows Form e.g. as per the following post.

    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites

    Tuesday, January 8, 2019 1:49 PM
    Moderator
  • Hmm... don't know how to do that :\ 

    must figure out... what is the best option?

    Tuesday, January 8, 2019 1:51 PM
  • In a service or create a windows form app that the form is hidden use code similar to this.

    Public Sub RemoveCertification()
        Dim store As New X509Store(StoreName.My, StoreLocation.CurrentUser)
        store.Open(OpenFlags.ReadWrite Or OpenFlags.IncludeArchived)
    
        ' You could also use a more specific find type such as X509FindType.FindByThumbprint
        Dim col As X509Certificate2Collection = store.Certificates.Find(X509FindType.FindBySubjectName, "yoursubjectname", False)
    
        For Each cert In col
            Console.Out.WriteLine(cert.SubjectName.Name)
    
            ' Remove the certificate
            store.Remove(cert)
        Next
        store.Close()
    End Sub
    Private Sub hookSystemEvents()
        ' Watch for shutdowns or logoffs...
        AddHandler Microsoft.Win32.SystemEvents.SessionEnding, New Microsoft.Win32.SessionEndingEventHandler(AddressOf onSessionEnding)
    End Sub
    Private Sub unhookSystemEvents()
        ' Stop watching.
        RemoveHandler Microsoft.Win32.SystemEvents.SessionEnding, New Microsoft.Win32.SessionEndingEventHandler(AddressOf onSessionEnding)
    End Sub
    
    Private Sub onSessionEnding(ByVal sender As Object, ByVal e As Microsoft.Win32.SessionEndingEventArgs)
        ' User session is ending...
        If e.Reason = Microsoft.Win32.SessionEndReasons.Logoff Then
            RemoveCertification()
        Else
            RemoveCertification()
        End If
    
        ' Cancel?
        e.Cancel = MessageBox.Show("Cancel?", "", MessageBoxButtons.YesNo) = DialogResult.Yes
    End Sub

    I don't have any example of writing a service in VB.NET but to get an idea look at my C# example service which really focuses more on testing, installing and debugging a service.

    The easier path is a hidden windows forms app.

    Both have advantages and disadvantages e.g. either one can be stopped by the user while the service is a tad more difficult as the user must know to looking under services in Task manager while most users don't look there.


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites

    Tuesday, January 8, 2019 2:22 PM
    Moderator
  • Thank you very much for your time... I'll try and let you know :)
    Tuesday, January 8, 2019 4:38 PM
  • I put this code in my Visual Studio but nothing happend durin LogOff or Shutdown - the certificate is still there...

        Public Sub RemoveCertification()
            Dim store As New X509Store(StoreName.My, StoreLocation.CurrentUser)
            store.Open(OpenFlags.ReadWrite Or OpenFlags.IncludeArchived)
    
            ' You could also use a more specific find type such as X509FindType.FindByThumbprint
            Dim col As X509Certificate2Collection = store.Certificates.Find(X509FindType.FindBySubjectName, "" & dgvLoginData.Item(1, dgvLoginData.CurrentRow.Index).Value & " " & dgvLoginData.Item(2, dgvLoginData.CurrentRow.Index).Value & "", False)
    
            For Each cert In col
                Console.Out.WriteLine(cert.SubjectName.Name)
    
                ' Remove the certificate
                store.Remove(cert)
            Next
            store.Close()
        End Sub
        Private Sub hookSystemEvents()
            ' Watch for shutdowns or logoffs...
            AddHandler Microsoft.Win32.SystemEvents.SessionEnding, New Microsoft.Win32.SessionEndingEventHandler(AddressOf onSessionEnding)
        End Sub
        Private Sub unhookSystemEvents()
            ' Stop watching.
            RemoveHandler Microsoft.Win32.SystemEvents.SessionEnding, New Microsoft.Win32.SessionEndingEventHandler(AddressOf onSessionEnding)
        End Sub
    
        Private Sub onSessionEnding(ByVal sender As Object, ByVal e As Microsoft.Win32.SessionEndingEventArgs)
            ' User session is ending...
            If e.Reason = Microsoft.Win32.SessionEndReasons.Logoff Then
                RemoveCertification()
            Else
                RemoveCertification()
            End If
    
            ' Cancel?
            e.Cancel = MessageBox.Show("Cancel?", "", MessageBoxButtons.YesNo) = DialogResult.Yes
        End Sub
    
        
    End Class
    
    Friend Class OpenFlags
        Friend Shared Function ReadWrite() As Boolean
            Throw New NotImplementedException()
        End Function
    
        Friend Shared Function IncludeArchived() As Boolean
            Throw New NotImplementedException()
        End Function
    End Class
    
    Friend Class X509Store
        Private my As Object
        Private currentUser As Object
    
        Public Sub New(my As Object, currentUser As Object)
            Me.my = my
            Me.currentUser = currentUser
        End Sub
    
        Friend Sub Open(p As Object)
            Throw New NotImplementedException()
        End Sub
    
        Friend Sub Remove(cert As Object)
            Throw New NotImplementedException()
        End Sub
    
        Friend Sub Close()
            Throw New NotImplementedException()
        End Sub
    
        Friend Function Certificates() As Object
            Throw New NotImplementedException()
        End Function
    End Class

    Wednesday, January 9, 2019 2:43 PM
  • Question, why are you creating X509Store, it's in the .NET Framework.

    The link below is the official docs with code sample.

    https://docs.microsoft.com/en-us/dotnet/api/system.security.cryptography.x509certificates.x509store.remove?view=netframework-4.7.2


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites

    Wednesday, January 9, 2019 2:59 PM
    Moderator
  • Hello... the story is that my last programing was 15 y ago in Visual Basic.

    Now with Visual Studio I'm pretty lost and I search solutions code by code.
    I use VB code in Visual Studio 2018 and I don't know what all the solutions are provided with .NET.
    If I am honest I don't know how to use them... :/ 

    The positive side is that I have the will to finish this project :)


    Thursday, January 10, 2019 7:59 AM
  • Hello... the story is that my last programing was 15 y ago in Visual Basic.

    Now with Visual Studio I'm pretty lost and I search solutions code by code.
    I use VB code in Visual Studio 2018 and I don't know what all the solutions are provided with .NET.
    If I am honest I don't know how to use them... :/ 

    The positive side is that I have the will to finish this project :)


    Hello,

    15 years is indeed a long time, lots has changed and nobody out of coding that long can just pick it back up, it takes time so just be persistent.  

    No matter, try the code I presented but remove the empty class you created then in the form being used add the following to as the first line which provides access to the Framework class X509Store

    Imports System.Security.Cryptography.X509Certificates


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites

    Thursday, January 10, 2019 10:47 AM
    Moderator
  • Hello... the story is that my last programing was 15 y ago in Visual Basic.

    Now with Visual Studio I'm pretty lost and I search solutions code by code.
    I use VB code in Visual Studio 2018 and I don't know what all the solutions are provided with .NET.
    If I am honest I don't know how to use them... :/ 

    The positive side is that I have the will to finish this project :)


    Hello,

    15 years is indeed a long time, lots has changed and nobody out of coding that long can just pick it back up, it takes time so just be persistent.  

    No matter, try the code I presented but remove the empty class you created then in the form being used add the following to as the first line which provides access to the Framework class X509Store

    Imports System.Security.Cryptography.X509Certificates


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites

    It seems I already have this.

    This is my current code for this whole Form:

    Imports System.Security.Cryptography.X509Certificates
    Imports Microsoft.Win32
    
    Public Class frmLogin
        Dim SQL As New SQLcontrol
        Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            'AddHandler Microsoft.Win32.SystemEvents.SessionEnding, AddressOf Handler_SessionEnding
            Me.Height = 160
            ntfObvestilo.Text = "Čakam ključ..."
        End Sub
    
        Private Sub cmdCallUser_Click(sender As Object, e As EventArgs) Handles cmdCallUser.Click
    
            If txtLoginPass.Text = "" Then
                MsgBox("Vnesite osebni ključ!", vbExclamation)
                Exit Sub
            End If
    
            If SQL.HasConnection = True Then
    
                SQL.RunQuery("Select ID,HolderName,HolderSurname,HolderPass,HolderCertName,CertPass from dbo.Holders where HolderPass = '" & txtLoginPass.Text & "'")
    
                If SQL.SQLDataset.Tables.Count > 0 Then
                    dgvLoginData.DataSource = SQL.SQLDataset.Tables(0)
                    Me.Height = 340
    
                End If
    
                If dgvLoginData.RowCount > 0 Then
    
                    lblImeNosilca.Text = dgvLoginData.Item(1, dgvLoginData.CurrentRow.Index).Value
                    lblPriimekNosilca.Text = dgvLoginData.Item(2, dgvLoginData.CurrentRow.Index).Value
                    ntfObvestilo.ShowBalloonTip(500, "NoPIN", "Ključ je veljaven.", ToolTipIcon.Info)
                    ntfObvestilo.Text = "Ključ je veljaven."
    
                End If
    
                If dgvLoginData.RowCount = 0 Then
                    Me.Height = 160
                    MsgBox("Ni uporabnika", vbInformation)
                    txtLoginPass.Text = ""
                    txtLoginPass.Focus()
                End If
            End If
    
        End Sub
    
        Private Sub cmdImportCert_Click(sender As Object, e As EventArgs) Handles cmdImportCert.Click
            'namestim certifikat v skritem CMD načinu
            'nastavi share mapo in skopiraj potrdila.. 
            'nastaviti dostop do mape??
            'Shell("cmd.exe /c certutil -f -user -p y55CN3PE -importpfx \\zdt-arc\certdb\majafortunat_g2.p12 NoExport", AppWinStyle.Hide)
            'Brišem pa tako: certutil -delstore -user my "maja fortunat"
    
            Shell("cmd.exe /c certutil -f -user -p " & dgvLoginData.Item(5, dgvLoginData.CurrentRow.Index).Value & "  -importpfx \\zdt-arc\certdb\" & dgvLoginData.Item(4, dgvLoginData.CurrentRow.Index).Value & " NoExport", AppWinStyle.Hide)
            ntfObvestilo.ShowBalloonTip(500, "NoPIN", "Certifikat je aktiven.", ToolTipIcon.Warning)
            ntfObvestilo.Text = "Certifikat je aktiven."
    
            Me.Hide()
            'frmCertList.Show()
    
        End Sub
    
        Private Sub ntfObvestilo_MouseDoubleClick(sender As Object, e As MouseEventArgs) Handles ntfObvestilo.MouseDoubleClick
            Me.Show()
        End Sub
    
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            frmNoPINSetup.Show()
    
        End Sub
    
        Private Sub cmdDeleteCert_Click(sender As Object, e As EventArgs) Handles cmdDeleteCert.Click
            Shell("cmd.exe /c certutil -delstore -user my """ & dgvLoginData.Item(1, dgvLoginData.CurrentRow.Index).Value & " " & dgvLoginData.Item(2, dgvLoginData.CurrentRow.Index).Value & "", AppWinStyle.Hide)
            ntfObvestilo.ShowBalloonTip(500, "NoPIN", "Certifikat je deaktiviran. Čakam nov ključ...", ToolTipIcon.Info)
            ntfObvestilo.Text = "Čakam ključ."
        End Sub
    
    
        'Public Sub Handler_SessionEnding(ByVal sender As Object, ByVal e As Microsoft.Win32.SessionEndingEventArgs)
        'If e.Reason = Microsoft.Win32.SessionEndReasons.Logoff Then
        '       Shell("cmd.exe /c certutil -delstore -user my """ & dgvLoginData.Item(1, dgvLoginData.CurrentRow.Index).Value & " " & dgvLoginData.Item(2, dgvLoginData.CurrentRow.Index).Value & "", AppWinStyle.Hide)
        'MessageBox.Show("User is logging off")
        'ElseIf e.Reason = Microsoft.Win32.SessionEndReasons.SystemShutdown Then
        '       Shell("cmd.exe /c certutil -delstore -user my """ & dgvLoginData.Item(1, dgvLoginData.CurrentRow.Index).Value & " " & dgvLoginData.Item(2, dgvLoginData.CurrentRow.Index).Value & "", AppWinStyle.Hide)
        'MessageBox.Show("System is shutting down")
        'End If
    
        'Ob odjavi ali izklopu poženem proceduro
        'End Sub
    
        'testna procedura za izbris ob odjavi in izklopu, testiram: 9.1.2019
    
        Public Sub RemoveCertification()
            Dim store As New X509Store(StoreName.My, StoreLocation.CurrentUser)
            store.Open(OpenFlags.ReadWrite Or OpenFlags.IncludeArchived)
    
            ' You could also use a more specific find type such as X509FindType.FindByThumbprint
            Dim col As X509Certificate2Collection = store.Certificates.Find(X509FindType.FindBySubjectName, "" & dgvLoginData.Item(1, dgvLoginData.CurrentRow.Index).Value & " " & dgvLoginData.Item(2, dgvLoginData.CurrentRow.Index).Value & "", False)
    
            For Each cert In col
                Console.Out.WriteLine(cert.SubjectName.Name)
    
                ' Remove the certificate
                store.Remove(cert)
            Next
            store.Close()
        End Sub
        Private Sub hookSystemEvents()
            ' Watch for shutdowns or logoffs...
            AddHandler Microsoft.Win32.SystemEvents.SessionEnding, New Microsoft.Win32.SessionEndingEventHandler(AddressOf onSessionEnding)
        End Sub
        Private Sub unhookSystemEvents()
            ' Stop watching.
            RemoveHandler Microsoft.Win32.SystemEvents.SessionEnding, New Microsoft.Win32.SessionEndingEventHandler(AddressOf onSessionEnding)
        End Sub
    
        Private Sub onSessionEnding(ByVal sender As Object, ByVal e As Microsoft.Win32.SessionEndingEventArgs)
            ' User session is ending...
            If e.Reason = Microsoft.Win32.SessionEndReasons.Logoff Then
                RemoveCertification()
            Else
                RemoveCertification()
            End If
    
            ' Cancel?
            e.Cancel = MessageBox.Show("Cancel?", "", MessageBoxButtons.YesNo) = DialogResult.Yes
        End Sub
    
        Private Sub cmdBrisiTest_Click(sender As Object, e As EventArgs) Handles cmdBrisiTest.Click
    
        End Sub
    
        Private Sub cmdCertList_Click(sender As Object, e As EventArgs) Handles cmdCertList.Click
            frmCertList.Show()
        End Sub
    End Class
    
    Friend Class OpenFlags
        Friend Shared Function ReadWrite() As Boolean
            Throw New NotImplementedException()
        End Function
    
        Friend Shared Function IncludeArchived() As Boolean
            Throw New NotImplementedException()
        End Function
    End Class
    
    Friend Class X509Store
        Private my As Object
        Private currentUser As Object
    
        Public Sub New(my As Object, currentUser As Object)
            Me.my = my
            Me.currentUser = currentUser
        End Sub
    
        Friend Sub Open(p As Object)
            Throw New NotImplementedException()
        End Sub
    
        Friend Sub Remove(cert As Object)
            Throw New NotImplementedException()
        End Sub
    
        Friend Sub Close()
            Throw New NotImplementedException()
        End Sub
    
        Friend Function Certificates() As Object
            Throw New NotImplementedException()
        End Function
    End Class
    

    Thursday, January 10, 2019 12:34 PM
  • Hi,

    Do you resolve the issue?

    Best Regards,

    Alex


    MSDN Community Support Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Friday, January 25, 2019 8:07 AM
  • Not quite yet..
    Friday, January 25, 2019 1:57 PM
  • Hi,

    Still can't finish some task before Logoff/Shutdown?

    https://social.msdn.microsoft.com/Forums/SECURITY/en-US/78b5423f-50ee-4d51-bc32-8aef382a3512/logoffshutdown-delay-to-finish-some-task?forum=vbgeneral

    Best Regards,

    Alex


    MSDN Community Support Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Tuesday, January 29, 2019 6:13 AM
  • On the other hand... I tried this to show some MsgBox when shutdown or logoff is detected.. like "You're logging off.. .

    Public Class frmDetectEnd
        Private Sub frmDetectEnd_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            AddHandler Microsoft.Win32.SystemEvents.SessionEnding, AddressOf Handler_SessionEnding
        End Sub
    
        Public Sub Handler_SessionEnding(ByVal sender As Object, ByVal e As Microsoft.Win32.SessionEndingEventArgs)
            If e.Reason = Microsoft.Win32.SessionEndReasons.Logoff Then
                MessageBox.Show("User is logging off")
            ElseIf e.Reason = Microsoft.Win32.SessionEndReasons.SystemShutdown Then
                MessageBox.Show("System is shutting down")
            End If
        End Sub
    End Class

    This detection work's OK but I want to stop shutdown/logoff process if MsgBox is shown, because at this point the shutdown/logoff process is executed and it stops with Windows message "This program is preventing to log you off...". If I solve this than I can create Button to remove cert before shutdown/logoff.

    What do you think?


    • Edited by Erik Hrast Friday, February 15, 2019 1:43 PM
    Friday, February 15, 2019 12:48 PM