Example #1
0
        private void btnResetYubiKey_Click(object sender, EventArgs e)
        {
            string devName   = YubikeyPivManager.Instance.ListDevices().FirstOrDefault();
            bool   hasDevice = !string.IsNullOrEmpty(devName);

            if (hasDevice && MetroMessageBox.Show(this, "Are you sure you want to reset the YubiKey?", "Reset confirmation", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == DialogResult.OK)
            {
                using (YubikeyPivDevice piv = YubikeyPivManager.Instance.OpenDevice(devName))
                {
                    piv.BlockPin();
                    piv.BlockPuk();

                    bool reset = piv.ResetDevice();
                    if (!reset)
                    {
                        MetroMessageBox.Show(this, "Unable to reset the yubikey. Try resetting it manually.", "An error occurred.", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                    else
                    {
                        MetroMessageBox.Show(this, "YubiKey has been successfully resettet.", "Successfully", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        RefreshInsertedKey();
                    }
                }
            }
        }
Example #2
0
        private void YubikeyStateChange()
        {
            // Piv Manager find only CCID enabled  Yubikeys
            List <string> listDevices = YubikeyPivManager.Instance.ListDevices().ToList();
            string        devName     = listDevices.FirstOrDefault();
            bool          hasDevice   = !string.IsNullOrEmpty(devName);

            YubmanUtil yu = new YubmanUtil();

            btnEnableCCID.Enabled   = false;
            btnExportCert.Enabled   = false;
            btnViewCert.Enabled     = false;
            btnResetYubiKey.Enabled = false;



            if (hasDevice)
            {
                using (YubikeyPivDevice dev = YubikeyPivManager.Instance.OpenDevice(devName))
                {
                    int  serialNumber    = (int)dev.GetSerialNumber(); // uint
                    bool success         = yu.GetYubikeyMode(serialNumber.ToString(), out bool HasOtp, out bool HasCcid, out bool HasFido, out string mode);
                    bool have2enableCcid = !HasCcid;
                    btnEnableCCID.Enabled   = HasCcid;
                    btnExportCert.Enabled   = !have2enableCcid;
                    btnViewCert.Enabled     = !have2enableCcid;
                    btnResetYubiKey.Enabled = !have2enableCcid;
                }
            }

            RefreshInsertedKey();
        }
Example #3
0
        private void btnViewCert_Click(object sender, EventArgs e) //Angepasst, sodass beide Zertifikate angezeigt werden können
        {
            X509Certificate2 cert  = null;                         //Standard Cert
            X509Certificate2 cert2 = null;                         //Admin Cert

            string devName = YubikeyPivManager.Instance.ListDevices().FirstOrDefault();

            if (!string.IsNullOrEmpty(devName))
            {
                using (YubikeyPivDevice dev = YubikeyPivManager.Instance.OpenDevice(devName))
                {
                    cert  = dev.GetCertificate9a();
                    cert2 = dev.GetCertificate9d();
                }
            }

            if (cert == null)
            {
                MetroMessageBox.Show(this, "No Standard User certificate on device.", "No Certificate", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                X509Certificate2UI.DisplayCertificate(cert);
            }
            if (cert2 == null)
            {
                MetroMessageBox.Show(this, "No Admin User certificate on device.", "No Certificate", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                X509Certificate2UI.DisplayCertificate(cert2);
            }
        }
Example #4
0
        private void btnExportCert_Click(object sender, EventArgs e) //Änderungen vorgenommen, dass beide Zertifikate, wenn vorhanden exportiert werden können
        {
            X509Certificate2 cert  = null;                           //Standard Cert
            X509Certificate2 cert2 = null;                           //Admin Cert
            int deviceSerial       = 0;

            string devName = YubikeyPivManager.Instance.ListDevices().FirstOrDefault();

            if (!string.IsNullOrEmpty(devName))
            {
                using (YubikeyPivDevice dev = YubikeyPivManager.Instance.OpenDevice(devName))
                {
                    deviceSerial = (int)dev.GetSerialNumber();
                }

                using (YubikeyPivDevice dev = YubikeyPivManager.Instance.OpenDevice(devName))
                {
                    cert  = dev.GetCertificate9a();
                    cert2 = dev.GetCertificate9d();
                }
            }

            if (cert == null && cert2 == null)
            {
                MetroMessageBox.Show(this, "No certificate on device.", "No Certificate", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            SaveFileDialog saveFileDialog = new SaveFileDialog();

            saveFileDialog.FileName = deviceSerial + "-" + cert.SerialNumber + ".crt"; //TODO: GetSerialNumber() can possibly fail

            DialogResult dlgResult = saveFileDialog.ShowDialog();

            if (dlgResult != DialogResult.OK)
            {
                return;
            }

            if (cert != null)
            {
                using (Stream fs = saveFileDialog.OpenFile())
                {
                    byte[] data = cert.GetRawCertData();
                    fs.Write(data, 0, data.Length);
                }
            }

            if (cert2 != null)
            {
                using (Stream fs = saveFileDialog.OpenFile())
                {
                    byte[] data = cert2.GetRawCertData();
                    fs.Write(data, 0, data.Length);
                }
            }
        }
        private void CheckForYubikey()
        {
            string devName = YubikeyPivManager.Instance.ListDevices().FirstOrDefault();

            _hadDevice = !string.IsNullOrEmpty(devName);

            if (!_hadDevice)
            {
                return;
            }

            using (YubikeyPivDevice dev = YubikeyPivManager.Instance.OpenDevice(devName))
            {
                _hasBeenFound = ((int)dev.GetSerialNumber()) == _key.DeviceSerial;
            }
        }
Example #6
0
        static void PrintPiv(string name)
        {
            Console.WriteLine($"[PIV] Device: {name}");

            if (!YubikeyPivManager.Instance.IsValidDevice(name))
            {
                Console.WriteLine("      Not a valid PIV device");
            }
            else
            {
                using (YubikeyPivDevice device = YubikeyPivManager.Instance.OpenDevice(name))
                {
                    Console.WriteLine($"      Version : {device.GetVersion()}");

                    byte[] chuid;
                    if (device.GetCHUID(out chuid))
                    {
                        Console.WriteLine($"      CHUID   : {BitConverter.ToString(chuid).Replace("-", "")}");
                    }
                    else
                    {
                        Console.WriteLine("      CHUID   : N/A");
                    }

                    Console.WriteLine($"      PinTries: {device.GetPinTriesLeft():N0}");

                    X509Certificate2 cert = device.GetCertificate9a();

                    if (cert != null)
                    {
                        Console.WriteLine($"      Cert 9A, Subject: {cert.SubjectName}");
                        Console.WriteLine($"               Issuer : {cert.IssuerName}");
                        Console.WriteLine($"               Start  : {cert.NotBefore.ToUniversalTime():O}");
                        Console.WriteLine($"               Expiry : {cert.NotAfter.ToUniversalTime():O}");
                        Console.WriteLine($"               Serial : {cert.SerialNumber}");
                        Console.WriteLine($"               Finger : {cert.Thumbprint}");
                    }
                    else
                    {
                        Console.WriteLine("      Cert 9A : N/A");
                    }
                }
            }

            Console.WriteLine();
        }
Example #7
0
        private void YubikeyStateChange()
        {
            string devName   = YubikeyPivManager.Instance.ListDevices().FirstOrDefault();
            bool   hasDevice = !string.IsNullOrEmpty(devName);

            _devicePresent   = hasDevice;
            _hasBeenEnrolled = false;

            if (hasDevice)
            {
                using (YubikeyPivDevice dev = YubikeyPivManager.Instance.OpenDevice(devName))
                {
                    _hasBeenEnrolled = _dataStore.Search((int)dev.GetSerialNumber()).Any();
                }
            }

            RefreshView();
        }
Example #8
0
        private void DlgChangePin_Load(object sender, EventArgs e)
        {
            AcceptButton = cmdChange;

            string devName   = YubikeyPivManager.Instance.ListDevices().FirstOrDefault();
            bool   hadDevice = !string.IsNullOrEmpty(devName);

            if (!hadDevice)
            {
                return;
            }

            using (YubikeyPivDevice dev = YubikeyPivManager.Instance.OpenDevice(devName))
            {
                int yubiSerial = (int)dev.GetSerialNumber();
                lblSerialNumber.Text = yubiSerial.ToString();
            }
        }
Example #9
0
        private void btnExportCert_Click(object sender, EventArgs e)
        {
            X509Certificate2 cert = null;
            int deviceSerial      = 0;

            string devName = YubikeyPivManager.Instance.ListDevices().FirstOrDefault();

            if (!string.IsNullOrEmpty(devName))
            {
                using (YubikeyPivDevice dev = YubikeyPivManager.Instance.OpenDevice(devName))
                {
                    deviceSerial = (int)dev.GetSerialNumber();
                }

                using (YubikeyPivDevice dev = YubikeyPivManager.Instance.OpenDevice(devName))
                {
                    cert = dev.GetCertificate9a();
                }
            }

            if (cert == null)
            {
                MessageBox.Show("No certificate on device.", "No Certificate", MessageBoxButtons.OK);
                return;
            }

            SaveFileDialog saveFileDialog = new SaveFileDialog();

            saveFileDialog.FileName = deviceSerial + "-" + cert.SerialNumber + ".crt"; //TODO: GetSerialNumber() can possibly fail

            DialogResult dlgResult = saveFileDialog.ShowDialog();

            if (dlgResult != DialogResult.OK)
            {
                return;
            }

            using (Stream fs = saveFileDialog.OpenFile())
            {
                byte[] data = cert.GetRawCertData();
                fs.Write(data, 0, data.Length);
            }
        }
Example #10
0
        private void cmdChange_Click(object sender, EventArgs e)
        {
            SetStatus(Color.Orange, "DO NOT REMOVE THE YUBIKEY");

            string devName   = YubikeyPivManager.Instance.ListDevices().FirstOrDefault();
            bool   hasDevice = !string.IsNullOrEmpty(devName);

            if (!hasDevice)
            {
                SetStatus(Color.Yellow, "Insert a Yubikey");
                return;
            }

            YubmanUtil yu = new YubmanUtil();

            using (YubikeyPivDevice dev = YubikeyPivManager.Instance.OpenDevice(devName))
            {
                try
                {
                    string serialNumber = dev.GetSerialNumber().ToString();  // uint
                    bool   success      = yu.SetYubikeyMode(serialNumber, _currentModeHasOTP, _currentModeHasCCID, _currentModeHasFIDO);
                    if (success)
                    {
                        SetStatus(Color.GreenYellow, "The mode was set. Please remove the Yubikey from the system.");
                    }
                    else
                    {
                        SetStatus(Color.Red, "Was unable to set the mode, please remove the Yubikey.");
                    }
                }
                catch (Exception ex)
                {
                    SetStatus(Color.Red, "Was unable to set the mode, please remove the Yubikey. Details: " + ex.Message);
                }

                _stateWaitingToRemove = true;
                foreach (Control control in grpChangeMode.Controls)
                {
                    control.Enabled = false;
                }
            }
        }
Example #11
0
        private void RefreshInsertedKeyInfo()
        {
            string devName   = YubikeyPivManager.Instance.ListDevices().FirstOrDefault();
            bool   hasDevice = !string.IsNullOrEmpty(devName);

            foreach (Control control in gbInsertedYubikey.Controls)
            {
                if (control.Name.StartsWith("lbl"))
                {
                    control.Visible = hasDevice;
                }
            }

            if (!hasDevice)
            {
                return;
            }

            lblAlreadyEnrolled.Visible = _hasBeenEnrolled;

            using (YubikeyPivDevice dev = YubikeyPivManager.Instance.OpenDevice(devName))
            {
                string serial = dev.GetSerialNumber().ToString();

                var  yi      = new YubikeyInfo();
                bool success = yi.GetYubikeyInfo(serial);

                /* Get currently only CCID enabled Yubikeys
                 * if (HasCcid)
                 *  lblInsertedMode.ForeColor = Color.Black;
                 * else
                 *  lblInsertedMode.ForeColor = Color.Red;
                 */
                lblInsertedTyp.Text      = yi.devicetype;
                lblInsertedSerial.Text   = yi.serial;
                lblInsertedMode.Text     = yi.usbinterface;
                lblInsertedFirmware.Text = yi.firmware;
            }
        }
Example #12
0
        private void UpdateCurrentView()
        {
            if (_stateWaitingToRemove)
            {
                // Don't update the UI - wait for the user to remove the current Yubikey
                return;
            }

            // using (YubikeyDetector.Instance.GetExclusiveLock())
            {
                string devName   = YubikeyPivManager.Instance.ListDevices().FirstOrDefault();
                bool   hasDevice = !string.IsNullOrEmpty(devName);

                foreach (Control control in grpChangeMode.Controls)
                {
                    control.Enabled = hasDevice;
                }

                if (!hasDevice)
                {
                    SetStatus(Color.Yellow, "Insert a Yubikey");
                    return;
                }
                YubmanUtil yu = new YubmanUtil();
                using (YubikeyPivDevice dev = YubikeyPivManager.Instance.OpenDevice(devName))
                {
                    int  serialNumber = (int)dev.GetSerialNumber(); // uint
                    bool success      = yu.GetYubikeyMode(serialNumber.ToString(), out _currentModeHasOTP, out _currentModeHasCCID, out _currentModeHasFIDO, out _currentMode);

                    _deferCheckboxEvents = true;
                    chkOTP.Checked       = _currentModeHasOTP;
                    chkCCID.Checked      = _currentModeHasCCID;
                    chkU2f.Checked       = _currentModeHasFIDO;
                    _deferCheckboxEvents = false;
                    SetStatus(Color.GreenYellow, "Currently set to " + _currentMode);
                }
            }
        }
Example #13
0
        private void cmdEnroll_Click(object sender, EventArgs e)
        {
            string devName   = YubikeyNeoManager.Instance.ListDevices().FirstOrDefault();
            bool   hasDevice = !string.IsNullOrEmpty(devName);

            if (!hasDevice)
            {
                return;
            }

            using (YubikeyPivDevice piv = YubikeyPivManager.Instance.OpenDevice(devName))
            {
                if (piv.GetCertificate9a() != null)
                {
                    // Already enrolled
                    DialogResult resp = MessageBox.Show("The inserted Yubikey has already been enrolled. Are you sure you wish to overwrite it?", "Already enrolled", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation);

                    if (resp != DialogResult.Yes)
                    {
                        return;
                    }
                }
            }

            cmdEnroll.Enabled = false;

            foreach (Control control in groupBox1.Controls)
            {
                control.Enabled = false;
            }

            foreach (Control control in groupBox3.Controls)
            {
                control.Enabled = false;
            }

            _enrollWorker.RunWorkerAsync();
        }
Example #14
0
        private void RefreshInsertedKey()
        {
            List <string> listDevices = YubikeyPivManager.Instance.ListDevices().ToList();
            string        devName     = listDevices.FirstOrDefault();
            bool          hasDevice   = !string.IsNullOrEmpty(devName);

            foreach (Control control in gbInsertedKey.Controls)
            {
                if (control.Name.StartsWith("lbl"))
                {
                    control.Visible = (hasDevice);
                }
            }

            if (hasDevice)
            {
                using (YubikeyPivDevice dev = YubikeyPivManager.Instance.OpenDevice(devName))
                {
                    int serialNumber = (int)dev.GetSerialNumber();   // uint
                    var yi           = new YubikeyInfo();
                    yi.GetYubikeyInfo(serialNumber.ToString());
                    lblDevType.Text                 = yi.devicetype;
                    lblInsertedSerial.Text          = yi.serial;
                    lblInsertedFirmware.Text        = yi.firmware;
                    lblInsertedMode.Text            = yi.usbinterface;
                    lblInsertedHasBeenEnrolled.Text = _dataStore.Search(serialNumber).Any().ToString();
                }
            }

            if (listDevices.Count > 1)
            {
                lblMultipleKeys.Text = $"{listDevices.Count:N0} keys inserted";
            }
            else
            {
                lblMultipleKeys.Text = "";
            }
        }
Example #15
0
        private void btnViewCert_Click(object sender, EventArgs e)
        {
            X509Certificate2 cert = null;

            string devName = YubikeyPivManager.Instance.ListDevices().FirstOrDefault();

            if (!string.IsNullOrEmpty(devName))
            {
                using (YubikeyPivDevice dev = YubikeyPivManager.Instance.OpenDevice(devName))
                {
                    cert = dev.GetCertificate9a();
                }
            }

            if (cert == null)
            {
                MessageBox.Show("No certificate on device.", "No Certificate", MessageBoxButtons.OK);
            }
            else
            {
                X509Certificate2UI.DisplayCertificate(cert);
            }
        }
Example #16
0
        private void cmdChange_Click(object sender, EventArgs e)
        {
            string devName   = YubikeyNeoManager.Instance.ListDevices().FirstOrDefault();
            bool   hadDevice = !string.IsNullOrEmpty(devName);

            if (!hadDevice)
            {
                return;
            }

            using (YubikeyPivDevice piv = YubikeyPivManager.Instance.OpenDevice(devName))
            {
                bool authed = piv.Authenticate(_yubikey.ManagementKey);

                if (!authed)
                {
                    MessageBox.Show("Unable to authenticate.", "An error occurred.", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                    return;
                }

                // Reset PIN
                piv.BlockPin();

                bool changed = piv.UnblockPin(_yubikey.PukKey, txtPinNew.Text);

                if (changed)
                {
                    MessageBox.Show("The PIN code has been reset.", "Success.", MessageBoxButtons.OK, MessageBoxIcon.Information);

                    Close();
                }
                else
                {
                    MessageBox.Show("An error occured while resetting the PIN code. Please try again.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                }
            }
        }
Example #17
0
        private void EnrollWorkerOnDoWork(object sender, DoWorkEventArgs doWorkEventArgs)
        {
            string devName   = YubikeyNeoManager.Instance.ListDevices().FirstOrDefault();
            bool   hasDevice = !string.IsNullOrEmpty(devName);

            if (!hasDevice)
            {
                throw new InvalidOperationException("No yubikey");
            }

            // 0. Get lock on yubikey
            using (YubikeyNeoDevice dev = YubikeyNeoManager.Instance.OpenDevice(devName))
            {
                // 1. Prep device info
                int     deviceId    = dev.GetSerialNumber();
                string  neoFirmware = dev.GetVersion().ToString();
                Version pivFirmware;

                using (YubikeyPivDevice piv = YubikeyPivManager.Instance.OpenDevice(devName))
                    pivFirmware = piv.GetVersion();

                _enrollWorker.ReportProgress(1);

                // 2 - Generate PUK, prep PIN
                byte[] randomKey = Utilities.GenerateRandomKey();
                string puk       = Utilities.MapBytesToString(randomKey.Take(8).ToArray());

                string pin = txtPin.Text;

                _enrollWorker.ReportProgress(2);

                // 3 - Prep CA
                WindowsCertificate enrollmentAgent = WindowsCertStoreUtilities.FindCertificate(_settings.EnrollmentAgentCertificate);
                string             ca         = _settings.CSREndpoint;
                string             caTemplate = _settings.EnrollmentCaTemplate;
                string             user       = txtUser.Text;

                if (enrollmentAgent == null)
                {
                    doWorkEventArgs.Cancel = true;
                    _enrollWorkerMessage   = "Unable to find the certificate with thumbprint: " + _settings.EnrollmentAgentCertificate;
                    return;
                }

                _enrollWorker.ReportProgress(3);

                // 4 - Prep Management Key
                // TODO: Consider a new key every time?
                byte[] mgmKey = _settings.EnrollmentManagementKey;

                _enrollWorker.ReportProgress(4);

                RSAParameters    publicKey;
                X509Certificate2 cert;
                byte[]           chuid;

                using (YubikeyPivDevice pivTool = YubikeyPivManager.Instance.OpenDevice(devName))
                {
                    // 5 - Yubico: Reset device
                    pivTool.BlockPin();
                    pivTool.BlockPuk();
                    bool reset = pivTool.ResetDevice();

                    if (!reset)
                    {
                        doWorkEventArgs.Cancel = true;
                        _enrollWorkerMessage   = "Unable to reset the YubiKey";
                        return;
                    }

                    _enrollWorker.ReportProgress(5);

                    // 6 - Yubico: Management Key
                    bool authenticated = pivTool.Authenticate(YubikeyPivDevice.DefaultManagementKey);

                    if (!authenticated)
                    {
                        doWorkEventArgs.Cancel = true;
                        _enrollWorkerMessage   = "Unable to authenticate with the YubiKey";
                        return;
                    }

                    bool setMgmKey = pivTool.SetManagementKey(mgmKey);

                    if (!setMgmKey)
                    {
                        doWorkEventArgs.Cancel = true;
                        _enrollWorkerMessage   = "Unable to set the management key";
                        return;
                    }

                    _enrollWorker.ReportProgress(6);

                    // 7 - Yubico: Set CHUID
                    bool setChuid = pivTool.SetCHUID(Guid.NewGuid(), out chuid);

                    if (!setChuid)
                    {
                        doWorkEventArgs.Cancel = true;
                        _enrollWorkerMessage   = "Unable to set CHUID";
                        return;
                    }

                    _enrollWorker.ReportProgress(7);

                    // 8 - Yubico: PIN
                    int  tmp;
                    bool setPin = pivTool.ChangePin(YubikeyPivDevice.DefaultPin, pin, out tmp);

                    if (!setPin)
                    {
                        doWorkEventArgs.Cancel = true;
                        _enrollWorkerMessage   = "Unable to set the PIN code";
                        return;
                    }

                    _enrollWorker.ReportProgress(8);

                    // 9 - Yubico: PUK
                    bool setPuk = pivTool.ChangePuk(YubikeyPivDevice.DefaultPuk, puk, out tmp);

                    if (!setPuk)
                    {
                        doWorkEventArgs.Cancel = true;
                        _enrollWorkerMessage   = "Unable to set the PUK code";
                        return;
                    }

                    _enrollWorker.ReportProgress(9);

                    // 10 - Yubico: Generate Key
                    YubikeyAlgorithm algorithm = (YubikeyAlgorithm)drpAlgorithm.SelectedItem;

                    bool keyGenerated = pivTool.GenerateKey9a(algorithm.Value, out publicKey);

                    if (!keyGenerated)
                    {
                        doWorkEventArgs.Cancel = true;
                        _enrollWorkerMessage   = "Unable to generate a keypair";
                        return;
                    }

                    _enrollWorker.ReportProgress(10);
                }

                // 11 - Yubico: Make CSR
                string csr;
                string csrError;
                bool   madeCsr = MakeCsr(Utilities.ExportPublicKeyToPEMFormat(publicKey), pin, out csrError, out csr);

                if (!madeCsr)
                {
                    doWorkEventArgs.Cancel = true;
                    _enrollWorkerMessage   = "Unable to generate a CSR" + Environment.NewLine + csrError;
                    return;
                }

                _enrollWorker.ReportProgress(11);

                // 12 - Enroll
                string enrollError;
                bool   enrolled = CertificateUtilities.Enroll(user, enrollmentAgent, ca, caTemplate, csr, out enrollError, out cert);

                if (!enrolled)
                {
                    doWorkEventArgs.Cancel = true;
                    _enrollWorkerMessage   = "Unable to enroll a certificate." + Environment.NewLine + enrollError;
                    return;
                }

                _enrollWorker.ReportProgress(12);

                using (YubikeyPivDevice pivTool = YubikeyPivManager.Instance.OpenDevice(devName))
                {
                    // 13 - Yubico: Import Cert
                    bool authenticatedForCert = pivTool.Authenticate(mgmKey);

                    if (!authenticatedForCert)
                    {
                        doWorkEventArgs.Cancel = true;
                        _enrollWorkerMessage   = "Unable to authenticate prior to importing a certificate";
                        return;
                    }

                    YubicoPivReturnCode imported = pivTool.SetCertificate9a(cert);

                    if (imported != YubicoPivReturnCode.YKPIV_OK)
                    {
                        doWorkEventArgs.Cancel = true;
                        _enrollWorkerMessage   = $"Unable to import a certificate, return code {imported}";
                        return;
                    }

                    _enrollWorker.ReportProgress(13);
                }

                // 14 - Create enrolled item
                EnrolledYubikey newEnrollment = new EnrolledYubikey();
                newEnrollment.DeviceSerial = deviceId;

                newEnrollment.Certificate.Serial         = cert.SerialNumber;
                newEnrollment.Certificate.Thumbprint     = cert.Thumbprint;
                newEnrollment.Certificate.Subject        = cert.Subject;
                newEnrollment.Certificate.Issuer         = cert.Issuer;
                newEnrollment.Certificate.StartDate      = cert.NotBefore;
                newEnrollment.Certificate.ExpireDate     = cert.NotAfter;
                newEnrollment.Certificate.RawCertificate = cert.RawData;

                newEnrollment.CA            = ca;
                newEnrollment.Username      = user;
                newEnrollment.ManagementKey = mgmKey;
                newEnrollment.PukKey        = puk;
                newEnrollment.Chuid         = BitConverter.ToString(chuid).Replace("-", "");

                newEnrollment.EnrolledAt = DateTime.UtcNow;

                newEnrollment.YubikeyVersions.NeoFirmware = neoFirmware;
                newEnrollment.YubikeyVersions.PivApplet   = pivFirmware.ToString();

                _dataStore.Add(newEnrollment);

                _enrollWorker.ReportProgress(14);

                // 15 - Save store
                _dataStore.Save(MainForm.FileStore);

                _enrollWorker.ReportProgress(15);

                // Report
                doWorkEventArgs.Cancel = false;
                _enrollWorkerMessage   = "Success";
            }
        }
Example #18
0
        private void terminateToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            if (lstItems.SelectedItems.Count <= 0)
            {
                return;
            }

            EnrolledYubikey item = lstItems.SelectedItems[0].Tag as EnrolledYubikey;

            if (item == null)
            {
                return;
            }

            X509Certificate2 currentCert = new X509Certificate2(item.Certificate.RawCertificate);

            DialogResult dlgResult = MessageBox.Show("This will terminate the Yubikey, wiping the PIN, PUK, Management Key and Certificates. " +
                                                     "This will also revoke the certificate. Proceeed?" + Environment.NewLine + Environment.NewLine +
                                                     "Will revoke: " + currentCert.Subject + Environment.NewLine +
                                                     "By: " + currentCert.Issuer, "Terminate (WILL revoke)",
                                                     MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button2);

            if (dlgResult != DialogResult.Yes)
            {
                return;
            }

            DlgPleaseInsertYubikey yubiWaiter = new DlgPleaseInsertYubikey(item);
            DialogResult           result     = yubiWaiter.ShowDialog();

            if (result != DialogResult.OK)
            {
                return;
            }

            DlgProgress prg = new DlgProgress("Terminating certificate");

            prg.WorkerAction = worker =>
            {
                worker.ReportProgress(20, "Revoking certificate ...");

                // Begin
                try
                {
                    CertificateUtilities.RevokeCertificate(item.CA, item.Certificate.Serial);

                    // Revoked
                    _dataStore.Remove(item);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(
                        "Unable to revoke certificate " + item.Certificate.Serial + " of " + item.CA +
                        " enrolled on " + item.EnrolledAt + ". There was an error." + Environment.NewLine +
                        Environment.NewLine + ex.Message, "An error occurred.", MessageBoxButtons.OK, MessageBoxIcon.Warning);

                    return;
                }

                // Wipe the Yubikey
                worker.ReportProgress(50, "Wiping Yubikey ...");

                string devName   = YubikeyPivManager.Instance.ListDevices().FirstOrDefault();
                bool   hasDevice = !string.IsNullOrEmpty(devName);

                if (hasDevice)
                {
                    using (YubikeyPivDevice dev = YubikeyPivManager.Instance.OpenDevice(devName))
                    {
                        int serial = (int)dev.GetSerialNumber();
                        if (item.DeviceSerial != serial)
                        {
                            // Something went seriously wrong - perhaps the user switched keys?
                            MessageBox.Show("Unable to reset the yubikey. The inserted key did not match the key you wanted to wipe.", "An error occurred.", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                            return;
                        }
                    }

                    using (YubikeyPivDevice piv = YubikeyPivManager.Instance.OpenDevice(devName))
                    {
                        piv.BlockPin();
                        worker.ReportProgress(70);

                        piv.BlockPuk();
                        worker.ReportProgress(90);

                        bool reset = piv.ResetDevice();
                        if (!reset)
                        {
                            MessageBox.Show("Unable to reset the yubikey. Try resetting it manually.", "An error occurred.", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        }

                        worker.ReportProgress(100);
                    }
                }

                // Write to disk
                _dataStore.Save(FileStore);
            };

            prg.ShowDialog();

            RefreshUserStore();

            RefreshInsertedKey();
        }
Example #19
0
        private void RefreshInsertedKeyInfo()
        {
            string devName   = YubikeyPivManager.Instance.ListDevices().FirstOrDefault();
            bool   hasDevice = !string.IsNullOrEmpty(devName);

            foreach (Control control in gbInsertedYubikey.Controls)
            {
                if (control.Name.StartsWith("lbl"))
                {
                    control.Visible = hasDevice;
                }
            }

            if (!hasDevice)
            {
                return;
            }

            using (YubikeyPivDevice dev = YubikeyPivManager.Instance.OpenDevice(devName))
            {
                X509Certificate2 cert  = null;  //Standard Cert
                X509Certificate2 cert2 = null;  //Admin Cert

                cert  = dev.GetCertificate9a();
                cert2 = dev.GetCertificate9d();

                if ((cert != null || cert2 != null) && _hasBeenEnrolled == true)
                {
                    lblAlreadyEnrolled.Text      = "Enrolled!";
                    lblAlreadyEnrolled.ForeColor = Color.Green;
                }
                else if ((cert != null || cert2 != null) && _hasBeenEnrolled == false)
                {
                    lblAlreadyEnrolled.Text      = "YubiKey is not empty!";
                    lblAlreadyEnrolled.ForeColor = Color.Red;
                }
                else if ((cert == null || cert2 == null) && _hasBeenEnrolled == true)
                {
                    lblAlreadyEnrolled.Text      = "YubiKey is empty! Please revoke Certificate!";
                    lblAlreadyEnrolled.ForeColor = Color.Red;
                }
                else if ((cert == null || cert2 == null) && _hasBeenEnrolled == false)
                {
                    lblAlreadyEnrolled.Text      = "YubiKey can be enrolled!";
                    lblAlreadyEnrolled.ForeColor = Color.DarkOrange;
                }
            }

            using (YubikeyPivDevice dev = YubikeyPivManager.Instance.OpenDevice(devName))
            {
                string serial = dev.GetSerialNumber().ToString();

                var  yi      = new YubikeyInfo();
                bool success = yi.GetYubikeyInfo(serial);

                /* Get currently only CCID enabled Yubikeys
                 * if (HasCcid)
                 *  lblInsertedMode.ForeColor = Color.Black;
                 * else
                 *  lblInsertedMode.ForeColor = Color.Red;
                 */
                lblInsertedTyp.Text      = yi.devicetype;
                lblInsertedSerial.Text   = yi.serial;
                lblInsertedMode.Text     = yi.usbinterface;
                lblInsertedFirmware.Text = yi.firmware;
            }
        }
Example #20
0
        private void RefreshInsertedKey()
        {
            List <string> listDevices = YubikeyPivManager.Instance.ListDevices().ToList();
            string        devName     = listDevices.FirstOrDefault();
            bool          hasDevice   = !string.IsNullOrEmpty(devName);

            foreach (Control control in gbInsertedKey.Controls)
            {
                if (control.Name.StartsWith("lbl"))
                {
                    control.Visible = (hasDevice);
                }
            }

            if (hasDevice)
            {
                using (YubikeyPivDevice dev = YubikeyPivManager.Instance.OpenDevice(devName))
                {
                    int serialNumber = (int)dev.GetSerialNumber();   // uint
                    var yi           = new YubikeyInfo();
                    yi.GetYubikeyInfo(serialNumber.ToString());
                    lblDevType.Text          = yi.devicetype;
                    lblInsertedSerial.Text   = yi.serial;
                    lblInsertedFirmware.Text = yi.firmware;
                    lblInsertedMode.Text     = yi.usbinterface;

                    X509Certificate2 cert  = null;  //Standard Cert
                    X509Certificate2 cert2 = null;  //Admin Cert



                    _hasBeenEnrolled = _dataStore.Search((int)dev.GetSerialNumber()).Any();


                    cert  = dev.GetCertificate9a();
                    cert2 = dev.GetCertificate9d();

                    if ((cert != null || cert2 != null) && _hasBeenEnrolled == true)
                    {
                        lblInsertedHasBeenEnrolled.Text      = "Enrolled!";
                        lblInsertedHasBeenEnrolled.ForeColor = Color.Green;
                    }
                    else if ((cert != null || cert2 != null) && _hasBeenEnrolled == false)
                    {
                        lblInsertedHasBeenEnrolled.Text      = "YubiKey is not empty!";
                        lblInsertedHasBeenEnrolled.ForeColor = Color.Red;
                    }
                    else if ((cert == null || cert2 == null) && _hasBeenEnrolled == true)
                    {
                        lblInsertedHasBeenEnrolled.Text      = "YubiKey is empty! Please revoke Certificate!";
                        lblInsertedHasBeenEnrolled.ForeColor = Color.Red;
                    }
                    else if ((cert == null || cert2 == null) && _hasBeenEnrolled == false)
                    {
                        lblInsertedHasBeenEnrolled.Text      = "YubiKey can be enrolled!";
                        lblInsertedHasBeenEnrolled.ForeColor = Color.DarkOrange;
                    }
                }
            }

            if (listDevices.Count > 1)
            {
                lblMultipleKeys.Text    = $"{listDevices.Count:N0} keys inserted";
                btnResetYubiKey.Enabled = false;
                btnViewCert.Enabled     = false;
                btnEnableCCID.Enabled   = false;
                btnExportCert.Enabled   = false;
                tsbEnroll.Enabled       = false;
                tsbAbout.Enabled        = false;
                tsbSettings.Enabled     = false;
            }
            else
            {
                lblMultipleKeys.Text = "";
            }
        }