Ejemplo n.º 1
0
 /// <summary>
 /// Card removed event handler gets triggered when card leaves nfc field
 /// </summary>
 /// <returns>None</returns>
 void CardRemoved(SmartCardReader sender, CardRemovedEventArgs args)
 {
     lock (CardConnectionLock)
     {
         if (CardConnection != null)
         {
             CardConnection.Dispose();
         }
     }
     ChangeTextBlockFontColor(TextBlock_Header, Windows.UI.Colors.Red);
 }
Ejemplo n.º 2
0
        protected void Cleanup()
        {
            if (connection != null)
            {
                connection.Dispose();
            }

            if (cardReader != null)
            {
                cardReader.CardAdded   -= CardReader_CardAdded;
                cardReader.CardRemoved -= CardReader_CardRemoved;
                cardReader              = null;
            }
        }
Ejemplo n.º 3
0
        protected override void Dispose(bool disposing)
        {
            Debug.WriteLine("Dispose: " + nameof(MiFareWin32CardReader));
            if (disposing)
            {
                connection?.Dispose();
                connection = null;
            }

            base.Dispose(disposing);
        }
Ejemplo n.º 4
0
        protected virtual void Dispose(bool disposing)
        {
            if (disposed)
            {
                return;
            }

            if (disposing)
            {
                connection.Dispose();
            }

            disposed = true;
        }
Ejemplo n.º 5
0
        public async Task ConnectAsync(SmartCard smartcard)
        {
            _MifareSmartCard = smartcard;
            var newConnection = await smartcard.ConnectAsync();

            lock (CardConnectionLock)
            {
                if (_MifareSmartCardConnection != null)
                {
                    _MifareSmartCardConnection.Dispose();
                }
                _MifareSmartCardConnection = newConnection;
            }
            mfStdAccess = new Mifare.AccessHandler(_MifareSmartCardConnection);
            IccDetection cardIdentification = new IccDetection(_MifareSmartCard, _MifareSmartCardConnection);
            await cardIdentification.DetectCardTypeAync();

            CurrentCardName = cardIdentification.PcscCardName;
            if (!(CurrentCardName == CardName.MifareStandard1K || CurrentCardName == CardName.MifareStandard4K))
            {
                throw new Mifare.Exceptions.CardTypeException("this Card is not mifare classic card");
            }
        }
Ejemplo n.º 6
0
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                try
                {
                    connection?.Dispose();
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex);
                }

                connection = null;
            }

            base.Dispose(disposing);
        }
Ejemplo n.º 7
0
 protected virtual void Dispose(bool cleanUpManagedToo)
 {
     _backingConnection.Dispose();
 }
Ejemplo n.º 8
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();
        }
Ejemplo n.º 9
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);
        }
Ejemplo n.º 10
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);
        }
Ejemplo n.º 11
0
        private async Task HandleCard(SmartCard card)
        {
            try
            {
                connection = await card.ConnectAsync();
                IccDetection cardIdentification = new IccDetection(card, connection);
                await cardIdentification.DetectCardTypeAync();
                LogMessage("Connected to card\r\nPC/SC device class: " + cardIdentification.PcscDeviceClass.ToString());
                LogMessage("Card name: " + cardIdentification.PcscCardName.ToString());
                LogMessage("ATR: " + BitConverter.ToString(cardIdentification.Atr));

                if ((cardIdentification.PcscDeviceClass == Pcsc.Common.DeviceClass.StorageClass) &&
                    (cardIdentification.PcscCardName == Pcsc.CardName.MifareUltralightC
                    || cardIdentification.PcscCardName == Pcsc.CardName.MifareUltralight
                    || cardIdentification.PcscCardName == Pcsc.CardName.MifareUltralightEV1))
                {
                    MifareUltralight.AccessHandler mifareULAccess = new MifareUltralight.AccessHandler(connection);
                    
                    byte[] responseUid = await mifareULAccess.GetUidAsync();
                    LogMessage("UID:  " + BitConverter.ToString(responseUid));
                    if (!BinaryDump && !ByteArrayEqual(responseUid, AmiiboUID)) //I used this because for some reasons responseUid == AmiiboUID was always false
                    {
                        MessageDialog dialog = new MessageDialog("The dump UID and the amiibo UID don't match");
                        LogMessage("Amiibo UID: " + BitConverter.ToString(responseUid) + " != Dump UID: " + BitConverter.ToString(AmiiboUID));
                        await dialog.ShowAsync();
                        return;
                    }
                    LogMessage("Using key: " + BitConverter.ToString(AmiiboPass));
                    byte[] Authresponse = await mifareULAccess.TransparentExchangeAsync(new byte[] { 0x1B, AmiiboPass[0], AmiiboPass[1], AmiiboPass[2], AmiiboPass[3] }); //PWD_AUTH
                    LogMessage("Auth sent !");
                    LogMessage("Auth Response length: " + Authresponse.Length.ToString());
                    if (Authresponse.Length == 0)
                    {
                        LogMessage("No response from Amiibo, can't restore dump !");
                        MessageDialog dlg = new MessageDialog("No response from Amiibo, wrong password ?");
                        await dlg.ShowAsync();
                        return;
                    }
                    LogMessage("Auth response: " + BitConverter.ToString(Authresponse));
                    //Using page layout from: https://www.3dbrew.org/wiki/Amiibo#Page_layout
                    #region WritePages
                    mifareULAccess.WriteAsync(0x4, getNBytes(AmiiboDump,0x10));
                    LogMessage("Page 0x4 wrote !");
                    mifareULAccess.WriteAsync(0x5, getNBytes(AmiiboDump, 0x14));
                    LogMessage("Page 0x5 wrote !");
                    mifareULAccess.WriteAsync(0x6, getNBytes(AmiiboDump, 0x18));
                    LogMessage("Page 0x6 wrote !");
                    mifareULAccess.WriteAsync(0x7, getNBytes(AmiiboDump, 0x1C));
                    LogMessage("Page 0x7 wrote !");
                    mifareULAccess.WriteAsync(0x8, getNBytes(AmiiboDump, 0x20));
                    LogMessage("Page 0x8 wrote !");
                    mifareULAccess.WriteAsync(0x9, getNBytes(AmiiboDump, 0x24));
                    LogMessage("Page 0x9 wrote !");
                    mifareULAccess.WriteAsync(0xA, getNBytes(AmiiboDump, 0x28));
                    LogMessage("Page 0xA wrote !");
                    mifareULAccess.WriteAsync(0xB, getNBytes(AmiiboDump, 0x2C));
                    LogMessage("Page 0xB wrote !");
                    mifareULAccess.WriteAsync(0xC, getNBytes(AmiiboDump, 0x30));
                    LogMessage("Page 0xC wrote !");
                    mifareULAccess.WriteAsync(0x20, getNBytes(AmiiboDump, 0x80));
                    LogMessage("Page 0x20 wrote !");
                    mifareULAccess.WriteAsync(0x21, getNBytes(AmiiboDump, 0x84));
                    LogMessage("Page 0x21 wrote !");
                    mifareULAccess.WriteAsync(0x22, getNBytes(AmiiboDump, 0x88));
                    LogMessage("Page 0x22 wrote !");
                    mifareULAccess.WriteAsync(0x23, getNBytes(AmiiboDump, 0x8C));
                    LogMessage("Page 0x23 wrote !");
                    mifareULAccess.WriteAsync(0x24, getNBytes(AmiiboDump, 0x90));
                    LogMessage("Page 0x24 wrote !");
                    mifareULAccess.WriteAsync(0x25, getNBytes(AmiiboDump, 0x94));
                    LogMessage("Page 0x25 wrote !");
                    mifareULAccess.WriteAsync(0x26, getNBytes(AmiiboDump, 0x98));
                    LogMessage("Page 0x26 wrote !");
                    mifareULAccess.WriteAsync(0x27, getNBytes(AmiiboDump, 0x9c));
                    LogMessage("Page 0x27 wrote !");//Until here i manually wrote the write addreses to test if the writing works, but i'm too lazy to replace those arleady working functions with a cycle
                    for (int i = 0; i < 0x5A; i++) mifareULAccess.WriteAsync((byte)(0x28/*Page*/ + i), getNBytes(AmiiboDump, 0xA0 /*ADDR of page 0x28*/ + (i*4)));
                    LogMessage("Page 0x28 to 0x81 wrote !");
                    #endregion
                    LogMessage("Dump restored :) !");
                    MessageDialog msg = new MessageDialog("Dump restored !");
                    await msg.ShowAsync();
                }
                else
                {
                    LogMessage("This tag is not an Amiibo !");
                    MessageDialog msg = new MessageDialog("This tag is not an Amiibo !");
                    await msg.ShowAsync();
                    var apduRes = await connection.TransceiveAsync(new Pcsc.GetUid());
                    if (!apduRes.Succeeded)
                    {
                        LogMessage("Failure getting UID of card, " + apduRes.ToString());
                    }
                    else
                    {
                        LogMessage("UID:  " + BitConverter.ToString(apduRes.ResponseData));
                    }
                }
                connection.Dispose();
            }
            catch (Exception ex)
            {
                connection.Dispose();
                LogMessage("Exception handling card: " + ex.ToString());
                MessageDialog msg = new MessageDialog("Exception handling card: " + ex.ToString());
                await msg.ShowAsync();
            }
        }
Ejemplo n.º 12
0
        private async Task HandleCard(SmartCard card)
        {
            try
            {
                connection = await card.ConnectAsync();
                IccDetection cardIdentification = new IccDetection(card, connection);
                await cardIdentification.DetectCardTypeAync();
                LogMessage("Connected to card\r\nPC/SC device class: " + cardIdentification.PcscDeviceClass.ToString());
                LogMessage("Card name: " + cardIdentification.PcscCardName.ToString());
                LogMessage("ATR: " + BitConverter.ToString(cardIdentification.Atr));

                if ((cardIdentification.PcscDeviceClass == Pcsc.Common.DeviceClass.StorageClass) &&
                    (cardIdentification.PcscCardName == Pcsc.CardName.MifareUltralightC
                    || cardIdentification.PcscCardName == Pcsc.CardName.MifareUltralight
                    || cardIdentification.PcscCardName == Pcsc.CardName.MifareUltralightEV1))
                {
                    MifareUltralight.AccessHandler mifareULAccess = new MifareUltralight.AccessHandler(connection);
                    List<byte> dumpTmp = new List<byte>();

                    byte[] responseUid = await mifareULAccess.GetUidAsync();
                    dumpTmp.AddRange(new byte[] { 0x41, 0x6D, 0x69, 0x69, 0x67, 0x6F, 0x44, 0x75, 0x6D, 0x70, 0x00, 0x00, 0x00, 0x00 }); //MAGIC
                    LogMessage("UID:  " + BitConverter.ToString(responseUid));
                    dumpTmp.AddRange(responseUid);
                    dumpTmp.AddRange(new byte[4]);
                    for (byte i = 0; i < 33; i++)
                    {
                        byte[] response = await mifareULAccess.ReadAsync((byte)(4 * i));
                        dumpTmp.AddRange(response);
                        LogMessage("Block " + (4 * i).ToString() + " to Block " + (4 * i + 3).ToString() + " " + BitConverter.ToString(response));
                    }
                    LogMessage("Dump ended :) !");
                    dumpTmp.AddRange(new byte[4] { 0x5F, 0x00, 0x00, 0x00 });
                    Dump = dumpTmp.ToArray();
                    MessageDialog msg = new MessageDialog("Dump completed !");
                    await msg.ShowAsync();
                }
                else
                {
                    LogMessage("This tag is not an Amiibo and can't be dumped!");
                    MessageDialog msg = new MessageDialog("This tag is not an Amiibo and can't be dumped !");
                    await msg.ShowAsync();
                    var apduRes = await connection.TransceiveAsync(new Pcsc.GetUid());
                    if (!apduRes.Succeeded)
                    {
                        LogMessage("Failure getting UID of card, " + apduRes.ToString());
                    }
                    else
                    {
                        LogMessage("UID:  " + BitConverter.ToString(apduRes.ResponseData));
                    }
                }
                connection.Dispose();
            }
            catch (Exception ex)
            {
                connection.Dispose();
                LogMessage("Exception handling card: " + ex.ToString());
                MessageDialog msg = new MessageDialog("Exception handling card: " + ex.ToString());
                await msg.ShowAsync();
            }
        }
Ejemplo n.º 13
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;
        }