Beispiel #1
0
        private async Task PresenceMonitor()
        {
            //ShowToastNotification("Presence monitor triggered!");
            System.Diagnostics.Debug.WriteLine("[PresenceMonitor] triggered");
            // Query the devices which can do presence check for the console user
            IReadOnlyList <SecondaryAuthenticationFactorInfo> deviceInfoList =
                await SecondaryAuthenticationFactorRegistration.FindAllRegisteredDeviceInfoAsync(SecondaryAuthenticationFactorDeviceFindScope.User);

            if (deviceInfoList.Count == 0)
            {
                return;
            }

            foreach (SecondaryAuthenticationFactorInfo deviceInfo in deviceInfoList)
            {
                if (deviceInfo.PresenceMonitoringMode !=
                    SecondaryAuthenticationFactorDevicePresenceMonitoringMode.AppManaged)
                {
                    // Skip the device which doesn't need to be monitored in the background task
                    continue;
                }

                await deviceInfo.UpdateDevicePresenceAsync(SecondaryAuthenticationFactorDevicePresence.Present);
            }
        }
Beispiel #2
0
        private async Task LockDevice(string deviceGUIDtoLock)
        {
            Debug.WriteLine("[LockDevice]");
            IReadOnlyList <SecondaryAuthenticationFactorInfo> deviceInfoList =
                await SecondaryAuthenticationFactorRegistration.FindAllRegisteredDeviceInfoAsync(SecondaryAuthenticationFactorDeviceFindScope.User);

            if (deviceInfoList.Count == 0)
            {
                return;
            }
            foreach (SecondaryAuthenticationFactorInfo deviceInfo in deviceInfoList)
            {
                if (deviceInfo.PresenceMonitoringMode !=
                    SecondaryAuthenticationFactorDevicePresenceMonitoringMode.AppManaged)
                {
                    // Skip the device which doesn't need to be monitored in the background task
                    continue;
                }
                SecondaryAuthenticationFactorDevicePresence state =
                    SecondaryAuthenticationFactorDevicePresence.Absent;
                await deviceInfo.UpdateDevicePresenceAsync(state);

                SecondaryAuthenticationFactorDevicePresenceMonitoringMode mode = deviceInfo.PresenceMonitoringMode;
            }
        }
Beispiel #3
0
        private async void UnregisterDevice_Click(object sender, RoutedEventArgs e)
        {
            if (m_selectedDeviceId == String.Empty)
            {
                return;
            }
            await SecondaryAuthenticationFactorRegistration.UnregisterDeviceAsync(m_selectedDeviceId);

            IReadOnlyList <SecondaryAuthenticationFactorInfo> deviceList = await SecondaryAuthenticationFactorRegistration.FindAllRegisteredDeviceInfoAsync(
                SecondaryAuthenticationFactorDeviceFindScope.User);

            listContent listItem = new listContent();

            listItem.deviceFriendlyName = m_selectedDeviceFriendlyName;
            listItem.deviceGUID         = m_selectedDeviceId;
            DeviceListBox.Items.Remove(listItem);
            if (deviceList.Count == 0)
            {
                this.Frame.Navigate(typeof(waitingForDevice));
            }
            else
            {
                this.Frame.Navigate(typeof(MainPage), "false");
            }
        }
        private async Task LockDevice()
        {
            // Query the devices which can do presence check for the console user
            IReadOnlyList <SecondaryAuthenticationFactorInfo> deviceInfoList =
                await SecondaryAuthenticationFactorRegistration.FindAllRegisteredDeviceInfoAsync(SecondaryAuthenticationFactorDeviceFindScope.User);

            if (deviceInfoList.Count == 0)
            {
                return;
            }

            foreach (SecondaryAuthenticationFactorInfo deviceInfo in deviceInfoList)
            {
                if (deviceInfo.PresenceMonitoringMode !=
                    SecondaryAuthenticationFactorDevicePresenceMonitoringMode.AppManaged)
                {
                    // Skip the device which doesn't need to be monitored in the background task
                    continue;
                }

                SecondaryAuthenticationFactorDevicePresence state =
                    SecondaryAuthenticationFactorDevicePresence.Absent;

                await deviceInfo.UpdateDevicePresenceAsync(state);
            }
        }
        private async Task Removed()
        {
            IReadOnlyList <SecondaryAuthenticationFactorInfo> deviceList = await SecondaryAuthenticationFactorRegistration.FindAllRegisteredDeviceInfoAsync(SecondaryAuthenticationFactorDeviceFindScope.User);

            if (deviceList.Count > 0)
            {
                await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                {
                    this.Frame.Navigate(typeof(MainPage), "false");
                });

                //this.Frame.Navigate(typeof(MainPage), "false");
            }
            else
            {
                //waitingForDevice.FrameProperty.
                //((Page)waitingForDevice).Frame.Navigate(typeof(waitingForDevice));
                //((Page)RegisterDevice).Frame.Navigate(typeof(waitingForDevice));

                await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                {
                    this.Frame.Navigate(typeof(waitingForDevice));
                });

                //this.Frame.Navigate(typeof(waitingForDevice));
            }
        }
Beispiel #6
0
        private async void UnregisterDevices()
        {
            IReadOnlyList <SecondaryAuthenticationFactorInfo> deviceList = await SecondaryAuthenticationFactorRegistration.FindAllRegisteredDeviceInfoAsync(SecondaryAuthenticationFactorDeviceFindScope.AllUsers);

            //DeviceListBox.Items.Clear();

            for (int index = 0; index < deviceList.Count; ++index)
            {
                SecondaryAuthenticationFactorInfo deviceInfo = deviceList.ElementAt(index);
                System.Diagnostics.Debug.WriteLine(deviceInfo.DeviceFriendlyName);
                //DeviceListBox.Items.Add(deviceInfo.DeviceId);

                await SecondaryAuthenticationFactorRegistration.UnregisterDeviceAsync(deviceInfo.DeviceId);
            }

            for (int index = 0; index < deviceList.Count; ++index)
            {
                SecondaryAuthenticationFactorInfo deviceInfo = deviceList.ElementAt(index);
                System.Diagnostics.Debug.WriteLine(deviceInfo.DeviceFriendlyName);
                //DeviceListBox.Items.Add(deviceInfo.DeviceId);

                //await SecondaryAuthenticationFactorRegistration.UnregisterDeviceAsync(deviceInfo.DeviceId);
            }

            //RefreshDeviceList(deviceList);
        }
        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            IReadOnlyList <SecondaryAuthenticationFactorInfo> deviceList = await SecondaryAuthenticationFactorRegistration.FindAllRegisteredDeviceInfoAsync(SecondaryAuthenticationFactorDeviceFindScope.User);

            RefreshDeviceList(deviceList);
        }
Beispiel #8
0
        async void OnStageChanged(Object sender, SecondaryAuthenticationFactorAuthenticationStageChangedEventArgs args)
        {
            //ShowToastNotification("In StageChanged!" + args.StageInfo.Stage.ToString());
            if (args.StageInfo.Stage == SecondaryAuthenticationFactorAuthenticationStage.CheckingDevicePresence)
            {
                Task t = PresenceMonitor();
                t.Wait();
                opCompletedEvent.Set();
                deferral.Complete();
                return;
            }
            if (args.StageInfo.Stage == SecondaryAuthenticationFactorAuthenticationStage.WaitingForUserConfirmation)
            {
                //ShowToastNotification("Stage = WaitingForUserConfirmation");
                // This event is happening on a ThreadPool thread, so we need to dispatch to the UI thread.
                // Getting the dispatcher from the MainView works as long as we only have one view.

                IReadOnlyList <SecondaryAuthenticationFactorInfo> deviceList = await SecondaryAuthenticationFactorRegistration.FindAllRegisteredDeviceInfoAsync(
                    SecondaryAuthenticationFactorDeviceFindScope.User);

                String deviceName = deviceList.ElementAt(deviceList.Count() - 1).DeviceFriendlyName;

                string str = "\"" + deviceName + "\"";

                await SecondaryAuthenticationFactorAuthentication.ShowNotificationMessageAsync(
                    str,
                    SecondaryAuthenticationFactorAuthenticationMessage.SwipeUpWelcome);
            }
            else if (args.StageInfo.Stage == SecondaryAuthenticationFactorAuthenticationStage.CollectingCredential)
            {
                //ShowToastNotification("Stage = CollectingCredential");
                System.Diagnostics.Debug.WriteLine("[OnStageChanged] Perform Auth / auth trigger");
                try
                {
                    Task  t = PerformAuthentication();;
                    await t;
                    t = writeConnectedRegisteredDevices();
                    await t;
                }
                catch (Exception ex)
                {
                }
                finally
                {
                    deferral.Complete();
                }
            }
            else
            {
                if (args.StageInfo.Stage == SecondaryAuthenticationFactorAuthenticationStage.StoppingAuthentication)
                {
                    SecondaryAuthenticationFactorAuthentication.AuthenticationStageChanged -= OnStageChanged;
                    opCompletedEvent.Set();
                }

                SecondaryAuthenticationFactorAuthenticationStage stage = args.StageInfo.Stage;
            }
        }
Beispiel #9
0
        public static async void UnregisterAll()
        {
            var infos = await SecondaryAuthenticationFactorRegistration.FindAllRegisteredDeviceInfoAsync(SecondaryAuthenticationFactorDeviceFindScope.User);

            foreach (var info in infos)
            {
                await SecondaryAuthenticationFactorRegistration.UnregisterDeviceAsync(info.DeviceId);
            }
        }
Beispiel #10
0
        private async void CancelButtonVisibilityUpdate()
        {
            IReadOnlyList <SecondaryAuthenticationFactorInfo> deviceList = await SecondaryAuthenticationFactorRegistration.FindAllRegisteredDeviceInfoAsync(SecondaryAuthenticationFactorDeviceFindScope.User);

            if (deviceList.Count != 0)
            {
                ((Grid)((Grid)this.Content).Children.ElementAt(3)).Children.ElementAt(5).Visibility = Visibility.Visible;
            }
            else
            {
                ((Grid)((Grid)this.Content).Children.ElementAt(3)).Children.ElementAt(5).Visibility = Visibility.Collapsed;
            }
        }
Beispiel #11
0
        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            IReadOnlyList <SecondaryAuthenticationFactorInfo> deviceList = await SecondaryAuthenticationFactorRegistration.FindAllRegisteredDeviceInfoAsync(SecondaryAuthenticationFactorDeviceFindScope.User);

            if (deviceList.Count == 0)
            {
                this.Frame.Navigate(typeof(waitingForDevice));
            }
            RefreshDeviceList(deviceList, 1000); //1000 ie: no item selected, max nb of items is 5
            //await CommomMethods.SetWindowSize();
            //this.Frame.Navigate(typeof(TestRelativePanel));
            return;
        }
Beispiel #12
0
        public static async Task UnregisterDevice(DeviceInfo info)
        {
            try
            {
                await SecondaryAuthenticationFactorRegistration.UnregisterDeviceAsync(info.DeviceId.ToString());

                if ((await SecondaryAuthenticationFactorRegistration.FindAllRegisteredDeviceInfoAsync(SecondaryAuthenticationFactorDeviceFindScope.AllUsers)).Count <= 0)
                {
                    BackgroundHelper.Unregister();
                }
            }
            catch (Exception e)
            {
                Debug.Write(e);
            }
        }
Beispiel #13
0
        private async void UnregisterDevice_Click(object sender, RoutedEventArgs e)
        {
            if (m_selectedDeviceId == String.Empty)
            {
                return;
            }

            //InfoList.Items.Add("Unregister a device:");

            await SecondaryAuthenticationFactorRegistration.UnregisterDeviceAsync(m_selectedDeviceId);

            //InfoList.Items.Add("Device unregistration is completed.");

            IReadOnlyList <SecondaryAuthenticationFactorInfo> deviceList = await SecondaryAuthenticationFactorRegistration.FindAllRegisteredDeviceInfoAsync(
                SecondaryAuthenticationFactorDeviceFindScope.User);

            RefreshDeviceList(deviceList);
        }
Beispiel #14
0
        private async Task writeConnectedRegisteredDevices()
        {
            string NanosATR = "3b00";
            string selector = SmartCardReader.GetDeviceSelector();

            selector += " AND System.Devices.DeviceInstanceId:~~\"Ledger\"";
            byte[] response = { 0 };
            string sw1sw2   = null;

            byte[] deviceDlockState = new byte[1];
            byte[] deviceIdArray    = new byte[16];
            string txt = "";

            DeviceInformationCollection readers = await DeviceInformation.FindAllAsync(selector);

            IReadOnlyList <SecondaryAuthenticationFactorInfo> RegisteredDeviceList_addEvent = await SecondaryAuthenticationFactorRegistration.FindAllRegisteredDeviceInfoAsync(
                SecondaryAuthenticationFactorDeviceFindScope.User);

            List <SecondaryAuthenticationFactorInfo> ConnectedRegisteredDeviceList = await getConnectedRegisteredDeviceList(RegisteredDeviceList_addEvent);

            foreach (SecondaryAuthenticationFactorInfo device in ConnectedRegisteredDeviceList)
            {
                foreach (DeviceInformation smartcardreader in readers)
                {
                    SmartCardReader reader = await SmartCardReader.FromIdAsync(smartcardreader.Id);

                    SmartCardReaderStatus readerstatus = await reader.GetStatusAsync();

                    IReadOnlyList <SmartCard> cards = await reader.FindAllCardsAsync();

                    foreach (SmartCard card in cards)
                    {
                        try
                        {
                            IBuffer ATR = await card.GetAnswerToResetAsync();

                            string ATR_str = CryptographicBuffer.EncodeToHexString(ATR);
                            if (ATR_str.Equals(NanosATR))
                            {
                                SmartCardConnection connection = await card.ConnectAsync();

                                response = await Apdu.TransmitApduAsync(connection, Apdu.getDeviceGuidCmdApdu);

                                sw1sw2        = Apdu.ApduResponseParser(response, out response);
                                deviceIdArray = response;
                                string deviceId = BitConverter.ToString(response).Replace("-", "");
                                if (deviceId == device.DeviceId) //update config data with dLockState
                                {
                                    if (device.PresenceMonitoringMode != SecondaryAuthenticationFactorDevicePresenceMonitoringMode.AppManaged)
                                    {
                                        // Skip the device which doesn't need to be monitored in the background task
                                        continue;
                                    }

                                    await device.UpdateDevicePresenceAsync(SecondaryAuthenticationFactorDevicePresence.Present);

                                    response = await Apdu.TransmitApduAsync(connection, Apdu.getDlockStateCmdApdu);

                                    sw1sw2           = Apdu.ApduResponseParser(response, out response);
                                    deviceDlockState = response;

                                    string deviceConfigString    = CryptographicBuffer.ConvertBinaryToString(0, device.DeviceConfigurationData);
                                    char[] deviceConfigCharArray = new char[deviceConfigString.Count()];
                                    deviceConfigCharArray = deviceConfigString.ToCharArray();
                                    string deviceConfigStringNew = "";
                                    int    count = device.DeviceFriendlyName.Count();
                                    if (deviceDlockState[0] == 0)
                                    {
                                        if (deviceConfigCharArray[35] == '0') // Indicates if device was used for last login
                                        {
                                            deviceConfigStringNew = device.DeviceId + "-0-0-" + device.DeviceFriendlyName + "-" + deviceConfigString.Substring(35 + 1 + count + 1 + 1);
                                        }
                                        else
                                        {
                                            deviceConfigStringNew = device.DeviceId + "-0-1-" + device.DeviceFriendlyName + "-" + deviceConfigString.Substring(35 + 1 + count + 1 + 1);
                                        }
                                    }
                                    else
                                    {
                                        if (deviceConfigCharArray[35] == '0')
                                        {
                                            deviceConfigStringNew = device.DeviceId + "-1-0-" + device.DeviceFriendlyName + "-" + deviceConfigString.Substring(35 + 1 + count + 1 + 1);
                                        }
                                        else
                                        {
                                            deviceConfigStringNew = device.DeviceId + "-1-1-" + device.DeviceFriendlyName + "-" + deviceConfigString.Substring(35 + 1 + count + 1 + 1);
                                        }
                                    }
                                    // Get a Ibuffer from combinedDataArray
                                    IBuffer deviceConfigData = CryptographicBuffer.ConvertStringToBinary(deviceConfigString, 0);

                                    await SecondaryAuthenticationFactorRegistration.UpdateDeviceConfigurationDataAsync(device.DeviceId, deviceConfigData);
                                }
                                connection.Dispose();
                            }
                        }
                        catch (Exception e)
                        {
                        }
                    }
                }
                txt += CryptographicBuffer.ConvertBinaryToString(0, device.DeviceConfigurationData) + Environment.NewLine;
            }
            StorageFolder folder = ApplicationData.Current.LocalFolder;
            StorageFile   ConnectedRegisteredDeviceListFile = await folder.CreateFileAsync("connectedRegisteredDeviceList.txt", CreationCollisionOption.ReplaceExisting);

            await FileIO.WriteTextAsync(ConnectedRegisteredDeviceListFile, txt);
        }
Beispiel #15
0
        private async Task DiscoverDevice()
        {
            var authStageInfo = await SecondaryAuthenticationFactorAuthentication.GetAuthenticationStageInfoAsync();

            if (authStageInfo.Stage != SecondaryAuthenticationFactorAuthenticationStage.CollectingCredential)
            {
                return;                                                                                               // Bad status!
            }
            findAuth = true;
            var deviceList = await SecondaryAuthenticationFactorRegistration.FindAllRegisteredDeviceInfoAsync(SecondaryAuthenticationFactorDeviceFindScope.User);

            var db          = new DatabaseContext();
            var devicesInDb = db.Devices.ToList();

            db.Dispose();
            IPDiscover.DiscoverIP();

            foreach (var device in deviceList)
            {
                var deviceInDb = devicesInDb.Find(d => d.DeviceId.ToString() == device.DeviceId);
                if (deviceInDb == null)
                {
                    continue;
                }
                var session = new DeviceAuthSession
                {
                    LastIP     = deviceInDb.LastConnectedHost,
                    MACAddress = deviceInDb.DeviceMacAddress,
                    DeviceID   = device.DeviceId,
                    DeviceInDb = deviceInDb
                };
                deviceSessions.Add(session);
            }
            while (findAuth)
            {
                foreach (var session in deviceSessions)
                {
                    switch (session.Status)
                    {
                    case DeviceStatus.NotConnected:
                        var payload = Convert.ToBase64String(Encoding.UTF8.GetBytes(session.DeviceID));
                        var data    = Encoding.UTF8.GetBytes(DeviceDiscoverPrefix + payload);
                        if (!string.IsNullOrWhiteSpace(session.LastIP))
                        {
                            try
                            {
                                UDPListener.Send(session.LastIP, data);
                            }
                            catch (Exception)
                            {
                                // ignored
                            }
                        }

                        var ips = session.FindIPs()?.ToList();
                        if ((ips == null || !ips.Any()) && string.IsNullOrWhiteSpace(session.MACAddress) && IPDiscover.IsDiscoveryCompleted)
                        {
                            session.Status = DeviceStatus.Unreachable;
                            continue;
                        }

                        if (ips != null)
                        {
                            foreach (var ip in ips)
                            {
                                try
                                {
                                    UDPListener.Send(ip, data);
                                }
                                catch (Exception)
                                {
                                    // ignored
                                }
                            }
                        }
                        await UDPListener.Send(UDPListener.DeviceMulticastGroupAddress, data);

                        break;

                    case DeviceStatus.Unreachable:
                        deviceSessions.Remove(session);
                        break;

                    case DeviceStatus.Established:
                        findAuth = false;
                        break;
                    }
                }
                Thread.Sleep(1000);
            }

            Auth(deviceSessions.FirstOrDefault(s => s.Status == DeviceStatus.Established));
            CurrentSession = null;
        }
        private async void StackRegsiter_tapped(object sender, TappedRoutedEventArgs e)
        {
            Window.Current.CoreWindow.PointerCursor = new Windows.UI.Core.CoreCursor(Windows.UI.Core.CoreCursorType.Arrow, 0);
            MessageDialog myDlg;
            bool          executeFinally = true;

            if ((sender is StackPanel) && (e.OriginalSource is TextBlock))
            {
                ((Grid)((StackPanel)sender).Parent).Children.ElementAt(3).Visibility = Visibility.Visible;
                ((StackPanel)sender).Children.ElementAt(1).Visibility = Visibility.Collapsed;
            }
            string deviceFriendlyName = NameYourDevice.Text.Trim();

            var    loader = new Windows.ApplicationModel.Resources.ResourceLoader();
            string deviceNameAlreadyUsedContent = loader.GetString("DeviceNameAlreadyUsed_content_error");
            string deviceNameAlreadyUsedTitle   = loader.GetString("DeviceNameAlreadyUsed_title_error");

            string deviceAlreadyRegisteredContent = loader.GetString("DeviceAlreadyRegistered_content_error");
            string deviceAlreadyRegisteredTitle   = loader.GetString("DeviceAlreadyRegistered_title_error");

            try
            {
                IReadOnlyList <SecondaryAuthenticationFactorInfo> deviceList = await SecondaryAuthenticationFactorRegistration.FindAllRegisteredDeviceInfoAsync(SecondaryAuthenticationFactorDeviceFindScope.User);

                foreach (SecondaryAuthenticationFactorInfo device in deviceList)
                {
                    if (device.DeviceFriendlyName == deviceFriendlyName)
                    {
                        throw new Exception(deviceNameAlreadyUsedContent);
                    }
                }
                await CommomMethods.RegisterDevice_Click(deviceFriendlyName);
            }
            catch (Exception ex)
            {
                if (ex.Message == deviceNameAlreadyUsedContent)
                {
                    myDlg = new MessageDialog(ex.Message, deviceNameAlreadyUsedTitle);

                    await myDlg.ShowAsync();

                    this.Frame.Navigate(typeof(RegisterDevice));
                    executeFinally = false;
                }
                else if (ex.Message == deviceAlreadyRegisteredContent)
                {
                    myDlg = new MessageDialog(deviceAlreadyRegisteredContent, deviceAlreadyRegisteredTitle);
                    await myDlg.ShowAsync();

                    this.Frame.Navigate(typeof(waitingForDevice));
                    executeFinally = false;
                }
                else
                {
                    IReadOnlyList <SecondaryAuthenticationFactorInfo> deviceList = await SecondaryAuthenticationFactorRegistration.FindAllRegisteredDeviceInfoAsync(SecondaryAuthenticationFactorDeviceFindScope.User);

                    if (deviceList.Count > 0)
                    {
                        this.Frame.Navigate(typeof(MainPage), "false");
                    }
                    else
                    {
                        this.Frame.Navigate(typeof(waitingForDevice));
                    }
                }
            }
            finally
            {
                if (executeFinally)
                {
                    this.Frame.Navigate(typeof(MainPage), "false");
                }
            }
        }
Beispiel #17
0
        /// <summary>
        /// Invoked when the application is launched normally by the end user.  Other entry points
        /// will be used such as when the application is launched to open a specific file.
        /// </summary>
        /// <param name="e">Details about the launch request and process.</param>
        protected override async void OnLaunched(LaunchActivatedEventArgs e)
        {
#if DEBUG
            if (System.Diagnostics.Debugger.IsAttached)
            {
                this.DebugSettings.EnableFrameRateCounter = true;
            }
#endif

            Frame rootFrame = Window.Current.Content as Frame;

            // Do not repeat app initialization when the Window already has content,
            // just ensure that the window is active
            if (rootFrame == null)
            {
                // Create a Frame to act as the navigation context and navigate to the first page
                rootFrame = new Frame();

                rootFrame.NavigationFailed += OnNavigationFailed;

                if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
                {
                    //TODO: Load state from previously suspended application
                }

                // Place the frame in the current Window
                Window.Current.Content = rootFrame;
            }

            if (rootFrame.Content == null)
            {
                // When the navigation stack isn't restored navigate to the first page,
                // configuring the new page by passing required information as a navigation
                // parameter

                bool          isSupported;
                MessageDialog myDlg;
                isSupported = await KeyCredentialManager.IsSupportedAsync();

                if (!isSupported)
                {
                    var    loader = new Windows.ApplicationModel.Resources.ResourceLoader();
                    string PleaseSetUpPinContent = loader.GetString("PleaseSetupPin_content_error");
                    string PleaseSetUpPinTitle   = loader.GetString("PleaseSetupPin_title_error");

                    myDlg = new MessageDialog(PleaseSetUpPinContent, PleaseSetUpPinTitle);
                    await myDlg.ShowAsync();

                    Application.Current.Exit();
                    return;
                }

                IReadOnlyList <SecondaryAuthenticationFactorInfo> registeredDeviceList = await SecondaryAuthenticationFactorRegistration.FindAllRegisteredDeviceInfoAsync(
                    SecondaryAuthenticationFactorDeviceFindScope.User);

                if (registeredDeviceList.Count == 0)
                {
                    rootFrame.Navigate(typeof(waitingForDevice), e.Arguments);
                }
                else
                {
                    rootFrame.Navigate(typeof(MainPage), e.Arguments);
                }
            }
            // Ensure the current window is active

            CommomMethods.SetWindowSize();
            Window.Current.Activate();
        }
Beispiel #18
0
        async void PerformAuthentication()
        {
            ShowToastNotification("Performing Auth!");

            //Get the selected device from app settings
            var    localSettings      = Windows.Storage.ApplicationData.Current.LocalSettings;
            String m_selectedDeviceId = localSettings.Values["SelectedDevice"] as String;

            SecondaryAuthenticationFactorAuthenticationStageInfo authStageInfo = await SecondaryAuthenticationFactorAuthentication.GetAuthenticationStageInfoAsync();

            if (authStageInfo.Stage != SecondaryAuthenticationFactorAuthenticationStage.CollectingCredential)
            {
                ShowToastNotification("Unexpected!");
                throw new Exception("Unexpected!");
            }

            ShowToastNotification("Post Collecting Credential");

            IReadOnlyList <SecondaryAuthenticationFactorInfo> deviceList = await SecondaryAuthenticationFactorRegistration.FindAllRegisteredDeviceInfoAsync(
                SecondaryAuthenticationFactorDeviceFindScope.AllUsers);

            if (deviceList.Count == 0)
            {
                ShowToastNotification("Unexpected exception, device list = 0");
                throw new Exception("Unexpected exception, device list = 0");
            }

            ShowToastNotification("Found companion devices");

            SecondaryAuthenticationFactorInfo deviceInfo = deviceList.ElementAt(0);

            m_selectedDeviceId = deviceInfo.DeviceId;

            ShowToastNotification("Device ID: " + m_selectedDeviceId);

            //a nonce is an arbitrary number that may only be used once - a random or pseudo-random number issued in an authentication protocol to ensure that old communications cannot be reused in replay attacks.
            IBuffer svcNonce = CryptographicBuffer.GenerateRandom(32);  //Generate a nonce and do a HMAC operation with the nonce


            //In real world, you would need to take this nonce and send to companion device to perform an HMAC operation with it
            //You will have only 20 second to get the HMAC from the companion device
            SecondaryAuthenticationFactorAuthenticationResult authResult = await SecondaryAuthenticationFactorAuthentication.StartAuthenticationAsync(
                m_selectedDeviceId, svcNonce);

            if (authResult.Status != SecondaryAuthenticationFactorAuthenticationStatus.Started)
            {
                ShowToastNotification("Unexpected! Could not start authentication!");
                throw new Exception("Unexpected! Could not start authentication!");
            }

            ShowToastNotification("Auth Started");

            //
            // WARNING: Test code
            // The HAMC calculation SHOULD be done on companion device
            //
            byte[] combinedDataArray;
            CryptographicBuffer.CopyToByteArray(authResult.Authentication.DeviceConfigurationData, out combinedDataArray);

            byte[] deviceKeyArray = new byte[32];
            byte[] authKeyArray   = new byte[32];
            for (int index = 0; index < deviceKeyArray.Length; index++)
            {
                deviceKeyArray[index] = combinedDataArray[index];
            }
            for (int index = 0; index < authKeyArray.Length; index++)
            {
                authKeyArray[index] = combinedDataArray[deviceKeyArray.Length + index];
            }
            // Create device key and authentication key
            IBuffer deviceKey = CryptographicBuffer.CreateFromByteArray(deviceKeyArray);
            IBuffer authKey   = CryptographicBuffer.CreateFromByteArray(authKeyArray);

            // Calculate the HMAC
            MacAlgorithmProvider hMACSha256Provider = MacAlgorithmProvider.OpenAlgorithm(MacAlgorithmNames.HmacSha256);

            CryptographicKey deviceHmacKey = hMACSha256Provider.CreateKey(deviceKey);
            IBuffer          deviceHmac    = CryptographicEngine.Sign(deviceHmacKey, authResult.Authentication.DeviceNonce);

            // sessionHmac = HMAC(authKey, deviceHmac || sessionNonce)
            IBuffer sessionHmac;

            byte[] deviceHmacArray = { 0 };
            CryptographicBuffer.CopyToByteArray(deviceHmac, out deviceHmacArray);

            byte[] sessionNonceArray = { 0 };
            CryptographicBuffer.CopyToByteArray(authResult.Authentication.SessionNonce, out sessionNonceArray);

            combinedDataArray = new byte[deviceHmacArray.Length + sessionNonceArray.Length];
            for (int index = 0; index < deviceHmacArray.Length; index++)
            {
                combinedDataArray[index] = deviceHmacArray[index];
            }
            for (int index = 0; index < sessionNonceArray.Length; index++)
            {
                combinedDataArray[deviceHmacArray.Length + index] = sessionNonceArray[index];
            }

            // Get a Ibuffer from combinedDataArray
            IBuffer sessionMessage = CryptographicBuffer.CreateFromByteArray(combinedDataArray);

            // Calculate sessionHmac
            CryptographicKey authHmacKey = hMACSha256Provider.CreateKey(authKey);

            sessionHmac = CryptographicEngine.Sign(authHmacKey, sessionMessage);

            ShowToastNotification("Before finish auth");

            SecondaryAuthenticationFactorFinishAuthenticationStatus authStatus = await authResult.Authentication.FinishAuthenticationAsync(deviceHmac,
                                                                                                                                           sessionHmac);

            if (authStatus != SecondaryAuthenticationFactorFinishAuthenticationStatus.Completed)
            {
                ShowToastNotification("Unable to complete authentication!");
                throw new Exception("Unable to complete authentication!");
            }

            ShowToastNotification("Auth completed");
        }
Beispiel #19
0
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            deferral = taskInstance.GetDeferral();

            StorageFolder folder = ApplicationData.Current.LocalFolder;

            //StorageFile logsFile = await folder.CreateFileAsync("BGtask.txt", CreationCollisionOption.OpenIfExists);
            //string txt = "[RUN]: " + DateTime.Now.ToString() + Environment.NewLine;
            //await FileIO.WriteTextAsync(logsFile, txt);

            // This event is signaled when the operation completes
            opCompletedEvent = new ManualResetEvent(false);
            SecondaryAuthenticationFactorAuthentication.AuthenticationStageChanged += OnStageChanged;
            //ShowToastNotification("BG Task Hit!");


            if (taskInstance.TriggerDetails is DeviceWatcherTriggerDetails)
            {
                DeviceWatcherTriggerDetails triggerDetails = (DeviceWatcherTriggerDetails)taskInstance.TriggerDetails;

                foreach (DeviceWatcherEvent e in triggerDetails.DeviceWatcherEvents)
                {
                    switch (e.Kind)
                    {
                    case DeviceWatcherEventKind.Add:
                        Debug.WriteLine("[RUN] Add: " + e.DeviceInformation.Id);
                        deferral = taskInstance.GetDeferral();
                        try
                        {
                            SecondaryAuthenticationFactorAuthenticationStageInfo authStageInfo = await SecondaryAuthenticationFactorAuthentication.GetAuthenticationStageInfoAsync();

                            SecondaryAuthenticationFactorAuthenticationStage stage = authStageInfo.Stage;
                            //Debugger.Break();
                            if ((authStageInfo.Stage == SecondaryAuthenticationFactorAuthenticationStage.WaitingForUserConfirmation) ||
                                (authStageInfo.Stage == SecondaryAuthenticationFactorAuthenticationStage.CollectingCredential))
                            {
                                System.Diagnostics.Debug.WriteLine("[RUN] Perform Auth / plug trigger");
                                Task  t = PerformAuthentication();
                                await t;
                            }
                            //Debugger.Break();
                            if (e.DeviceInformation.Name.Contains("Ledger"))
                            {
                                Task  t = writeConnectedRegisteredDevices();
                                await t;
                            }
                        }
                        catch (Exception ex)
                        {
                        }
                        finally
                        {
                            deferral.Complete();
                        }
                        break;

                    //case DeviceWatcherEventKind.Update:
                    //    Debug.WriteLine("[RUN] Update: " + e.DeviceInformationUpdate.Id);
                    //    deferral = taskInstance.GetDeferral();
                    //
                    //    try
                    //    {
                    //        Task i = writeConnectedRegisteredDevices();
                    //        await i;
                    //    }
                    //    catch (Exception ex)
                    //    {
                    //        Debugger.Break();
                    //    }
                    //    finally
                    //    {
                    //        deferral.Complete();
                    //    }
                    //    break;

                    case DeviceWatcherEventKind.Remove:
                        Debug.WriteLine("[RUN] Remove: " + e.DeviceInformationUpdate.Id);
                        deferral = taskInstance.GetDeferral();
                        try
                        {
                            List <dLock> pluggedRegisteredDeviceListBeforeRemove = await readConnectedRegisteredDevices();

                            List <Tuple <string, bool, bool> > pluggedRegisteredDeviceListBeforeRemove_tuple = new List <Tuple <string, bool, bool> >();
                            foreach (dLock device in pluggedRegisteredDeviceListBeforeRemove)
                            {
                                Tuple <string, bool, bool> newElem = new Tuple <string, bool, bool>(device.DeviceId, device.isDlockEnabled, device.isUsedForLastLogin);
                                pluggedRegisteredDeviceListBeforeRemove_tuple.Add(newElem);
                            }

                            IReadOnlyList <SecondaryAuthenticationFactorInfo> registeredDeviceList_removeEvent = await SecondaryAuthenticationFactorRegistration.FindAllRegisteredDeviceInfoAsync(
                                SecondaryAuthenticationFactorDeviceFindScope.User);

                            List <SecondaryAuthenticationFactorInfo> pluggedRegisteredDeviceListAfterRemove = await getConnectedRegisteredDeviceList(registeredDeviceList_removeEvent);

                            foreach (SecondaryAuthenticationFactorInfo deviceToCheck in pluggedRegisteredDeviceListAfterRemove)
                            {
                                foreach (dLock device in pluggedRegisteredDeviceListBeforeRemove)
                                {
                                    if (deviceToCheck.DeviceId == device.DeviceId)
                                    {
                                        var t = pluggedRegisteredDeviceListBeforeRemove_tuple.FirstOrDefault(i => i.Item1 == device.DeviceId);
                                        if (t != null)
                                        {
                                            // delete
                                            pluggedRegisteredDeviceListBeforeRemove_tuple.Remove(t);
                                        }
                                    }
                                }
                            }

                            bool   lockDevice = true;
                            string deviceId   = "";
                            for (int i = 0; i < pluggedRegisteredDeviceListBeforeRemove_tuple.Count(); i++)
                            {
                                deviceId = pluggedRegisteredDeviceListBeforeRemove_tuple[i].Item1;
                                if ((!pluggedRegisteredDeviceListBeforeRemove_tuple[i].Item2) || (!pluggedRegisteredDeviceListBeforeRemove_tuple[i].Item3))
                                {
                                    lockDevice = false;
                                }
                            }
                            if (lockDevice)
                            {
                                Task  t = LockDevice(deviceId);
                                await t;
                            }
                            await writeConnectedRegisteredDevices();
                        }
                        catch (Exception ex)
                        {
                        }
                        finally
                        {
                            deferral.Complete();
                        }
                        break;
                    }
                }
            }
            else
            {
                Debug.WriteLine("[RUN] Unknown trigger");
                deferral = taskInstance.GetDeferral();
                //try
                //{
                //    Task t = writeConnectedRegisteredDevices();
                //    await t;
                //}
                //catch (ConnectedRegisteredDevicesListTxtFileEmpty Ex)
                //{

                //}
                //finally
                //{
                //    deferral.Complete();
                //}
            }
            // Wait until the operation completes
            opCompletedEvent.WaitOne();

            deferral.Complete();
        }
Beispiel #20
0
        private async Task AuthenticateWithSmartCardAsync(SmartCard card)
        {
            var localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;

            String m_selectedDeviceId           = localSettings.Values["SelectedDevice"] as String;
            string m_selectedDeviceFriendlyName = string.Empty;
            string m_selectedDeviceAddDate      = string.Empty;
            string deviceConfigString           = string.Empty;

            char[] deviceConfigCharArray;
            byte[] deviceIdArray    = new byte[16];
            byte[] deviceDlockState = new byte[1];

            bool foundCompanionDevice = false;

            byte[] response = { 0 };
            string sw1sw2   = null;

            SecondaryAuthenticationFactorAuthenticationStageInfo authStageInfo = await SecondaryAuthenticationFactorAuthentication.GetAuthenticationStageInfoAsync();

            if ((authStageInfo.Stage != SecondaryAuthenticationFactorAuthenticationStage.CollectingCredential) && (authStageInfo.Stage != SecondaryAuthenticationFactorAuthenticationStage.WaitingForUserConfirmation))
            {
                throw new Exception("Unexpected! Stage: " + authStageInfo.Stage);
            }
            //ShowToastNotification("Post Collecting Credential");
            System.Diagnostics.Debug.WriteLine("[AuthenticateWithSmartCardAsync] Post Collecting Credential");
            IReadOnlyList <SecondaryAuthenticationFactorInfo> deviceList = await SecondaryAuthenticationFactorRegistration.FindAllRegisteredDeviceInfoAsync(
                SecondaryAuthenticationFactorDeviceFindScope.AllUsers);

            if (deviceList.Count == 0)
            {
                //ShowToastNotification("Unexpected exception, device list = 0");
                throw new Exception("Unexpected exception, device list = 0");
            }

            SmartCardConnection connection = await card.ConnectAsync();

            System.Diagnostics.Debug.WriteLine("[AuthenticateWithSmartCardAsync] Connection");

            response = await Apdu.TransmitApduAsync(connection, Apdu.getDeviceGuidCmdApdu);

            sw1sw2        = Apdu.ApduResponseParser(response, out response);
            deviceIdArray = response;
            string deviceId = BitConverter.ToString(response).Replace("-", "");

            response = await Apdu.TransmitApduAsync(connection, Apdu.getDlockStateCmdApdu);

            sw1sw2           = Apdu.ApduResponseParser(response, out response);
            deviceDlockState = response;

            //string deviceFriendlyName = null;

            byte[]  deviceConfigDataArray = new byte[18]; //16 bytes for GUID and 1 byte for dLockstate
            IBuffer deviceConfigData;

            byte[] deviceConfigurationDataArray;
            //List<byte[]> deviceConfigList = new List<byte[]>();



            foreach (SecondaryAuthenticationFactorInfo device in deviceList)
            {
                CryptographicBuffer.CopyToByteArray(device.DeviceConfigurationData, out deviceConfigurationDataArray);
                //deviceConfigList.Add(deviceConfigurationDataArray);

                //deviceFriendlyName = device.DeviceFriendlyName;
                if (device.DeviceId == deviceId)
                {
                    m_selectedDeviceId           = deviceId;
                    m_selectedDeviceFriendlyName = device.DeviceFriendlyName;
                    deviceConfigString           = CryptographicBuffer.ConvertBinaryToString(0, device.DeviceConfigurationData);
                    //deviceConfigCharArray = new char[deviceConfigString.Count()];
                    //deviceConfigCharArray = deviceConfigString.ToCharArray();
                    int count = device.DeviceFriendlyName.Count();
                    m_selectedDeviceAddDate = deviceConfigString.Substring(35 + 1 + count + 1 + 1);
                    foundCompanionDevice    = true;
                    //continue;
                }
            }
            //Debugger.Break();
            if (!foundCompanionDevice)
            {
                throw new CompanionDeviceNotFoundException();
            }
            System.Diagnostics.Debug.WriteLine("[AuthenticateWithSmartCardAsync] Start Nonce APDU sending");
            response = await Apdu.TransmitApduAsync(connection, Apdu.getNonceCmdApdu);

            sw1sw2 = Apdu.ApduResponseParser(response, out response);
            if (sw1sw2 != "9000")
            {
                throw new UnableTogetNonceFromDeviceException();
            }
            System.Diagnostics.Debug.WriteLine("[AuthenticateWithSmartCardAsync] Nonce APDU recieved without error");

            string  nonce    = BitConverter.ToString(response).Replace("-", "");
            IBuffer svcNonce = CryptographicBuffer.DecodeFromHexString(nonce);

            System.Diagnostics.Debug.WriteLine("[AuthenticateWithSmartCardAsync] Start Authentication");
            SecondaryAuthenticationFactorAuthenticationResult authResult = await SecondaryAuthenticationFactorAuthentication.StartAuthenticationAsync(
                m_selectedDeviceId, svcNonce);

            if (authResult.Status != SecondaryAuthenticationFactorAuthenticationStatus.Started)
            {
                //ShowToastNotification("Unexpected! Could not start authentication!");
                throw new Exception("Unexpected! Could not start authentication! Status: " + authResult.Status);
            }

            byte[] devNonce  = { 0 };
            byte[] svcHmac   = { 0 };
            byte[] sessNonce = { 0 };

            CryptographicBuffer.CopyToByteArray(authResult.Authentication.ServiceAuthenticationHmac, out svcHmac);
            CryptographicBuffer.CopyToByteArray(authResult.Authentication.SessionNonce, out sessNonce);
            CryptographicBuffer.CopyToByteArray(authResult.Authentication.DeviceNonce, out devNonce);

            byte[] cmd = new byte[Apdu.challengeCmdApdu.Length + svcHmac.Length + sessNonce.Length + devNonce.Length];
            System.Buffer.BlockCopy(Apdu.challengeCmdApdu, 0, cmd, 0, Apdu.challengeCmdApdu.Length);
            System.Buffer.BlockCopy(svcHmac, 0, cmd, Apdu.challengeCmdApdu.Length, svcHmac.Length);
            System.Buffer.BlockCopy(sessNonce, 0, cmd, Apdu.challengeCmdApdu.Length + svcHmac.Length, sessNonce.Length);
            System.Buffer.BlockCopy(devNonce, 0, cmd, Apdu.challengeCmdApdu.Length + svcHmac.Length + sessNonce.Length, devNonce.Length);

            System.Diagnostics.Debug.WriteLine("[AuthenticateWithSmartCardAsync] Send Challenge");

            string str = "\"" + m_selectedDeviceFriendlyName + "\"";

            await SecondaryAuthenticationFactorAuthentication.ShowNotificationMessageAsync(
                str,
                SecondaryAuthenticationFactorAuthenticationMessage.DeviceNeedsAttention);

            response = await Apdu.TransmitApduAsync(connection, cmd);

            sw1sw2 = Apdu.ApduResponseParser(response, out response);

            if (sw1sw2 == "6985")
            {
                throw new UnauthorizedUserException();
            }
            else if (sw1sw2 == "6984")
            {
                //ShowToastNotification("Log-in denied by user");
                throw new LogInDeniedByUserException();
            }

            System.Diagnostics.Debug.WriteLine("[AuthenticateWithSmartCardAsync] Response recieved");
            byte[] HMACdk = new byte[32];
            byte[] HMACsk = new byte[32];
            System.Buffer.BlockCopy(response, 0, HMACdk, 0, 32);
            System.Buffer.BlockCopy(response, 32, HMACsk, 0, 32);

            IBuffer deviceHmac  = CryptographicBuffer.CreateFromByteArray(HMACdk);
            IBuffer sessionHmac = CryptographicBuffer.CreateFromByteArray(HMACsk);

            SecondaryAuthenticationFactorFinishAuthenticationStatus authStatus = await authResult.Authentication.FinishAuthenticationAsync(deviceHmac,
                                                                                                                                           sessionHmac);

            if (authStatus != SecondaryAuthenticationFactorFinishAuthenticationStatus.Completed)
            {
                //ShowToastNotification("Unable to complete authentication!");
                System.Diagnostics.Debug.WriteLine("[AuthenticateWithSmartCardAsync] Unable to complete authentication");
                throw new Exception("Unable to complete authentication!");
            }

            deviceConfigString = "";
            if (deviceDlockState[0] == 0)
            {
                deviceConfigString = deviceId + "-0-1-" + m_selectedDeviceFriendlyName + "-" + m_selectedDeviceAddDate;
            }
            else
            {
                deviceConfigString = deviceId + "-1-1-" + m_selectedDeviceFriendlyName + "-" + m_selectedDeviceAddDate;
            }
            deviceConfigCharArray = new char[deviceConfigString.Count()];
            deviceConfigString.CopyTo(0, deviceConfigCharArray, 0, deviceConfigString.Count()); // because deviceConfigString is readonly
            deviceConfigCharArray[35] = '1';                                                    // to indicate that device was not used for last login
            string deviceConfigStringNew = new string(deviceConfigCharArray);

            //Debugger.Break();
            deviceConfigData = CryptographicBuffer.ConvertStringToBinary(deviceConfigStringNew, 0);
            await SecondaryAuthenticationFactorRegistration.UpdateDeviceConfigurationDataAsync(deviceId, deviceConfigData); //update deviceConfigData

            foreach (SecondaryAuthenticationFactorInfo device in deviceList)
            {
                if (device.DeviceId != deviceId)
                {
                    deviceConfigString    = CryptographicBuffer.ConvertBinaryToString(0, device.DeviceConfigurationData);
                    deviceConfigCharArray = new char[deviceConfigString.Count()];
                    deviceConfigString.CopyTo(0, deviceConfigCharArray, 0, deviceConfigString.Count()); // decause deviceConfigString is readonly
                    deviceConfigCharArray[35] = '0';                                                    // to indicate that device was not used for last login
                    deviceConfigStringNew     = new string(deviceConfigCharArray);
                    deviceConfigData          = CryptographicBuffer.ConvertStringToBinary(deviceConfigStringNew, 0);
                    //Debugger.Break();
                    await SecondaryAuthenticationFactorRegistration.UpdateDeviceConfigurationDataAsync(device.DeviceId, deviceConfigData); //update deviceConfigData
                }
            }
            System.Diagnostics.Debug.WriteLine("[AuthenticateWithSmartCardAsync] Auth completed");
            connection.Dispose();
        }
Beispiel #21
0
        public static async Task RegisterDevice_Click(string deviceFriendlyName)
        {
            String  deviceId  = "";
            IBuffer deviceKey = CryptographicBuffer.GenerateRandom(32);
            IBuffer authKey   = CryptographicBuffer.GenerateRandom(32);

            byte[] deviceKeyArray            = new byte[32];
            byte[] authKeyArray              = new byte[32];
            byte[] deviceIdArray             = new byte[16];
            byte[] deviceDlockState          = new byte[1];
            byte[] response                  = { 0 };
            int    numberOfDevices           = 0;
            int    numberOfRegisteredDevices = 0;
            string sw1sw2 = null;
            //byte[] combinedDataArray = new byte[64];
            string NanosATR          = "3b00";
            String deviceModelNumber = "0001";
            //List<SmartCardListItem> cardItems = new List<SmartCardListItem>();
            MessageDialog myDlg;

            bool isSupported;

            isSupported = await KeyCredentialManager.IsSupportedAsync();

            if (!isSupported)
            {
                var    loader = new Windows.ApplicationModel.Resources.ResourceLoader();
                string PleaseSetUpPinContent = loader.GetString("PleaseSetupPin_content_error");
                string PleaseSetUpPinTitle   = loader.GetString("PleaseSetupPin_title_error");

                myDlg = new MessageDialog(PleaseSetUpPinContent, PleaseSetUpPinTitle);
                await myDlg.ShowAsync();

                return;
            }

            IReadOnlyList <User> users = await User.FindAllAsync(UserType.LocalUser, UserAuthenticationStatus.LocallyAuthenticated);

            string userId = users.ElementAt(0).NonRoamableId;

            string selector = SmartCardReader.GetDeviceSelector();

            selector += " AND System.Devices.DeviceInstanceId:~~\"Ledger\"";
            //string test = selector.Replace(" ", ((char)34).ToString());
            DeviceInformationCollection devices = await DeviceInformation.FindAllAsync(selector);

            foreach (DeviceInformation device in devices)
            {
                SmartCardReader reader = await SmartCardReader.FromIdAsync(device.Id);

                IReadOnlyList <SmartCard> cards = await reader.FindAllCardsAsync();

                foreach (SmartCard card in cards)
                {
                    SmartCardProvisioning provisioning = await SmartCardProvisioning.FromSmartCardAsync(card);

                    IBuffer ATR = await card.GetAnswerToResetAsync();

                    string ATR_str = CryptographicBuffer.EncodeToHexString(ATR);

                    if (ATR_str.Equals(NanosATR))
                    {
                        numberOfDevices++;
                        bool foundCompanionDevice = false;
                        // List the registered devices to prevent registering twice the same device
                        IReadOnlyList <SecondaryAuthenticationFactorInfo> registeredDeviceList = await SecondaryAuthenticationFactorRegistration.FindAllRegisteredDeviceInfoAsync(
                            SecondaryAuthenticationFactorDeviceFindScope.AllUsers);

                        SmartCardConnection connection = await card.ConnectAsync();

                        response = await Apdu.TransmitApduAsync(connection, Apdu.getDeviceGuidCmdApdu);

                        sw1sw2 = Apdu.ApduResponseParser(response, out response);
                        connection.Dispose();
                        deviceIdArray = response;
                        deviceId      = BitConverter.ToString(response).Replace("-", "");
                        // Loop on registered devices to check if device to register has already been registered
                        for (int i = 0; i < registeredDeviceList.Count(); i++)
                        {
                            if (registeredDeviceList.ElementAt(i).DeviceId == deviceId)
                            {
                                //deviceFriendlyName = registeredDeviceList.ElementAt(i).DeviceFriendlyName;
                                numberOfRegisteredDevices++;
                                foundCompanionDevice = true;
                                break;
                            }
                        }
                        if (foundCompanionDevice)// This device has already been registered
                        {
                            // New message dialog to inform user, and break from card loop
                            //myDlg = null;
                            //myDlg = new MessageDialog("The device \"" + deviceFriendlyName + "\" has already been registered");
                            //await myDlg.ShowAsync();
                            continue;
                        }

                        connection = await card.ConnectAsync();

                        response = await Apdu.TransmitApduAsync(connection, Apdu.getDlockStateCmdApdu);

                        sw1sw2           = Apdu.ApduResponseParser(response, out response);
                        deviceDlockState = response;

                        response = await Apdu.TransmitApduAsync(connection, Apdu.startRegistrationCmdApdu);

                        sw1sw2 = Apdu.ApduResponseParser(response, out response);

                        connection.Dispose();

                        if (sw1sw2 != "9000")
                        {
                            var    loader = new Windows.ApplicationModel.Resources.ResourceLoader();
                            string RegistrationDeniedContent = loader.GetString("RegsitrationDenied_content_error");
                            string RegistrationDeniedTitle   = loader.GetString("RegsitrationDenied_title_error");

                            myDlg = null;
                            myDlg = new MessageDialog(RegistrationDeniedContent, RegistrationDeniedTitle);
                            await myDlg.ShowAsync();

                            return;
                        }
                        // Get device key from response
                        for (int index = 0; index < 32; index++)
                        {
                            deviceKeyArray[index] = response[index];
                        }
                        deviceKey = CryptographicBuffer.CreateFromByteArray(deviceKeyArray);
                        // Get auth key from response
                        for (int index = 0; index < 32; index++)
                        {
                            authKeyArray[index] = response[index + 32];
                        }
                        authKey = CryptographicBuffer.CreateFromByteArray(authKeyArray);

                        byte[] deviceConfigDataArray = new byte[18]; //16 bytes for GUID and 1 byte for dLockstate

                        for (int i = 0; i < 16; i++)
                        {
                            deviceConfigDataArray[i] = deviceIdArray[i];
                        }
                        deviceConfigDataArray[16] = deviceDlockState[0];
                        deviceConfigDataArray[17] = 0; // 1 if used for last logon, 0 instead

                        string   deviceConfigString = "";
                        DateTime addDate            = DateTime.Now;
                        //DateTime addDate = new DateTime(2017, 5, 31, 13, 23, 45);
                        if (deviceDlockState[0] == 0)
                        {
                            deviceConfigString = deviceId + "-0-0-" + deviceFriendlyName + "-" + addDate.ToString() + "-" + userId;
                        }
                        else
                        {
                            deviceConfigString = deviceId + "-1-0-" + deviceFriendlyName + "-" + addDate.ToString() + "-" + userId;
                        }

                        // Get a Ibuffer from combinedDataArray
                        IBuffer deviceConfigData = CryptographicBuffer.ConvertStringToBinary(deviceConfigString, 0);
                        //IBuffer deviceConfigData = CryptographicBuffer.CreateFromByteArray(deviceConfigDataArray);

                        SecondaryAuthenticationFactorDeviceCapabilities capabilities = SecondaryAuthenticationFactorDeviceCapabilities.SecureStorage |
                                                                                       SecondaryAuthenticationFactorDeviceCapabilities.HMacSha256 | SecondaryAuthenticationFactorDeviceCapabilities.StoreKeys |
                                                                                       SecondaryAuthenticationFactorDeviceCapabilities.SupportSecureUserPresenceCheck;

                        SecondaryAuthenticationFactorRegistrationResult registrationResult = await SecondaryAuthenticationFactorRegistration.RequestStartRegisteringDeviceAsync(
                            deviceId,
                            capabilities,
                            deviceFriendlyName,
                            deviceModelNumber,
                            deviceKey,
                            authKey);

                        if (registrationResult.Status != SecondaryAuthenticationFactorRegistrationStatus.Started)
                        {
                            myDlg = null;

                            if (registrationResult.Status == SecondaryAuthenticationFactorRegistrationStatus.DisabledByPolicy)
                            {
                                //For DisaledByPolicy Exception:Ensure secondary auth is enabled.
                                //Use GPEdit.msc to update group policy to allow secondary auth
                                //Local Computer Policy\Computer Configuration\Administrative Templates\Windows Components\Microsoft Secondary Authentication Factor\Allow Companion device for secondary authentication
                                myDlg = new MessageDialog("Disabled by Policy.  Please update the policy and try again.");
                            }

                            if (registrationResult.Status == SecondaryAuthenticationFactorRegistrationStatus.PinSetupRequired)
                            {
                                //For PinSetupRequired Exception:Ensure PIN is setup on the device
                                //Either use gpedit.msc or set reg key
                                //This setting can be enabled by creating the AllowDomainPINLogon REG_DWORD value under the HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\System Registry key and setting it to 1.
                                var loader = new Windows.ApplicationModel.Resources.ResourceLoader();
                                var str    = loader.GetString("PleaseSetupPin_error");
                                myDlg = new MessageDialog(str);
                            }

                            if (myDlg != null)
                            {
                                await myDlg.ShowAsync();

                                return;
                            }
                        }

                        System.Diagnostics.Debug.WriteLine("[RegisterDevice_Click] Device Registration Started!");
                        await registrationResult.Registration.FinishRegisteringDeviceAsync(deviceConfigData);

                        //DeviceListBox.Items.Add(deviceFriendlyName);
                        System.Diagnostics.Debug.WriteLine("[RegisterDevice_Click] Device Registration is Complete!");

                        IReadOnlyList <SecondaryAuthenticationFactorInfo> deviceList = await SecondaryAuthenticationFactorRegistration.FindAllRegisteredDeviceInfoAsync(
                            SecondaryAuthenticationFactorDeviceFindScope.AllUsers);

                        SecondaryAuthenticationFactorDevicePresenceMonitoringRegistrationStatus status =
                            await SecondaryAuthenticationFactorRegistration.RegisterDevicePresenceMonitoringAsync(
                                deviceId,
                                device.Id,
                                SecondaryAuthenticationFactorDevicePresenceMonitoringMode.AppManaged /*,
                                                                                                      * deviceFriendlyName,
                                                                                                      * deviceModelNumber,
                                                                                                      * deviceConfigData*/);

                        switch (status)
                        {
                        //case SecondaryAuthenticationFactorDevicePresenceMonitoringRegistrationStatus.Succeeded:
                        //    await new MessageDialog("Registered for presence monitoring!").ShowAsync();
                        //    break;

                        case SecondaryAuthenticationFactorDevicePresenceMonitoringRegistrationStatus.DisabledByPolicy:
                            await new MessageDialog("Registered for presence disabled by policy!").ShowAsync();
                            break;
                        }

                        listContent listItem = new listContent();
                        listItem.deviceFriendlyName = deviceFriendlyName;
                        listItem.deviceGUID         = deviceId;
                        //listItem.isVisible = false;
                        listItem.date       = addDate;
                        listItem.dateString = FormatDate(addDate);
                        //DeviceListBox.Items.Add(listItem);
                        //StartWatcher();
                        //this.Frame.Navigate(typeof(MainPage), "false");
                    }
                }
            }
            if (numberOfDevices == numberOfRegisteredDevices)
            {
                var    loader = new Windows.ApplicationModel.Resources.ResourceLoader();
                string str    = loader.GetString("DeviceAlreadyRegistered_content_error");


                throw new Exception(str);
                //myDlg = new MessageDialog("Ledger Nano-s for Windows Hello not found" + Environment.NewLine + Environment.NewLine + "Please plug a ledger Nano-s in a usb port");
                //await myDlg.ShowAsync();
                //return;
            }
            return;
        }
Beispiel #22
0
        private async void RegisterDevice_Click(object sender, RoutedEventArgs e)
        {
            String deviceId = System.Guid.NewGuid().ToString();

            // WARNING: Test code
            // These keys should be generated on the companion device
            // Create device key and authentication key
            IBuffer deviceKey = CryptographicBuffer.GenerateRandom(32);
            IBuffer authKey   = CryptographicBuffer.GenerateRandom(32);

            //
            // WARNING: Test code
            // The keys SHOULD NOT be saved into device config data
            //
            byte[] deviceKeyArray = { 0 };
            CryptographicBuffer.CopyToByteArray(deviceKey, out deviceKeyArray);

            byte[] authKeyArray = { 0 };
            CryptographicBuffer.CopyToByteArray(authKey, out authKeyArray);

            //Generate combinedDataArray
            int combinedDataArraySize = deviceKeyArray.Length + authKeyArray.Length;

            byte[] combinedDataArray = new byte[combinedDataArraySize];
            for (int index = 0; index < deviceKeyArray.Length; index++)
            {
                combinedDataArray[index] = deviceKeyArray[index];
            }
            for (int index = 0; index < authKeyArray.Length; index++)
            {
                combinedDataArray[deviceKeyArray.Length + index] = authKeyArray[index];
            }

            // Get a Ibuffer from combinedDataArray
            IBuffer deviceConfigData = CryptographicBuffer.CreateFromByteArray(combinedDataArray);

            //
            // WARNING: Test code
            // The friendly name and device model number SHOULD come from device
            //
            String deviceFriendlyName = "Test Simulator";
            String deviceModelNumber  = "Sample A1";

            SecondaryAuthenticationFactorDeviceCapabilities capabilities = SecondaryAuthenticationFactorDeviceCapabilities.SecureStorage;

            SecondaryAuthenticationFactorRegistrationResult registrationResult = await SecondaryAuthenticationFactorRegistration.RequestStartRegisteringDeviceAsync(deviceId,
                                                                                                                                                                    capabilities,
                                                                                                                                                                    deviceFriendlyName,
                                                                                                                                                                    deviceModelNumber,
                                                                                                                                                                    deviceKey,
                                                                                                                                                                    authKey);

            if (registrationResult.Status != SecondaryAuthenticationFactorRegistrationStatus.Started)
            {
                MessageDialog myDlg = null;

                if (registrationResult.Status == SecondaryAuthenticationFactorRegistrationStatus.DisabledByPolicy)
                {
                    //For DisaledByPolicy Exception:Ensure secondary auth is enabled.
                    //Use GPEdit.msc to update group policy to allow secondary auth
                    //Local Computer Policy\Computer Configuration\Administrative Templates\Windows Components\Microsoft Secondary Authentication Factor\Allow Companion device for secondary authentication
                    myDlg = new MessageDialog("Disabled by Policy.  Please update the policy and try again.");
                }

                if (registrationResult.Status == SecondaryAuthenticationFactorRegistrationStatus.PinSetupRequired)
                {
                    //For PinSetupRequired Exception:Ensure PIN is setup on the device
                    //Either use gpedit.msc or set reg key
                    //This setting can be enabled by creating the AllowDomainPINLogon REG_DWORD value under the HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\System Registry key and setting it to 1.
                    myDlg = new MessageDialog("Please setup PIN for your device and try again.");
                }

                if (myDlg != null)
                {
                    await myDlg.ShowAsync();

                    return;
                }
            }

            System.Diagnostics.Debug.WriteLine("Device Registration Started!");
            await registrationResult.Registration.FinishRegisteringDeviceAsync(deviceConfigData);

            DeviceListBox.Items.Add(deviceId);
            System.Diagnostics.Debug.WriteLine("Device Registration is Complete!");

            IReadOnlyList <SecondaryAuthenticationFactorInfo> deviceList = await SecondaryAuthenticationFactorRegistration.FindAllRegisteredDeviceInfoAsync(
                SecondaryAuthenticationFactorDeviceFindScope.User);

            RefreshDeviceList(deviceList);
        }