Esempio n. 1
0
        public static async Task <SmartCardReader> GetSmartCardReader()
        {
            DeviceInformationCollection devices = await DeviceInformation.FindAllAsync
                                                      (SmartCardReader.GetDeviceSelector());

            return(await SmartCardReader.FromIdAsync(devices[0].Id));
        }
Esempio n. 2
0
        private async Task InitSmartCardAsync()
        {
            // Check if the SmartCardConnection API exists on this currently running SKU of Windows
            if (!ApiInformation.IsTypePresent("Windows.Devices.SmartCards.SmartCardConnection"))
            {
                // This SKU of Windows does not support Smart Card Connections
                SetStatusOutput("This SKU of Windows does not support Smart Card connections");
                return;
            }

            // Initialize smart card reader
            var devSelector = SmartCardReader.GetDeviceSelector(SmartCardReaderKind.Nfc);
            var devices     = await DeviceInformation.FindAllAsync(devSelector);

            if (devices != null && devices.Count == 0)
            {
                SetStatusOutput("No NFC Smart Card Reader found in this device.");
                return;
            }

            // Subscribe to Smart Cards
            _smartCardReader = await SmartCardReader.FromIdAsync(devices.FirstOrDefault().Id);

            _smartCardReader.CardAdded += SmartCardReaderOnCardAdded;
            SetStatusOutput("Subscribed for NFC Smart Cards");
        }
Esempio n. 3
0
        //public static bool Status
        //{
        //    get
        //    {
        //        var scStatus = await Reader.GetStatusAsync();
        //        if(scStatus == SmartCardReaderStatus.Ready) return false;
        //    }
        //}


        public static async void DeviceSetAsync()
        {
            // Reader検索
            var selector = SmartCardReader.GetDeviceSelector(SmartCardReaderKind.Any);
            var devices  = await DeviceInformation.FindAllAsync(selector);

            var device = devices.FirstOrDefault();

            if (device == null)
            {
                return;
            }
            Debug.WriteLine("Device Set");

            Reader = await SmartCardReader.FromIdAsync(device.Id);

            if (Reader == null)
            {
                return;
            }
            Debug.WriteLine("Reader Set");

            Reader.CardAdded += OnCardAdded;

            return;
        }
Esempio n. 4
0
        public async Task GetAllSmartCardsAsync()
        {
            string selector = SmartCardReader.GetDeviceSelector();
            var    readers  = await DeviceInformation.FindAllAsync(selector);

            foreach (var reader in readers)
            {
                this.AllReadersInfo.Add(new Tuple <string, string>(reader.Name, reader.Id));
            }
        }
Esempio n. 5
0
        // カード読込メソッド
        private async Task <string> Getmid()
        {
            // Reader検索
            var selector = SmartCardReader.GetDeviceSelector(SmartCardReaderKind.Any);
            var devices  = await DeviceInformation.FindAllAsync(selector);

            var device = devices.FirstOrDefault();

            if (device == null)
            {
                return("");
            }

            var reader = await SmartCardReader.FromIdAsync(device.Id);

            if (reader == null)
            {
                return("");
            }

            // カード検索
            var cards = await reader.FindAllCardsAsync();

            var card = cards.FirstOrDefault();

            if (card == null)
            {
                return("");
            }

            // 接続してポーリングコマンド送信
            using (var con = await card.ConnectAsync())
            {
                var handler = new AccessHandler(con);
                try
                {
                    var result = await handler.TransparentExchangeAsync(new byte[] { 6, 0, 0xff, 0xff, 0, 3 });

                    byte[] idm = new byte[8];
                    Array.Copy(result, 2, idm, 0, idm.Length);
                    string s = "";
                    foreach (byte b in idm)
                    {
                        // 0x00がでたらループを抜けるならここにif文とかいれる
                        s += b.ToString("X2");
                    }
                    return(s);
                }
                catch
                {
                    return("");
                }
            }
        }
Esempio n. 6
0
        public static async Task <SmartCardReader> FindAsync(Func <DeviceInformationCollection, DeviceInformation> selector = null)
        {
#if WINDOWS_UAP
            // Make sure we have the API we need
            if (!ApiInformation.IsTypePresent(typeof(SmartCardConnection).FullName))
            {
                return(null);
            }
#endif

            var devices = await DeviceInformation.FindAllAsync(SmartCardReader.GetDeviceSelector(SmartCardReaderKind.Nfc));

// if none, fall back to generic
            if (devices.Count == 0)
            {
                devices = await DeviceInformation.FindAllAsync(SmartCardReader.GetDeviceSelector(SmartCardReaderKind.Generic));
            }

            // There is a bug on some devices that were updated to WP8.1 where an NFC SmartCardReader is
            // enumerated despite that the device does not support it. As a workaround, we can do an additonal check
            // to ensure the device truly does support it.
            var workaroundDetect = await DeviceInformation.FindAllAsync("System.Devices.InterfaceClassGuid:=\"{50DD5230-BA8A-11D1-BF5D-0000F805F530}\" AND System.Devices.InterfaceEnabled:=System.StructuredQueryType.Boolean#True");

            if (workaroundDetect.Count == 0 || devices.Count == 0)
            {
                return(null);
            }

#if WINDOWS_UAP
            // See if one of the reader names contains a -CL
            if (devices.Count > 1 && selector == null)
            {
                var di = devices.SingleOrDefault(d => d.Id.Contains("-CL"));
                if (di != null)
                {
                    return(await SmartCardReader.FromIdAsync(di.Id));
                }
            }
#endif

            var func = selector ?? (d => d.First());
            var dev  = func(devices);
            if (dev == null)
            {
                return(null);
            }

            var reader = await SmartCardReader.FromIdAsync(dev.Id);

            return(reader);
        }
Esempio n. 7
0
        private void StartWatcher()
        {
            DeviceWatcherEventKind[] triggerEventKinds = { DeviceWatcherEventKind.Add, DeviceWatcherEventKind.Remove /*, DeviceWatcherEventKind.Update */ };
            //IEnumerable<DeviceWatcherEventKind> triggerEventKinds = DeviceWatcherEventKind.Add;
            DeviceWatcher deviceWatcher = null;

            string selector = SmartCardReader.GetDeviceSelector();

            selector += " AND System.Devices.DeviceInstanceId:~~\"Ledger\"";

            deviceWatcher = DeviceInformation.CreateWatcher(selector, null);
            DeviceWatcherTrigger deviceWatcherTrigger = deviceWatcher.GetBackgroundTrigger(triggerEventKinds);

            RegisterTask(deviceWatcherTrigger);
        }
        private void StartWatcher()
        {
            string selector = SmartCardReader.GetDeviceSelector();

            selector += " AND System.Devices.DeviceInstanceId:~~\"Ledger\"";

            deviceWatcher = DeviceInformation.CreateWatcher(selector, null);

            handlerRemoved = new TypedEventHandler <DeviceWatcher, DeviceInformationUpdate>(async(watcher, deviceInfoUpdate) =>
            {
                StopWatcher();
                await Removed();
            });
            deviceWatcher.Removed += handlerRemoved;
            deviceWatcher.Start();
        }
Esempio n. 9
0
        private async void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            string selector = SmartCardReader.GetDeviceSelector();
            DeviceInformationCollection devices = await DeviceInformation.FindAllAsync(selector);

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

                reader.CardAdded   += Reader_CardAdded;
                reader.CardRemoved += Reader_CardRemoved;
                foreach (var foundCard in (await reader.FindAllCardsAsync()))
                {
                    await ReadCard(foundCard);
                }
            }
        }
Esempio n. 10
0
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            await SharedState.LogAsync($"BackgroundScanner ({taskInstance.InstanceId}): Starting run of background task...");

            _taskInstance           = taskInstance;
            _deferral               = taskInstance.GetDeferral();
            _taskInstance.Progress  = 1;
            _taskInstance.Canceled += TaskInstance_Canceled;

            string selector = SmartCardReader.GetDeviceSelector();
            DeviceInformationCollection devices = await DeviceInformation.FindAllAsync(selector);

            var reader = await SmartCardReader.FromIdAsync(devices.FirstOrDefault().Id);

            await SharedState.LogAsync($"BackgroundScanner ({taskInstance.InstanceId}): Got card reader device.");

            reader.CardAdded += Reader_CardAdded;
        }
Esempio n. 11
0
        public async Task Setup()
        {
            if (reader != null)
            {
                reader.CardAdded -= Reader_CardAdded;
            }

            var devices = await DeviceInformation.FindAllAsync(SmartCardReader.GetDeviceSelector(SmartCardReaderKind.Generic));

            foreach (DeviceInformation device in devices)
            {
                reader = await SmartCardReader.FromIdAsync(device.Id);
            }
            if (reader == null)
            {
                Debug.WriteLine("No NFC reader found");
                return;
            }
            reader.CardAdded += Reader_CardAdded;
        }
Esempio n. 12
0
        private async void waitingForDeviceInsertion()
        {
            bool   nanosDetected = false;
            string selector      = SmartCardReader.GetDeviceSelector();

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

            while (!nanosDetected)
            {
                DeviceInformationCollection devices = await DeviceInformation.FindAllAsync(selector);

                if (devices.Count > 0)
                {
                    nanosDetected = true;
                    await Task.Delay(1000);

                    this.Frame.Navigate(typeof(RegisterDevice));
                }
            }
        }
Esempio n. 13
0
        private async Task DoRead()
        {
            string selector = SmartCardReader.GetDeviceSelector();

            DeviceInformationCollection smartCardReaders =
                await DeviceInformation.FindAllAsync(selector);

            var device = smartCardReaders.FirstOrDefault();

            SmartCardReader reader = await SmartCardReader.FromIdAsync(device.Id);

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

            var card = cards.FirstOrDefault();

            if (card == null)
            {
                return;
            }

            (Dictionary <byte, string> address, Dictionary <byte, string> identity)? data = null;

            using (SmartCardConnection connection = await card.ConnectAsync())
            {
                data = await connection.ReadEIdData();
            }
            var identityData = data.Value.identity;
            var addressData  = data.Value.address;

            var dateOfBirth = EIdDateHelper.GetDateTime(identityData[Tags.ID_BIRTH_DATE]);

            FullName.Text       = $"{identityData[Tags.ID_FIRST_NAME]} {identityData[Tags.ID_LAST_NAME]}";
            PlaceOfBirth.Text   = identityData[Tags.ID_BIRTH_LOCATION];
            DateOfBirth.Text    = dateOfBirth.Value.ToString("dd/MM/yyyy");
            Gender.Text         = identityData[Tags.ID_SEX];
            Nationality.Text    = identityData[Tags.ID_NATIONALITY];
            NationalNumber.Text = identityData[Tags.ID_NATIONAL_NUMBER];
            Address.Text        = $"{addressData[Tags.ADDRESS_STREET_NUMBER]} {addressData[Tags.ADDRESS_ZIP_CODE]} {addressData[Tags.ADDRESS_MUNICIPALITY]}";
        }
        /*public static async void GetSmartCardReader()
         * {
         *  while (true == true)
         *  {
         *      DeviceInformationCollection devices = await DeviceInformation.FindAllAsync
         *          (SmartCardReader.GetDeviceSelector());
         *
         *      if (devices.Count > 0)
         *      {
         *          List<SmartCardReader> readers = new List<SmartCardReader>();
         *
         *          foreach (DeviceInformation device in devices)
         *          {
         *              readers.Add(await SmartCardReader.FromIdAsync(device.Id));
         *          }
         *
         *          Thread scanSmartCard = new Thread(new ParameterizedThreadStart(ScanSmartCard));
         *          scanSmartCard.Start(readers);
         *          Console.WriteLine("Card Reader Ready");
         *          Thread.CurrentThread.Abort();
         *      }
         *
         *      Thread.Sleep(2000);
         *  }
         * }*/


        public static void ScanSmartCard()
        {
            List <SmartCardReader> readers = new List <SmartCardReader>();

            DeviceWatcher smartCardReaderWatcher = DeviceInformation.CreateWatcher();

            smartCardReaderWatcher.Added += async(sender, args) =>
            {
                DeviceInformationCollection devices =
                    await DeviceInformation.FindAllAsync(SmartCardReader.GetDeviceSelector());

                foreach (DeviceInformation device in devices)
                {
                    if (device.Id == args.Id)
                    {
                        readers.Add(await SmartCardReader.FromIdAsync(args.Id));
                        readers[readers.Count - 1].CardAdded += GetCardID;
                        Console.WriteLine("{0} is running and ready", readers[readers.Count - 1].Name); //can be changed to output in a popup
                    }
                }
            };

            smartCardReaderWatcher.Removed += (sender, args) =>
            {
                for (int idCounter = 0; idCounter < readers.Count; idCounter++)
                {
                    if (readers[idCounter].DeviceId == args.Id)
                    {
                        readers[idCounter].CardAdded -= GetCardID;
                        Console.WriteLine("{0} has been removed", readers[idCounter].Name); //can be changed to output in a popup
                        readers.RemoveAt(idCounter);
                        break;
                    }
                }
            };
            smartCardReaderWatcher.Start();
        }
Esempio n. 15
0
        /// <summary>
        /// Click handler for the 'ListSmartCard' button.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void ListSmartCard_Click(object sender, RoutedEventArgs e)
        {
            Button b = sender as Button;

            b.IsEnabled = false;
            try
            {
                rootPage.NotifyUser("Enumerating smart cards...", NotifyType.StatusMessage);

                // This list will be bound to our ItemListView once it has been
                // filled with SmartCardListItems.  The SmartCardListItem class
                // is defined above, and describes a reader/card pair with a
                // reader name and a card name.
                List <SmartCardListItem> cardItems = new List <SmartCardListItem>();

                // First we get the device selector for smart card readers using
                // the static GetDeviceSelector method of the SmartCardReader
                // class.  The selector is a string which describes a class of
                // devices to query for, and is used as the argument to
                // DeviceInformation.FindAllAsync.  GetDeviceSelector is
                // overloaded so that you can provide a SmartCardReaderKind
                // to specify if you are only interested in a particular type
                // of card/reader (e.g. TPM virtual smart card.)  In this case
                // we will list all cards and readers.
                string selector = SmartCardReader.GetDeviceSelector();
                DeviceInformationCollection devices = await DeviceInformation.FindAllAsync(selector);

                // DeviceInformation.FindAllAsync gives us a
                // DeviceInformationCollection, which is essentially a list
                // of DeviceInformation objects.  We must iterate through that
                // list and instantiate SmartCardReader objects from the
                // DeviceInformation objects.
                foreach (DeviceInformation device in devices)
                {
                    SmartCardReader reader = await SmartCardReader.FromIdAsync(device.Id);

                    // For each reader, we want to find all the cards associated
                    // with it.  Then we will create a SmartCardListItem for
                    // each (reader, card) pair.
                    IReadOnlyList <SmartCard> cards = await reader.FindAllCardsAsync();

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

                        SmartCardListItem item = new SmartCardListItem()
                        {
                            ReaderName = card.Reader.Name,
                            CardName   = await provisioning.GetNameAsync()
                        };

                        cardItems.Add(item);
                    }
                }

                // Bind the source of ItemListView to our SmartCardListItem list.
                ItemListView.ItemsSource = cardItems;

                rootPage.NotifyUser("Enumerating smart cards completed.", NotifyType.StatusMessage);
            }
            catch (Exception ex)
            {
                rootPage.NotifyUser("Enumerating smart cards failed with exception: " + ex.ToString(), NotifyType.ErrorMessage);
            }
            finally
            {
                b.IsEnabled = true;
            }
        }
Esempio n. 16
0
        private async Task PerformAuthentication()
        {
            string NanosATR             = "3b00";
            bool   showNotificationFlag = true;

            string selector = SmartCardReader.GetDeviceSelector();

            selector += " AND System.Devices.DeviceInstanceId:~~\"Ledger\"";
            DeviceInformationCollection devices = await DeviceInformation.FindAllAsync(selector);

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

                SmartCardReaderStatus readerstatus = await reader.GetStatusAsync();

                //System.Diagnostics.Debug.WriteLine("Reader : " + reader.Name + " status : " + readerstatus.ToString());
                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))
                        {
                            Task  t = AuthenticateWithSmartCardAsync(card);
                            await t;
                        }
                    }
                    catch (CompanionDeviceNotFoundException ex)
                    {
                        ex.DisplayError();
                        break;
                    }
                    catch (UnableTogetNonceFromDeviceException ex)
                    {
                        ex.DisplayError();
                        showNotificationFlag = false;
                        break;
                    }
                    catch (UnauthorizedUserException ex)
                    {
                        ex.DisplayError();
                        await SecondaryAuthenticationFactorAuthentication.ShowNotificationMessageAsync(
                            "",
                            SecondaryAuthenticationFactorAuthenticationMessage.UnauthorizedUser);

                        //ShowToastNotification("Wrong Response");
                        showNotificationFlag = false;
                        break;
                    }
                    catch (LogInDeniedByUserException ex)
                    {
                        ex.DisplayError();
                        await SecondaryAuthenticationFactorAuthentication.ShowNotificationMessageAsync(
                            "",
                            SecondaryAuthenticationFactorAuthenticationMessage.TryAgain);

                        showNotificationFlag = false;
                        break;
                    }
                    catch (Exception ex)
                    {
                        System.Diagnostics.Debug.WriteLine("[PerformAuthentication] Unhandled Exception / " + ex.Message);
                        showNotificationFlag = false;
                        return;
                    }
                    finally
                    {
                    }
                }
            }
            if (showNotificationFlag)
            {
                var loader = new Windows.ApplicationModel.Resources.ResourceLoader();
                var str    = loader.GetString("LookingForDevice");

                await SecondaryAuthenticationFactorAuthentication.ShowNotificationMessageAsync(
                    str,
                    SecondaryAuthenticationFactorAuthenticationMessage.LookingForDevicePluggedin);
            }
            showNotificationFlag = true;
        }
Esempio n. 17
0
        private async Task <List <SecondaryAuthenticationFactorInfo> > getConnectedRegisteredDeviceList(IReadOnlyList <SecondaryAuthenticationFactorInfo> devicesToCheck)
        {
            //byte[] deviceConfigurationDataArray;
            string selector = SmartCardReader.GetDeviceSelector();

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

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

            List <SecondaryAuthenticationFactorInfo> outList = new List <SecondaryAuthenticationFactorInfo>();

            DeviceInformationCollection readers = await DeviceInformation.FindAllAsync(selector);

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

                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 and increment counter
                                {
                                    outList.Add(device);
                                }
                                connection.Dispose();
                            }
                        }
                        catch
                        {
                        }
                    }
                }
            }
            return(outList);
        }
Esempio n. 18
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);
        }
Esempio n. 19
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;
        }
        async private void GetDevices()
        {
            try
            {
                DeviceInformationCollection devices = await DeviceInformation.FindAllAsync(SmartCardReader.GetDeviceSelector(SmartCardReaderKind.Nfc));

                // There is a bug on some devices that were updated to WP8.1 where an NFC SmartCardReader is
                // enumerated despite that the device does not support it. As a workaround, we can do an additonal check
                // to ensure the device truly does support it.
                var workaroundDetect = await DeviceInformation.FindAllAsync("System.Devices.InterfaceClassGuid:=\"{50DD5230-BA8A-11D1-BF5D-0000F805F530}\" AND System.Devices.InterfaceEnabled:=System.StructuredQueryType.Boolean#True");

                if (workaroundDetect.Count == 0 || devices.Count == 0)
                {
                    PopupMessage("No Reader Found!");
                }

                CardReader = await SmartCardReader.FromIdAsync(devices.First().Id);

                MifareCard = new MifareCard(new MifareClassic());

                CardReader.CardAdded   += CardAdded;
                CardReader.CardRemoved += CardRemoved;
            }
            catch (Exception e)
            {
                PopupMessage("Exception: " + e.Message);
            }
        }